简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM