import random
print("Welcome to the Number Guessing Game!")
number=random.randint(1,100)
print("I'm thinking of a number between 1 and 100.")
print(number)
def guess(lives):
guess_number=int(input("Make a guess: "))
while guess_number!=number and lives>0:
if guess_number>number:
print("Too High")
elif guess_number<number:
print("Too Low")
else:
print(f"You got it! The answer was {number}")
if lives==0:
print("You are out of moves.YOu loose")
else:
print(f"You have {lives-1} attempts remaining to guess the number")
print("Guess Again:")
guess(lives-1)
def set_lives():
level=input("Choose a difficulty.Type 'easy' or 'hard': ")
if level=="easy":
lives=10
else:
lives=5
return lives
guess(set_lives())
After the number of lives ==0 the while statement is false and it must come out of the loop.
but in this case the loop is executed even when its false.
I can see that we can solve this problem by make the solution simpler, we need just to change guess function, here you are the code and I'll explain it:
def guess(lives):
while lives > 0:
guess_number = int(input("Make a guess: "))
if guess_number == number:
print(f"You got it! The answer was {number}")
return
if guess_number > number:
print("Too High")
elif guess_number < number:
print("Too Low")
lives -= 1
print(f"You have {lives} attempts remaining to guess the number")
print("You are out of moves. You loose")
now what this code says is:
1- we need to loop at least the {number of alives} times
2- if what the user guess {guess_number} is == to the number, then print "You got it! The answer was... " then return statement will get out of the function, so we have just one success story and this is it/
3- the other 2 if conditions will still loop becouse the user didn't get the the requird guess.
4- if the loop has been finished and we still in the functions, that means that the user finished his {lives} with no correct answer, so it will print "You are out of moves. You loose"
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.
I've just begun learning how to code so I'm working on some pretty basic projects so far, bear with me :)
Today's project is a very simple number guessing game and I have everything figured out except for one part. (The problem area is under "#Play again" in my code.)
What I want, is when someone has finished the game for them to be able to answer the question "Would you like to play again?" with yes or no. If they say yes, it will restart the game. If they say no, it will end the code. As it is right now, when you answer "no" the game will stop. However, if you answer "yes" the game will not restart and instead will ask "Would you like to play again?" over and over.
Any help would be greatly appreciated as I've tried it many different ways and I can't seem to figure it out. Thank you!
import random
#introduce variables
number = random.randint(1, 100)
guess = None
name = input("What is your name?\n")
turns = 10
#name
print(f"Hello, {name}, let's play a game!")
#loop
while True:
while guess != number:
guess = input("Guess a number between 1 and 100: ")
guess = int(guess)
if guess == number:
print(f"Congratulations, {name}! You won with {turns} turn(s) left!")
elif guess > number:
turns -= 1
print(f"Sorry, your guess is too high! You have {turns} turn(s) left. Guess again.")
elif guess < number:
turns -= 1
print(f"Sorry, your guess is too low! You have {turns} turn(s) left. Guess again.")
if turns == 0:
print("Sorry, {name}, you lose :(")
#Play again
again = input(f"Would you like to play again, {name}? yes or no.\n")
if "yes" in again:
print(f"Let's see if you can get it again, {name}!")
continue
elif "no" in again:
print(f"Thanks for playing, {name}!")
break
else:
print(f"Sorry, {name}, please enter yes or no.")
You need to initialize the parameter values every time the game starts, and end it every success or failure, ie exit the inner loop.
import random
#introduce variables
name = input("What is your name?\n")
#name
print(f"Hello, {name}, let's play a game!")
#loop
while True:
number = random.randint(1, 100)
guess = None
turns = 10
while guess != number:
guess = input("Guess a number between 1 and 100: ")
guess = int(guess)
if guess == number:
print(f"Congratulations, {name}! You won with {turns} turn(s) left!")
break
elif guess > number:
turns -= 1
print(f"Sorry, your guess is too high! You have {turns} turn(s) left. Guess again.")
elif guess < number:
turns -= 1
print(f"Sorry, your guess is too low! You have {turns} turn(s) left. Guess again.")
if turns == 0:
print("Sorry, {name}, you lose :(")
break
#Play again
again = input(f"Would you like to play again, {name}? yes or no.\n")
if "yes" in again:
print(f"Let's see if you can get it again, {name}!")
continue
elif "no" in again:
print(f"Thanks for playing, {name}!")
break
else:
print(f"Sorry, {name}, please enter yes or no.")
This is working fine
import random
# introduce variables
number = random.randint(1, 100)
guess = None
name = input("What is your name?\n")
turns = 10
# name
print(f"Hello, {name}, let's play a game!")
# loop
while True:
while guess != number:
guess = input("Guess a number between 1 and 100: ")
guess = int(guess)
if guess == number:
print(f"Congratulations, {name}! You won with {turns} turn(s) left!")
elif guess > number:
turns -= 1
print(f"Sorry, your guess is too high! You have {turns} turn(s) left. Guess again.")
elif guess < number:
turns -= 1
print(f"Sorry, your guess is too low! You have {turns} turn(s) left. Guess again.")
if turns == 0:
print("Sorry, {name}, you lose :(")
break;
# Play again
again = input(f"Would you like to play again, {name}? yes or no.\n")
if "yes" in again:
print(f"Let's see if you can get it again, {name}!")
continue
elif "no" in again:
print(f"Thanks for playing, {name}!")
break
else:
print(f"Sorry, {name}, please enter yes or no.")
So, im new to python and i have this challenge: I have to make the Guess the Number game, between me and computer. So this is where im at so far.
import random
the_number = random.randint(1, 4)
guess = 0
print(the_number)
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player guess lower...\n")
elif guess < the_number:
print("Player guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Player wins!")
break
guess = random.randint(1, 100)
if guess > the_number:
print("Computer guess lower...\n")
elif guess < the_number:
print("Computer guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Computer wins!")
break
print("Thank you for playing")
I wanna know how to make this to not stop until one of us is right?
# Import random library
import random
# Assign random value between 1-100
secret_number = random.randint(1, 100)
# get the user guess
guess = int(input("Guess the secret number between 1-100: "))
# Loop untill guess not equal to secret number
while guess != secret_number:
if guess < secret_number:
print("Sorry, your guess is too low.")
else:
print("Sorry, your guess is too high.")
# guess the number again
guess = int(input("Guess the secret number between 1-100: "))
# This statement will execute after coming out of while loop
print("You guessed the number!")
You can do something like this to make the computer smarter.
import random
the_number = random.randint(1, 4)
guess = 0
print(the_number)
minPossible = 0
maxPossible = 100
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player, guess lower...\n")
if guess < maxPossible:
maxPossible = guess - 1
elif guess < the_number:
print("Player, guess higher...\n")
if guess > minPossible:
minPossible = guess + 1
else:
print("Game Over! The number was", the_number, "The Player wins!")
break
guess = random.randint(minPossible, maxPossible)
if guess > the_number:
print("Computer, guess lower...\n")
maxPossible = guess - 1
elif guess < the_number:
print("Computer, guess higher...\n")
minPossible = guess + 1
else:
print("Game Over! The number was", the_number,"The Computer wins!")
print("Thank you for playing")
Your problem is the break statement at the end of the while loop. The code is iterating through the loop one time, then the break is ending the loop.
To get the desired output, you just need to tweak the code a bit, the break in the if statement for the computer is out of the loop of else, so it will stop the execution no matter what.
To counter this condition, you can move the break inside the else block. By doing this, the program will only break if either CPU or you correctly guess the right number.
One more thing i wanted to point out is you are printing the selecting number in the program, if it is a guessing game, isn't it supposed to be in the back-end of the code. By entering the printed number, you can win the game in the first iteration.
And just to point out, your program is selecting the number from (1, 4) but the computer is set to guess the number from (1, 100).
Kindly tick the answer if it is correct.
The modified code is -
import random
the_number = random.randint(1, 4)
guess = 0
while guess != the_number:
guess = int(input("Please enter a number: "))
if guess > the_number:
print("Player guess lower...\n")
elif guess < the_number:
print("Player guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Player wins!")
break
guess = random.randint(1, 4)
if guess > the_number:
print("Computer guess lower...\n")
elif guess < the_number:
print("Computer guess higher...\n")
else:
print("Game Over! The number was", the_number,"The Computer wins!")
break
print("Thank you for playing")
I have a few days of Python knowledge. I've been going to courses like Codecademy and I wanted to dive into a project. I followed a YouTube video at the start of this project to get the hang of it.
My game will ask if it wants to be played, if "yes" it will keep playing. If "no" the program will stop. I don't know how to change this to make it keep playing.
The program also will not show that the number is greater than or less than after the while loop shows up. Originally I had that section of code after the while loop, but it made no difference.
I'm just a total beginner who wanted to learn Python better with an actual project, so I really am not sure which steps to take here:
import random
number = random.randint(1,10)
tries = 1
name = input("Hello, What is your name?")
print("Hello there,", name)
question = input("Time to guess, ready? [Y/N]")
if question == "n":
print("sorry, lets go!")
if question == "y":
print("Im thinking of a number between 1 and 10.")
guess = int(input("Have a guess"))
if guess < number:
print("That is too low!")
if guess == number:
print("Congrats! You win!!")
if guess > number:
print("That is too high!")
while guess != number:
tries += 1
guess = int(input("Try again: "))
.
Hello, What is your name?name
Hello there, name
Time to guess, ready? [Y/N]y
Im thinking of a number between 1 and 10.
Have a guess1
That is too low!
Try again: 10
Try again: 10
Try again: 10
Try again:
The message "too high" is never displayed.
The if statements can go inside the while loop.
And you can use the break statement to terminate the while loop.
You can find more details here: https://docs.python.org/2.0/ref/break.html
Use elif not consecutive if statements. Change your while loop to allow breaking out, so you can display the correct win message.
import random
number = random.randint(1,10)
tries = 1
name = input("Hello, What is your name?")
print("Hello there,", name)
question = input("Time to guess, ready? [Y/N]")
if question == "n":
print("sorry, lets go!")
if question == "y":
print("Im thinking of a number between 1 and 10.")
guess = int(input("Have a guess"))
while True:
if guess < number:
print("That is too low!")
elif guess == number:
print("Congrats! You win!!")
break
elif guess > number:
print("That is too high!")
tries += 1
guess = int(input("Try again: "))
I'm with #furas in that this really should be a pair of nested while loops with a structure something like:
import random
name = input("Hello, What is your name? ")
print("Hello there,", name)
answer = "y"
while answer.lower().startswith("y"):
number = random.randint(1, 10)
print("I'm thinking of a number between 1 and 10.")
guess = int(input("Have a guess: "))
while True:
if guess < number:
print("That is too low!")
elif guess > number:
print("That is too high!")
else:
print("Congrats! You win!")
break
guess = int(input("Try again: "))
answer = input("Play again? [Y/N]: ")
print("Goodbye!")
I finally got it working! But for some reason the program prints out the previous error statement (too high or too low or please enter values between...), along with the value error message if the user enters in something that the try catches. Could anyone explain why? Any shortening/cleanup is also welcome. Sorry for any errors. Thanks!
'''
This is a guessing game that finds a random number, and then
Tells the user if their guess is too low or too high. It will also give
Error messages for any numbers outside of the accepted range, and will also
Give errors for anything not an integer.
At the end (if the user guesses correctly) it will ask if the
User would like to play again or quit.
'''
import random
def start_here():
print("Welcome to the guessing game!")
play_game()
def play_game():
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
if user_guess > 100 or user_guess < 1:
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number:
replay = (input("Great! You guessed it! would you like to play again? y or n"))
if replay == "y":
start_here()
else:
print("See ya later!")
start_here()
Keep in mind that the code after the try-except block gets executed irrespective of whether an exception was thrown or not. If the except block gets invoked you want your code to skip through the rest of the statements in the while loop and continue at the next iteration of the loop, where the user is prompted for input again. This can be achieved by using the continue keyword in the except block like so:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue
The continue statement directs the interpreter to skip the remaining statements in the current iteration of the loop. The flow of control can then re-enter the loop or exit, depending on the loop condition.
Now that your code runs the way it is intended to, here is how you can make it more concise:
Firstly, there is a neat feature in Python which allows you to write conditions like not 1 <= user_guess <= 100. These conditions are much quicker to read, and you can replace this in your code.
Secondly, the start_here() function is redundant. You can easily replace play_game() in its place with a few modifications like so:
import random
def play_game():
print("Welcome to the guessing game!") #Modification here
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue #Modification here
if not 1<=user_guess<=100: #Modification here
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number:
replay = (input("Great! You guessed it! would you like to play again? y or n"))
if replay == "y":
play_game() #Modification here
else:
print("See ya later!")
play_game() #Modification here
or you could entirely replace the play_game() function with a while loop like so:
import random
replay = 'y' #Modification here
while replay == 'y': #Modification here
print("Welcome to the guessing game!")
random_number = random.randrange(1, 100)
correct = False
user_guess = True
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
continue
if not 1<=user_guess<=100 :
print("Please only enter numbers between 1 and 100!")
elif user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
elif user_guess == random_number:
break
if user_guess == random_number: #Modification here
replay = input("Great! You guessed it! would you like to play again? y or n")
print("See ya later!") #Modification here
Here:
while not correct:
try:
user_guess = int(input("Enter your guess: "))
except ValueError:
print("Please only use integers")
if user_guess > 100 or user_guess < 1:
# etc
If the user input is not a valid int, you display an error message but still proceed with testing the value against the random number. You should instead skip the rest of the loop, or extract the part getting the user input into it's own loop. As a general rule, one function should do only one thing, then you use another function to control the whole program's flow:
def get_num():
while True:
try:
user_guess = int(input("Enter your guess: ").strip())
except ValueError:
print("Please only use integers")
continue
if user_guess > 100 or user_guess < 1:
print("Please only enter numbers between 1 and 100!")
continue
return user_guess
def again():
replay = input("would you like to play again? y or n"))
return replay.strip().lower() == "y"
def play_game():
random_number = random.randrange(1, 100)
while True:
user_guess = get_num()
if user_guess > random_number:
print("Too high, try again. ")
elif user_guess < random_number:
print("Too low, try again! ")
else:
# if it's neither too high nor too low then it's equal...
break
# no need to test again, we can only get here when the user
# found the number
print("Great! You guessed it!")
def main():
print("Welcome to the guessing game!")
while True:
play_game()
if not again():
break
if __name__ == "__main__":
main()