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.
Related
Here is the method causing the error:
class Kilpailu():
def __init__(self, nimi, pituuskm, osallistujat):
self.nimi = nimi
self.pituuskm = pituuskm
self.osallistujat = osallistujat
def kilpailu_ohi(self):
for i in self.osallistujat:
if (i.getKuljettuMatka>=self.pituuskm):
return True
else:
return False
edit: here is also where getKuljettuMatka is defined
class Auto:
def __init__(self, rekisteritunnus, huippunopeus):
self.rekisteritunnus = rekisteritunnus
self.huippunopeus=huippunopeus
self.nopeus=0
self.KuljettuMatka=0
def getKuljettuMatka(self):
return int(self.KuljettuMatka)
I am trying to call the method that just returns a boolean value and print whether the value is true or false.
class main():
autot = []
for i in range(10):
auto = Auto("ABC-" + str(i + 1), random.randint(100, 200))
autot.append(auto)
k = Kilpailu("Suuri romuralli", 8000, autot)
tunnit = 0
print(k.kilpailu_ohi()) #Should return true/false, instead throws an error
and here is the actual console output for the error
Traceback (most recent call last):
File "/root/PycharmProjects/ohjelmisto1/Harjoitustehtävät/Assosisaatio/autoKilpailu.py", line 51, in <module>
class main():
File "/root/PycharmProjects/ohjelmisto1/Harjoitustehtävät/Assosisaatio/autoKilpailu.py", line 59, in main
print(k.kilpailu_ohi())
File "/root/PycharmProjects/ohjelmisto1/Harjoitustehtävät/Assosisaatio/autoKilpailu.py", line 45, in kilpailu_ohi
if (i.getKuljettuMatka>=self.pituuskm):
TypeError: '>=' not supported between instances of 'method' and 'int'
I have tried changing stuff in the method like variable names in case i was accidentally overwriting something but it didnt work either
def getKuljettuMatka(self): defines .getKuljettuMatka on instances of Auto as a method (that happens to return an integer). You can call the method with i.getKuljettuMatka() (note the parentheses), but what you're doing is comparing the method itself to self.pituuskm, which is an integer, and that doesn't work.
Instead:
def kilpailu_ohi(self):
for i in self.osallistujat:
if (i.getKuljettuMatka() >= self.pituuskm):
return True
else:
return False
By the way, I think the code is a bit roundabout in other ways, but this is you main issue right now.
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
I am currently having an issue, as i am relatively new to python , it might be a very easy solution for others.
I want to pass a parameter between both functions 'eg1' and 'eg2', there is a common number the user will input (example:10) then 'eg1' will add 1 to it and 'eg2' will take the final value of 'eg1' and add 1 more to it, (example: 10 will become 11 then 12)
It is troubling me because this keeps popping up:
Traceback (most recent call last):
File "example.py", line 69, in <module>
eg2(a)
File "example.py", line 63, in eg2
b = a.d
AttributeError: 'int' object has no attribute 'd'
I can't seem to find my mistake.
class Helper:pass
a = Helper()
def one(a):
d = a
d += 1
print d
def two(a):
b = a.d
b += 1
print b
print
print ("Please enter a number.")
a = int(input('>> ')
print
one(a)
print
two(a)
Reference for parameter passing:
Python definition function parameter passing
'Print' with nothing means to leave an empty line, for me
I messed up the title, fixed.
Since you are already using a class, you can pass the number you want to increment twice as an instance attribute, and call your increment functions on that attribute. This will avoid passing the updated value after calling one in the method two
Calling one and then two makes sure that two is working on the updated value after calling one.
class Helper:
# Pass num as parameter
def __init__(self, num):
self.num = num
# Increment num
def one(self):
self.num += 1
# Increment num
def two(self):
self.num += 1
h = Helper(10)
h.one()
print(h.num) # 11
h.two()
print(h.num) # 12
Based on your comments, here's one way to get the result. I am using python3:
class Helper:
d = None
cl = Helper()
def one(a):
cl.d = a
cl.d += 1
return cl.d
def two():
cl.d += 1
return cl.d
print ("Please enter a number.")
a = int(input('>> '))
print(one(a))
print(two())
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'm new to python OOP and I'm struggling with figuring out my error in this code, if anyone can help that would be great!
class Toy:
def __init__(self, price):
self.__price = price
def SetPrice(self, p):
self.__price = p
def GetPrice(self):
return(self.__price)
def InsertionSort(x):
for index in range(1, len(x)):
value = x[index].GetPrice()
i = index -1
while i >= 0:
if value < (x[i].GetPrice()):
x[i+1].SetPrice(x[i])
x[i].SetPrice(value)
i = i -1
else:
break
prices = []
prices.append(Toy(200))
prices.append(Toy(10))
prices.append(Toy(20))
Toy.InsertionSort(prices)
but when I run it I get back this, but I don't really understand what the error means and I've tried writing it other ways but I'm not sure what to do now.
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\testId.py",
line 34, in <module>
Toy.InsertionSort(prices)
File "C:\Users\USER\AppData\Local\Programs\Python\Python36-32\testId.py",
line 20, in InsertionSort
if value < (x[i].GetPrice()):
TypeError: '<' not supported between instances of 'int' and 'Toy'
Thank you in advance!
The problem is because the line
x[i+1].SetPrice(x[i])
sets x[i+1] to x[i] which is a Toy, not an int.