How should I insert try-except in this scenario - python

Task1
Write a script that reads a string from STDIN and raise ValueError
exception if the string has more than 10 characters or else prints the
read string.
I wrote the code like this
a = input("Enter a string")
if(len(a) > 10):
raise ValueError
else:
print(a)
Task2
Use try ... except clauses. Print the error message inside except
block.
I am now confused about how to use try-except here because to print any message in except block the program has to fail at try block.
My input will be PythonIsAmazing

You can just wrap the whole thing in try ... except as follows:
a = input("Enter a string: ")
try:
if(len(a) > 10):
raise ValueError
print(a)
except ValueError:
print("String was longer than 10 characters")
Alternatively, if you had lots of different ValueErrors that might be raised, you could give each a separate error message:
a = input("Enter a string: ")
try:
if(len(a) > 10):
raise ValueError("String was longer than 10 characters")
print(a)
except ValueError as e:
print(e)
Eg:
Enter a string: test
test
Enter a string: PythonIsAmazing
String was longer than 10 characters

Related

Try/except for check string in Python

I would like to use Try/ecept to check if a string is really a string. I made the following code:
nome = input('Name: ')
try:
if not nome.isalpha() or nome == '':
raise ValueError('Invalid!')
else:
print(f'Name {nome} valid.')
except ValueError as e:
print(f'Error: {e}')
But, I would like to do it without using the raise command, just try/except.
Can anyone help me? I thank you.
The only way to trigger an exception without raising it yourself is to attempt something invalid, such as this:
nome = input('Name: ')
try:
f = float(nome)
except ValueError as e:
print('Is alpha')
else:
print('Not alpha')
Here I try to convert the input to a float, and if there are any alpha characters in the value, it will raise the ValueError exception.

Exception In Python Doesn't Do Anything

I am beginner to python and I have doubt in one program when using try except part
I try to take input from user and add that number by 1 like if you enter 5 then 6 will be printed but if you enter string then except would come in role and print enter only number
I've written code but except is not working there, code is working like if I enter 5 then 6 gets printed but except statement is not working
Here is the code that I've written
def increment(num):
try:
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = int(input("enter your num: "))
a = increment(n)
print(a)
You would have to change to the following:
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The reason for that is that the exception was raised by the int() functions, because it couldn't convert your input to int. The call to int() was before the increment function. Therefore the exception was unhandled.
You tried converting the input to int before going into the try/except block. If you just put it in the try block it will work.
def increment(num):
try:
num = int(num)
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
You have to use the type conversion within the try block so that if num is not a number, the controller would move to expect portion.
The problem here is you are using type conversion outside of try-catch block.
Another point to note, convert e to string as a good practice.
Third point to note,the last line print(a) will itself cause trouble in cases of exception as you have returned nothing from the exception part and directly printed the error. Use a return statement in there else it would return None type and which itself will mess up the flow.
def increment(num):
try:
return int(num) + 1 #Updated Line
except Exception as e:
return "ufff error occurred :" + str(e) #Updated Line
n = input("enter your num: ")
a = increment(n)
print(a)
Might I recommend the following?
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occurred:", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The only difference here is that the attempt to convert the user's input to an int occurs within the try-except block, rather than outside. This allows the type conversion error to be caught and your message ("ufff error occurred: ...") to be displayed.
Edit: regarding your comment:
yes it worked out thanks everyone, but can anyone tell what should i have to do if i use int with input line what changes i've to make
Optionally, you could do the following:
def increment(num):
return num + 1
try:
n = int(input("enter your num: "))
a = increment(n)
print(a)
except Exception as e:
print("ufff error occurred:", e)
In this case, I would recommend removing the try-except block in the increment function, because you can safely assume that all values passed to that function will be numeric.
The only code that would raise an exception is the int(...) conversion - and it is not protected under a try/except block. You should put it under the try:
def increment():
try:
return int(input("enter your num: ")) + 1
except ValueError as e:
return f"ufff error occured: {e}"
print(increment())
You should always try to catch the narrowest exception. In this case, a ValueError.

How can my program know an exception from a separate method [duplicate]

This question already has answers here:
Manually raising (throwing) an exception in Python
(11 answers)
Closed 3 years ago.
I am writing a python program.
It calls a private method which has try...except... and returns a value.
Such as:
def addOne(x):
try:
a = int(x) + 1
return a
except Exception as e:
print(e)
def main():
x = input("Please enter a number: ")
try:
y = addOne(x)
except:
print("Error when add one!")
main()
The output is this when I entered an invalid input "f"
Please enter a number: f
invalid literal for int() with base 10: 'f'
I want to detect the exception in both main() and addOne(x)
So the ideal output may looks like:
Please enter a number: f
invalid literal for int() with base 10: 'f'
Error when add one!
Could anyone tell me how to do? Thanks!
Handling an exception prevents it from propagating further. To allow handling the exception also in an outer scope, use a bare raise inside the exception handler:
def addOne(x):
try:
a = int(x) + 1
return a
except Exception as e:
print(e)
raise # re-raise the current exception

