Am trying to print a given result using the str.format() in python but I keep running into an TypeError. Here is my current piece of code that gives me the error:
def Restaurant_calorie_average(rest):
result = []
for item in rest.menu:
result.append(item.calories)
return sum(result)/len(rest.menu)
def Restaurant_str(self: Restaurant) -> str:
return (
"Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: " + Menu_str(self.menu) + "\n"+
"\t Average Price: {0:3.2f}. Average calories {1:}: ".format(Restaurant_price_average(self), str(Restaurant_calorie_average(self))) + "\n\n")
def Collection_str(C: list) -> str:
''' Return a string representing the collection
'''
s = ""
if not C:
return ''
else:
for r in C:
s = s + Restaurant_str(r)
return s
This is the error I get:
Traceback (most recent call last):
File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 229, in <module>
restaurants()
File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 19, in restaurants
our_rests = handle_commands(our_rests)
File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 48, in handle_commands
print(Collection_str(C))
File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 176, in Collection_str
s = s + Restaurant_str(r)
File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 84, in Restaurant_str
"\tAverage Price: {0:3.2f}. Average calories: {1:}".format(Restaurant_price_average(self), Restaurant_calorie_average(self)) + "\n\n")
File "C:\Users\Sage\workspace\hello\restaurantsg.py", line 113, in Restaurant_calorie_average
return float(sum(result)/len(rest.menu))
TypeError: unsupported operand type(s) for +: 'int' and 'str'
What I don't understand is, that another function Restaurant_price_average() in my program has the exact same parameters and returns a float like the Restaurant_calorie_average() and it works just fine in the current program if I remove the Restaurant_calorie_average() part. I tried type converting 'Restaurant_calorie_average()into string, putting float in format {1:3.1f} but it still doesn't seem to work. Can anyone help me with this? The full program is here Rprogram for your reference.
The error means that the items in the result list have strings as calories and not numbers (at least some of them). The sum() function can't work like that because it internally adds the elements to 0, which results in the error you see:
In [1]: sum(['42'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-86653ad6b5d8> in <module>()
----> 1 sum(['42'])
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [2]: sum([1, 2, '42'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-c2f90238e02a> in <module>()
----> 1 sum([1, 2, '42'])
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The error is not related to the .format() call, because, as you can see in the traceback, it happens inside Restaurant_calorie_average.
You should fix your code (not shown in the question) so that rest.menu items only contain numbers in their calories attribute. Looking at your full code, apparently this part needs to be fixed:
def Dish_get_info() -> Dish:
""" Prompt user for fields of Dish; create and return.
"""
return Dish(
input("Please enter the Dish's name: "),
float(input("Please enter the price of that dish: ")),
input("Please enter the calories in the food: ") # <-- you are not converting
# to float here
)
As a side note, I agree with Kevin's comment that you would have much more readable code if you wrote actual classes with methods, rather than functions. And if you do use functions, it's a widely adopted convention that function names start with lowercase letters.
Related
I am writing a code to make a table of 2 countries' population growth, here is my final function to make the table
def table(population1, population2, rate1, rate2, duration, interval,):
header(country1, country2)
for i in range [0, duration]:
print (str(i) + " " + str(calc(population1, rate1, duration)) + " " + str(calc(population2, rate2, time)))
i += interval
whenever I run the code, everything works fine until it gets to this function.
Exception has occurred: TypeError
'type' object is not subscriptable
File "C:\Users\rayro\OneDrive\Documents\Fall22\CSC 130\05 Population Growth.py", line 83, in table
for i in range [0, duration]:
File "C:\Users\rayro\OneDrive\Documents\Fall22\CSC 130\05 Population Growth.py", line 102, in <module>
table(popC1, popC2, growth1, growth2, time, gaps)
I have tried making the functions called inside the print strings, and integers, tried changing to while loops, and tried pulling in recursion
New error
Exception has occurred: TypeError
unsupported operand type(s) for +: 'int' and 'str'
File "C:\Users\rayro\OneDrive\Documents\Fall22\CSC 130\05 Population Growth.py", line 84, in table
print (i + "\t" + calc(population1, rate1, duration) + "\t" + calc(population2, rate2, time))
File "C:\Users\rayro\OneDrive\Documents\Fall22\CSC 130\05 Population Growth.py", line 102, in <module>
table(popC1, popC2, growth1, growth2, time, gaps)
I want to convert the final list as tuple. However i am receiving an error.How can i get rid of this?
li= [(19343160,),(39343169,)]
def render_list_sql(li):
l = []
for index, tuple in enumerate(li):
idd = str(tuple[0])
l.append(idd)
return tuple(l)
print(render_list_sql(li))
Expected value to be returned is:
(19343160,39343169)
Error
Traceback (most recent call last):
File "test.py", line 20, in <module>
print(render_list_sql(list))
File "test.py", line 14, in render_list_sql
return tuple(l)
TypeError: 'tuple' object is not callable
As commented, don't use names for variables that mean other things to Python. This is called "shadowing" and you lose the meaning of the original name.
Example:
>>> tuple # This is the class used to create tuples.
<class 'tuple'>
>>> for index,tuple in enumerate([1,2,3]): # This is similar to your code
... print(index,tuple)
...
0 1
1 2
2 3
>>> tuple # tuple is no longer a class, but an instance of an integer.
3
>>> tuple([1,2,3]) # so this fails
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
>>> 3([1,2,3]) # You are basically doing this:
<interactive input>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'int' object is not callable
So don't do that:
li = [(19343160,),(39343169,)] # don't reassign list
def render_list_sql(li):
l = []
for index, tup in enumerate(li): # don't reassign tuple
idd = str(tup[0])
l.append(idd)
return tuple(l) # now this will work
print(render_list_sql(li))
Output:
('19343160', '39343169')
FYI, a shorter version using a generator:
li = [(19343160,),(39343169,)]
tup = tuple(str(i[0]) for i in li)
print(tup)
I have this simple script but i get an operand error in Line 16
Code:
class Person:
number_of_people = 0
Gravity = -9.5
def __init__(self, name):
self.name = name
Person.add_person()
#classmethod
def number_of_people(cls):
return cls.number_of_people
#classmethod
def add_person(cls):
cls.number_of_people += 1
p1 = Person("joe")
p2 = Person("frank")
print(Person.number_of_peple())
Error message:
Traceback (most recent call last):
File "app4.py", line 19, in <module>
p1 = Person("joe")
File "app4.py", line 7, in __init__
Person.add_person()
File "app4.py", line 16, in add_person
cls.number_of_people += 1
TypeError: unsupported operand type(s) for +=: 'method' and 'int'
What can i do to fix this error?
In this question it say i need to take the varaible name but I only want to increment and not have a variable for that
TypeError: unsupported operand type(s) for +=: 'method' and 'int' (Python)
Your static variable number_of_people and your class method def number_of_people(cls) are named the exact same thing.
Thus when you add one to cls.number_of_people, the interpreter thinks you want to add a number to the class method which doesn't make sense. You have to change the name of one of those things.
print ('welcome to the new world')
print('what is your name')
myName = input()
print ('it is good to meet you , ' + myName)
print (' Th length of your name is : ')
print (len(myName))
print('what is your age')
myEdge = input()
print ('you were born on ,')
print (2018 - myEdge)
The above code fails at last line.
Traceback (most recent call last):
File "C:\Users\Pratik\Desktop\python\First_Program.py", line 10, in <module>
print (2018 - myEdge)
TypeError: unsupported operand type(s) for -: 'int' and 'str'
But I can run it manually by assigning value and it is running while we convert the variable data type to string print (2018 - int(myEdge))
confused why difference between script and command line execution
myEdge = 29
print ( 2018 - myEdge )
1989
In line command :
myEdge = 29 # You put an integer in the variable
In script :
myEdge = input("Enter your age -> ") # You put a string in the variable
It's why you have a difference between line command and script.
You have the solution for the script int(myEdge) . For the tips you can add text into the input : input("add_the_text_here") .
Moreover in line command you can test the same :
>>> t = input(">")
>29
>>> type(t)
<class 'str'>
>>> 30 - t
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
30 - t
TypeError: unsupported operand type(s) for -: 'int' and 'str'
I intend to perform a Newton Raphson iteration on some data I read in from a file. I use the following function in my python program.
def newton_raphson(r1, r2):
guess1 = 2 * numpy.log(2) / (numpy.pi() * (r1 + r2))
I call this function as so:
if answer == "f": # if data is in file
fileName = input("What is the name of the file you want to open?")
dataArray = extract_data_from_file(fileName)
resistivityArray = []
for i in range(0, len(dataArray[0])):
resistivity_point = newton_raphson(dataArray[0][i], dataArray[1][i])
resistivityArray += [resistivity_point]
On running the program and entering my file, this returns `TypeError: 'float' object is not callable'. Everything I've read online suggests this is due to missing an operator somewhere in my code, but I can't see where I have. Why do I keep getting this error and how do I avoid it?
numpy.pi is not a function, it is a constant:
>>> import numpy
>>> numpy.pi
3.141592653589793
Remove the () call from it:
def newton_raphson(r1, r2):
guess1 = 2 * numpy.log(2) / (numpy.pi * (r1 + r2))
as that is causing your error:
>>> numpy.pi()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object is not callable