Exception handling on Python [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm new here, and I'm also new in coding.
I'm actually learning Python, and I have a question, because I already tried everything, but I was unable to resolve it.
I have this code from a little game I saw in a tutorial. The objective is to the user guess the number. What I was trying to do is to handle the exception if the user enters a letter, then show an error message and go back to the loop. If someone helps me, I will be grateful.
import random
highest = 200
answer = random.randrange(highest)
guess = raw_input("Guess a number from 0 to %d:" %highest)
while(int(guess)!=answer):
if (int(guess) < answer):
print "Answer if higher"
else:
print "Answer is lower"
guess=raw_input("Guess a number from 0 to %d: " %highest)
raw_input ("You're a winner Face!!!")

This is how i would do it:
import random
highest = 200
answer = random.randrange(highest)
while True:
try:
guess = int(input("Guess a number from 0 to %d: " %highest))
if guess < answer:
print("Answer if higher")
elif guess > answer:
print("Answer is lower")
else:
print("You're a winner Face!!!")
break
except:
print('Input not valid!')
continue
I have a dummy condition on the while and i am directing the flow from inside the loop using continue and break. I wrapped the whole guess checking procedure in a try-except block but the only thing that is really tried is the conversion of the input to integer. Everything else could also be moved after the except bit.

Related

How do I stop the user from inputing an invalid literal and throwing an error? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am making a fizzbuzz game [see code below] I wanted to add a condition to the if statement that would loop the user back to the beginning of the function if they enter anything other than a number but it did not work it gave me a error anyway is there a way I can go about doing that?
def fizzbuzz():
print(f"\nEnter a number {name}.\n")
number = int(input('> '))
if number % 3 == 0:
print("We got a FIZZ! And I ain't talking about the kid from B2k! You a bad MF!")
elif number % 5 == 0:
print("Buzz lightyear to star command. We are in the mist of a BAMF!")
elif number % 3 == 0 and number % 5 == 0:
print("FIZZBUZZ!" * 10, " FIZ [*head explodes*] [kid picks up the mic] How's that for Television")
elif number / number != 1 or number == 0:
print("Someones a little slow. Try again sweetheart.")
fizzbuzz()
else:
print("Do you kiss your mother with that none Fizzed or buzzed mouth? Shame! Sercurity!")
print("Join us next time for the show where you better bring your fizzbuzz buzz fizz!......Or else.\n\n")
Try using try and except to handle the errors.

If/else statement in Python 3x [duplicate]

This question already has answers here:
Python - User input data type
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am very new to programming and Python. To get started I'm working on a little game that will ask the user for some input and then do "something" with it. My problem is I've seem to account for if the user types in an int lower or high than my parameters BUT i can't seem to find a way to re-prompt the user if they type in anything but an int.
With my limited knowledge I thought that when using an if/elif/else statement if you didn't define what the if/elif is looking for than the else statement was there for everything else that you didn't account for?
Looking for some more insight on how to master this fundamental concept
Thank you in advance!
prompt = True
while prompt == True:
user_input = input("Please give me a number that is greater than 0 but less than 10 \n >")
if user_input > 0 and user_input <= 10:
print("Good job " + str(user_input) + " is a great number")
break
elif (user_input > 10):
print("Hey dummy " + str(user_input) + " is greater than 10")
elif (user_input <= 0):
print("Hey dummy " + str(user_input) + " is less than 0")
else:
print("I have no idea what you typed, try again!")
How about something like this?
a = -1
while a < 0 or a > 10:
try:
a = int(input("Enter a number between 0 and 10: "))
except ValueError:
continue
This will only allow the user to enter an int from 0 to 10, this will also remove the need to print those messages if the number is outside of this range, if you would like to keep those messages I could make adjustments and show you how to handle that as well

IF statement will only consider ELIF? [duplicate]

This question already has answers here:
Numeric comparison with user input always produces "not equal" result
(4 answers)
Closed 4 years ago.
whats up? I'm playing around with my mastermind project for school, only recently started dabbling into Python - and I've ran into a problem I simply cannot figure out? I've looked at other people's questions, who seem to have the same problem as me, but it seems to be more selective, and my code is kind of different. Can anyone tell me why whenever I reply to the question, it immediately skips to "Try again!", even if I know for a fact rnumber == tnumber? (Using Python 3.4.2).
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = input("Guess the four digit number. ")
type(tnumber)
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
elif rnumber != tnumber:
print ("Try again!")
numot = numot+1
you need to make your input an int so it considers it a number, try this
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = int(input("Guess the four digit number. "))
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
else rnumber != tnumber:
print ("Try again!")
numot = numot+1

Python: How to fix my code that will allow to repeat the input task whenever I enter anything except integer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Another newbie question:
I'm trying to add a statement inside a while loop that if the person enters anything except integer it will repeat the input but I didn't figure out how to do that without ruining the program. Whenever I enter anything i get the following error: "ValueError: invalid literal for int() with base 10" What is needed to be added to my code?
Here is my code:
import random
#Playing dice game against the computer
num = int(input("Enter a number between 1 and 6 please: "))
while not int(num) in range(1, 7):
num = int(input("Please choose a number between 1 and 6: "))
def roll_dice(num):
computer_dice = random.randint(1, 6)
if num > computer_dice:
print("Congratulations you win! Your opponent's dice is:", computer_dice)
elif num < computer_dice:
print("Sorry but you lose! Your opponent's dice is:", computer_dice)
else:
print("Draw. Your opponent's dice is:", computer_dice)
roll_dice(num)
Thank you in advance!
I think the problem is that you are trying an empty string to an integer. Same problem when you type in alphabetical characters.
You can use try and except to try the conversion of the input to an integer and then when it failed you run the loop again and when the conversion was successfully you have your number.

How to repeat an input until given suitable answer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
I have finished a code, so that it asks the user to answer an arithmetic question and tell them if their answer is correct or not and so on.... I started doing some tests and realised if user enters anything then a number is gives me an error.
My Code:
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer:
print('Correct!')
score += 1
else:
print('Incorrect!')
print(name,"You got",score,"out of 10")
if score>1 and score<=3 :
print('Practice More!')
elif score>4 and score<=7 :
print('You did well!')
elif score>7 and score<=9 :
print('Excellent!')
elif score==10 :
print('You are a Genius!')
else:
print('Have you tried your best?')
I want to know how do I repeat line 9 until the user enters a number?
THIS IS NOT A DUPLICATE BECUASE I WANT THE USER TO SPECIFICALLY ENTER A NUMBER. IF HE/SHE DID IT WILL TELL THEM IT IS WRONG OR RIGHT AND MOVE ON TO THE NEXT QUESTION.
I would recommend putting the for loop in a while loop until true then exit the loop. Did that answer your question?

Categories

Resources