How to iterate in a for loop with error handling - python

I am trying to catch input errors from the user. The input should be a float. I cannot figure out the logic.
I want the user to redirected to the same key value in material_vars if they enter an invalid input. Currently I can make it work so if an incorrectly it goes back to the first key input rather than the key the invalid entry occurred on.
def material_costs(update=False):
global material_vars
while update:
try:
for key in material_vars:
material_vars[key] = float(input(f"Enter {key}:\n"))
except ValueError:
print ('Please enter a valid input')
else:
save_defaults('material_vars', material_vars)
update = False
else:
material_vars = open_defaults('material_vars')
return material_vars

You can modify your function like this
def material_costs(update=False):
global material_vars
while update:
for key in material_vars:
correct = False
while (not correct):
try:
material_vars[key] = float(input(f"Enter {key}:\n"))
correct = True
except ValueError:
print ('Please enter a valid input')
correct = False
save_defaults('material_vars', material_vars)
update = False
else:
material_vars = open_defaults('material_vars')
return material_vars
Run a while loop for each input until the user enters the correct input.
The input will be verified by the try-except blocks inside the while.
I hope this helps.

Related

How can we check input entry is empty or not which is converted into float while getting the input from the user?

Getting input from the user and convert it into the float, while getting the entry from the user and then I want to check if user press enter without giving any input or value then it will bring the user to again enter the marks.
while(True):
assign1=float(input("Please enter the marks: "))
if(assign1>100 or assign1<0):
continue
else:
marks=(assign1*20)/100
break
Use try/except to handle the exception. Please find below code. Hope it helps.
while(True):
try:
assign1=float(input("Please enter the marks: "))
except Exception as e:
print (e) ## do you stuff with error
else:
if(assign1>100 or assign1<0):
continue
else:
marks=(assign1*20)/100
break
i'd go with a try/except clause:
while(True):
try:
assign1=float(input("Please enter the marks: "))
except:
continue
if(assign1>100 or assign1<0):
continue
else:
marks=(assign1*20)/100
break
In this way, anything that raise an error when converted to float (including '', or Enter without giving any input) will result in he repetition of the question.

Python 3 except TypeError not working

Please kindly note I am new to this. Your help will be appreciated.
while True:
user = str(input('Enter users sex:'))
try:
if user == 'female' or user == 'male': break
except TypeError:
print('Please enter male or female')
continue
print('The user is:',user)
I do not understand when an integer is entered the
except TypeError:
print('Please enter male or female')
does not print('Please enter male or female') and ask the user for input.
You actually don't need an exception check here. Also, your conditional statement will not raise that TypeError. Instead, simply use your conditional statement to continue your loop. This will also not require you to have to use any continue statement here either.
Furthermore, all input calls will return a string, so you do not need to cast as such. So, simply take your input without the str call:
while True:
user = input('Enter users sex:')
if user == 'female' or user == 'male':
break
else:
print('Please enter male or female')
print('The user is:', user)
If you were putting this in to a function, you can simply return your final result once satisfied and then print the "result" of what that function returns. The following example will help illustrate this:
def get_user_gender():
while True:
user = str(input('Enter users sex:'))
if user == 'female' or user == 'male':
break
else:
print('Please enter male or female')
return 'The user is: {}'.format(user)
user_gender = get_user_gender()
print(user_gender)
Small note, you will notice I introduced the format string method. It makes manipulating strings a bit easier getting in to the habit with dealing with your string manipulation/formatting in this way.
input() returns a string in Python 3. Calling str on it leaves it as it is, so it will never raise an exception.
You could get an error if you tried to do something like:
number = int(input("enter a number: "))
enter a number: abc
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-ec0ea39b1c6c> in <module>()
----> 1 number = int(input("enter a number: "))
ValueError: invalid literal for int() with base 10: 'abc'
because the string 'abc' can't be converted to an integer (in base 10, at least...)

Try-Except ErrorCatching

I'm trying to force the user to input a number using try-except in python however it seems to have no effect.
while count>0:
count=count - 1
while (length != 8):
GTIN=input("Please enter a product code ")
length= len(str(GTIN))
if length!= 8:
print("That is not an eight digit number")
count=count + 1
while valid == False:
try:
GTIN/5
valid = True
except ValueError:
print("That is an invalid number")
count=count + 1
Actually, if the user inputs for example a string, "hello"/5 yields a TypeError, not a ValueError, so catch that instead
You could try to make the input value an int int(value), which raises ValueError if it cannot be converted.
Here's a function that should do what you want with some comments:
def get_product_code():
value = ""
while True: # this will be escaped by the return
# get input from user and strip any extra whitespace: " input "
value = raw_input("Please enter a product code ").strip()
#if not value: # escape from input if nothing is entered
# return None
try:
int(value) # test if value is a number
except ValueError: # raised if cannot convert to an int
print("Input value is not a number")
value = ""
else: # an Exception was not raised
if len(value) == 8: # looks like a valid product code!
return value
else:
print("Input is not an eight digit number")
Once defined, call the function to get input from the user
product_code = get_product_code()
You should also be sure to except and handle KeyboardInterrupt anytime you're expecting user input, because they may put in ^C or something else to crash your program.
product code = None # prevent reference before assignment bugs
try:
product_code = get_product_code() # get code from the user
except KeyboardInterrupt: # catch user attempts to quit
print("^C\nInterrupted by user")
if product_code:
pass # do whatever you want with your product code
else:
print("no product code available!")
# perhaps exit here

Python 3.x input variable

I want to get user input of a code that has to be 11 numbers long and must not contain any characters. Otherwise the question to enter will be repeated.
code=input("Please enter your code ")
while len((code)) !=11: #here should be something to nullify strings inout :)
code = input("Please enter your code and in numbers only ")
There is definitely a better solution for this, just can't think of any.
This might be what you're after
def validate(s):
for char in s: #iterate through string
if not char.isdigit(): # checks if character is not a number
return False # if it's not a number then return False
return True # if the string passes with no issues return True
def enter_code():
while True: #Will keep running until break is reached
code = input("Please enter your code: ") #get user input
# if the length of input and it passes the validate then print 'Your code is valid'
if len(code) == 11 and validate(code):
print('Your code is valid')
break #break out of loop if valid
# if code fails test then print 'Your code is invalid' and return to start of while loop
print('Your code is invalid')
if __name__ == '__main__':
enter_code()

ERROR-HANDLING not working

My error-handling code is not working. I'm trying to do following: if user enters any input other than 1, 2 or 3, then the user should get error message and the while-loop should start again.
However my code is not working. Any suggestion why?
def main():
print("")
while True:
try:
number=int(input())
if number==1:
print("hei")
if number==2:
print("bye")
if number==3:
print("hei bye")
else:
raise ValueError
except ValueError:
print("Please press 1 for hei, 2 for bye and 3 for hei bye")
main()
You can also use exception handling a bit more nicely here to handle this case, eg:
def main():
# use a dict, so we can lookup the int->message to print
outputs = {1: 'hei', 2: 'bye', 3: 'hei bye'}
print() # print a blank line for some reason
while True:
try:
number = int(input()) # take input and attempt conversion to int
print(outputs[number]) # attempt to take that int and print the related message
except ValueError: # handle where we couldn't make an int
print('You did not enter an integer')
except KeyError: # we got an int, but couldn't find a message
print('You entered an integer, but not, 1, 2 or 3')
else: # no exceptions occurred, so all's okay, we can break the `while` now
break
main()

Categories

Resources