-2
這是我的program的代碼片段,其中當輸入要求的值時,增加該變量的值,並在按下鍵q
後退出循環來打印結果。請注意,我的代碼通過從用戶sys
導入argv
的參數(這就是爲什麼我的名字在命令行中)。compare int with char
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:請不要將此標記爲重複。
你可以做的快速改變是要求-1而不是q。這樣,所有輸入類型都是相同的。 – Antimony
請遵循以下指導原則:https://stackoverflow.com/help/mcve – klutt