from subprocess import Popen
counter =0
while True:
i= raw_input('enter an integer')
i = int(i)
if counter == 0:
if i == 1:
play = Popen (['omxplayer audio_tart.mp3'], shell = True)
m=i
counter+=1
elif i == 2:
play = Popen(['omxplayer audio_lemon.mp3'], shell = True)
m=i
counter+=1
elif counter!=0:
if i == m:
print "same input"
pass
elif i == 1:
play = Popen(['omxplayer audio_tart.mp3'], shell = True)
m=i
counter+=1
elif i == 2:
play = Popen(['omxplayer audio_lemon.mp3'], shell = True)
m=i
counter+=1
大家好,我是python的新手,这是我的简化版代码。我基本上试图在与用户进行比较时获得多个输入。例如。如果输入(变量i)与前一个i相同,则执行某些操作...当我第一次输入有效整数时,它工作正常但输入第二个有效输入后出错。
Traceback (most recent call last):
File "2.py", line 7, in <module>
i = int(i)
ValueError: invalid literal for int() with base 10: ''
此外,我已尝试使用以下代码进行用户输入:
i= input('enter an integer')
并收到此错误:
Traceback (most recent call last):
File "2.py", line 6, in <module>
i= int(input('enter an integer'))
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
如果有人能提供帮助,我将不胜感激 PS:我使用的是python 2.7
答案 0 :(得分:0)
while True:
while True:
try:
i = int(raw_input(...))
break
except ValueError:
print('Please enter a number')
if counter == 0:
...
这将循环,直到用户输入可以正确转换为整数的值。请注意,这将允许用户输入任何数字。如果还有其他限制,您需要考虑这些限制。