try:
num=float(num)
except:
print "Invalid input"
continue
this part of my code seems to be bugging, but when i remove the try and except everything works smoothly, so this seems to be the problem.
i want to convert the input inside a while loop to an integer, if the input isn't an integer it'll display an error and just continue with the loop and ask again. however, it doesn't continue the loop and just keeps printing "Invalid input" forever. how come it isn't continuing the loop?
here is the entire code, in case something else might be wrong:
c=0
num2=0
num=raw_input("Enter a number.")
while num!=str("done"):
try:
num=float(num)
except:
print "Invalid input"
continue
c=c+1
num2=num+num2
num=raw_input("Enter a number.")
avg=num2/c
print num2, "\t", c, "\t", avg
You can solve the problem by moving the variable assignments into the try block. That way, the stuff you want to skip is automatically avoided when an exception is raised. Now there is no reason to continue and the next prompt will be displayed.
c=0
num2=0
num=raw_input("Enter a number.")
while num!=str("done"):
try:
num=float(num)
c=c+1
num2=num+num2
except:
print "Invalid input"
num=raw_input("Enter a number.")
avg=num2/c
print num2, "\t", c, "\t", avg
You can tighten this a bit further by removing the need to duplicate the prompt
c=0
num2=0
while True:
num=raw_input("Enter a number. ")
if num == "done":
break
try:
num2+=float(num)
c=c+1
except:
print "Invalid input"
avg=num2/c
print num2, "\t", c, "\t", avg
continue means return back to while, and as num never changes, you will be stuck in an infinite loop.
If you want to escape the loop when that exception occurs then use the term break instead.
# this function will not stop untill no exception trown in the try block , it will stop when no exception thrown and return the value
def get() :
i = 0
while (i == 0 ) :
try:
print("enter a digit str : ")
a = raw_input()
d = int(a)
except:
print 'Some error.... :( '
else:
print 'Everything OK'
i = 1
return d
print(get())
Related
I'm creating a simple login program. It asks you for a username, then the password. If you type the correct password, you're in, else, you get a genial request to repeat your password. here is the code:
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
break
else:
print ("Incorrect. You have",turns," more turns")
now the thing is, it gives me an error message: incorrect syntax for else: print ("incorrect... I know this is meant an issue because I wrote two 'breaks', the latter out of the for loop... which means it will break the while True loop at the start whether or not I go into the loop... which means the 'else' statement is out of the loop (sorry, I am not the best explainer at these things)... which gives the error message. But I don't understand how I should fix this problem... can anyone help?
I hope you understood me!
This could be triviallized by using a function and returning from it once you reach that if statement.
def func():
while True:
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
return
else:
print ("Incorrect. You have",turns," more turns")
However, if you insist on not having a function, you can basically have a flag in your code that you set to true inside that if block. Before continuing the outer loop, you should check if this flag is set to True, if it is, you can safely break.
while True:
success = False
turns= 5
turns= turns-1
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
success = True
break
else:
print ("Incorrect. You have",turns," more turns")
if success:
break
Note should be taken for nested loops and such intense nesting for what is essentially a trivial problem. Please try to use a singular loop with your conditions.
You need to swap the else and break and change the break's indentation. If the user gets the correct username you want to test the password at most 5 times and then quit
while True:
turns= 5
print ("Username")
L_username= input ("")
print ("Authorising...")
time.sleep(2)
if(L_username)==("test#test.test"):
for x in range (5):
print ("Please enter the password")
passwordlogin= input("")
if passwordlogin == ("beta123"):
print ("Hello, developer.")
break
else:
turns -= 1
print ("Incorrect. You have",turns," more turns")
break
So in this case you run the for loop and then break
Well I have written your concept in my own way. Hope this works for you
turns = 5
while turns != 0:
username = input('Enter Username: ')
password = input(f'Enter password for {username}: ')
if username == 'test#test.test' and password == 'beta123':
print('Hello developer')
turns = 0 # Breaking while loop if user get access within number of "turns"
else:
turns = turns - 1 # Or turns -= 1
print('Incorrect username or password')
print(f'You have {turns} turns for gaining access')
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.
I am trying to get the type of data user inputs, but I am getting some issues with code. I tried with the below code:
def user_input_type():
try:
user_input = int(raw_input("Enter set of characters or digit"))
except:
try:
user_input = str(user_input)
except Exception as e:
print e
return type(user_input)
return type(user_input)
print user_input_type()
but it gives me 2 warnings before running the code.
Local variable user_input might be referenced before assignment.
Too broad exception clause such as no exception class specified, or specified as Exception.
After running the code when I enter digits it gives me proper value but when I enter character it gives me an error:
UnboundLocalError: local variable 'user_input' referenced before assignment
Please help.
You need to set the 'user_input' outside of the try-catch.
Ex:
def user_input_type():
user_input = raw_input("Enter set of characters or digit") #---->Outside try-except
try:
user_input = int(user_input)
except:
try:
user_input = str(user_input)
except Exception as e:
print e
return type(user_input)
print user_input_type()
I'm trying to make a simple program that will calculate the area of a circle when I input the radius. When I input a number it works, but when I input something else I'd like it to say "That's not a number" and let me try again instead of giving me an error.
I can't figure out why this is not working.
from math import pi
def get_area(r):
area = pi * (r**2)
print "A= %d" % area
def is_number(number):
try:
float(number)
return True
except ValueError:
return False
loop = True
while loop == True:
radius = input("Enter circle radius:")
if is_number(radius) == True:
get_area(radius)
loop = False
else:
print "That's not a number!"
When you don't input a number, the error is thrown by input itself which is not in the scope of your try/except. You can simply discard the is_number function altogether which is quite redundant and put the print statement in the except block:
try:
radius = input("Enter circle radius:")
except (ValueError, NameError):
print "That's not a number!"
get_area(radius)
radius is still a string,
replace
get_area(radius)
with
get_area(float(radius))
You also have to replace input with raw_input since you're using Python 2
in= 0
while True:
try:
in= int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
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()