Let's try this again as my previous post wasn't that clear. I'm a newbie in Python and I'm working on a school project. However I'm stuck on a small part of code.
#Goal
Raise a ValueError when class is called with the wrong arguments.
Check argument age for float/int type and check if arguments is between 0 and 10.
Example:
class Dog():
def __init__(self, name, age):
self.name = name
def check_arg(age):
if isinstance(age, (int,float)) and age >= 0 and age <= 10:
return age
else:
raise ValueError
self.age = check_arg(age)
Now to check if it works I first put
henry = Dog("Henry", 10)
print(henry.age)
The results is printed: 10
Now I check if it is not true and put:
henry = Dog("Henry", 11)
print(henry.age)
Now I get the following:
Traceback (most recent call last):
File "c:\Folder\test.py", line 17, in
henry = Dog("Henry", 11)
File "c:\Folder\test.py", line 12, in init
self.age = check_arg(age)
File "c:\Folder\test.py", line 10, in check_arg
raise ValueError
ValueError
So it does return a ValueError, but I think the function is handling it wrong. When I return instead of raise ValueError it shows: <class 'ValueError'>
Any tips?
I wish my teacher was as fast as you guys. But he said I could ignore the traceback bit. (spend hours trying to solve this)
raise ValueError()
was correct
Related
In this exercise, you'll raise a manual exception when a condition is not met in a particular function. In particular, we'll be converting birth year to age.
Specifications
One a new cell in your notebook, type the following function
import datetime
class InvalidAgeError(Exception):
pass
def get_age(birthyear):
age = datetime.datetime.now().year - birthyear
return age
Add a check that tests whether or not the person has a valid (0 or greater)
If the age is invalid, raise an InvalidAgeError
Expected Output
>>> get_age(2099)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.InvalidAgeError
My code is as following, but it shows error on raise line, how can i get expected output?
import datetime
class InvalidAgeError(Exception):
pass
def get_age(birthyear):
age = datetime.datetime.now().year - birthyear
if age >=0:
return age
else:
raise InvalidAgeError
get_age (2099)
As mentioned in the comments, your code is correct. I guess you would like to see the error message that explains why the error is raised. Here is the code for it.
def get_age(birthyear):
age = datetime.datetime.now().year - birthyear
if age >=0:
return age
else:
raise InvalidAgeError(f'InvalidAgeError: the birthyear {birthyear} exceeds the current year ({datetime.datetime.now().year})')
Please feel free to modify the Exception message the way you find appropriate.
Am facing the error while executing the below code , could someone help on this?
def getting_input():
while True:
try:
x=int(input("enter the value"))
return x
except Exception as e:
print(f'error: {e}')
continue
class armstrong:
def __init__(self):
self.Lower = getting_input()
self.Upper = getting_input()
def calculation(self):
res=0
a=len(str(self.number))
temp= self.number
while temp > 0:
digit = temp % 10
res += digit ** a
temp //= 10
if self.number == res:
print(self.number)
obj=armstrong()
obj.calculation()
Output:
enter the value1
enter the value50
Traceback (most recent call last):
File "C:\Users\Desktop\TOM\armstrong using list and dic.py", line 25, in <module>
obj.calculation()
File "C:\Users\Desktop\TOM\armstrong using list and dic.py", line 16, in calculation
a=len(str(self.number))
AttributeError: 'armstrong' object has no attribute 'number'
Just like the error says, your 'armstrong' object has no attribute 'number'. I'm not quite sure what you are trying to do, but you are trying to calculate something with self.number, but you never made the attribute in your constructor (__init__). You should do that first.
I need to store num_of_divisions and num_of_classes in the object School
file1.py
import file1
name_of_school=input("Enter name of Schoool\n")
printschool=f"Your School's name is {name_of_school}"
print(printschool)
try:
num_of_class=int(input("How many class are there in your School?\n"))
except (ValueError, TypeError) as okok:
print("Please Enter a valid number")
else:
if num_of_class<=0:
print("Number cannot be zero or less")
else:
printvalue=f"Number of class in school are {num_of_class}"
print(printvalue)
num_of_divisions=[]
for divisionloop in range(num_of_class):
divisionloop=divisionloop+1
num_of_divisions.append(int(input("Enter number of Divisions for class %d:"%(divisionloop))))
pak=file1.School.mouse(num_of_class, num_of_divisions)
print(pak)
fil2.py
this file below is a module
class School:
def mouse(self, num_of_class, num_of_divisions):
print(num_of_class and num_of_divisions)
self.num_of_class=num_of_class
self.num_of_divisions=num_of_divisions
return num_of_class
Error :
Traceback (most recent call last):
File "ttmain.py", line 24, in <module>
pak=classes.School.mouse(num_of_class, num_of_divisions)
TypeError: mouse() missing 1 required positional argument: 'num_of_divisions'
plus I need mouse to return value of num_of_class and num_of_divisions both
You need to create instance of your School class first and then you can access the mouse function.
schoolObj = file1.School()
return_value = schoolObj.mouse(num_of_class, num_of_divisions)
print(return_value)
I have seen other posts/videos in order to figure out how to solve this issue I am having but with no success. I am trying to raise an exception if the third parameter(p) is a string datatype but all my attempts in order to achieve this have not been successful and was looking for some help on what I am doing wrong.
class Friends(Ben):
def __init__(self, frank, greg, p):
Ben.__init__(self, frank, greg)
self.p = p
try:
if p == str:
raise TypeError("This is a string!")
except:
print("This not a string")
There are a number of oddities in your piece of code; however, to address the issue of raising an Exception, you use raise to do that, as other answers indicate.
The try/except syntax is used to catch and handle exceptions when they occur. As an example, here is a reworked, standalone version of your code snippet that illustrates this.
class Friends:
def __init__(self, frank, greg, p):
if isinstance(p, str):
raise TypeError(p, "This is a string!")
self.p = p
try:
friends = Friends('Frank', 'Greg', 'dubious_string')
except TypeError as e:
print("Hey, I caught the error!")
# print the exception
print(e)
# raise the exception again
raise e
Output:
Hey, I caught the error!
('dubious_string', 'This is a string!')
Traceback (most recent call last):
File "tmp.py", line 14, in <module>
raise e
File "tmp.py", line 10, in <module>
friends = Friends('Frank', 'Greg', 'dubious_string')
File "tmp.py", line 5, in __init__
raise TypeError(p, "This is a string!")
TypeError: ('dubious_string', 'This is a string!')
I'm not sure what you are trying to do with the class, but I think this is what you are looking for:
#p = 10
p = "some string"
if type(p) == str:
raise Exception("This is a string")
class Ben:
def __init__(self):
pass
class Friends(Ben):
def __init__(self,frank,greg,p):
if isinstance(p, str):
raise TypeError('Why are you giving me strings!')
Ben.__init__(frank,greg)
self.p = p
group = Friends('frank', 'greg', 'evil_string')
Output:
Traceback (most recent call last):
File "C:\Users\StackOverflow\Desktop\temp.py", line 15, in <module>
group = Friends('frank', 'greg', 'evil_string')
File "C:\Users\StackOverflow\Desktop\temp.py", line 10, in __init__
raise TypeError('Why are you giving me strings!')
TypeError: Why are you giving me strings!
I copied and pasted these lines of code from a Python tutorial book. Why does this code not work when I try to run it in PyCharm?
def inputNumber ():
x = input ('Pick a number: ')
if x == 17:
raise 'BadNumberError', '17 is a bad number'
return x
inputNumber()
This is what I got when I run the code:
Pick a number: 17
Traceback (most recent call last):
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 153, in <module>
inputNumber()
File "C:/Users/arman/Desktop/Scribble/Hello.py", line 151, in inputNumber
raise 'BadNumberError', '17 is a bad number'
TypeError: exceptions must be old-style classes or derived from BaseException, not str
You can use standard exceptions:
raise ValueError('17 is a bad number')
Or you can define your own:
class BadNumberError(Exception):
pass
And then use it:
raise BadNumberError('17 is a bad number')
Just inherit from Exception class, then you can throw your own exceptions:
class BadNumberException(Exception):
pass
raise BadNumberException('17 is a bad number')
output:
Traceback (most recent call last):
File "<module1>", line 4, in <module>
BadNumberException: 17 is a bad number
If you want to define a your own error you have to do:
class BadNumberError(Exception):
pass
and then use it:
def inputNumber ():
x = input ('Pick a number: ')
if x == 17:
raise BadNumberError('17 is a bad number')
return x
inputNumber()
You should be raising exceptions as raise as follows BadNumberError('17 is a bad number') if you have already defined BadNumberError class exception.
If you haven't, then
class BadNumberError(Exception):
pass
And here is the docs with information about raising exceptions