This code:
import random
print("\tWelcome to the guess my number program\n")
print("im thinking of a number between 1 and 100")
print("try to guess it in 5 attempts\n")
randomNum = random.randint(1,101)
tries = 0
userNumber = int(input("please pick a number"))
while userNumber != randomNum:
if userNumber > randomNum:
print ("lower")
else:
print("higher")
tries += 1
print ("you guessed it! the number was" , randomNum)
For some reason this produces an infinite loop. Any help, im still getting used to python.
You never updated your userNumber or randomNum inside the while loop. So once the loop condition is met, it will execute infinitely.
You need to update your while loop as:
while userNumber != randomNum:
if userNumber > randomNum:
print ("lower")
else:
print("higher")
tries += 1
userNumber = int(input("please pick a number"))
You've forgotten to ask the user to guess again. Try this!
while userNumber != randomNum:
if userNumber > randomNum:
print("lower")
else:
print("higher")
tries += 1
userNumber = int(input("please pick a number")
Try This:
import random
print("Welcome to the guess my number program!")
randomnum = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")
print("Try to guess it in 5 attempts.")
tries = 0
usernumber = 0
while not usernumber == randomnum:
usernumber = int(raw_input("please pick a number.")
if usernumber > randomnum:
print("Too High")
if usernumber < randomnum:
print("Too Low")
tries = tries + 1
if usernumber == randomnum:
print("You got the number!")
print("It took you " + str(tries) + " attempts.")
Related
I have a program that works fine, however I need to make it so that it can execute again when the if statement regarding playing again is satisfied.
import random
n=random.randint(0,10)
print(n)
number= int(input('Guess what the number is'))
count=0
while number !=n:
count=count+1
number= int(input('Guess what the number is'))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
else:
print("You got it right in"+ " "+str(count+1)+" "+ "tries")
print(count+1)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="y":
number= int(input('Guess what the number is'))
elif yesorno=="n":
print("Goodbye")
If you don't want an ugly big while loop, use functions. It makes your code cleaner.
import random
def play():
input("Guess a number between 1 and 10: ")
random_number = random.randint(1, 10)
guess = None
attempts = 0
while guess != random_number:
guess = int(input("Pick a number from 1 to 10: "))
attempts += 1
if guess < random_number:
print("TOO LOW!")
elif guess > random_number:
print("TOO HIGH!")
print("YOU GOT IT! The number was {}, you got it in {} attempts.".format(random_number, attempts))
def main():
play()
while input("Play again? (y/n) ").lower() != "n":
play()
main() # Call the main function
import random
n=random.randint(0,10)
count = 0
while True:
count=count+1
number= int(input('Guess what the number is'))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
else:
print("You got it right in"+ " "+str(count)+" "+ "tries")
print(count)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="y":
n=random.randint(0,10)
count = 0
elif yesorno=="n":
print("Goodbye")
break
import random
n=random.randint(0,10)
print(n)
count=0
while True:
count=count+1
number= int(input('Guess what the number is '))
if number< n:
print("that is too low")
elif number>n:
print("That is too high")
elif number == n:
print("You got it right in"+ " "+str(count+1)+" "+ "tries")
print(count+1)
yesorno= str(input('Do you want to play again? y or n'))
if yesorno=="n":
print("Goodbye")
break
Use a while loop with a condition that will always be true, like while True:.
To stop this infinite loop, use the break statement within the while loop.
If user inputs "y", the loop will continue because it has not been told the break.
Running Python code for guessing game - if guess number outside of range - do not want it to count against tries. Code works but counts erroneous numbers as tries.
My code:
import random
print("The number is between 1 and 10")
print("You have 5 tries!")
theNumber = random.randrange(1,10)
maxTries = 5
tries = 1
guess = int(input("Take a guess: "))
while ((tries < maxTries) & (guess != theNumber)):
try:
if guess > theNumber:
print("Guess lower...")
elif guess < theNumber:
print("Guess higher...")
if guess > 10:
raise ValueError
except ValueError:
print("Please enter a numeric value between 1 and 10.")
#continue
guess = int(input("Guess again: "))
tries = tries + 1
if(guess == theNumber):
print("You guessed it! The number was", theNumber)
print("And it only took you", tries, "tries!\n")
else:
print("You failed to guess", theNumber, "!")
It allows continued guessing up to 5 tries as long as guess is between 1 and 10. If outside of this range - it will not count as a try but tells the user to "Please enter a numeric value between 1 and 10"). Which the code does - it just counts those tries when I do not want it to work that way.
Try this one:
import random
min_number = 1
max_number = 10
number = random.randrange(min_number, max_number + 1)
print(number) # To know the number you are guessing
maximum_tries = 5
print(f"The number is between {min_number} and {max_number}")
print(f"You have {maximum_tries} tries!")
guess = int(input("Take a guess: "))
j = 1
while True:
if guess > max_number or guess < min_number:
print("Please enter a numeric value between 1 and 10.")
j = j - 1
elif guess > number:
print("Guess lower...")
print("You failed to guess", j, "!")
elif guess < number:
print("Guess higher...")
print("You failed to guess", j, "!")
if guess == number:
print("You guessed it! The number was", number)
print("And it only took you", j, "tries!\n")
break
if j == maximum_tries:
break
guess = int(input("Guess again: "))
j = j + 1
I need to generate a random number from 1 to 9 and ask the user to guess it. I tell the user if its too high, low, or correct. I can't figure out how to keep the game going until they guess it correctly, and once they get it right they must type in exit to stop the game. I also need to print out how many guesses it took for them in the end. Here's my code so far:
import random
while True:
try:
userGuess = int(input("Guess a number between 1 and 9 (including 1 and 9):"))
randomNumber = random.randint(1,9)
print (randomNumber)
except:
print ("Sorry, that is an invalid answer.")
continue
else:
break
if int(userGuess) > randomNumber:
print ("Wrong, too high.")
elif int(userGuess) < randomNumber:
print ("Wrong, too low.")
elif int(userGuess) == randomNumber:
print ("You got it right!")
import random
x = random.randint(1,9)
print x
while (True):
answer=input("please give a number: ")
if ( answer != x):
print ("this is not the number: ")
else:
print ("You got it right!")
break
Here is the solution for your problem from:
Guessing Game One Solutions
import random
number = random.randint(1,9)
guess = 0
count = 0
while guess != number and guess != "exit":
guess = input("What's your guess?")
if guess == "exit":
break
guess = int(guess)
count += 1
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("You got it!")
print("And it only took you",count,"tries!")
from random import randint
while 1:
print("\nRandom number between 1 and 9 created.")
randomNumber = randint(1,9)
while 1:
userGuess = input("Guess a number between 1 and 9 (including 1 and 9). \nDigit 'stop' if you want to close the program: ")
if userGuess == "stop":
quit()
else:
try:
userGuess = int(userGuess)
if userGuess > randomNumber:
print ("Wrong, too high.")
elif userGuess < randomNumber:
print ("Wrong, too low.")
else:
print ("You got it right!")
break
except:
print("Invalid selection! Insert another value.")
I have an issue with my simple guess the number game in python.The code is given below.The program never gives me a correct guess,it keep asking the number.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " iam thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
break
print("yahoo,you guessed the number!")
input()
time2 = time.time()
that is number guessing game in python 3.
You need to indent the code correctly, you should also use if/elif's as guess can only be one of higher, lower or equal at any one time. You also need to print before you break on a successful guess:
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
elif guess < number:
print("too low!")
elif guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
There is no way your loop can break as your if's are nested inside the outer if guess > number:, if the guess is > number then if guess < number: is evaluated but for obvious reasons that cannot possibly be True so you loop infinitely.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " i am thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
without changing too much, here is a working code.
secret_number = 5
chance = 1
while chance <= 3:
your_guess = int(input("Your Guess:- "))
chance = chance + 1
if your_guess == secret_number:
print("You Won !!")
break
else:
print("You failed..TRY AGAIN..")
import random as rand
# create random number
r =rand.randint(0,20)
i=0
l1=[]
while(i<4):enter code here
number = int(input("guess the number : "))
if(number in l1):
print("this number is alraedy entered")
i=i
else:
l1.append(number)
if(number == r):
print(number)
break
if(number>r):
print(" number is less than your number ")
elif(number<r):
print("number is greater than your number")
i =i+1
print("number is")
print(r)
Why does the too low, too high and got it print repeatedly lots of times?
This is my code:
import random
name = input("Hello there! What's your name?\n")
print("Hello there", name, ". Welcome to GUESS THE NUMBER GAME")
number = random.randint(1,100)
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n=n+1
You need to move the guess inside the loop, from:
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n = n+1
to:
n = 1
while n < 10:
guess = int(input("Please guess a number"))
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n += 1
Also, you can simplify with:
for _ in range(9):
guess = int(input("Please guess a number"))
...
And should break when the user makes a correct guess:
elif guess == number:
print("Got it")
break
Is this your real indentation ?
if yes:
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
and the last elif guess == number: can be just else ;)
edit: and I have forgotten your n++ and the real problem: the input
so:
while n<10:
guess = int(input("Please guess a number"))
n = n+1
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
print("Got it")
and to exit the loop:
while n<10:
guess = int(input("Please guess a number"))
n = n+1
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
print("Got it in "+n+" attempts.")
n=11
Assuming the code you provided has the correct indentation, then it's because the n = n + 1 statement is outside of the while loop. The corrected code is:
import random
name = input("Hello there! What's your name?\n")
print("Hello there", name, ". Welcome to GUESS THE NUMBER GAME")
number = random.randint(1,100)
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n=n+1
One piece of advice (assuming you're using Python 2.X): Use raw_input() instead of input, because raw_input automatically parses the input into a string, while input allows your users to inject arbitrary python code.
ETA: As pointed out by others, the guess statement (guess = int(input("Please guess a number"))) should be moved into the while loop, and a break statement used if the guess is correct.