Looping a program with "while" statement - python

So, I have this program where you have to guess a number and I've coded it so that the program will tell you if the number you guessed was above or below the true number. My issue is that the program ends after it tells the user to guess higher or lower. I want the program to loop such that the program won't end until the number that I preset is guessed.This is my code:
number = 10
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
while guess!= number:
print ("Try Again")
print ("Done")
I tried to use a while loop to loop the program until the number was correctly guessed, but the "Try Again" script was looped forever... Thanks for the help!

Your flow control was not properly designed, but you can fix by wrapping your code in the while loop, and applying break once guess == number. The other cases where guess!=number, the loop just keeps running:
number = 10
while True:
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
break
elif guess < number:
print ("The number is higher")
else:
print ("The number is lower")
print ("Done")
You can read more about while loops in python here

while loops don't work that way. It looks like you're expecting some kind of goto where it guesses what you would like it to repeat, but all it will repeat is the content of the block. When it gets to while guess != number:, which is true, it will print that phrase, then check whether guess is not equal to number, which will still be true because it hasn't changed, forever.
Put everything that needs to be repeated into the loop:
number = 10
guess = int(input("Type in an integer: "))
while guess != number:
if guess < number:
print ("The number is higher")
else:
print ("The number is lower")
guess = int(input("Type in an integer: "))
print ("Good Job!")
print ("Done")

Try the following:
number = 10
guess = 9
while guess!= number:
guess = int(input("Type in an integer: "))
if guess == number:
print ("Good Job!")
elif guess < number:
print ("The number is higher")
elif guess > number:
print ("The number is lower")
else:
print ("Try Again")
print ("Done")

Related

how to add an error message when an integer is input instead of a string

I am trying to add an error when a string is entered instead of an integer. I've looked at other similar posts but when I try and implement it into my code it keeps spitting errors out. I have a number guessing game between 1 and 50 here. Can't for the life of me figure out what's wrong.
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") )
break
except ValueError:
print("Please input a number.")**
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Note that you're asking three times for the exact same input. There is really no need for that and no need for two loops at all. Just set the guess to a default value that will never be equal to the number (None) and use one single input, wrapped with try/except:
import random
number = random.randrange(1, 50)
guess = None
while guess != number:
try:
guess = int(input("Guess a number between 1 and 50: "))
except ValueError:
print("Please input a number.")
else:
if guess < number:
print("You need to guess higher. Try again.")
elif guess > number:
print("You need to guess lower. Try again.")
print("You guessed the number correctly!")
You could try running a while loop for the input statements. Checking if the input(in string format) is numeric and then casting it to int.
Sample code:
a = input()
while not a.isnumeric():
a = input('Enter a valid integer')
a = int(a)
The code executes until the value of a is an int
your code did not work because the indentation is not right
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") ) # here
break # here
except ValueError: # here
print("Please input a number.")
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Output
Guess a number between 1 and 50: aa
Please input a number.
Guess a number between 1 and 50: 4
You need to guess higher. Try again.

How to fix guessing game

The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.

Loop until entry matches a predetermined value

I want to have a user try a guessing game. The program should loop until the user guesses right.
How can I compare the values? Right now its going through the else part every time, even when the user guesses right.
Here is the code;
import sys
from random import randint
secret_number = randint(0, 100)
num_guesses = 0
guess = 0
while guess != secret_number:
guess = raw_input("Enter a number: ")
if (guess < secret_number):
print "Your guess is too low. Please try again."
else:
print "Your guess is too high. Please try again."
num_guesses = num_guesses + 1
print "Thank you, you guessed right"
print guess
You need to convert the string that raw_input returns into an integer using int, so the comparison operator works the way you expect it to:
guess = int(raw_input("Enter a number: "))
raw_input will return string, you compare string with int and nothing works
also you will never guess the number:
your code hav 2 options: too low or too high
also you never compare tries with max tries (try to fix that by yourself)
corrected version:
import sys
from random import randint
secret_number = randint(0, 100)
num_guesses = 0
guess = 0
while guess != secret_number:
guess = raw_input("Enter a number: ")
if (int(guess) < secret_number):
print "Your guess is too low. Please try again."
elif (int(guess) > secret_number) :
print "Your guess is too high. Please try again."
else:
print "Thank you, you guessed right"
break
num_guesses = num_guesses + 1
print guess

