简体   繁体   中英

How to write a range so that one of the values is left open to user input

I would like to write a function for range where you enter a value when you are calling the function.

def randomRange():
    for num in range(0, ())
        print num

I would like the user to call the function like this "randomizeRange()"

And then I would like them to enter an integer to represent the maximum value in the range. I'm trying to get a better understanding of how to use the range function.

You need to prompt the user for input using the input() or raw_input() methods and then convert this to an int()

Python 2:

def randomRange():
    for it in range(int(raw_input("How many loops?: "))):
        print it

Python 3:

def randomRange():
    for it in range(int(input("How many loops?: "))):
        print(it)

Example >input and >>output:

>>How many loops?:
> 2
>> 0
>> 1

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