How do u add lives and a counter to display the lives - python

I want to add lives to and a counter displaying how many lives I have left
I tried adding a counter using range but it prints all the no like 1, 2, 3 I just need it to display 1 number that represents lives u have left
num = random.randint(1,10);
print(num)
guess = int(input('Guess a number: '))
if(guess == num):
print("correct")
else:
print("incorrect")

Try a for loop:
import random
num = random.randint(1,10)
for i in range(3):
guess = int(input('Guess a number: '))
if(guess == num):
print("correct")
break
else:
print("incorrect")
print(2 - i, 'tries left')

I would use a while loop for this. Each guess a counter would be decreased by one. The loop would run while lives > 0.
num = random.randint(1,10);
print(num)
lives = 3
while lives > 0:
guess = int(input('Guess a number: '))
if(guess == num):
print("correct")
break
else:
print("incorrect")
print("%s lives left." % lives-1)
lives -= 1

Related

Python - How to return to previous function after calling another function?

Heres the copy of my code :) this game is part of my personal activity.
so after purchasing a clue (from: def game_hints) i want to return to def Game_process.
import random
SCORE = 0
ROUNDS = 1
def player_stats():
print(f"SCORE: {SCORE} | ROUNDS: {ROUNDS}")
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Mystery Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
def Game_Process():
global ROUNDS
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) #remove before final product
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
global SCORE
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
def Game():
user_opt = input("\"Welcome to Guess Game\" \nPress [Y] to Play or [N] to Exit: ").lower()
if user_opt == "n":
print("Good bye!")
exit()
elif user_opt == "y":
Game_Process()
else:
print("Invalid Input! [1/2]")
Game()
Game()
As shown below, this is the fuction for the hints. I was able to call this function but the only problem is that the after this fuction is done, it changes the Myster_Num.
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Secret Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
First, you must remove the else statement in the game_hints function because it restarts a full GameProcess and therefore indeed recompute a mysterious number.
Then, when you exit game_hints and come back to GameProcess, you must not come back to the big loop because it will indeed recompute a mysterious number. The solution is to have an inner loop inside each round that you exit only if the player guessed the correct value using the break keyword.
def Game_Process():
SCORE = 0
ROUNDS = 1
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) # remove before final product
while True:
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
break
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()

I want my program to terminates when the 5x trials are over

This is my code, everything seems to work fine, only part of the trial is not working.
counter = 1
max_attempt = 5
secrect_nu = 313
num = int(input("Guess my number: "))
while num != secrect_nu:
max_attempt = max_attempt - 1
print(emoji.emojize(":winking_face_with_tongue: :winking_face_with_tongue: \U0001F606"))
num = int(input(f"HHHHH! You stuck in my loop you've {max_attempt} left \nGuess my number: "))
if num >= max_attempt:
print("Game Over!")
break
counter += 1
# while num >= max_attempt:
#
# break
if num == secrect_nu:
print("==========================================")
print("Congrats, You've broken the chain of my loop. ")
print("You got my secrect number in your " + str(counter) + "th attempt.")
I want to solve the trial issue, I want the program to stop if the user exceeds 5 trials
Doing this should work for you:
counter = 1
max_attempt = 5
secrect_nu = 313
num = int(input("Guess my number: "))
while num != secrect_nu:
max_attempt = max_attempt - 1
num = int(input(f"HHHHH! You stuck in my loop you've {max_attempt} left \nGuess my number: "))
if counter==4:
print("Game Over!")
break
counter += 1
if num == secrect_nu:
print("==========================================")
print("Congrats, You've broken the chain of my loop. ")
print("You got my secrect number in your " + str(counter) + "th attempt.")
It is going to check everytime if counter is 4 or not and num is equal to secrect_nu or not.

Python Program Loop

