Kevin
Kevin

Reputation: 4351

print statement in for loop only executes once

I am teaching myself python. I was thinking of small programs, and came up with an idea to do a keno number generator. For any who don't know, you can pick 4-12 numbers, ranged 1-80, to match. So the first is part asks how many numbers, the second generates them. I came up with

x = raw_input('How many numbers do you want to play?')
for i in x:
   random.randrange(1,81)
print i

Which doesn't work, it prints x. So I am wondering the best way to do this. Make a random.randrange function? And how do i call it x times based on user input.

As always, thank you in advance for the help

Upvotes: 0

Views: 971

Answers (1)

Paolo Bergantino
Paolo Bergantino

Reputation: 488404

This should do what you want:

x = raw_input('How many numbers do you want to play?')
for i in xrange(int(x)):
   print random.randrange(1,81)

In Python indentation matters. It is the way it knows when you're in a specific block of code. So basically we use the xrange function to create a range to loop through (we call int on x because it expects an integer while raw_input returns a string). We then print the randrange return value inside the for block.

Upvotes: 5

Related Questions