这是我的program的代码段,当输入要求的值时,会增加该变量的值,并在按下键q
后退出循环打印结果。请注意,我的代码通过从用户argv
导入sys
来获取参数(这就是为什么我的名字在命令行中)。
prompt = "# "
come_out = True
one = 0
two = 0
three = 0
four = 0
answer = 0
while (come_out == True):
print """
Enter q to exit()
> Do you like Got?
> What about LoTR?
> Okay, Fargo?
> Alright, last choice: American Gods?
"""
answer = raw_input(prompt)
if answer == 1:
one = one + 1
elif answer == 2:
two = two + 1
elif answer == 3:
three = three + 1
elif answer == 4:
four = four + 1
elif answer == ord('q'):
come_out = False
else:
print "Not applicable ~~~ exiting"
come_out = False
当我按命令执行脚本时:
$ python ex14.py Sambhav-Jain
它没有给出任何错误但是没有按照假设运行,因为它必须一直运行循环,直到用户通过按键q
显式退出,但是:
Hi, Sambhav-Jain. Welcome to your ex14.py script.
Enter q to exit()
> Do you like Got?
> What about LoTR?
> Okay, Fargo?
> Alright, last choice: American Gods?
# 1
Not applicable ~~~ exiting
GoT Lovers: 0
LoTR Lovers: 0
Fargo Lovers: 0
American God Lovers: 0
然后我在网上搜索并找到了一种方法将answer
变量明确地转换为int
,即:
answer = int(raw_input(prompt))
通过这样做并执行我用于前一版本的相同命令,它会产生错误:
Hi, Sambhav-Jain. Welcome to your ex14.py script.
Enter q to exit()
> Do you like Got?
> What about LoTR?
> Okay, Fargo?
> Alright, last choice: American Gods?
# 1
Enter q to exit()
> Do you like Got?
> What about LoTR?
> Okay, Fargo?
> Alright, last choice: American Gods?
# q
Traceback (most recent call last):
File "ex14.py", line 26, in <module>
answer = int(raw_input(prompt))
ValueError: invalid literal for int() with base 10: 'q'
PS:请不要将此标记为副本。
答案 0 :(得分:1)
raw_input()
返回一个字符串。
所以你需要将其转换或仅与字符串进行比较。
如果您将比较更改为:
if answer == '1':
one = one + 1
elif answer == '2':
two = two + 1
elif answer == '3':
three = three + 1
elif answer == '4':
four = four + 1
elif answer == 'q':
come_out = False
它会像你期望的那样工作。