-2

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.

Smartie
  • 13
  • 4

3 Answers3

3
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."
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
1

Wrap your input in int or float depending on the data type you are expecting.

times = int(raw_input('Enter a number: '))
print type(times)

Outputs:

Enter a number:  10
<type 'int'>

If a user inputs something other than a number, it will throw a ValueError (for example, inputing asdf results in:)

ValueError: invalid literal for int() with base 10: 'asdf'
Andy
  • 49,085
  • 60
  • 166
  • 233
0

You can cast the input as an integer and catch the exception if it isn't:

try:
    times = int(raw_input('Enter a number: '))
    # do something with the int
except ValueError:
    # not an int
    print 'Not an integer'
Karl
  • 3,394
  • 2
  • 22
  • 31