input being ignored, function looping at for statement - python

I was just introduced to python less than a week ago and I'm trying to make a simple game of blackjack. I've written out the core of the program and it seems that it's ignoring the raw input, and just continually looping through the for conditional. It doesn't matter if what I type, hit, stay, whatever. Here's the code:
def main_game():
number = random.randint(1,13)
card_type_number = random.randint(1,4)
total = 0
dealer = random.randint(1,21)
input = raw_input("Would you like to Hit or Stay? \n")
if input == "hit" or "Hit":
card_number = numberConverter(number)
card_type = typeConverter(card_type_number)
new_amount = number
print "You got a %s of %s. You currently have %s. \n" % (card_number, card_type, number)
total += number
number = random.randint(1,13)
card_type_number = random.randint(1,5)
main_game()
elif input == ("Stay" or "stay") and total == 21:
print "Holy Cow! A perfect hand!"
main_game()
elif input == ("Stay" or "stay") and total < dealer:
print "Sorry, the dealer had %s" % (dealer)
maingame()
elif input == ("Stay" or "stay") and total > 21:
print "Sorry, you have more than 21"
main_game()
else:
print "Could you say again?"
main_game()
I'm at a loss and would appreciate any help.
Thanks!

if input == "hit" or "Hit":
That means if (input == "hit") or ("Hit"), which is always true.
Try
if input == "hit" or input == "Hit":
Or
if input in ("hit", "Hit"):
Or, even better:
if input.lower() == "hit"
(same for all the other elifs)

Related

Guess the number, play again

I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.

I would like to add Debt to my blackjack game

