What I am trying to do is create a while loop that always begins by gathering input. However, whenever I run it and input "hit", it seems to skip the prompt and go directly to the conditional statements under "if hit".
while current_score <= 21:
hit = input("Do you want to hit or stay? ")
if hit == 'stay' or ' Stay':
print("The dealer's hand:", dealer_hand)
if(current_score < dcurrent_score):
print("you have lost")
break
if(current_score > dcurrent_score):
print("you have won")
break
if hit == 'hit' or 'Hit':
z = randint(0, 51)
card_three = deck[z]
while card_three == card_two or card_three == card_one:
z = randint(0, 51)
card_three = deck[z]
current_hand.append(card_three)
if current_score > 21:
print("you have lost")
break
You have a problem in this line:
if hit == 'stay' or 'Stay':
and this one
if hit == 'hit' or 'Hit':
'Stay' and 'Hit' are truthy values so condition always pass. Change them to
if hit == 'stay' or hit == 'Stay':
and
if hit == 'hit' or hit == 'Hit':
Or more pythonic way:
if hit.lower() == 'stay':
'lower' method fill make string lowercase
I believe your problem would be solved if you type:
if (hit=="stay" or hit=="Stay"):
<statements>
if (hit=="hit" or hit=="Hit"):
<statements>
I suggest you go through the following article:
https://www.geeksforgeeks.org/basic-operators-python/
https://realpython.com/python-or-operator/
Related
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 need to include a decrement life counter that has 5 lives. I need to use a while loop and once the player loses a life it needs to send them back to the choice between going left and right in the code. I am new to python so I am not very familiar with it, any help is appreciated.
answer = input("Do you want to go on an adventure? (Yes/No) ")
if answer.lower().strip() == "yes":
x=5
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
answer= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack":
print("She turned you into a green one-legged chicken, you lost!")
elif answer == "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer == "right":
import random
num = random.randint(1, 3)
answer = input("Pick a number from 1 to 3: ")
if answer == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer != num:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print("You can't run away...")
else:
print("That's too bad!")
You should try to add comments to your code, it will help you and others as well.
I think for getting user answer, you should use a different variable. It will make things easier.
I removed the following code, it didn't make any sense to me.
while x > 0:
print("You have ",x,"lives left.")
if x > 0:
break
x-=1
if x == 0:
break
--
This is the code, which works:
# Try to write imported modules at the top, it's a good practice.
import random
# Start the game
answer_start = input("Do you want to go on an adventure? (Yes/No) ")
# user chooses to play
if answer_start.lower().strip() == "yes":
lives=5
# function for displaying the lives
def display_lives():
print("You have ",lives,"lives")
#display lives
display_lives()
# As long lives are more than 0, this will keep going.
while lives>0:
#First choice
answer1= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
#User chooses left
if answer1 == "left":
answer2 = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer2 == "attack":
print("She turned you into a green one-legged chicken, you lost!")
lives=lives-1
display_lives()
# User is running away
elif answer2 == "run":
print("Wise choice, you made it away safely.")
answer3 = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer3 == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer3 == "car":
print("You found your way home. Congrats, you won!")
elif answer3 != "plane" or answer3 != "car":
print("You spent too much time deciding...")
else:
print("You are frozen and can't talk for 100 years...")
elif answer1 == "right":
num = random.randint(1, 3)
answer4 = input("Pick a number from 1 to 3: ")
if answer4 == str(num):
print("I'm also thinking about {} ".format(num))
print("You woke up from this dream.")
elif answer4 != num:
print("You fall into deep sand and get swallowed up. You lost!")
lives=lives-1
else:
print("You can't run away...")
#Player chose not to play or player out of lives.
else:
print("That's too bad!")
I am a beginner in python and I got a task to make a game of guesses using python. In my assignment, I was told to count the number of tries. But I can't make it work. Any suggestion would be appreciated. (note: the list is for nothing...I was just messing with the code and trying things.)
`
# import random
# a=random.randint(1,30)
a = 23
Dict1 = ["Hello there! How are you?", 0,
"Guess a number Between 1 to 50",
"Your number is too high",
"Your Number is too low",
"Make Your Number A Bit Higher",
"Make Your Number a Bit Lower",
"Congratulations You Have guessed the right number :)"
]
print(Dict1[0])
name = input("What is your Name?\n=")
# print("hi!,{}, Wanna Play a game?".format(name))
print(Dict1[2])
while 1:
inp = float(input("="))
if inp > 50:
print(Dict1[3])
continue
elif inp < 1:
print(Dict1[4])
continue
elif inp < a:
print(Dict1[5])
continue
elif inp > a:
print(Dict1[6])
continue
elif inp == a:
print(Dict1[7])
q = input("Do You Want to Go again? Y or N\n=")
if q.capitalize() == "Y":
print('You have', 5 - 4, "tries left")
print(Dict1[2])
continue
elif q.capitalize() == "N":
break
else:
break
op = inp
while 1:
x = 4
if -137247284234 <= inp <= 25377642:
x = x + 1
print('You have', 5 - x, "tries left")
if x == 5:
break
if x == 5:
print("Game Over")
`
One way to go about it would be to set up a variable to track attempts outside the while loop between a and Dict1
a = 23
attempts = 1
Dict1 = [...]
Then each time they make an attempt, increment in the while loop:
if inp > 50:
print(Dict1[3])
attempts += 1
continue
elif inp < 1:
print(Dict1[4])
attempts += 1
continue
elif inp < a:
print(Dict1[5])
attempts += 1
continue
elif inp > a:
print(Dict1[6])
attempts += 1
continue
EDIT:
Looking more carefully at your code, it seems like you want a countdown. So you could change it to
attempts = 5
and in the while loop
while 1:
...
if q.capitalize() == "Y":
attempts -= 1
print('You have', attempts, "tries left")
print(Dict1[2])
continue
If I play one round of the game and select the option to quit, the game finishes, BUT, if I play a second round and try to quit, the game continues and the user is prompted to enter a guess again, instead of terminating the game.
It seems to be stuck in a loop.
Here is my code:
from random import randint
def core_game():
def init_hangman():
hangman = []
for x in range(7):
hangman.append([" "] * 7)
hangman[0][0] = "_"
hangman[0][1] = "_"
hangman[0][2] = "_"
hangman[1][3] = "|"
return hangman
hangman = init_hangman()
def print_hangman():
for x in hangman:
print(str.join("", x))
def get_input(guess):
your_guess = input(guess)
if your_guess in guessed_letters:
print("You already guessed that letter!")
return get_input(guess)
elif your_guess.isalpha() and len(your_guess) == 1:
return your_guess
else:
print("Please guess a single letter!")
return get_input(guess)
words_list = ["monkey", "cow"]
city_list = ["Amarillo", "Houston"]
lists = ["animals", "cities"]
random_list = randint(0,1)
random_word = randint(0,1)
if lists[random_list] == "cities":
rand_list = city_list
elif lists[random_list] == "animals":
rand_list = words_list
word = rand_list[random_word]
guessed = ""
guessed_letters = []
hang = 6
Cont = True
for letter in word:
guessed += "-"
print("\n\n\nWELCOME TO HANGMAN!")
print("The category is: ", lists[random_list])
print("The secret word: ", guessed, "is", len(guessed), "letters")
while Cont:
your_guess = get_input("\nEnter your guess: ")
if your_guess in word.lower():
for x in range(len(word)):
if word[x].lower() == your_guess.lower():
guessed = guessed[:x] + word[x] + guessed[x+1:]
guessed_letters.append(your_guess)
print("\nThe secret word: ", guessed)
if guessed.lower() == word.lower():
print("\n\nCongratulations, you guessed the word!")
play_again = input("\nWould you like to play again?(y/n) ")
if play_again == "y" or play_again == "yes":
core_game()
else:
Cont = False
else:
hang -= 1
guessed_letters.append(your_guess)
print("\nGuessed letters: ", guessed_letters)
if hang == 5:
hangman[2][3] = "O"
print_hangman()
print(guessed)
elif hang == 4:
hangman[3][3] = "|"
print_hangman()
print(guessed)
elif hang == 3:
hangman[3][2] = "-"
print_hangman()
print(guessed)
elif hang == 2:
hangman[3][4] = "-"
print_hangman()
print(guessed)
elif hang == 1:
hangman[4][2] = "/"
print_hangman()
print(guessed)
elif hang == 0:
hangman[4][4] = "\\"
print_hangman()
print("Game Over!")
print("The word was: ", word)
play_again = input("Would you like to play again?(y/n) ")
if play_again == "y" or play_again == "yes":
core_game()
else:
Cont = False
core_game()
The main function is core_game() and this is called when the program is run.
Okay- yes, I like the game- played it in the browser at trinket.io
Then I walked through an entire game here. Use this to debug your code, step by step and you can view all of the variables, lists etc. as well as enter input and view output.
The reason that your game is repeating is because:
1) In the function core_game you have the following code:
if play_again == "y" or play_again == "yes":
core_game()
This means that when you select yes after the first game, you are opening another "instance" of the function- you can see this if you trace through the code. You can also see this in the screenshot below (f19).
2) after you play the second game (remember that the first instance is still open) and select "n", this causes the "Cont" variable to change to False, but only in the second instance. The "while" is closed then, and the code goes back to the first instance where Cont is still True. You can also see both instances in the screenshot, and the state of each value of "Cont". The closed frame is "greyed out".
3) The program resumes in the first instance of the core_game at the start of the while loop, and the user is prompted to enter a guess.
This is difficult to see until you trace through the code, but I have included a snapshot here where you can (I hope) see what I mean.
So the issue is that you are calling the function from within itself.
Consider something more like this:
def core_game():
print("I was called")
while Cont:
ans = ("Do you wish to play a game? (Y/N)")
if ans[0].lower() == "y": # works for Y, y, Yup, Yeah, Yes etc.
core_game()
else:
Cont = False
PS
there are other really good reference sources out there, such as this as well.
Never give up- you'll find the step-thru really handy, and you might try Rice Universities MOOC on Coursera at some later stage.
Why wont this stop when 'n' is entered?
I've tried using break on the bottom else but I get errors doing that. That's a common problem I have with break. I have no idea why I'm thrown off with break.
import random
def game():
secret_num = random.randint(1, 10)
guesses = []
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! The number was {}.".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower than {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it! My number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'Y':
game()
else:
print("Bye!")
game()
You convert play_again to a lower-case letter but compare it to an upper-case letter.
You could simply change it to:
if play_again.lower() != 'n': # 'y' was wrong, right?
game()
else:
print("Bye!")
return # works also without the explicit return but it makes the intention clearer.