I have game I'm making. Have a question. My current code is this:
import random
print("Welcome to Python Acey Ducey Card Game")
print()
print("Acey-ducey is played in the following manner: the dealer (computer) deals two cards faced up and you have an option to bet or not bet depending on whether or not you feel the card will have a value between the first two. If you do not want to bet, enter a $0 bet.")
bankbalance = 100
def main():
global bankbalance
print()
print("These cards are open on the table:")
print()
print("First card:")
firstcard = random.randint(1,13)
print(firstcard)
print("Second card:")
secondcard = random.randint(1,13)
print(secondcard)
playerinput = input("Enter your bet: ")
playerinput = int(playerinput)
dealercard = random.randint(1,13)
dealercard = int(dealercard)
print("The card you drew was", (dealercard), "!")
if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
print("You win!")
bankbalance = bankbalance + playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
exit
elif playerinput > (bankbalance):
print("You cannot bet more than you have!")
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
exit
elif bankbalance == (0):
print("Oh no! You have no more money to bid.")
exit
else:
print("You lost!")
bankbalance = bankbalance - playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
exit
main()
The problem is that you can have negative amount of money. How do I fix this? I've tried this:
elif bankbalance == (0):
print("Oh no! You have no more money to bid.")
exit
But that doesn't seem to work either. Any answers? I've tried to fix that issue, but my console doesn't follow it. It just says "You currently have $ 0".
You need to check if balance is equal to 0 whenever call your function. So, before proceeding any further, you need to add that if statement under global bankbalance:
import random
print("Welcome to Python Acey Ducey Card Game")
print()
print("Acey-ducey is played in the following manner: the dealer (computer) deals two cards faced up and you have an option to bet or not bet depending on whether or not you feel the card will have a value between the first two. If you do not want to bet, enter a $0 bet.")
bankbalance = 100
def main():
global bankbalance
if bankbalance == 0:
print("Oh no! You have no more money to bid.")
return
print()
print("These cards are open on the table:")
print()
print("First card:")
firstcard = random.randint(1,13)
print(firstcard)
print("Second card:")
secondcard = random.randint(1,13)
print(secondcard)
playerinput = input("Enter your bet: ")
playerinput = int(playerinput)
dealercard = random.randint(1,13)
dealercard = int(dealercard)
print("The card you drew was", (dealercard), "!")
if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
print("You win!")
bankbalance = bankbalance + playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
return
elif playerinput > (bankbalance):
print("You cannot bet more than you have!")
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
return
else:
print("You lost!")
bankbalance = bankbalance - playerinput
print("You currently have $", (bankbalance))
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
return
main()
Result when you reach 0 bank balance:
...
First card:
2
Second card:
2
Enter your bet: 100
The card you drew was 3 !
You lost!
You currently have $ 0
Would you like to play again y/n: y
Oh no! You have no more money to bid.
import random
print("\n\tWelcome to Python Acey Ducey Card Game\t\n")
print("Acey-ducey is played in the following manner: the dealer (computer) deals two cards faced up and you have an option to bet or not bet depending on whether or not you feel the card will have a value between the first two. If you do not want to bet, enter a $0 bet.")
bankbalance = 100
def main():
global bankbalance
print("\nThese cards are open on the table:\n")
print("First card:")
firstcard = random.randint(1,13)
print(firstcard)
print("Second card:")
secondcard = random.randint(1,13)
print(secondcard)
playerinput = int(input("Enter your bet: "))
if playerinput > (bankbalance):
print("You cannot bet more than you have!")
play_again()
dealercard = random.randint(1,13)
dealercard = int(dealercard)
print(f"The card you drew was {dealercard} !")
if dealercard > firstcard and dealercard < secondcard or dealercard < firstcard and dealercard > secondcard:
print("You win!")
bankbalance += playerinput
print(f"You currently have $ {bankbalance}")
play_again()
elif bankbalance <= 0:
print("Oh no! You have no more money to bid.")
exit()
else:
print("You lost!")
bankbalance -= playerinput
print(f"You currently have $ {bankbalance}")
play_again()
def play_again():
playagain = input("Would you like to play again y/n: ")
if playagain == ("y"):
main()
else:
exit()
main()
I rewrite your code a little bit.
import random
bank_balance = 100
play_again = True
def random_card() -> int:
return random.randint(1,13)
def set_bet():
try:
bet = int(input("Enter your bet: "))
except ValueError:
bet = 0
return bet
def play():
global bank_balance
print("These cards are open on the table:")
first_card = random_card()
second_card = random_card()
print(f"First card: {first_card}")
print(f"Second card: {second_card}")
bet = set_bet()
while (bet < 0) or (bet > bank_balance):
if bet > bank_balance:
print("You cannot bet more than you have!")
elif bet < 0:
print("You cannot bet <= 0 ")
bet = set_bet()
player_card = random_card()
print(f"The card you drew was {player_card}!")
if sorted([first_card, second_card, player_card])[1] == player_card:
bank_balance += bet
print('you win!')
else:
bank_balance -= bet
print('you lost!')
def main():
print("Welcome to Python Acey Ducey Card Game")
print()
print("Acey-ducey is played in the following manner: the dealer (computer)"
" deals two cards faced up and you have an option to bet or not bet"
" depending on whether or not you feel the card will have a value"
" between the first two. If you do not want to bet, enter a $0 bet.")
global play_again, bank_balance
while play_again:
print(f"You currently have $ {bank_balance}")
play()
if bank_balance <= 0:
print("Oh no! You have no more money to bid.")
play_again = False
else:
play_again = input("Would you like to play again y/n: ") == 'y'
main()
Related
I'm practicing with a simple roulette program. At this moment, I have a problem with balance input(), if I put it outside the function, the function betting() doesn't recognize it. But, if I put it inside, the function, the program asks me again to input the amount of money and it overwrites the amount of money after the bet.
How to avoid that, so the program asks me only once for input? This is my code:
import random
def betting():
balance = float(input("How much money do you have? $"))
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
betting()
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting()
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting()
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
betting()
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
Pass the balance as a function parameter to betting(). Then ask once in the choice() function
import random
def betting(balance):
your_number = int(input("Choose the number between 0 and 36, including these: "))
if your_number < 0 or your_number > 36:
print("Wrong input, try again!")
return your_number
else:
bet = float(input("Place your bet: "))
while balance > 0:
if bet > balance:
print("You don't have enough money! Place your bet again!")
betting(balance)
else:
number = random.randint(0,36)
print(f"Your number is {your_number} and roulette's number is {number}.")
if number == your_number:
balance = balance + bet*37
print(f"You won! Now you have ${balance}!")
else:
balance = balance - bet
print(f"You lost! Now you have ${balance}!")
betting(balance)
else:
print("You don't have more money! Goodbye!")
quit()
def choice():
choice = str(input("Y/N "))
if choice.lower() == "y":
balance = float(input("How much money do you have? $"))
betting(balance)
elif choice.lower() == "n":
print("Goodbye!")
quit()
else:
print("Wrong input, try again!")
choice()
print("Welcome to the Grand Casino! Do you want to play roulette?")
choice()
You can ask for both at the same time and split the given string:
inp = input("State how much money you have and a number between 0 and 36 inclusive, separated by space: ")
bal, num = inp.split()
Python allocate a variable in the closest namespace.
This mean that balance is allocated in 'betting' namespace and will not be known outside 'betting'.
What you need is a global variable.
'global' mean that the variable must be allocated in the embracing namespace.
def betting():
global balance
print( balance)
def choice():
global balance
sel = input( ...)
if sel.lower() == 'y':
balance = int( input(">"))
betting()
choice()
Please note that you used 'choice' for 2 purposes. It's a function but it is also a variable. While it is possible, it is considered a bad habit.
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.
from random import randint
play = "yes"
while play == "yes":
choice = int(input("Would you like to play yourself(1) or let machine(2) play? press '1' or '2': "))
if choice == 1:
print("You chose to play yourself")
num = randint(1,9999)
counter = 0
while True:
num_guess = int(input("Guess the number: "))
if num_guess == 0:
print("Player has left the game")
break
else:
if num_guess > num:
print("Your guess is too high")
elif num_guess < num:
print("Your guess is too low")
elif num_guess == num:
print("Yay,you found it")
print("It took you " + str(counter) + " tries to guess the number")
break
counter += 1
elif choice == 2:
print("You chose to let the machine play")
your_num = int(input("Enter your number: "))
lowest = 1
highest = 9999
counter = 0
machine_guess = randint(1,9999)
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
else:
while True:
print("My guess is ",machine_guess)
is_it_right = input("Is it too small(<) or too big(>) or machine found(=) the number?: ")
if is_it_right == ">":
if machine_guess > your_num:
highest = machine_guess
counter += 1
else:
print("!!!Don't cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" < " + str(your_number) + ",so you should have written '<' instead of what you wrote.Continue ")
elif is_it_right == "<":
if machine_guess < your_num:
lowest = machine_guess + 1
counter += 1
else:
print("!!!Don't Cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" > " + str(your_number) + ",so you should have written '>' instead of what you wrote.Continue ")
elif is_it_right == "=":
if machine_guess == your_num:
if your_num == machine_guess:
counter += 1
print("Yayy,I found it")
print("It took me " + str(counter) + " tries to guess the number")
else:
print("You cheated and changed the number during the game.Please play fairly")
your_number = input("What was your number?: ")
print(str(machine_guess) +" = " + str(your_number) + ",so you should have written '=' instead of what you wrote ")
break
elif is_it_right == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
machine_guess = (lowest+highest)//2
elif choice == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player has left the game")
break
request = input("Do you want to play again? Answer with 'yes' or 'no': ")
if request == "no":
print("You quitted the game")
break
elif request == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
This is my code for game "guess my number",here the complicated ones is me trying to make the program prevent user from cheating (It is a university task,due in 3 hours)
So choice 1 is when user decides to play game "guess my number" and 2nd choice when computer plays the game.The problem that I have is :
I can't make the code make the user input the number in range of(1,9999) and THEN continue the process
As you see I have a lot of "if ... == 0" --> .In task it is said that whenever(any of inputs) user types 0 the game has to stop.The others work well but the one in choice 2 the first if is not working
If somebody has solution for this,please help.I would be grateful
Whenever you want to ask a question repeatedly until the correct input is given, use a while loop
print("You chose to let the machine play")
your_num = -1
while your_num < 0 or your_num > 9999:
your_num = int(input("Enter your number [0..9999]: "))
1- To force the user to input a number in the range of (1,9999), you must have an a condition like:
while True:
try:
num_guess= int(input("Enter your number in range 1-9999: "))
except ValueError:
print("That's not a number!")
else:
if 1 <= num_guess <= 9999:
break
else:
print("Out of range. Try again")
Edit: I didn't understand which input you wanted to keep in the range of 1-9999. I gave answer with num_guess but you can use it with your_num, too.
2- Add play = "no" line to the condition when the user inputs 0:
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
play = "no"
break
I want my code to end after "thank you for playing", however underneath it, i get the message going back to "Guess my number:". I appreciate the help and advice! Thank you
def guess_number():
import random
import sys
guessesTaken = 0
max_number = float(input("What should the maxium number be for this game be? "))
print("")
number = random.randint(1,max_number)
while (guessesTaken) < 100000:
guesses = float(input("Guess my number: "))
guessesTaken = guessesTaken + 1
if guesses < number:
print("Your guess is too low.")
print("")
elif guesses > number:
print("Your guess is too high.")
print("")
elif guesses == number:
print("You guessed my number!")
print("")
again = (input("Do you wish to play again? (Y/N): "))
print("")
if again.lower() == "y":
guess_number()
else:
print("")
print("Thank you for playing!")
Instead of print("thank you for playing") try return "Thank you for playing!"
Whenever it takes me several tries to beat the game, it always says the number_of_guesses is 1, which isn't true. What have I done wrong?
My code:
import random
print("Welcome to Rock, Paper, Scissors. \nYou will be going up against the computer, who will randomly",
"choose an object to duel you with!")
user_win = False
while not user_win:
user_guess = input("\nChoose either Rock, Paper or Scissors: ")
user_guess = user_guess.lower()
if user_guess != "rock" and user_guess != "paper" and user_guess != "scissors":
print("You didn't enter a valid guess. Try again, please.")
user_guess = input("\nChoose either Rock, Paper or Scissors: ")
user_guess = user_guess.lower()
computer_guess = random.randint(1,3)
if computer_guess == 1:
computer_guess = "rock"
elif computer_guess == 2:
computer_guess = "paper"
else:
computer_guess = "scissors"
print("Your guess:", user_guess.capitalize(), "\nComputer guess:", computer_guess.capitalize())
number_of_guesses = 1
if user_guess == computer_guess:
print("\nThe game is a tie. You guessed", user_guess, "and so did the computer.")
number_of_guesses += 1
user_win = False
elif (user_guess == "rock" and computer_guess == "scissors") or (user_guess == "paper" and computer_guess == "rock"):
print("\nCongratulations! You have beaten the computer by playing", user_guess.capitalize(), "while the computer played", computer_guess.capitalize())
user_win = True
number_of_guesses += 1
else:
print("\nDamn! The computer won by playing", computer_guess.capitalize(), "while you played", user_guess.capitalize())
user_win = False
number_of_guesses += 1
if number_of_guesses == 1:
print("\nYou won, and it only took you %d try!" % number_of_guesses)
else:
print("\nYou won, and it only took you %d tries!" % number_of_guesses)
input("\nPress enter to exit the program.")
I think that's formatted correctly. It's not easy to put code in here. Thank you!
You are always setting numbers of guesses equal to 1 inside your loop:
print("Your guess:", user_guess.capitalize(), "\nComputer guess:", computer_guess.capitalize())
number_of_guesses = 1 # setting here
Set the number_of_guesses outside the while loop
First of all in the while loop you always initialize number_of_guesses = 1 on every run. That is why this will always be 1 in each run.
Take this initialization before the while.