你能在if语句中定义一个变量吗?

时间:2014-03-20 06:00:55

标签: python

我试图在if语句中创建一个变量但它不允许它。还有其他方法可以做我正在尝试的事情吗?

print ('Type numbers 1 or 2')
c = int(input())

if c == 1:
    answer = (90) #so the variable "answer" will be set to '90' if the user types "1"

if c == 2:
    answer = (50)

print (answer)

2 个答案:

答案 0 :(得分:3)

如果输入12作为输入,代码将以预期的方式运行。但如果用户输入另一个号码,您将获得Exception

NameError: name 'answer' is not defined

为避免这种情况,您可以在answer语句之前声明变量if

answer = 0    # or a reasonable number

if c == 1:
    answer = 90
# ...

注意: ()中的answer = (90)不是必需的,因为它只是一个数字。

答案 1 :(得分:1)

您需要允许input()可能超出您的先入为主的选项:

c = int(input("Type no. 1 or 2: "))

if c==1: 
    answer=90
    print(answer)
elif c==2: 
    answer =50
    print(answer)
else:
    print("you input neither 1 nor 2")

这是使用assert

的更紧凑的解决方案
c = int(input("Type no. 1 or 2: "))
assert c in [1,2], "You input neither 1 nor 2."
answer = 90 if c == 1 else 50
print(answer)
相关问题