Need to validate user input as an integer

I want to add code so that if the user enters anything other than an integer, it prints something out. On the last line where I wrote
if guess != int I want the program to decide if the guess is anything other than a number.
import random
number = random.randint(1,100)
guess = 0
guesses = 0
while guess != number:
guess = int(input("Guess my number between 1 and 100(inclusive):"))
guesses = guesses + 1
if guess == number:
print("Well done! My number is:"number,"You had",guesses,"guesses"
elif guess < number:
print ('sorry, my number is higher')
elif guess > number:
print ('Sorry, My number is lower')
if guess != int:
print ("Enter a Number!!")
Let's use good old EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
guess = input("Guess my number between 1 and 100(inclusive):")
try:
guess = int(guess)
except ValueError:
print ("Enter a Number!!")
else:
if guess == number:
print("Well done! My number is:"number,"You had",guesses,"guesses"
elif guess < number :`
print ('sorry, my number is higher')
else:
print ('Sorry, My number is lower')
After I was kindly warned about raw input always being a string. Perhaps this is what you need
guess =int(input("Guess my number between 1 and 100(inclusive):"))
guesses = guesses + 1
try:
guess = int(guess)
if guess == number:
print("Well done! My number is:", number,"You had",guesses,"guesses")
elif guess < number :
print ('sorry, my number is higher')
elif guess > number:
print ('Sorry, My number is lower')
except:
print("Enter a number!")
Do notice that you don't use guesses anywhere, and that this isn't a loop so it will repeat itself only once and that also you never defined what your number is. Perhaps a more complete example would be this:
guesses = 0
number = 10
while True:
try:
guess =int(input("Guess my number between 1 and 100(inclusive):"))
except:
print("Enter a number!")
continue
guesses = guesses + 1
if guess == number:
print("Well done! My number is:", number,"You had",guesses,"guesses")
break
elif guess < number :
print ('sorry, my number is higher')
elif guess > number:
print ('Sorry, My number is lower')
I like #Nsh's answer - it's more common and probably better in practice. But if you don't like using try-catch statement and a fan of sql...
import random
my_number = random.randint(1,100)
your_number = None
counter = 0
While your_number != my_number:
s = input("Guess my number between 1 and 100(inclusive):")
counter += 1
if all(i in '0123456789' for i in s):
your_number = int(s)
if my_number == your_number: print 'Well done!'
else: print 'sorry, my number is {}'.format('higher' if my_number > your_number else 'lower')
Enjoy.

How to delete space in Python?

I have a question about How to delete a space in my guessing game.
Here is my source code:
import random
print ("I’m thinking of an integer, you have three guesses.")
def tovi_is_awesome():
random_integer = random.randint (1, 10)
chances = 3
for i in [1,2,3]:
print ("Guess", i, ": ", end=" ")
guess = eval(input("Please enter an integer between 1 and 10: "))
if guess < random_integer:
print ("Your guess is too small.")
elif guess > random_integer:
print ("Your guess is too big.")
else:
print ("You got it!")
break
if guess != random_integer:
print ("Too bad. The number is: ", random_integer)
tovi_is_awesome ()
When I run it, I got this:
I’m thinking of an integer, you have three guesses.
Guess 1 : Please enter an integer between 1 and 10:
How can I delete that space after "Guess 1"?
Or are there any better ways to avoid that space?
Thank you!
This is my first question in SOF lol
print ("Guess", i, ": ", end=" ")
You could write it like;
print ("Guess {}: ".format(i), end=" ")
So you can avoid from that space. You could check this one for examples.
Here is a simple guess game, check it carefully please. It may improve your game. You dont' have to use eval().
random_integer = random.randint (1, 10)
chances = 3
gs=1
while 0<chances:
print ("Guess {}".format(gs))
guess = int(input("Please enter an integer between 1 and 10: "))
if guess<random_integer:
print ("Your guess is too small.")
chances -= 1 #lost 1 chance
gs += 1 #increase guess number
elif guess > random_integer:
print ("Your guess is too big.")
chances -= 1
gs +=1
else:
print ("You got it!")
break
It's really simple, just showing you some basic logic. You may consider in the future catching errors with try/except etc.
print ("Guess %d:" % (i) )
Writing this way will delete the space.

Categories

Resources