How to get function to loop properly? - python

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

Related

Python -- 3 dices game question by using while loop

I am a new learner on Python, I created a game to roll 3 dices randomly. I want to know how to go back to the "play" under "else". Please check my screenshot
import random
game = False
game1 = False
def roll():
money = 0
while game == False :
money += 1
key = input("Please hit 'y' to roll the 3 dicks: ")
if key == "y":
roll1 = random.randint(0,10)
roll2 = random.randint(0,10)
roll3 = random.randint(0,10)
print("Roll 1,2,3 are: ", roll1, roll2, roll3)
else:
print("Invalid input, try again")
return roll()
if roll1 == roll2 == roll3:
money +=1
print("You Win!")
print("Your award is ", money)
game == False
else:
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
??????????????????????
roll()
You can just put it inside a while loop there:
else:
while True: # you can
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
pass

Aid needed with school task

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.

How to make my 'Secret Number Game' replay without having to execute the code again?

Beginner in Python. I've been attempting to make my game give the user a 'play again?' option once the initial game is complete. The replay works if I failed to guess the number after 6 tries, however if I managed to guess the number and try to replay nothing happens.
import random
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
while userInput == False:
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
else:
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
Thanks in advance for any tips.
You can also define your game in a separate function. I'd do something like this:
import random
def play_game():
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
if __name__ == '__main__':
playGame = 'y'
while playGame == 'y':
play_game()
playGame = input('Would you like to play again? [y/n] ').lower()
print("Goodbye!")
Just add a break at the if where you're 'restarting' the game:
import random
secretNumber = random.randint(1, 20)
userGuesses = 0
userInput = False
while userInput == False:
print("Let's play a game!")
print("I'll think of a number between 1 and 20 and you have 6 attempts to get it right.")
print("What is your first guess?")
while userGuesses <= 5:
userInput = input()
if int(userInput) > secretNumber:
print("Too High! Try again!")
userGuesses += 1
elif int(userInput) < secretNumber:
print("Too Low! Try again!")
userGuesses += 1
else:
print("Congratulations! You guessed the secret number in " + str(userGuesses + 1) + " guesses!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
#Break here to exit while loop
break
else:
userInput = True
print("Goodbye!")
else:
print("You have run out of guesses! The number I was thinking of was " + str(secretNumber) + ". Better luck "
"next time!")
print("Would you like to play again? Y or N")
playGame = input()
if playGame == "Y":
userInput = False
userGuesses = 0
else:
userInput = True
print("Goodbye!")
Hope this helps you!

NameError: guesses not defined

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

Could This Python Program Be Simplified Or Better Written?

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)

Categories