I am getting an error when running this code saying str1 is not defined,when i have already defined it in try block

I am trying to write a small code block where in i take an input (user can enter any input in words or letters), my code should try to find if it is a positive or negative number or the entered value is a string.
try:
str1=int(input('Enter a number:'))
print('try block is completed')
except:
str1=str(str1)
if str1>0:
print('entered value is positive')
elif str1<0:
print('entered value is negative')
else:
print(str1)
The reason is the exception is caused in int(input(...)) so the str1 remains undeclared.
str1=input('Enter a number:')
try:
str1=int(str1)
print('try block is completed')
except:
str1=str(str1)
if str1>0:
print('entered value is positive')
elif str1<0:
print('entered value is negative')
else:
print(str1)
Modify your code like this to handle exception on integer and string
On your except branch you have the following call:
str1=str(str1)
Since you are on your except, and you haven't defined your str1 variable outside the try/except block, your statement will fail when it tries to cast the contentes of the str1 variable (which does not exist outside of the try branch).
A possible implementation to deal with this case would be to set str1 to None or an empty string on your except block. Something like this:
try:
str1 = int(input('Enter a number:'))
print('try block is completed')
except:
str1 = None
# First we check that our variable is not None (caught an exception)
try:
int_str1 = int(str1)
except:
int_str1 = None
if int_str1:
if int_str1 > 0:
print('entered value is positive')
elif int_str1 < 0:
print('entered value is negative')
else:
print('Could not get integer value of input')
It's because you use str1 in your except clause. If there is an exception during the processing of input or int, the variable str1 is never set.
If you add str1=None before your try statement, I am sure, it won't complain anymore, but you need to change your except clause then.
If you're just concerned about the cast to int, you could do:
str1= None
try:
str1=input('Enter a number:')
val=int(str1)
print('try block is completed')
except:
val=None
if val is None:
print('input is not a valid number')
elif val>0:
print('entered value is positive')
elif val<0:
print('entered value is negative')
else:
print(str1)
in the case fn an exception in the call int, the variable str1 never gets created, because int is evaluated (and raises the error) before str1 gets assigned.
also - in the case of an exception you'll get a TypeError for trying to compare a string with 0, so put all you int-assuming logic inside the try, like this:
str1=input('Enter a number:')
try:
str1=int(str1)
if str1>0:
print('entered value is positive')
elif str1<0:
print('entered value is negative')
except:
str1=str(str1)
print(str1)

Why can't I call a function here?

Hi guys I was working on a shoppinglist-creator code but at the end I faced with a surprise.
My code:
import time
import math
import random
dict_of_lists={}
def addlist():
while True:
try:
listname=str(raw_input("=>Name of the list:\n"))
dict_of_lists[listname]={}
break
except ValueError:
print "=>Please enter a valid name.\n"
print "=>You added a new list named %s.\n" % (listname)
def printlists():
for lists in dict_of_lists:
return "-"+lists
def addproduct():
while True:
try:
reachlistname=input("=>Name of the list you want to add a product,Available lists are these:\n %s \nPlease enter one:\n" % (printlists()))
break
except ValueError:
print "=>Please enter a valid list name.\n"
while True:
try:
productname=raw_input("=>Name of the product:\n")
break
except ValueError:
print "=>Please enter a valid name.\n"
while True:
try:
productprice=input("=>Price of the product:\n")
if isinstance(float(productprice),float):
break
except ValueError:
print "=>Please enter a valid number.\n"
while True:
try:
productcount=input("=>Amount of the product:\n")
if isinstance(int(productcount),int):
break
except ValueError:
print "=>Please enter a valid number.\n"
dict_of_lists[reachlistname][productname]={"price":productprice,"count":productcount}
dict_of_lists[reachlistname]={productname:{"price":productprice,"count":productcount}}
allevents="1-Add a list"+" 2-Add a product to a list"
def eventtochoose():
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
if not isinstance(int(event),int):
print "\n=>Please enter a number.\n"
else:
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
while True:
print "%s" % ("\n"*100)
eventtochoose()
So, the problem is (I suggest you run the code) it says "=>What would you like to do? Here are the all things you can do:
1-Add a list 2-Add a product to a list
Please enter the number before the thing you want to do:" and when i put an answer it simply doesn't call the fucntion.
If I put 1 It should have called the fucntion addlist but I think it doesn't. There is nothing to explain I think just look at the code and find the problem if you want to help crocodiles. Thx
When you do int(event), that returns an int if possible, and raises a ValueError if not. So, testing the type of the result doesn't do you any good—if your code gets that far, the type has to be an int.
You already have code to handle the ValueError, so you don't need any other test for the same problem.
Meanwhile, you want to start the number that you got from int(event). That's the thing that can be == 1; the original string '1' will never be == 1.
So:
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
event = int(event)
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
You are not converting your input to an integer before comparing, so the comparisons are always false:
'1' == 1 # false
Try:
event = raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
try:
event = int(event)
if event == 1:
addlist()
elif event == 2:
addproduct()
break
except ValueError:
print('Please enter a valid input')

Categories