繁体   English   中英

Python 基本问题:elif 无效语法错误

[英]Basic Python Question: elif Invalid Syntax Error

我是 Python 的新手,正在尝试弄清楚缩进与括号的工作原理。 我在使用 elif 时遇到问题:

"""This program calculates the area of a circle or triangle."""
print "Area Calculator is on."
option = raw_input("Enter C for Circle or T for Triangle: ")
if option == 'C': radius = float(raw_input("Enter the radius: ")) 
  area = 3.14159*radius**2
  print "The area of circle with radius %s is %s." % (radius, area)
elif option == 'T':
    base = float(rawinput("Enter the base: "))
    height = float(rawinput("Enter the height: "))
    area2 = .5*base*height
    print "The area of triangle with base %s and height %s is %s." % (base, height, area2)

else: print "ERROR"

每当我尝试提交此文件时,它都会在 elif 上给我一个无效的语法错误。 我曾尝试查看有关此问题的不同线程,但那些 elif 缩进得太远,或者忘记将冒号放在 elif 的末尾。 我该怎么做才能解决这个问题?

在缩进方面,Python 是一种非常无情的语言。 PEP-8 风格指南在这里对你有好处,但你的代码问题是在if之后和elif之后的缩进不一致(2 对 4 个空格),以及if冒号后面的变量声明。

这是您的 Python 2 脚本的修订版:

#!/usr/bin/env python2

"""This program calculates the area of a circle or triangle."""
print "Area Calculator is on."
option = raw_input("Enter C for Circle or T for Triangle: ")
if option == 'C':
    radius = float(raw_input("Enter the radius: ")) 
    area = 3.14159*radius**2
    print "The area of circle with radius %s is %s." % (radius, area)
elif option == 'T':
    base = float(raw_input("Enter the base: "))
    height = float(raw_input("Enter the height: "))
    area2 = .5*base*height
    print "The area of triangle with base %s and height %s is %s." % (base, height, area2)
else:
    print "ERROR"

您使用的是 Python 2 还是 3..

我在 Python 3 中,经过一些更改后运行您的代码,它工作正常。 请尝试 :

print ("Area Calculator is on.")
option = input("Enter C for Circle or T for Triangle: ")
if option == 'C':
    radius = float(input("Enter the radius: "))
    area = 3.14159*radius**2
    print ("The area of circle with radius %s is %s." % (radius, area))
elif option == 'T':
    base = float(input("Enter the base: "))
    height = float(input("Enter the height: "))
    area2 = .5*base*height
    print ("The area of triangle with base %s and height %s is %s." % (base, height, area2))
else: 
    print ("ERROR")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM