我想在我的覆盆子pi上创建一个简单的程序,让LED闪烁的次数与你输入的数字一样多。我的程序正在运行,但有点重复:
times = raw_input('Enter a number: ')
if times == '1':
times = 1
elif times == '2':
times = 2
elif times == '3':
times = 3
elif times == '4':
times = 4
elif times == '5':
times = 5
这需要大量的编程才能处理更大的输入,例如145。
有人知道更智能,更快捷的方式吗?
PS:代码完成;
# I know i need to import GPIO and stuff, this is just an example.
import time
while True:
try:
times = int(raw_input('Enter a number: '))
break
except ValueError:
print "Enter a number!"
print 'Ok, there you go:'
while times > -1:
if times > 0:
print 'hi'
times = times-1
time.sleep(1)
continue
elif times == 0:
print 'That was it.'
time.sleep(2)
print 'Prepare to stop.'
time.sleep(3)
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
print 'BYE'
break
谢谢。
答案 0 :(得分:3)
times = int(raw_input('Enter a number: '))
如果有人输入的不是整数,它会引发异常。如果这不是您想要的,您可以捕获异常并自行处理,如下所示:
try:
times = int(raw_input('Enter a number: '))
except ValueError:
print "An integer is required."
如果您想在有人输入有效输入之前继续询问输入,请将上述内容置于while循环中:
while True:
try:
times = int(raw_input('Enter a number: '))
break
except ValueError:
print "An integer is required."
答案 1 :(得分:1)
times = int(raw_input('Enter a number: '))
print type(times)
输出:
Enter a number: 10
<type 'int'>
如果用户输入的数字不是数字,则会抛出ValueError
(例如,输入asdf
结果:)
ValueError: invalid literal for int() with base 10: 'asdf'
答案 2 :(得分:0)
您可以将输入转换为整数,如果不是
,则捕获异常try:
times = int(raw_input('Enter a number: '))
# do something with the int
except ValueError:
# not an int
print 'Not an integer'