+ 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...
10 Réponses
+ 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'
+ 4
You should try something like this
https://code.sololearn.com/cTERSBlFtfGM/?ref=app
+ 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
+ 2
You probably could use try/catch, but maybe first you should actually share the language so we can give a straight answer.
+ 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?
+ 2
string has isnumeric method to check if the string only contains numeric value. it'll return boolean.
if str.isnumeric():
+ 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
}
+ 1
I'm sorry, it's python
+ 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")
+ 1
Use raise for errors