字符串比较 - 未定义值
我有一个小程序,它会让你输入一个字符,比如 y、b 或 s,然后检查你输入的是什么。
我在运行这个程序时遇到的问题是:
NameError: name 'b' is not defined
如果输入的是 b。
这是我的代码:
print("Please think of a number between 1 and 7")
print("Is it 4? (y,s,b)")
answer=char(input())
if (answer=='y'):
print("It is Four!")
elif (answer=='s'):
print("Is it 2? (y,s,b)")
answer=input()
if (answer=='y'):
print("It is two!")
elif (answer=='s'):
print("It is one!")
elif (answer=='b'):
print("It is Three!")
elif (answer=='b'):
print("Is it 6? (y,s,b)")
answer=input()
if (answer=='y'):
print("It is Six!")
elif (answer=='s'):
print("It is Five!")
elif (answer=='b'):
print("It is Seven!")
1 个回答
3
看起来你在用Python 2,所以你需要使用raw_input()
,而不是input()
。这两者的区别在于,后者会尝试去计算你输入的内容。举个例子,如果你输入了b
,它会去找一个叫b
的变量。
在Python 3中,已经没有raw_input()
这个函数了,而input()
也不再计算你输入的内容。换句话说,Python 3的input()
就像Python 2的raw_input()
一样。