I was given an assignment for my computer science class with the goal of creating a number guessing game. I have created the program but I cannot seem to solve some problems that I came across while making it.
The code I wrote is....
import random
print("Welcome to the Number Guessing Game!")
Play_again = "yes"
i = 10
tries = 0
Random_Number = random.randint(1,100)
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
while Play_again.casefold() == "y" or Play_again.casefold() == "yes":
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing!")
break
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
if i == 0:
print("Sorry you have no more guesses left.")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
break
else:
print("You have entered an invalid input.")
break
Some of the problems I have with this code is that the randomly generated number stays the same even after you have played one game and are on your second. At first, I thought of putting the random.randint(1,100) inside the while loop, but that just creates a random number every time you guess. The second problem is that the 'i' and 'tries' values continue to go down but I need them to reset to their original value every time the user plays a new game.
By a new game I mean when the user answers 'yes' to Play_again.
Just a quick fix, create a 'reset' function, that updates all necessary variables:
import random
print("Welcome to the Number Guessing Game!")
Play_again = "yes"
def reset():
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
i = 10
tries = 0
Random_Number = random.randint(1,100)
return (i, tries, Random_Number)
i, tries, Random_Number = reset()
while Play_again.casefold() == "y" or Play_again.casefold() == "yes":
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
i, tries, Random_Number = reset()
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing!")
break
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
if i == 0:
print("Sorry you have no more guesses left.")
Play_again = input("Would you like to play again (N/Y)?")
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
i, tries, Random_Number = reset()
continue
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
break
else:
print("You have entered an invalid input.")
break
Output:
...
Your guess was too low. You have 0 guesses left.
Sorry you have no more guesses left.
Would you like to play again (N/Y)?y
A random number between 1 and 100 has been generated.
You have 10 tries to guess the number.
Whats your guess?:2
Your guess was too low. You have 9 guesses left.
...
I made full code for you check this out:
import random
import sys
def menu():
Play_again = input("Would you like to play again (N/Y)?").lower()
if Play_again.casefold() == "yes" or Play_again.casefold() == "y":
game()
elif Play_again.casefold() == "no" or Play_again.casefold() == "n":
print("Thank you for playing.")
sys.exit()
else:
print("You have entered an invalid input.")
menu()
def game():
i = 10
tries = 0
Random_Number = random.randint(1,100)
#print(Random_Number)
while i>0:
try:
Guess = int(input("Whats your guess?:"))
i -= 1
tries += 1
if Guess == Random_Number:
print(f"Correct! You got in {tries} tries!")
menu()
elif Guess > Random_Number:
print(f"Your guess was too high. You have {i} guesses left." )
elif Guess < Random_Number:
print(f"Your guess was too low. You have {i} guesses left.")
except:
print('Please Enter Numbers only')
print("Sorry you have no more guesses left.")
menu()
if __name__=='__main__':
print("Welcome to the Number Guessing Game!")
print("A random number between 1 and 100 has been generated.")
print("You have 10 tries to guess the number.")
game()
In addition, I made it to get only numbers.
If there is an error in this code, tell me I'll fix it for you.
Related
In this code, the user is to guess a number the computer has chosen randomly between 0 and 100.
The problem is that the while loop doesn't get executed at all. Everything was working until I put that code block into the while loop to get it repeated until the user guesses the number or runs out of attempts. How do I get the while loop to work? Please I am a beginner in python.
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while number_guessed:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
You define number_guessed as False, so the loop does not execute at all. Try while not number_guessed.
This should work:
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while number_guessed == False:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
The error with your code was that when you use a while loop like while somevariable and somevariable equals False, the while loop will not run. You could also just try while not number_guessed
The numbers_guessed is false, and the while loop must be true to run. So change the while loop or the variable.
Code:
import random
def guessing_game():
print('''Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.''')
select_level = input("Choose a difficulty. Type 'easy' or 'hard': easy: ")
if select_level == "easy":
attempt_left = 10
print("You have 10 attempts remaining to guess the number.")
elif select_level == "hard":
attempt_left = 5
print("You have 5 attempts remaining to guess the number.")
computer_choice = random.randint(0,100)
#print(f"Pssst, the correct answer is {computer_choice}")
number_guessed = False
while not number_guessed:
user_choice = int(input("Please enter a number between 0 and 100: "))
if computer_choice == user_choice:
number_guessed = True
print(f"You got it! The answer was {computer_choice}")
else:
attempt_left -= 1
if user_choice > computer_choice:
print(f"That is too high!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
else:
print(f"That is too low!\nGuess again.\nYou have {attempt_left} attempts remaining to guess the number.")
if attempt_left == 0:
number_guessed = True
print("You've run out of guesses, you lose.")
guessing_game()
I made a coin flip game with a gambling aspect but it wont iterate. It goes through once but then will only run line 6 on the second run after the user says they want to play again.
import random
import sys
money = 1000000
flip = random.randint(0,1)
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
money = money + 250000
else:
print("you lose")
money = money - 250000
print ("your balance is",money)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
game()
if replay == "n":
sys.exit("goodbye")
This is the output:
do you want to play the coin flip? y/ny
your balance is 1000000
heads or tails? 0 for heads 1 for tails1
heads
you lose
your balance is 750000
play again? y/ny
welcome to the coin flip
you need to call game() at the end of the code once more.
import random
import sys
money = 1000000
flip = random.randint(0,1)
step=25000
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
fact=1
else:
print("you lose")
fact=-1
print ("your balance is",money+fact*step)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
print("welcome again")
game()
if replay == "n":
sys.exit("goodbye")
game()
Add this up in your game function:
global money, flip
I'm setting up a basic hangman game and am trying to get the program to loop back to the beginning when the game is finished.
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
print("Play again? (y/n)")
Wrap your game in a function and throw it in a while loop.
After the play game function, they'll be asked to play again. If they respond with anything but 'y', the loop breaks.
while True:
# play_game()
if input("Play again?") != 'y':
break
print("Thanks for playing!")
You can use an user input and a while loop
play_again = "Y"
while play_again == "Y" or play_again == "y":
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
print("Play Again? (y/n)")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
play_again = input("Play again? (Y/N)")
or in short just put in in a function:
play_again = "Y"
while play_again == "Y" or play_again == "y":
game()
play_again = input("Play again? (Y/N)")
You could put it all into a function and have it loop back like this:
def start():
replay = True
while (replay):
game_started()
inp = input("Play again? Y/n ")
if inp == 'n' or inp == 'N':
replay = False
def game_started():
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print (char),
else:
print("_"),
failed += 1
if failed == 0:
print("You won")
break
guess = input("Guess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
break
start()
Edit:
Your check if a letter was guesses is also flawed:
If you guess "abcdefghijklmnopqrstuvwxyz", you always win.
I'd suggest checking the length of the input before appending it to guesses.
Also, to print it all into one line, you could use "print(char, end='')" (and "print('_', end='')", respectively). Just make sure to print a newline after the loop, to finish the line.
Hey friend here is what I came up with I hope it helps! Instead of using your turns to control the while loop you can use a "running" variable that is set to a boolean which you can use input statements for your replay feature to control when you want to exit (False) or continue through your loop (True).
print("Welcome to Hangman")
print("Start guessing")
word = "hangman"
guesses = ''
turns = 10
running = True
while running:
failed = 0
for char in word:
if char in guesses:
print(char),
else:
print("_"),
failed += 1
if failed <= 0:
print("You won")
x = input("Play Again? (y/n) \n")
if x == "y":
turns = 10
else:
running = False
guess = input("Guess a character: \n")
guesses += guess
if guess not in word:
turns -= 1
print("wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You Lose")
z = input("Play Again? (y/n) \n")
if z == "y":
turns = 10
else:
running = False
I'm just starting out on python and I'm wondering exactly why my variable guesses is not defined. I feel as if it's a indentation issue but once I change the indentation I usually come upon a syntax error any help understanding this issue would be greatly appreciated.
import random
def game():
guesses = []
secret_num = random.randint(1, 10)
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10 "))
except ValueError:
print("{} isn't a number!".format(guess))
else:
if guess == secret_num:
print("You got it! My number was {}".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower tha {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it my secret number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/N")
if play_again.lower() != 'n':
game()
else:
print("Bye thanks for playing!")
This doesn't throw any errors on my computer. Note you'll have to call the game() function if you want to actually run the code.
import random
def game():
guesses = []
secret_num = random.randint(1, 10)
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10 "))
except ValueError:
print("{} isn't a number!".format(guess))
else:
if guess == secret_num:
print("You got it! My number was {}".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower tha {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it my secret number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/N")
if play_again.lower() != 'n':
game()
else:
print("Bye thanks for playing!")
game() # to run the code
Okay so I have been learning quite a bit of Python over the past few days, two or three, and I decided to take my knowledge and create something simple, but sort of entertaining, so I created a Guessing Game.
After about 30 minutes of creating this program and getting it to work 100% I was wondering if there was anything I could have done better, etc. I want to make sure I learn from any mistakes so I appreciate it!
So here is the code:
import random
def guessingGame():
randomNumber = random.randrange(1, 10)
yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))
while yourGuess != randomNumber:
print("DOH! You Did Not Guess Right, TRY AGAIN")
yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))
else:
if yourGuess == randomNumber:
print("Congrats You Beat The Guess Game!")
playGame = input("Would You Like To Play The Guessing Game (Y/N): ")
if playGame == "Y" or playGame == "y":
print("Okay Lets Play!")
guessingGame()
elif playGame == "N" or playGame == "n":
print("Okay Thanks Anyways!")
break
Thanks Again!
Instead of
if playGame == "Y" or playGame == "y":
print("Okay Lets Play!")
guessingGame()
I kind of like
if playGame.lower() == "y":
# ...
I even better like:
def quit():
print("Okay Thanks Anyways!")
actions = {"y": guessingGame}
actions.get(playGame.lower(), quit)()
from random import randint
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That's no integer!")
def play():
secret = randint(1,10)
while True:
guess = getInt("Take a guess (1-10):")
if guess==secret:
print("Congrats, you beat The Guess Game!")
break
else:
print("D'oh! You guessed wrong. Try again!")
def main():
while True:
inp = input("Would you like to play The Guessing Game? (Y/N)").lower()
if inp=="y":
print("Okay, let's play!")
play()
elif inp=="n":
print("Alright. Thanks anyways!")
break
else:
print("You don't follow directions too good, eh?")
if __name__=="__main__":
main()
A few things I noticed:
You should handle the case where user tries to guess something that doesn't look like a number, say the letter 'a' for example.
Python style guide says to prefer lower_with_underscores over CamelCase for variable names.
The line yourGuess = int(input("Take A Guess, Numbers 1 Through 10: ")) is unnecessarily duplicated, see below for one possible way to refactor that part.
General cleanup:
import random
def guessing_game():
random_number = random.randint(1, 10)
assert random_number in range(1, 11)
your_guess = None
while your_guess != random_number:
try:
your_guess = int(input("Take A Guess, Numbers 1 Through 10: "))
except ValueError:
print("That wasn't a number")
continue
if your_guess != random_number:
print("DOH! You Did Not Guess Right, TRY AGAIN")
else:
print("Congrats You Beat The Guess Game!")
break
play_game = None
while play_game not in ['y', 'n']:
play_game = input("Would You Like To Play The Guessing Game (Y/N): ").lower()
if play_game == "y":
print("Okay Lets Play!")
guessing_game()
else:
assert play_game == "n":
print("Okay Thanks Anyways!")
I imagine you could use a "break" statement inside a while loop, as in
import random
def guessingGame():
randomNumber = random.randrange(1, 10)
while True:
yourGuess = input("Take A Guess, Numbers 1 Through 10: ")
if !yourGuess.isdigit():
print ("That's not a number!")
elif int(yourGuess) not in range(1,10):
print("I said between 1 and 10!")
elif int(yourGuess) != randomNumber:
print("DOH! You Did Not Guess Right, TRY AGAIN")
else:
break
print("Congrats You Beat The Guess Game!")
playGame = input("Would You Like To Play The Guessing Game (Y/N): ")
if playGame.lower() == "y":
print("Okay Lets Play!")
guessingGame()
elif playGame.lower() == "n":
print("Okay Thanks Anyways!")
break
Read the Pep 8 documentation on naming conventions and Python's style of coding.
import random
def guessing_game(x=1, y=10):
"""
A simple number guessing game.
"""
while int(input("Take A Guess, Numbers 1 Through 10: ")) \
!= random.randrange(x, y):
print("DOH! You Did Not Guess Right, TRY AGAIN")
print("Congrats You Beat The Guess Game!")
if input("Would You Like To Play The Guessing Game (Y/N): ") == 'Y':
print("Okay Lets Play!")
guessing_game()
else:
print("Okay Thanks Anyways!")
if __name__ == '__main__':
guessing_game(1, 10)