简体   繁体   中英

Is there any way to use raw_input variables in random.randint?

I'm making a game where the "Computer" tries to guess a number you think of. Here's a couple snippets of code:

askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 = str(raw_input('Name the max number you want here.'))

That's to get the range of numbers they want the computer to use.

print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'

That's the computer asking if it got the number right, using random.randint to generate a random number. The problems are 1) It won't let me combine strings and integers, and 2) Won't let me use the variables as the min and max numbers.

Any suggestions?

It would be better if you created a list with the numbers in the range and sort them randomly, then keep poping until you guess otherwise there is a small possibility that a number might be asked a second time.

However here is what you want to do:

askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.')))
askNumber2 = int(str(raw_input('Name the max number you want here.')))

You save it as a number and not as a string.

As you suggested, randint requires integer arguments, not strings. Since raw_input already returns a string, there's no need to convert it using str() ; instead, you can convert it to an integer using int() . Note, however, that if the user enters something which is not an integer, like "hello", then this will throw an exception and your program will quit. If this happens, you may want to prompt the user again. Here's a function which calls raw_input repeatedly until the user enters an integer, and then returns that integer:

def int_raw_input(prompt):
    while True:
        try:
            # if the call to int() raises an
            # exception, this won't return here
            return int(raw_input(prompt))
        except ValueError:
            # simply ignore the error and retry
            # the loop body (i.e. prompt again)
            pass

You can then substitute this for your calls to raw_input .

The range numbers were stored as strings. Try this:

askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 =int(raw_input('Name the max number you want here.'))

That's to get the range of numbers they want the computer to use.

print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'

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