Python Error handling for an input requiring a integer - python-3.x

I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()

To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review

Related

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

How do I add a score to this game

I've been trying to figure out how to add a score to this for ages. I'm still not sure ;( sorry I'm new to coding.
this is the code for the main part
while roundsPlayed > 0:
chips_left = MAX_CHIPS
n = 1
rounds = 1
while chips_left > 0:
while True:
print("Number of chips left {}".format(chips_left))
if n%2 == 0:
print("{} How many chips would you like to take (1 - 3): ".format(playerTwo))
else:
print("{} How many chips would you like to take (1 - 3): ".format(playerOne))
try:
chipsTaken = int(input())
if chipsTaken < 1 or chipsTaken > 3:
print("Please enter a valid number from 1 to 3!")
else:
break
except:
print("Thats not even a number brotherman")
n += 1
chips_left = chips_left - chipsTaken
roundsPlayed = roundsPlayed - 1
rounds += 1

dice_values within a function aren't returning, could someone please explain my error

I'm doing an assignment that requires me to simulate a dice roll game.
My problem is that when I roll the dice whithin my function and then later call it,
when I display try to display the die1, die2, die3 value from another function the values ar empty, unless I use global values, but I want to understand how the functions work and what i'm doing wrong rather than work around with global. :)
#importing the random library to make the random.randint function available
import random
#Making declrations for variable values
total_games = (0)
chip_balance = 100
total_chips = ()
games_won = 0
games_lost = 0
even_stevens = 0
games_draw = 0
play_game = 0
die1 = ()
die2 = ()
die3 = ()
#defining the dice roll function and logic
def die_roll(die1, die2, die3):
#Global Statements to make the die values available to the pre_display_dice function and the display_dice function.
die1 = random.randint (1, 12)
die2 = random.randint (1, 12)
die3 = random.randint (1, 12)
return die1, die2, die3
#defining the authorship details in this function
def display_details():
print('File : tobxz001_inbetween.py')
#defining the get_play_game_function to set the loop
def get_play_game():
global play_game
play_game = input('Would you like to play in-between [y|n]?')
while play_game != 'y' and play_game != 'n':
play_game = input("please enter either 'y' or 'n': ")
play_game = play_game.lower()
return play_game
#defining the Play_again function
def play_again():
global play_game
play_game = input('Would you like to play again squire?')
while play_game != 'y' and play_game != 'n':
play_game = input("please enter either 'y' or 'n' :")
play_game = play_game.lower()
#Defining the dice display here. Only two values are displayed before the bet is made
def pre_display_dice():
print('Dice rolled:')
print('+-------------------------------------+')
print('| Die 1 | | Die 2 |')
print('| ',die1,' | 0 | ',die2, ' |')
print('+-------------------------------------+')
#Defining the final dice roll display with all values of the roll displayed after the bet is made
def display_dice():
print('Dice rolled:')
print('+-------------------------------------+')
print('| Die 1 | | Die 2 |')
print('| ',die1,' | ',die3, ' | ',die2, ' |')
print('+-------------------------------------+')
#Defining the game summary here. Wins, Loses, and draws are called from this function at the end of the game
def game_summary():
print('\n')
print('Game Summary')
print('============')
print('\n')
print('You played',total_games,'Games:')
print('|--> Games Won:', games_won)
print('|--> Games Lost', games_lost)
print('|--> Even-Stevens:', even_stevens)
display_details()
get_play_game()
while play_game == 'y':
die_roll(die1, die2, die3)
temp = int()
winner = ()
loser = (0)
bet_result = ()
#Code for swapping the dice around to always display the lower value on the left
if (die1 >= die2):
temp = die1
die1 = die2
die2 = temp
else:
die1 = die1
die2 = die2
if die1 == die2:
total_games = total_games + 1
print('\n')
print('You hit the post')
print("Even-Stevens! Let\'s play again!")
print('\n')
get_play_game
pre_display_dice()
print('\n')
print("Number of Chips : ", chip_balance)
bet = input("Place your bet: ")
while bet == '':
bet = input("Can't be an empty bet please try again ")
while bet.isalpha():
bet = input("Must be a numerical value entered \n \n Place You're bet:")
bet = int(bet)
while bet > chip_balance:
print('Sorry, you may only bet what you have ')
bet = input("Place your bet: ")
while bet == '':
bet = input("Can't be an empty bet please try again ")
while bet.isalpha() or bet == '':
bet = input("Must be a numerical value entered \n \n Place You're bet:")
bet = int(bet)
chip_balance = chip_balance - bet
if die1 < die3 & die3 < die2:
winner = (bet * 2) + chip_balance
chip_balance = winner
else:
chip_balance
#Code to compare if the results are even or not STAGE 3, if they aren't Die3 will be rolled
if die1 == die2:
print('\n')
display_dice()
print('You hit the post')
print("Even-Stevens! Let\'s play again!")
print('\n')
even_stevens = even_stevens + 1
total_games = total_games + 1
else:
print('\n')
display_dice()
print('\n')
#Winning and Losing logic
#Winning conditions
if die1 < die3 & die3 < die2:
print("***You Win!***")
print("You now have", chip_balance, "Chips")
print('\n')
games_won = games_won + 1
total_games = total_games + 1
#Evaluate to see if any of the dice' match is done here
elif die1 == die3 or die3 == die2:
print('\n')
print("***You hit the post - You Lose! ***")
print("You now have", chip_balance, "chips left")
print('\n')
games_lost = games_lost + 1
total_games = total_games + 1
#Losing Logic
else:
print("*** Sorry - You Lose! ***")
print('\n')
print("You now have", chip_balance, "chips left!")
games_lost = games_lost + 1
total_games = total_games + 1
#Chip balance check, if it's zero, game is over, otherwise keep playing
if chip_balance == 0:
print('\n')
print('You\'re all out of chips! \n ***GAME OVER***')
play_game = 'n'
else:
play_again()
if play_game == 'n':
game_summary()
if play_game == 'n':
print('\n')
print('No worries... another time perhaps...:)')

Need some insight on following python 3 code

I was trying to build this basic code for fun but I ran into some weird error. The following code asks for an answer of a basic printed out equation. When the answer is 10 or greater, it is behaving weirdly. I tried to implement some error handling methods (the failure is at int(ansr_raw) I guess). I think a better method will help me out. You don't need to spell out the code for me but pointing me at the right direction will be helpful. The code and output are given below.
code -
import random
signs = ['+', '-']
verbals = ['out', 'quit', 'help', 'break']
while True:
a, b = random.randint(1, 9), random.randint(1, 9)
ch = random.choice(signs)
print("{} {} {} = ?".format(a, ch, b))
ansr_raw = input("Enter the answer: ")
if ansr_raw in '0123456789': # trying to handle error
ansr = int(ansr_raw)
else:
for i in verbals:
if ansr_raw == i:
choice = input("Wish to Quit? [y/n] ").lower()
if choice in 'yes':
print("Quit Successful.")
break
elif choice in 'no':
continue
else:
print("Wrong choice. continuing game.")
continue
print('answer format invalid')
continue
if ch == '+':
if ansr == (a + b):
print("Right Answer.")
else:
print("wrong answer.")
elif ch == '-':
if ansr in ((a - b), (b - a)):
print("Right Answer.")
else:
print("wrong answer.")
Here is the output (arrow marks added)-
9 + 3 = ?
Enter the answer: 12
answer format invalid <----
2 - 9 = ?
Enter the answer: 5
wrong answer.
1 - 3 = ?
Enter the answer: 2
Right Answer.
8 + 3 = ?
Enter the answer: 11
answer format invalid <----
1 + 2 = ?
Enter the answer: 3
Right Answer.
6 + 2 = ?
Enter the answer:
The problem is where you say
if ansr_raw in '0123456789': # trying to handle error
ansr = int(ansr_raw)
For a single digit number like 9, yes there is a 9 in that string, but there is only a few two digits(01,23,34,45,56,67,78,89), to what you're trying to do, check if the string can become an integer; do this.
try:
ansr = int(ansr_raw)
except ValueError:
Full Code:
import random
import sys
signs = ['+', '-']
verbals = ['out', 'quit', 'help', 'break']
running = True
while running:
a, b = random.randint(1, 9), random.randint(1, 9)
ch = random.choice(signs)
print("{} {} {} = ?".format(a, ch, b))
ansr_raw = input("Enter the answer: ")
try:
ansr = int(ansr_raw)
except ValueError:
answerInv = True
for i in verbals:
if ansr_raw == i:
choice = input("Wish to Quit? [y/n] ").lower()
if choice in 'yes':
print("Quit Successful.")
sys.exit(0)
elif choice in 'no':
continue
answerInv = False
else:
print("Wrong choice. continuing game.")
answerInv = False
continue
if answerInv:
print('answer format invalid')
if ch == '+':
if ansr == (a + b):
print("Right Answer.")
else:
print("wrong answer.")
elif ch == '-':
if ansr in ((a - b), (b - a)):
print("Right Answer.")
else:
print("wrong answer.")

How can I get my game to finish when the player runs out of health?

I'm currently making a simple rogue-like dungeon game for an assignment, i'm pretty new to coding so I've run into problems along the way. I want my game to end when the player's health reaches 0 so i've written this function
def main_game():
global room_count
global player_health
welcome_text()
while player_health >= 1:
room_enter(empty_room, ghost_room, monster_room, exit_room)
else:
print("Game Over :(")
print("Number of rooms entered: ", room_count)
time.sleep(7)
quit()
For whatever reason when the health reaches 0 the game continues to carry on and I can't figure out why, it's far from finished but here's the full game code below:
import time
import random
import sys
player_health = 1
room_count = 1
def scroll_text(s):
for c in s:
sys.stdout.write( "%s" % c )
sys.stdout.flush()
time.sleep(0.03)
def welcome_text():
scroll_text("\nYou wake up and find yourself in a dungeon.")
time.sleep(1.5)
scroll_text("\nYou have no idea how long you have been trapped for.")
time.sleep(1.5)
scroll_text("\nSuddenly, one day, for no apparent reason, your cell door opens.")
time.sleep(1.5)
scroll_text("\nEven though weak from having no food, you scramble out as the door closes behind you.")
time.sleep(1.5)
scroll_text("\nYou see many paths and many rooms ahead of you.")
print("\n ")
print( "-"*20)
def room_enter(empty_room, ghost_room, monster_room, exit_room):
global player_health
global room_count
security = True
while security == True:
direction = input("\nYou have the option to go Left (l), Forward (f), or Right (r), which direction would you like to go? ")
if direction == "l" or direction == "f" or direction == "r":
security == False
room_no = random.randint(1,8)
if room_no == 1 or room_no == 2 or room_no == 3:
empty_room()
room_count = room_count + 1
if room_no == 4 or room_no == 5 or room_no == 6:
ghost_room()
room_count = room_count + 1
if room_no == 7:
monster_room()
room_count = room_count + 1
if room_no == 8:
exit_room()
room_count = room_count + 1
else:
print("\nInvalid Entry")
return player_health
def empty_room():
global player_health
scroll_text("You enter a cold empty room, doesn't look like anyone has been here in years.")
player_health = player_health - 1
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
return player_health
def ghost_room():
global player_health
scroll_text("You enter a room and feel a ghostly presence around you")
time.sleep(1)
scroll_text("\nWithout warning, the ghostly mist surrounding you pools together and the shape of a human-like figure emerges.")
time.sleep(1)
scroll_text("\nI AM THE SPIRIT OF AN UNFORTUNATE EXPLORER KILLED IN THEIR PRIME, DOOMED TO SPEND AN ETERNITY TRAPPED IN THIS CHAMBER!")
time.sleep(1)
scroll_text("\nANSWER MY QUESTION MORTAL AND CONTINUE IN PEACE, GET IT WRONG HOWEVER AND YOU WILL BE BEATEN!")
time.sleep(1)
x = random.randint(1,500)
y = random.randint(1,500)
time.sleep(1)
print("\nTELL ME WHAT", x, "PLUS", y, "IS!")
okay = False
while not okay:
try:
player_answer = int(input("\nWHAT IS YOUR ANSWER?! "))
okay = True
if player_answer == x+y:
scroll_text("\nCONGRATULATIONS YOU GOT IT CORRECT! HAVE A BIT OF HEALTH!")
player_health = player_health + 2
else:
scroll_text("\nUNFORTUNATELY FOR YOU THAT ANSWER IS WRONG! PREPARE FOR THE BEATING!")
player_health = player_health - 1
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
except ValueError:
print("\nInvalid Entry")
return player_health
def monster_room():
global player_health
scroll_text("\nYou hear grunting noises as you enter the room and your worst fears are confirmed when your eyes meet the gaze of a giant monster guarding the other doors.")
time.sleep(1)
scroll_text("\nWith no way to fight the creature, you manage to slip around it however as you are making your escape the beast swipes at you and lands a blow to your back.")
player_health = player_health - 5
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
return player_health
def exit_room():
global player_health
scroll_text("\nYou stumble into the room, almost passing out from the lack of food and energy.")
time.sleep(1)
scroll_text("\nIs that...")
time.sleep(1)
scroll_text("\n... You can't believe your eyes! It's the exit from the dungeon at last!")
time.sleep(1)
print("\nWINNER WINNER CHICKEN DINNER")
print("\n ")
print("-"*21)
print("| Final Health: ", player_health, "|")
print("-"*21)
print("Number of rooms entered: ", room_count)
return player_health
def main_game():
global room_count
global player_health
welcome_text()
while player_health >= 1:
room_enter(empty_room, ghost_room, monster_room, exit_room)
else:
print("Game Over :(")
print("Number of rooms entered: ", room_count)
time.sleep(7)
quit()
main_game()
In room_enter you have a typo - security == False instead of security = False, causing an infinite loop in room_enter, so the condition in main_game is never checked.
it is very simple,
if direction == "l" or direction == "f" or direction == "r":
security == False
you basically never set security to false. It should be
if direction == "l" or direction == "f" or direction == "r":
security = False
Btw, if you declare playerHealth to be global, you don't need to return it at the end of every function you'll have the current value anyways.
Also, I think you don't need those parameters on "room_enter" since they are just functions to be executed. If you find an error saying that they are not declared, just move the declaration above the function room_enter
Let me know if something wasn't clear! Happy coding!

Resources