简体   繁体   中英

How can i generate different numbers using Python3.9s random module

I did this beginner project a few weeks back where i made a random number generator that generates infinite numbers. i used the random module and figured it out from the docs (this was my first proj i was very proud of myself). So now i want to use it for more practical things. i tried to recreate it, and when the script is run it only generates one number and repeatedly prints that number to the terminal. nothing is wrong with the module, i belive, i think its a problem with my script but i cannot(for the life of me) figure out whats wrong.

this is my script


#number is the number the user enters this is here for other uses
number = input('Enter your number. >>> ')
#guess is the computers guess
guess = random.randrange(1, 1000)

while number != guess:
    print(guess)

this is my terminal

347
347
347
347
347
347
347
347
347

ect..(im not gonna type a ton of these you get the idea)

is there anything i can do to make it generate different numbers?

this is the module im using: https://docs.python.org/3/library/random.html

The issue is that the guess assignment is outside of your loop.

Looking at your code

import random

# `number` is a string
number = input('Enter your number. >>> ')

# `guess` is only set here 
guess = random.randrange(1, 1000)

while number != guess:
    # `guess` does not change here
    print(guess)

What you probably want is something like

import random

# parse input as a number
number = int( input( 'Enter your number. >>> ' ) )

# `guess` is initialized here
guess = random.randrange(1, 1000)

while number != guess:
    # reassign `guess`
    guess = random.randrange(1, 1000)
    print(guess)

Note the order of the loop here too though. If guess is correct on the first try nothing will be printed. You likely want to add a statement once guess is correct saying something like You're number was: <number> .

You only set the value of guess once outside of your loop. Therefore, it never changes and hence your loop never ends. What you need to do is generate a new guess for each iteration:

guess = random.randrange(1, 1000)

while number != guess:
    print(guess)
    guess = random.randrange(1, 1000)

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