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)
Related
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
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 am working on a project for university and I am having trouble with raising errors.
I am supposed to create several functions that will eventually be re-used in even more functions that I am about to create. I am supposed to use Raise ValueError when some specific arguments are being used. Yet, when I use the initial functions to define new functions, the ValueError that gets raised is the initial one and not the new one.
def first_function(arg1):
if isinstance(arg1, tuple):
return True
else:
raise ValueError("This is not a tuple")
def second_function(arg2):
if first_function(arg2):
print("That Is Indeed a Tuple")
else:
raise ValueError("This is really not a tuple")
argument = "(1, 1)"
print(second_function(argument))
# output: ValueError: This is not a tuple
# desired output: ValueError: This is really not a tuple
How can I fix this? I am not supposed to repeat code. I am supposed to keep re-using the functions I build, yet the errors seem to interfere.
So, technically, the "This is not a tuple" error is functioning correctly. The error will stop the code - where the error happens - and report on the stack in that state. This is desirable.
That said, you can use a try/except/finally to catch the first error and pass it back to the second function, which is what I think you're trying to do.
def first_function(arg1):
if isinstance(arg1, tuple):
return True
else:
raise ValueError("This is not a tuple")
def second_function(arg2):
# The try statement wraps the if/then/else
try:
# When you call first_function, it will error
# That error will be recognized and passed to
# second_function's "except" statement
if first_function(arg2):
print("That Is Indeed a Tuple")
# This else is probably not necessary
# Since first_function will either work (return True), or
# raise an error, you will never have a situation where
# "if first_function(arg2):" will ever reach this else
# else:
# raise ValueError("This is not a tuple")
except ValueError:
raise ValueError("This is really not a tuple")
argument = "(1, 1)"
print(second_function(argument))
Traceback (most recent call last):
File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 18, in second_function
if first_function(arg2):
File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 6, in first_function
raise ValueError("This is not a tuple")
ValueError: This is not a tuple
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 27, in <module>
print(second_function(argument))
File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 23, in second_function
raise ValueError("This is really not a tuple")
ValueError: This is really not a tuple
As an aside...
The functional goal you're usually trying to accomplish with this type of design pattern, is to avoid the need to do checks like you're doing in first_function (where it checks if the arg is a tuple).
This design pattern is usually so you can leave the error checking to the main calling method, and all the called methods can just do their thing - raising errors if bad code is sent.
I.e.
def first_function(arg1):
return arg1.append("I should be a list")
def second_function(arg2):
try:
_list = first_function(arg2)
print("arg2 is, indeed, a list")
except Exception as e:
raise ValueError("You did not pass a list (ORIG ERROR: {}".format(e))
argument = "(1, 1)"
print(second_function(argument))
OUTPUT:
Traceback (most recent call last):
File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 7, in second_function
_list = first_function(arg2)
File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 2, in first_function
arg1.append("I should be a list")
AttributeError: 'str' object has no attribute 'append'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 13, in <module>
print(second_function(argument))
File "/home/rightmire/eclipse-workspace/junkcode/test.py", line 10, in second_function
raise ValueError("You did not pass a list (ORIG ERROR: {}".format(e))
ValueError: You did not pass a list (ORIG ERROR: 'str' object has no attribute 'append'
Functionally, the try/except/finally is used to silence errors. As an example...
def first_function(_list, arg1):
_list.append(int(arg1))
return _list
def second_function():
_list = []
while True:
arg2 = input("Enter an integer:")
try:
_list = first_function(_list, arg2)
print("a list containing {}".format(_list))
except Exception as e:
print ("You did not pass an integer. Try again")
second_function()
OUTPUT:
Enter an integer:1
a list containing [1]
Enter an integer:2
a list containing [1, 2]
Enter an integer:3
a list containing [1, 2, 3]
Enter an integer:r
You did not pass an integer. Try again
Enter an integer:4
a list containing [1, 2, 3, 4]
Enter an integer:
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
What is the error below? Also, is there a better way to implement the following classes?
#!/usr/bin/python
class Datacenters:
def __init__(self,name,location,cpu,mem):
self.name=name
self.location=location
self.cpu=cpu
self.mem=mem
def getparam(self):
return self.name,self.location ,self.cpu,self.mem
def getname(self):
return self.name
class WS(Datacenters):
def __init__(self,name,location,cpu,mem,obj):
#datacentername = Datacenters.__init__(self) #To which data center it is associated
self.dcname =obj.name #To which data center it is associated
Datacenters.__init__(obj,name,location,cpu,mem)
def getparam(self,obj):
self.name,self.location ,self.cpu,self.mem = obj.getparam()
print self.dcname
#return self.name,self.location ,self.cpu,self.mem,obj.name
def getwsname(self):
return self.name
class Pcs(WS):
def __init__(self,name,location,cpu,mem,obj):
self.wsname = obj.getwsname() #To which WS it is associated
WS.__init__(obj,name,location,cpu,mem)
def getparam(self,obj):
print obj.getparam()
print self.wsname
a = Datacenters("dc1","Bl1",20,30)
print a.getparam()
b = WS("WS1","Bl1",21,31,a)
print b.getparam(a)
c = Pcs("PC1","Bl1",20,30,b)
#print c.getparam(b)
output:
Press ENTER or type command to continue
('dc1', 'Bl1', 20, 30)
dc1
None
Traceback (most recent call last):
File "class1.py", line 45, in <module>
c = Pcs("PC1","Bl1",20,30,b)
File "class1.py", line 34, in __init__
WS.__init__(obj,name,location,cpu,mem)
TypeError: __init__() takes exactly 6 arguments (5 given)
The error is that you pass in five arguments, but the __init__ needs six. Count them:
def __init__(self,name,location,cpu,mem,obj):
Six arguments. You call it like so:
WS.__init__(obj,name,location,cpu,mem)
Five arguments. The first one, self is missing. What you should ask yourself is why you don't have to pass in six arguments all the time.
And that is because self is passed in automatically when you call the method on an instance. However, in this case you don't call it on an instance, you call it directly on the class. There is of course no need to do so in this case, the correct syntax is:
WS(obj,name,location,cpu,mem)
As you indeed above note works further up.