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!")
Related
def set_number():
import random
return random.randint(1,500)
#This function plays the game
def number_guessing_game(number):
guess_counter = 0
guess = int(input("Enter a number between 1 and 500."))
while guess != number:
guess_counter += 1
if guess > number:
print(f"You guessed too high. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
elif guess < number:
print(f"You guessed too low. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
if guess == number:
print(f"You guessed the number! Good Job.!")
again = str(input("would you like to play again? Enter 'y' for yes or 'n' to close the game."))
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
number = set_number()
guess_count = number_guessing_game(number)
main()
I am working on a simple game project for my coding class. I am not good at coding at all. I came up with this part of the program, I just cannot figure out how to loop the entire number_guessing_game function until the user enters 'n' to stop it, I can't use a break because we did not learn it in the class and I will receive a 0 if I use a break.
I tried nesting a while loop inside of the function but I know I did it wrong.
Instead of using break use return.
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
while True:
number = set_number()
number_guessing_game(number)
again = input("would you like to play again? Enter 'y' for yes or 'n' to close the game.")
if again == 'n':
return
main()
You will probably want to remove the last line of the number_guessing_game function if you use this approach
First, your code is assuming the return of input is an integer that can be converted with int(). If you were to give it 'n' your program will crash.
Instead you could use the string class method isdigit() to see if the input was an integer value and then make a logical decision about it. Also note you do not need to convert the return from input to a str() as it is already a str type. You can confirm this with a print(type(input("give me something")))
guess = input("Enter a number between 1 and 500. 'n' to quit"))
if guess.isdigit():
[your code to check the value]
elif ('n' == guess):
return
else:
print(f"You entered an invalid entry: {guess}. Please re-enter a valid value")
If you dont like the idea of using 'return' you could change your while loop to look something like:
while(('n' != guess) or (guess != number)):
If you want the function body looping continuously you could have some code like:
def number_guessing_game(number):
exit_game = False
guess_counter = 0
while(exit_game != True):
guess = input("Enter a number between 1 and 500.))
guess_counter += 1
if guess.isdigit():
if int(guess) > number:
print("You guessed too high. Try Again!")
elif int(guess) < number:
print("You guessed too low. Try Again!")
elif int(guess) == number:
print("You guessed the number! Good Job.!")
again = input("would you like to play again? Enter 'y' for yes or 'n' to close)
if ('n' == again):
exit_game = True
else:
print("Error, please enter a valid value")
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.")
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"
I'm trying to get my program to work. It's a number guessing game where a user inputs their name, and then the program generates a number 1-100. From there they have to guess the number and the program tells them if their number is higher or lower.
If the user succeeded in guessing the number they have the option to play again. I've programmed this but it breaks after the first number input. Any idea where I went wrong?
import random
#importing the randoms
#getting the name from the user
message=("What is your name?")
name=input(message)
#challange message from user
print("Hello! ", name,"I have a number from 1 to 100! It is your job to try and guess it!")
gamestat=False
while gamestat==False:
#generate number
number = random.randint(1,101)
#start the game
guess = int(input("start to guess: "))
#GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses +=1
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
print("congrats it took you", num_guesses, "tries")
message=("Would you like to play again? (yes or no)")
result=input(message)
if result == "no":
gamestat= True
Program indentation is not correct. Try using
import random
#importing the randoms
#getting the name from the user
message=("What is your name?")
name=input(message)
#challange message from user
print("Hello! ", name,"I have a number from 1 to 100! It is your job to try and guess it!")
gamestat=False
while gamestat==False:
#generate number
number = random.randint(1,101)
#start the game
guess = int(input("start to guess: "))
#GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses +=1
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
print("congrats it took you", num_guesses, "tries")
message=("Would you like to play again? (yes or no)")
result=input(message)
if result == "no":
gamestat= True
Happy Coding!
As a comment already mentioned, it's an indentation issue.
if guess < number:
print ("higher")
guess = int(input("start to guess: "))
num_guesses +=1
This block is intended one tab to far, it resides under if guess > number and can thus never be reached.
Change your while loop to
while not gamestat:
# you can just invert it, same result as comparing to False
number = random.randint(1, 101)
# add some try except logic here and in the other inputs if the user doesn't input an int
guess = int(input("start to guess: "))
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
guess = int(input("try again: "))
num_guesses += 1
if guess < number:
print("higher")
guess = int(input("start to guess: "))
num_guesses += 1
Here is your code after minor modifications.
One was indentation issue as pointed righty. Apart from this in guess< number block the message was start to guess which is not consistent with above which may cause ambiguity. Also you can remove the common part outside the if block.
import random
# importing the randoms
# getting the name from the user
message = ("What is your name?")
name = input(message)
# challange message from user
print("Hello! ", name, "I have a number from 1 to 100! It is your job to try and guess it!")
gamestat = False
while not gamestat:
# generate number
number = random.randint(1, 101)
# start the game
guess = int(input("start to guess: "))
# GAME LOGIC
num_guesses = 1
while guess != number:
if guess > number:
print("lower")
if guess < number:
print("higher")
guess = int(input("try again: "))
num_guesses += 1
if number == guess:
print("congrats it took you", num_guesses, "tries")
message = ("Would you like to play again? (yes or no)")
result = input(message)
if result == "no":
gamestat = True
I tried to add a do you want to play again feature to my guessing game and it stopped working :( pls help. Im very new to python so i bet i have done many oblivious mistakes :S
import random
n = random.randint(1, 100)
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()
print("play_game")
while play_game == 'Y':
guess = int(input("Guess a number between 1 och 100: "))
while n != "gissning":
if guess < n:
print("You guessed to low")
guess = int(input("Guess a number between 1 och 100: "))
elif guess > n:
print ("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
else:
print("Gratz you guessed it")
break
while play_game == 'Y':
# your game
play_game = input("Do you want to play again? Y/N :").upper()
Actually there are a few little problems in your code, but with a bit of logic you can figure it out.
First, you don't want three separated while loops, since when you quit one you'll never reach it again unless you restart your code. You actually want nested loops. The outer one will verify if the user wants to play again, while the inner one will keep asking guesses until it matches the random number.
And second, you want to compare n, the random number, to guess, the user's input. In your code you're comparing n != "gissning", which will never be true since n is a number and "gissning", a string.
With that in mind you can change your code a little bit and have something like:
import random
print("play_game")
play_game = input("Do you want to play ? Y/N :").upper()
highscore = 0
while play_game == 'Y':
n = random.randint(1, 100)
guess = int(input("Guess a number between 1 och 100: "))
score = 1
while n != guess:
if guess < n:
print("You guessed to low")
elif guess > n:
print("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
score += 1
else:
print("Gratz you guessed it")
highscore = score if score < highscore or highscore == 0 else highscore
print('Your score this turn was', score)
print('Your highscore is', highscore)
play_game = input("Do you want to play again? Y/N :").upper()
Hope this helps you out. Good luck in your Python journey! Let us know if you have any further questions.
The next input prompt should be inside the outer-while loop. You also need to print the "Gratz you guessed it" along with the prompt and outside the inner-while loop when it's already n == guess.
import random
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()
while play_game == 'Y':
print("play_game")
n = random.randint(1, 100)
guess = int(input("Guess a number between 1 och 100: "))
while n != guess:
if guess < n:
print("You guessed to low")
guess = int(input("Guess a number between 1 och 100: "))
elif guess > n:
print ("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
print("Gratz you guessed it")
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()