Python program ends even if the condition are not met - python

The condition is that the program will end:
-if the balance is less than or equal to zero.
-if the balance is greather than or equal to 200.
But the problem is that it ends after I input 1 or 2 (1 for heads and 2 for tails) and you need to run it again and the balance is not saved.
Here is my code:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = int( random.choice([1,2]))
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return(1)
if Balance >=200:
print("Congrats!! You reached your Target $200.")
return(1)
balance = 100 #beginning amount
while True:
bal = Balance_Check(balance) #check the available balance
if bal==1:
break
print("Guess heads by entering 1 or tails by entering 2 for this coin flip.") #Asking the player to guess
guess = int(input())
Balance = Guess_Check(guess,balance)

You messed up a few of the things like which balance to take at the right time when to stop the loop etc.
Here's the code if you want to take the user input once and then check the guess:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = random.choice([1,2])
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return 0
elif Balance >=200:
print("Congrats!! You reached your Target $200.")
return 1
balance = 100 #beginning amount
print("Guess heads by entering 1 or tails by entering 2 for this coin flip.") #Asking the player to guess
guess = int(input())
while Balance_Check(balance) not in [0,1]: # You need to run the loop till balance becomes 0 or 200
balance = Guess_Check(guess,balance)
But if you want to take user input on every chance use:
import random
def Guess_Check(guess,balance): #function for guess check
coin_flip = random.choice([1,2])
if coin_flip == 1:
print("It's heads!!")
else:
print("It's tail!")
if guess == coin_flip: #if guess is correct
print("Congrats you guessed right, You won $9.")
balance = balance+9
else: #if guess is wrong
print("Sorry your guess was wrong, You loss $10.")
balance = balance-10
print("Avalilable balanace is :", balance)
return (balance)
def Balance_Check(Balance): #Balance Check
if Balance <= 10: #we can't play the game if balance is below $10
print("Sorry!! You run out of money.")
return 0
elif Balance >=200:
print("Congrats!! You reached your Target $200.")
return 1
balance = 100 #beginning amount
while Balance_Check(balance) not in [0,1]: # You need to run the loop till balance becomes 0 or 200
guess = int(input("Guess heads by entering 1 or tails by entering 2 for this coin flip."))
balance = Guess_Check(guess,balance)
Sample output: (Not complete output as it was long)
Congrats you guessed right, You won $9.
Avalilable balanace is : 206
Congrats!! You reached your Target $200.

Related

how could I create restriction in input when input is 100 above

There are I have two problem please help
problem 1 - input should be integer 1-100 rand_num = random.randint(1,100) if input goes 100 above then show enter valid number 1 to 100 how could I achieve this please help
Thanks!
and also Could please give me a another suggestion to make my project more better.
import random
LIVES = 10
SCORE = 0
HIGH_SCORE = 0
print("\t\t =============> Welcome to the number guessing game developed by Python <===============\n")
print("You have only 10 lives to guessing the number\n\
")
rand_num = random.randint(1,100)
print(rand_num)
while LIVES >=0:
try:
user = int(input("Choose a number between 1-100 : "))
if user == rand_num:
print("Congratulations You guessed it right.")
SCORE=11-LIVES
if SCORE > SCORE:
SCORE += HIGH_SCORE
print(f"Your score is {SCORE} ")
print(f"The Score Is {HIGH_SCORE}")
break
elif user > rand_num:
LIVES-=1
print(f"Too high! Please guess lower number.\n Current Lives= {LIVES}")
elif user < rand_num:
LIVES-=1
print(f"Too Low! Please guess higher number.\n Current Lives= {LIVES}")
except Exception as e:
print(e)
I added a few embellishments to your code so that it could be played more than once.
import random
LIVES = 10
SCORE = 0
HIGH_SCORE = 0
DONE = False
print("\t\t =============> Welcome to the number guessing game developed by Python <===============\n")
print("You have only 10 lives to guessing the number\n")
rand_num = int(random.randint(1,100))
print(rand_num)
while True:
while LIVES >=0:
try:
user_string = input("Choose a number between 1-100 : ")
if user_string == "Q" or user_string == "q":
DONE = True
break
user = int(user_string)
if user > 100 or user < 1: # To account for invalid guesses
print("Guesses must be from 1 to 100")
continue
if user == rand_num:
print("Congratulations You guessed it right.")
SCORE = LIVES
print(f"Your score is {SCORE} ")
if SCORE > HIGH_SCORE:
print("This is also a new high score!!!")
HIGH_SCORE = SCORE
print(f"The Current High Score Is {HIGH_SCORE}")
break
elif user > rand_num:
LIVES-=1
print(f"Too high! Please guess lower number.\n Current Lives= {LIVES}")
elif user < rand_num:
LIVES-=1
print(f"Too Low! Please guess higher number.\n Current Lives= {LIVES}")
except Exception as e:
print(e)
if (DONE == True):
break
# Let's do this again
print("\t\t =============> Welcome to the number guessing game developed by Python <===============\n")
print("You have only 10 lives to guessing the number\n")
rand_num = int(random.randint(1,100))
print(rand_num)
LIVES = 10
SCORE = 0
First off, I ensured that the user input was an integer by wrapping the value inside the "int" function. Next, per your request, I added a range test of the entered value so that it only allows guesses from "1" to "100". Then, I also added in another "while" loop to provide for a continuous number of games. That way, the number of tries could be kept and compared to any previous high score to see if a new high score was achieved. In order to exit the game and the highest level "while" loop a test is made to see if the user has entered "Q" or "q" to quit (you might want to add verbiage to the program to direct the user).
Anyway, try those out and see if that is close to what your are trying to accomplish.

