Search code examples
pythonraspberry-pigpioraw-input

How to make a raw input a number?


I wanted to make a simple program on my raspberry pi that will let a LED flash as many times as the number you type in. My program is working, but is a bit repetitive:

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

This would take a lot of programming to handle a larger inputs like 145.

Does anybody know a smarter and faster way of doing it?

PS: Code is finished;

   # 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

Thank you.


Solution

  • times = int(raw_input('Enter a number: '))
    

    If someone enters in something other than an integer, it will throw an exception. If that's not what you want, you could catch the exception and handle it yourself, like this:

    try:
        times = int(raw_input('Enter a number: '))
    except ValueError:
        print "An integer is required."
    

    If you want to keep asking for input until someone enters a valid input, put the above in a while loop:

    while True:
        try:
            times = int(raw_input('Enter a number: '))
            break
        except ValueError:
            print "An integer is required."