+ 2

How do you make a program that if error occurs, I want to print something instead of the shell giving you value error report?

The program that i want to make is basically just printing "spam" as much as you want depending on the value in the user input. You know that we can't print a value of decimal word with a meaning. I have made the "if" for people putting 0 in the input and negative. But I don't know how to make the "if" case for the error. Please help...

12th Jul 2019, 5:02 AM
Leonardo Ginting
Leonardo Ginting - avatar
10 Answers
+ 4
i would like to add something to Airees sample which gives a detailed info about the the exeption that is raised: try: times = int(input()); for i in range(times): print("Spam") except Exception as e: print("Invalid input!") print(e) # output is: hhhh # is input Invalid input! invalid literal for int() with base 10: 'hhhh'
12th Jul 2019, 5:53 AM
Lothar
Lothar - avatar
+ 4
You should try something like this https://code.sololearn.com/cTERSBlFtfGM/?ref=app
12th Jul 2019, 5:11 AM
Airree
Airree - avatar
+ 3
Here 2 methods to check what content a string holds; >>> a='3' >>> a.isnumeric() True >>> a.isdigit() True >>> a.isalpha() False >>> b='g' >>> b.isalpha() True >>> b.isdigit() False
13th Jul 2019, 7:44 PM
Lothar
Lothar - avatar
+ 2
You probably could use try/catch, but maybe first you should actually share the language so we can give a straight answer.
12th Jul 2019, 5:07 AM
Airree
Airree - avatar
+ 2
How do you make it something like, the program can recognize integers and alphabet. example, i made an if statement for negative numbers like if w < 0 : print("no negative numbers alowed") elif w == 1 : print("why only one?) elif w == 0 : print("really you're confusing me) How do make an alphabet exception? Is it using another if statement? or is it something else?
13th Jul 2019, 5:30 PM
Leonardo Ginting
Leonardo Ginting - avatar
+ 2
string has isnumeric method to check if the string only contains numeric value. it'll return boolean. if str.isnumeric():
13th Jul 2019, 6:42 PM
Taste
Taste - avatar
+ 1
what language ? in many c-like using try catch to do this. the usage is a bit different in each language, but the structure is same try{ //error hapen here catch(exception e){ //the action you wanted when error is occur here }
12th Jul 2019, 5:06 AM
Taste
Taste - avatar
+ 1
I'm sorry, it's python
12th Jul 2019, 5:08 AM
Leonardo Ginting
Leonardo Ginting - avatar
+ 1
In Python we can use "raise" keyword for displaying custom messages than actual errors, x = -1 if x < 0:   raise Exception("Sorry, no numbers below zero")
22nd Jul 2019, 8:43 PM
Anil
+ 1
Use raise for errors
24th Jul 2019, 10:16 PM
Az Rael
Az Rael - avatar