creating a python number guessing game

SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break

I am trying to replay the game when I run out of guesses (Play again when I run out of gusses or find the right answer)

I am trying to reply to this game and store the count in the passed memory but, any time I run the code again the game starts from scratch and the previous score is lost.
How can I store and continue from the past round.
import random
MAX_GUESSES = 5 #max number of guesses allowed
MAX_RANGE = 20 #highest possible number
#show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
#choose random target
target = random.randrange(1, MAX_RANGE + 1)
#guess counter
guessCounter = 0
#loop fovever
while True:
userGuess = input("take a guess:")
userGuess =int(userGuess)
#increment guess counter
guessCounter = guessCounter + 1
#if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you",guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
#if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
#main code
while True:
playOneRound() #call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
break
you forgot to mention the function name playOneRound. The code below works fine.
import random
MAX_GUESSES = 5 # max number of guesses allowed
MAX_RANGE = 20 # highest possible number
# show introductionpygame
print("welcome to my franchise guess number game")
print("guess any number between 1 and", MAX_RANGE)
print("you will have a range from", MAX_GUESSES, "guesses")
def playOneRound():
# choose random target
target = random.randrange(1, MAX_RANGE + 1)
# guess counter
guessCounter = 0
# loop fovever
while True:
userGuess = input("take a guess:")
userGuess = int(userGuess)
# increment guess counter
guessCounter = guessCounter + 1
# if user's guess is correct, congratulate user, we're done
if userGuess == target:
print("you got it la")
print("it only took you", guessCounter, "guess(es)")
break
elif userGuess < target:
print("try again, your guess is too low.")
else:
print(" your guess was too high")
# if reached max guesses, tell answer correct answer, were done
if guessCounter == MAX_GUESSES:
print(" you didnt get it in ", MAX_GUESSES, "guesses")
print("the number was", target)
break
print("Thanks for playing ")
# main code
while True:
playOneRound() # call a function to play one round of the game
goAgain = input("play again?(press ENTER to continue, or q to quit ):")
if goAgain == "q":
break

Printing / math on Python gambling game?

