0
Implementing a random number guessing game
any ideas. how will I get the computer to pick a number at random from 0-9, and ask user to guess the number.. If correct or incorrect the computer would notify. I'm into randint now
8 ответов
+ 1
# This is how to make the computer pick a number from 0 to 9 in python.
import random
num = random.randint(0,9)
+ 1
Thank you
+ 1
I appreciated, yes please. I'll be able to understand better
0
get computer number
start loop
get player guess
check if guess is correct
if guess is wrong, print too high or too low
if guess is correct, announce victory and stop loop
* Tip - One thing to keep in mind.. Input by default is a string. so if you say something like
guess=input("Enter your guess")
and you check it against the computers chosen num it will return False. You would be checking a string against an integer
if 5=="5"
Easiest way around this is to get your input as an integer.
guess=int(input("Enter your guess "))
Notice the input is wrapped inside an int()
0
Justin. I'm not understanding
0
which part? would you like to see a completed code to learn from?
0
import random
num=random.randint(0,9)
run=True
while run:
guess=int(input("Enter your guess "))
if guess==num:
print("You Are Correct!")
run=False
if guess>num:
print("Guess Is Too High")
if guess<num:
print("Guess Is Too Low")
##############################
First 2 lines are pretty clear. import random and then use randint to pick a random number.
Then we have a variable called run and set it to True. we use this in the next line for our while loop. as long as run=True, the loop will continue to run.
on the first line of the loop we get a guess from the Player and set it to a variable called guess.
Then we check it with if statements for 3 possible outcomes. if the guess matches the computer number it declares a winner and sets run to false. run=False will stop the while loop.
if the guess is wrong it goes on to check if the guess is either too high or too low. if so it tells the player which. The loop will then start over and go back to the first line which is get a guess from the Player again. It will continue until the player wins
0
Keep in mind this works in a computer with a proper IDE such as pycharm. It doesn't work in code playground because code playground doesn't loop back for multiple inputs