Could someone look at my code and see why I'm getting a syntax error on line 41, please?''' This is program that gives the user the option of playing a number guessing
game where they have the option of unlimited guesses between 1 and 100 or only
5 guesses.
'''
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
Set the Loop
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
count = count+1
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
count = count+1
elif (guess == x):
print ("Congratulations, you guessed the number in", count,
"attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:")
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!)
if (guess == x):
print ("You won!")
else:
print ("You lost!")
elif (guess == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")
After correcting some errors it looks like this:
import random
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
count=0
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
count = count+1
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
print(f"Congratulations, you guessed the number in {count} attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:"))
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!")
elif (gameCode == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")

How to add a second player to this number guessing game for python?

Hi i am unsure on how to add a second player for this number guessing game whereby after player 1 makes a guess, then player 2 makes a guess. like between every guess. I am only able to make it so that the player 2 guesses after player 1 guesses finish all of his choices(code below) if anyone is able to tell me if what i am looking for is possible or if there is any advice, it would be greatly appreciated. thanks in advance.
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: "))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances")
break
if guess < n:
print("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances")
break
if guess1 < n1:
print("guess is low")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no')")
if retry == "yes":
main()
else:
print("Okay. have a nice day! :D ")
main()
to achieve this I would use a while loop and a variable to detect which players turn it is. Like this:
import random
random_number = random.randint(1, 99)
player_chances = 5
current_player = 1
while player_chances > 0:
if current_player == 1:
guess = int(input("Player 1 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 2
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
else:
guess = int(input("Player 2 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 1
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
print("####")
print("Out of chances! The number was {}.".format(random_number))
print("####")
To make this possible in an efficient way I would have created a player class as such:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTrys = 0
self.guess = 0
def getNumberOfTrys(self):
return self.getNumberOfTrys
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTrys+=1
return self.guess
except Exception as error:
print(error)
return None
this class is responsible to create the player with the number of tries,his guess and his name.
the logic will be going through the list of players (you can add as much as you want) and perform the game logic as follows:
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1)
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1)
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear()
break
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Basically, create a list of players then go through each one and apply the game logic (getting input, comparing and checking number of tries)
after a player loses, we should remove him from the list and if a player wins we can clear the list and thus exiting the game.
Here is the full code:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTries = 0
self.guess = 0
def getNumberOfTries(self):
return self.getNumberOfTries
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTries+=1
return self.guess
except Exception as error:
print(error)
return None
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1) #addding player
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1) #for debug
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear() # exit game
break #exit loop
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Hope I got your question right, and excuse me If there is any errors or typos, I just created something fast that you can be inspired by. I highly suggest you get into OOP, it very simple and it can make your life much easier :)
All the best!

higher or lower game unexpected EOF while parsing

need help with a higher or lower game I think the problem has something to do with the loop. I have been told been told to add an except but I have no idea where to add it
print('Welcome to higher or lower game')
input('press enter to start.\n')
import random
Max = 10
Min = 0
num = random.randint(1, 10)
print('your starting number is a ' + str(num))
while 'well done.\n' :
guess = input('higher (h) or lower (l).\n')
new_num = random.randint(1, 10)
print('your new number is a ' + str (new_num))
try :
if new_num > num and guess == 'h':
print('well done.\n')
elif new_num < num and guess == 'l':
print('well done.\n')
break
if num and guess == 'l' and new_num > num and guess:
print('game over')
elif num and guess == 'h' and new_num < num and guess:
print('game over')
else:
print('game over you got a score of ' + str(score))
You do not have an except clause in the try statement. That clause is required unless you have a finally clause.
You really shouldn't have a try statement there. You could take it out and just go with some if and elif statements.
Example:
import random
number = random.randint(1,10)
lives = 3
Success = False
while lives > 0:
guess = int(input("What is your guess between 1 and 10? \r\n"))
if guess > number:
print("Too high! Go lower. \r\n")
lives -= 1
elif guess < number:
print("Too low! Go higher. \r\n")
lives -= 1
elif guess == number:
print("Congratulations, you win!")
global Success = True
break
if Success != True:
print("Sorry. Try again! The number was ", number, ".")
As far as I understand, try statements are mainly used for error handling.

Categories

Resources