this is a simple blackjack game. I want to add debt and user will have bank account as;
bank=1000
Program will ask to user: "How much do you debt? $" and his money in the bank will increase or decrease then if user has 0 dollar in the bank game will over. The issue is whenever I input "y" for cont, the bank becomes 1000 again.I declared debt in the main function and the condition was below the "while cmp_sc!=0 and cmp_sc<17" when I tried to do that.
import os
import random
cards=[11,2,3,4,5,6,7,8,9,10,10,10,10]
def rand_card(card):
r_card=random.choice(card)
return r_card
def result_card(card):
sum_card=sum(card)
if sum_card == 21 and len(card)==2:
return 0
if 11 in card and sum(card)==21:
card.remove(11)
card.append(1)
return sum(card)
def comparing(result1,result2):
if result1>result2 and result1<=21:
return "You win"
elif result1==result2:
return "Draw"
elif result2>result1 and result2<=21:
return "You lose"
elif result1>21 and result2>21:
return "You are flying, you lose"
elif result1==0:
return "Blackjaack, You win!"
elif result2==0:
return "Computer Blackjaack, You lose!"
elif result1 > 21:
return "You went over. You lose"
elif result2 > 21:
return "Opponent went over. You win"
def main():
user=[]
computer=[]
flag=False
for i in range(2):
user.append(rand_card(cards))
computer.append(rand_card(cards))
while not flag:
usr_sc = result_card(user)
cmp_sc = result_card(computer)
print(f" Your cards: {user}, current score: {usr_sc}")
print(f" Computer's first card: {computer[0]}")
if usr_sc==0 or cmp_sc==0 or usr_sc>21:
flag=True
else:
cont = input("Type 'y' to get another card, type 'n' to pass: ").lower()
if cont=='y':
user.append(rand_card(cards))
else:
flag=True
while cmp_sc!=0 and cmp_sc<17:
computer.append(rand_card(cards))
cmp_sc=result_card(computer)
print(f" Your final hand: {user}, final score: {usr_sc}")
print(f" Computer's final hand: {computer}, final score: {cmp_sc}")
print(comparing(usr_sc, cmp_sc))
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clearConsole = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear')
clearConsole()
main()
The typical use of main() would be as a way to start your program, not as something that would be called each round. So, let's change that up a bit and call your current main() something like play_game(). Then we can reimplement main() more like:
def main():
balance = 1000
while input(f"You have {balance}. Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clearConsole()
bet = 100
balance -= bet
balance += play_game(bet)
print(f"Final Balance: {balance}")
if __name__ == "__main__":
main()
So now we have a balance and each round we have a bet and what we bet will initially decrease our balance but with luck it will increase as a result of play_game()
The changes we will make to play_game(bet) will be to accept a "bet amount" and then return winnings based on how our hand compares to the computers hand. This will require a small change to comparing() to return not only a message but an indication of a win/draw/loss so we can figure out what to give back.
At the end of play_game(bet) rather than:
print(comparing(usr_sc, cmp_sc))
We will:
win_multiplier, message = comparing(usr_sc, cmp_sc)
print(message)
return win_multiplier * bet
Finally, the return values of comparing() need to include the absolute indication of a win/draw/loss that we will use as a multiplier against bet.
def comparing(result1,result2):
if result1>result2 and result1<=21:
return (2, "You win")
elif result1==result2:
return (1, "Draw")
elif result2>result1 and result2<=21:
return (0, "You lose")
elif result1>21 and result2>21:
return (0, "You are flying, you lose")
elif result1==0:
return (2, "Blackjaack, You win!")
elif result2==0:
return (0, "Computer Blackjaack, You lose!")
elif result1 > 21:
return (0, "You went over. You lose")
elif result2 > 21:
return (2, "Opponent went over. You win")
If you really want to have it persisted, you need to store it somewhere outside the process memory e.g in some file on disk. The easiest way could be with something like that:
try:
with open("bank.txt", "r") as f:
# assing bank to content of your file
bank = int(f.read())
except FileNotFoundError:
# if file not exist, it's first game of user, we set bank to 1000 then
bank = 1000
print(bank)
bet = int(input("What is your bet?"))
# at the end of program
bank = bank + bet if user_won else bank - bet
with open("bank.txt", "w+") as f:
f.write(str(bank))
Now the actual bank of player will be stored in bank.txt file. You can set its content manually before run to modify user bank

Trying to get the number of tries to start at 1 and not 0

Whenever you run the game and start guessing it asks first what is guess #0? I'm trying to get it to display "what is guess #1?" but. at the same time keep the number of guesses equal to the number guessed (if that makes sense). Here's my code so far:
import random
def play_game(name, lower=1, upper=10):
secret = random.randint(lower, upper)
tries = 0
print("-----------------------------\n"
"Welcome, {}!\n"
"I am thinking of a number\n"
"between {} and {}.\n"
"Let's see how many times it\n"
"will take you to guess!\n"
"-----------------------------".format(name, lower, upper))
# Main loop
guessing_numbers = True
while guessing_numbers:
guess = input("What is guess #{}?\n".format(tries))
while not guess.isdigit():
print("[!] Sorry, that isn't a valid input.\n"
"[!] Please only enter numbers.\n")
guess = input("What is guess #{}?\n".format(tries))
guess = int(guess)
tries += 1
if guess < secret:
print("Too low. Try again!")
elif guess > secret:
print("Too high. Try again!")
else:
guessing_numbers = False
if tries == 1:
guess_form = "guess"
else:
guess_form = "guesses"
print("--------------------------\n"
"Congratulations, {}!\n"
"You got it in {} {}!\n"
"--------------------------\n".format(name,tries,guess_form))
if tries < 3:
# Randomly chooses from an item in the list
tries_3 = ["Awesome job!","Bravo!","You rock!"]
print (random.choice(tries_3))
# ---
elif tries < 5:
tries_5 = ["Hmmmmmpff...","Better luck next time.","Ohhh c'mon! You can do better than that."]
print (random.choice(tries_5))
elif tries < 7:
tries_7 = ["You better find something else to do..","You can do better!","Maybe next time..."]
print (random.choice(tries_7))
else:
tries_8 = ["You should be embarrassed!","My dog could do better. Smh...","Even I can do better.."]
print (random.choice(tries_8))
choice = input("Would you like to play again? Y/N?\n")
if "y" in choice.lower():
return True
else:
return False
def main():
name = input("What is your name?\n")
playing = True
while playing:
playing = play_game(name)
if __name__ == "__main__":
main()
I have the number of "tries" set to 0 at the beginning. However, if I set that to 1 then play the game and it only takes me 3 tries it will display that it took me 4 tries. so I'm not sure what to do. Still somewhat new to python so I would love some help
Anywhere that you have input("What is guess #{}?\n".format(tries)), use guess = input("What is guess #{}?\n".format(tries+1)). (adding +1 to tries in the expression, but not changing the variable itself)

Trying to use list function to limit input in while loop in my guessing game

def random():
x_val = randint(1,100)
limit = []
limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if limit2 <= 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print limit2
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif limit2 > 5:
return "You guessed over 5 times. You lose, sucker..."
break
elif limit2 == 4:
print "Last guess!"
continue
print "Welcome to my world! You will have to pick a correct number from 1 to 100!
If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Hi, I am working on a guessing game from 1-100 that I built from ground up by myself and doing research, my original code is not even close to this.
Now, I am stuck on the last part I cannot use the list to limit the input in while loop. I want to stop the game after 5 guesses. However every time it always keep going and once it win it printed out "0" for limit2 variable.
Thank you
The main problem with your code is that you never update the "counter" of the attempted tries made by the user. You initialize it at the beginning (through limit2 = len(limit)), but you never update that value, therefore causing an endless loop.
You simply need to perform the check on len(limit) instead of on limit2.
Working solution can be found below. I took the liberty of commenting limit2 (as it is not needed anymore), improving the indentation, adding two imports, replacing sleep with time.sleep, and fixing the number of checks to perform (if you are aiming at 5 maximum tries, len(limit) needs to be less than 5).
from random import randint
import time
def random():
x_val = randint(1,100)
limit = []
# limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if len(limit) < 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
time.sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
time.sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print len(limit)
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif len(limit) >= 5:
return "You guessed over 5 times. You lose, sucker..."
break
print "Welcome to my world! You will have to pick a correct number from 1 to 100! If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Worthy of note is that -- among several other things that should be fixed in your code -- you should avoid calling a function random, since it is already a name used by a very common module.

PYTHON: Unable to loop properly

EDIT: Thank you, the question has been answered!
The program works properly, asides from the fact that it does not loop to allow the user to play a new game. ie, after entering too many, too few, or the perfect amount of change, the program asks "Try again (y/n)?: " as it should. But I can't find out why it doesn't loop... And when it loops, it doesn't need to include the large paragraph about explaining the game. Just the line about "Enter coins that add up to "+str(number)+" cents, one per line." Any tips?
#Setup
import random
playagain = "y"
#Main Loop
if (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
By using break, you're completely leaving the while loop and never checking the playagain condition. If you want to see if the user wants to play again put the 'playagain' check in another while loop.
#Setup
import random
playagain = "y"
#Main Loop
while (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
You set playagain to y/n, but the code doesn't go back around to the beginning if playagain is equal to 'y'. Try making if playagain == "y" into while playagain == "y". That way, it goes through the first time and keeps going back to the beginning if playagain is still set to "y".
Also, indent your last line (playagain = str(....)) so it's part of the while playagain == "y" loop. If it's not, then the code will be stuck in an infinite loop because playagain isn't being changed inside the while loop.
Indent the last line as far as the while True line. And change the if (playagain == "y"): to a
while (playagain == "y"):
Your "Main loop" is not a loop, it is just an if statement. Also it is better to use raw_input because input will eval your input. Try something along the lines of this:
playagain = 'y'
#Main loop
while playagain == 'y':
print "do gamelogic here..."
playagain = raw_input("Try again (y/n)?: ")
Inside your gamelogic, you could use a boolean to check wether you need to print the game explanation:
show_explanation = True
while playagain == 'y':
if show_explanation:
print "how to play is only shown once..."
show_explanation = False
print "Always do this part of the code"
...
playagain = raw_input("Try again (y/n)?: ")

Categories

Resources