if print statement repeated lots of times - python

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.

Related

How can I make my program repeat execute many times?

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.

How do you start a Python game loop?

I have this very simple console game and I would like to restart the loop after the user answers a question but something doesn't seem to work properly.
import random
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
gameOn = 1
while gameOn == 1:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer == "Y" or "y" or "yes":
gameOn = 0
else:
print("Goodbye!")
You can do a simple thing, just put the whole code in a function and when you want to restart just call the function
Look at the code below:
import random
def game():
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
while True:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer.lower() == "y" or "yes": # Lower() is used for changing the whole string to lowercase
game()
else:
print("Goodbye!")
When you ask to play again you are setting gameOn to be 0 (as gameOn needs to be 1), which will exit the loop, your code should look like this
if answer in ("Y", "y", "yes"):
print("Starting again")
else:
print("Goodbye!")
gameOn = 0
for further clarification since you are choosing a number each game you need to put that into the loop as well
import random
gameOn = 1
while gameOn == 1:
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer in ("Y", "y", "yes"):
print("Starting again")
else:
print("Goodbye!")
gameOn = 0
The loop will automatically restart if you don't change any of the variables. So I would change your if else statement to just an if statement that says:
if answer.lower() != "y" or answer.lower() != "yes":
break
but in order for the game to be re-run properly and change the random number variable you need to re-execute the entire program which you can do by putting the program in a function then putting the function and the if statement in that loop for example:
import random
def runGame():
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
running = True
while running:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
while gameOn == 1:
runGame()
answer = input("Do you want to play again? Y/N ")
if answer.lower() != "y" or answer.lower() != "yes":
gameOn = 0

Player already guessed the number

I'm having difficulties telling the player that the player already guessed the number.
This is my code:
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
guessing = 1
def get_guess(already_guessed):
guess = input()
if guess in already_guessed:
print("You already guessed that number.")
else:
return guess
while guess != number:
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
guess = get_guess(input("Try again.\n\n"))
You never updating your already_guessed variable you could add it to your get_guess function. And also you have too many input. Try that:
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
already_guessed = []
def get_guess(already_guessed):
if guess in already_guessed:
print("You already guessed that number.")
else:
already_guessed.append(guess)
return already_guessed
while guess != number:
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
guess = int(input("Try again.\n\n"))
already_guessed = get_guess(already_guessed)
You don't maintain a list of guesses seen, but you try to use it.
You pass input in place of the already_guessed list at the end.
Your input statement flow is not consistent with game play.
Your termination doesn't tell the player that s/he won, and you use a redundant break statement.
import random
number = random.randint (1, 100)
guess = int(input("\nCan you guess the number?\n\n"))
guessing = 1
seen = []
def get_guess(already_guessed):
guess = int(raw_input("Your guess?"))
if guess in already_guessed:
print("You already guessed that number.")
else:
return guess
while guess != number:
seen.append(guess)
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
guess = get_guess(seen)
print "You win!"

Issue with simple Guess the number game in python

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)

A simple python loop issue

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.")

Categories

Resources