So I ran into trouble with this code again with output. Basically, there are some key features I need it to print, but whenever I manage to get it to print one thing it completely messes up the rest of the printing. So for example, I need it to print Roll # 1 (1 - 3) was (whatever number) not Roll (whatever number) if that makes sense. But I also need it to only max out to 3 rolls. This is where my second issue comes in; whenever I try to code it to subtract the bet from the bank when a user doesn't match any rolls, it counts my subtraction as a fourth roll and screws up the math. So instead of Roll #1 through #3 its now up to Roll #4
My third problem is, I need to the program to continue looping until the user enters 0 (zero) to end the script or the bank amount reaches 0 (zero).
You should redesign your program. First of all, you are generating new results for each condition check at
if guess == rollDice():
bank = bet * 2
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
Your code is not properly indented.
[...]
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
else:
guess != rollDice()
bank = bank - bet
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
And so on...
Have a function that simulates a single dice roll, like:
def roll():
return random.randint(1, 6)
And handle the rest in your main function like:
prog_info()
while True: #main loop
rolls = list() #redefines after each loop
score = 2
for i in range(3): #3 dice roll
bank, bet = total_bank(bank)
guess = get_guess()
if not guess: #exit condition
break
rolls.append(roll())
if sum(rolls) == guess:
bank = bet * score
break #break on match
score = score - 0.5 #after each roll we have less money to win
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')
A couple changes get the result you want
Pass the roll count to the rollDice function
Add an else to the bottom of the if block to check 0 bank
Here is the updated code:
import random
def rollDice(cnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', cnt, 'was', x)
return x
def prog_info():
print("My Dice Game .v02")
print("You have three rolls of the dice to match a number you select.")
print("Good Luck!!")
print("---------------------------------------------------------------")
print(f'You will win 2 times your wager if you guess on the 1st roll.')
print(f'You will win 1 1/2 times your wager if you guess on the 2nd roll.')
print(f'You can win your wager if you guess on the 3rd roll.')
print("---------------------------------------------------------------")
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
if get_bet == '0':
print('Thanks for playing!')
exit()
bet = int(get_bet)
return bank,bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
prog_info()
bank = 500
guess = get_guess
while True:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * .5
elif guess == rollDice(rcnt+3):
bank = bank
else:
bank = bank - bet # no match
if bank == 0:
print('You have no money left. Thanks for playing!')
exit()
Output
You have $500 in your bank.
Enter your bet (or 0 to quit): 500
Choose a number between 2 and 12: 4
Roll # 1 was 11
Roll # 2 was 6
Roll # 3 was 7
You have no money left. Thanks for playing!

Function unable to change variable

I am trying to make a full-on guessing game with a shop that you can buy stuff with coins. but I had a function that was supposed to give the user a certain amount of coins depending on how many attempts it took them to guess the number. However, when I have a variable called 'coins' and when a player gets the number, I add coins to 'coins' it doesn't actually add coins. When I print 'coins' it still tells me 0. It's very confusing I know but I just want to fix this. I am using a mac with python 3, and am using two files, one for the main code, and the other for the functions. Do you see where I'm going wrong?
Main Code:
from guessing_functions import guess_game, guess_home
home = False
attempt = 0
coins = 0
print ("Atemps:Coins, 10:5, 7:10, 5:20, 3:40, 1:100 ")
guess_game(coins, attempt)
while not home:
guess_home(coins)
Functions:
import random
def guess_game(coins, attempt):
print ("This is a guessing game. ")
found = False
num = random.randint(1, 100)
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == num:
print ("You got it!")
found = True
elif userGuess > num:
print ("Guess Lower!")
else:
print ("Guess Higher")
attempt += 1
if attempt == 1 and found == True:
print ("You won 100 coins!")
coins += 100
elif attempt == 2 and found == True:
print ("You won 40 coins")
coins += 40
elif attempt == 3 and found == True:
print ("You won 40 coins")
elif attempt == 4 and found == True:
print ("You won 20 coins")
coins += 20
elif attempt == 5 and found == True:
print ("You won 20 coins")
coins += 20
elif attempt == 6 and found == True:
print ("You won 10 coins")
coins += 10
elif attempt == 7 and found == True:
print ("You won 10 coins")
coins += 10
elif attempt == 8 and found == True:
print ("You won 5 coins")
coins += 5
elif attempt == 9 and found == True:
print ("You won 5 coins")
coins += 5
elif attempt == 10 and found == True:
print ("You won 5 coins")
coins += 5
Your function uses coins in it's local scope. In order for the function to change the value of the outter scope (global) coins variable you need to explicity state that.
Add global coins inside your function before changing coins value.
coins = 0
def f():
global coins
coins = 5
f()
print coins
# 5
Or, an alternative way is to return coins value from the function, and call your function coins = guess_game(attempt)
Here is some useful resource for this subject
To get it to work, you need only add return coins to the end of the guess_game function and collect the returned value in your main code as coins = guess_game(coins, attempt). However, if you'd like, you can simplify your code a little bit like so:
import random
def guessing_game(coins):
print("This is a guessing game. ")
attempts = 0
number = random.randint(1, 100)
user_guess = -number
while user_guess != number:
user_guess = int(input("Your Guess: "))
if user_guess > number:
print("Guess Lower!")
elif user_guess < number:
print("Guess Higher")
else:
print("You got it!")
if attempts == 1:
winnings = 100
elif attempts in [2, 3]:
winnings = 40
elif attempts in [4, 5]:
winnings = 20
elif attempts in [6, 7]:
winnings = 10
elif attempts in [8, 9, 10]:
winnings = 5
else:
winnings = 0
print("You won {} coins!".format(winnings))
return coins + winnings
attempts += 1
With your main code as:
from guessing_functions import guessing_game
coins = 0
print("Starting balance: {} coins".format(coins))
print ("Winnings vs. Attempts: 10:5, 7:10, 5:20, 3:40, 1:100")
coins = guessing_game(coins)
print("Current balance: {} coins".format(coins))
Where the output from a sample run is as follows:
Starting balance: 0 coins
Winnings vs. Attempts: 10:5, 7:10, 5:20, 3:40, 1:100
This is a guessing game.
Your Guess: 50
Guess Lower!
Your Guess: 25
Guess Higher
Your Guess: 37
Guess Higher
Your Guess: 44
Guess Higher
Your Guess: 47
Guess Lower!
Your Guess: 46
You got it!
You won 20 coins!
Current balance: 20 coins
You should return the number of coins from the function and assign it to coins:
def guess_game(coins, attempt):
... # code to determine coin amount
return coins
coins = guess_game(coins, attempt)
Defining Functions

Categories

Resources