exception handling mistake - python

So I have a condition for accepting only a negative value for a variable and it should also not raise a value error.
My code goes like this ->
try:
x = int(input("Enter -ve value : "))
while x >= 0:
print("Error wrong value!")
x = int(input("Enter -ve value : " )
except ValueError:
print("Error wrong value!")
x = int(input("Enter -ve value : "))
while x >= 0:
print("Error wrong value!")
x=int(input("Enter -ve value : " )
The only problem with this approach is that, suppose I press enter without entering a value for the first time. It takes me to the "except" condition and it works fine but if I enter a blank value again my code stops because of value error. How do I stop this from happening? Is there a more efficient way of writing this code without importing any modules?
Thank you for your time and efforts! I wrote this question on the mobile app so sorry if it causes any inconvenience!

You could try it like this:
x = 0
while x >= 0:
try:
x = int(input("Enter -ve value : "))
except ValueError:
print("Error wrong value!")
x = 0
This will achieve what you are asking for in that it will keep prompting you to enter a number while x >= 0 and will also ensure the exception handling is always carried out on each input too.

Related

How to exit loop when input is nothing

I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.

Using a While loop in python when asking for something specific

Question is to
Prompt the user for a number from 1 to 100. Using a while loop, if they entered an invalid number, tell them the number entered is invalid and then prompt them again for a number from 1 to 100. If they enter a valid number - thank them for their input.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
int(input("please enter a number 1-100, inclusive: ")
else:
print("thank you for your input")
my code is incorrect. Help me fix it please?
Aren't you missing a parenthesis in the statement before else: ? Looks like it says else: is invalid due to that.
Besides the syntax error (missing ) before the line of else, your code also have logical error, you need to set the y = False when user give proper input to get out from the while loop, like :
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
value = int(input("please enter a number 1-100, inclusive: "))
if value >= 0 and value <= 100:
y = False
else:
print("thank you for your input")
Simplification and correction of your code
while True:
x = int(input("please enter a number 1-100, inclusive: "))
if 1 <= x <= 100: # range check
print("thank you for your input")
break # terminates while loop
else:
print("invalid.") # print then continue in while loop
#Krish says a really good answer about how you are missing a second bracket during the line that you prompt inside the while loop. I assume you receive a SyntaxError about it (probably listing the immediately following line--unfortunately common in software).
Solution
However, you have a much more fundamental issue with your code: you never update y so you have an infinite loop that will always think that the input is invalid.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y: # it is unnecessary to check a boolean against a condition
print("invalid.")
x = int(input("please enter a number 1-100, inclusive: ")) # missing bracket
y = x<0 or x>100 # necessary to end the loop
else:
print("thank you for your input")
Improvement
Another option is to use break to exit the loop on the spot. It can make for cleaner code with less duplication because now everything is inside the loop.
while True: # infinite loop...but not because of break
x = int(input("please enter a number 1-100, inclusive: "))
if x<0 or x>100:
print("invalid.")
else:
print("thank you for your input")
break
Advanced
For completeness I will also include a couple more advanced features. You can skip this part since you are starting out, but it may be interesting to come back to once you have become more familiar with the language.
Lambda
Helps make the code cleaner.
user_input = lambda: int(input("please enter a number 1-100, inclusive: "))
condition = lambda x: x<0 or x>100
while condition(user_input()):
print("invalid.")
else:
print("thank you for your input")
Cmd
This one is really advanced and overkill for what you are trying to accomplish. Still, it is good to know about for a later, more advanced problem that it would be appropriate for. Docs found here.
from cmd import Cmd
class ValidNumberPrompter(Cmd):
"""
This is a class for a CLI to prompt users for a valid number.
"""
prompt = "please enter a number 1-100, inclusive: "
def parseline(self, line): # normally would override precmd but this is modifying the way the line is parsed for commands later
command, args, line = super().parseline(line) # superclass behaviour
return (command, args, int(line))
def default(self, line): # don't care about commands
if line<0 or line>100:
print("invalid.")
return False
else:
print("thank you for your input")
return True
"""
Only start if module is being run at the cmdline.
If it is being imported, let the caller decide
what to do and when to run it.
"""
if __name__ = '__main__':
ValidNumberPrompter().cmdloop()

Validating int numbers in a certain range. Python-3.x [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am making this game where the user has to choose from 5 options. So, he must type any number from 1 to 5 to choose an option. Now here is the problem I am facing, I just can't figure out a way in which the user cannot type in any other character except the int numbers from 1 to 5, and if he does type in a wrong character, how should I show his error and make him type in the input again? Here is what I've tried:
def validateOpt(v):
try:
x = int(v)
if int(v)<=0:
x=validateOpt(input("Please enter a valid number: "))
elif int(v)>5:
x=validateOpt(input("Please enter a valid number: "))
return x
except:
x=validateOpt(input("Please enter a valid number: "))
return x
Here validateOpt is to validate the number for the option, i.e., 1,2,3,4,5. It works fine, but whenever I type 33,22, 55, or any other int number from 1 to 5 twice (not thrice or even four times, but only twice), it doesn't show any error and moves on, and that, I suppose, is wrong. I am just a beginner.
You can do this with a while loop, something like this should be a good start:
def getValidInt(prompt, mini, maxi):
# Go forever if necessary, return will stop
while True:
# Output the prompt without newline.
print(prompt, end="")
# Get line input, try convert to int, make None if invalid.
try:
intVal = int(input())
except ValueError:
intVal = None
# If valid and within range, return it.
if intVal is not None and intVal >= mini and intVal <= maxi:
return intVal
Then call it with something like:
numOneToFive = getValidInt("Enter a number, 1 to 5 inclusive: ", 1, 5)
use a while loop instead of recursion, you can check the user data and return if its valid, although you might want to consider a break out clause should the user want to exit or quit without a valid input.
def get_input(minimum, maximum):
while True:
try:
x = int(input(f"please enter a valid number from {minimum} to {maximum}: "))
if minimum <= x <= maximum:
return x
except ValueError as ve:
print("Thats not a valid input")
value = get_input(1, 5)
Use for loop in the range between 1 and 5
Try this code, it will keep prompting user till he enters 5, note that this may cause stackoverflow if recursion is too deep:
def f():
x = input("Enter an integer between 1 and 5:")
try:
x = int(x)
if x<=0 or x>5:
f()
except:
f()
f()

Python3: creating error for input of negative

Taking an intro course and need to create an over/under guessing game. I want to fine-tune my user inputs by creating an error if someone inputs a negative or non-integer. I have the non-integer error reporting correctly, and the negative loops back correctly, but the negative will not print my error message.
#Number of plays
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
except ValueError:
print ("Integer numbers only please.")
except:
if x <=0:
print ("Positive numbers only please.")
i = get_plays("\nHow many times would you like to play?")
print ("The game will play " +str(i)+" times.")
Separately, if I wanted to use a similar setup to produce an error for any negative non-integer number between 1 and 20, how would this look?
Try:
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
if x <=0:
print("Positive numbers only please.")
continue
if x not in range(20):
print("Enter a number between 1 - 20.")
continue
return x
except ValueError:
print("Integer numbers only please.")
It will accept only positive numbers between 1 to 20
The problem is this section
except:
if x <=0:
Empty except clauses trigger on any error that hasn't been caught yet, but negative numbers don't trigger an exception. You want something like this instead. Notice that in the try clause we can just proceed as if x is an int already, because we can assume that no ValueError was thrown.
def get_plays(msg):
while True:
try:
x = (int(input(msg)))
if x <=0:
print ("Positive numbers only please.")
else:
return x
except ValueError:
print ("Integer numbers only please.")

Python user must only enter float numbers

I am trying to find out how to make it so the user [only enters numbers <0] and [no letters] allowed. Can someone show me how I would set this up. I have tried to set up try/catch blocks but I keep getting errors.
edgeone = input("Enter the first edge of the triangle: ")
I think you want numbers only > 0, or do you want less than zero? Anyway to do this you can using try/except, inside a while loop.
For Python 3, which I think you are using?
goodnumber = False
while not goodnumber:
try:
edgeone = int(input('Enter the first edge of the triangle:'))
if edgeone > 0:
print('thats a good number, thanks')
goodnumber = True
else:
print('thats not a number greater than 0, try again please')
except ValueError:
print('Thats not a number, try again please')
hope this helps.
you must use except handler for this case :
try:
value = int(raw_input("Enter your number:"))
if not ( value < 0 ):
raise ValueError()
except ValueError:
print "you must enter a number <0 "
else:
print value #or something else
Also This question already has an answer here: Accepting only numbers as input in Python
You can do like this.
i = 1
while(type(i)!=float):
i=input("enter no.")
try:
int(i):
except:
try:
i = float(i)
except:
pass
print(i)

Categories

Resources