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

时间:2019-03-01 03:32:31

标签: python python-2.x

我是Python的新手,正在尝试弄清缩进的工作方式(而不是括号)。我在使用elif时遇到问题:

NSLocationAlwaysUsageDescription

每当我尝试提交此文件时,它就会在elif处给我一个无效的语法错误。我曾尝试过寻找与此不同的线程,但那些elif缩进得太远了,否则忘记将冒号放在elif的末尾。我该怎么做才能解决此问题?

2 个答案:

答案 0 :(得分:0)

在缩进方面,Python是一种非常宽容的语言。 PEP-8 style指南将在这里为您带来好处,但是您的代码问题是在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"

答案 1 :(得分:0)

您使用的是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")