Python poulation growth function giving errors - python-3.x

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)

Related

how to make a greater than or lower than with tkinter StringVar

My code keeps giving this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "d:/Python Code stuff I did/print.py", line 209, in <lambda>
button = Button(root,text="Change Config", width=20, height=3, bg="#0f0f0f",fg="#ffffff", command=lambda:[do_it(), do_it1(), do_it2(), do_it3(),do_the_it(),do_the_it1()])
File "d:/Python Code stuff I did/print.py", line 149, in do_the_it
if str(number_1) > 4:
TypeError: '>' not supported between instances of 'str' and 'int'
I want it to check if that specific number is greater than 4 for example i input a number for example lets say its 7 I want it to print and that number is too high here is my code:
def do_the_it():
a = updater['Trading Settings']['minimum_offer'].value
updater.read('settings.ini')
updater['Trading Settings']['minimum_offer'].value = number_1.get()
updater.update_file()
updater.read('settings.ini')
updater['Trading Settings']['maximum_offer'].value = number_2.get()
updater.update_file()
if str(number_1) > 4:
print("Number can only exceed to 4")
updater.read('settings.ini')
updater['Trading Settings']['minimum_offer'].value = 4
updater.update_file()
You can't compare a string to a number. Use:
if float(number_1.get()) > 4:
You can also use int(), but if some joker enters a decimal point, this will prevent errors.

python code error at calculation

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'

Itertuples() in Tkinter function reveals an AttributeError: 'tuple' object has no attribute 'A'

Within a Tkinter function, I need to create the list named: 'value' extracting every 10 rows the value of dataframe column named: df['A'].
The following for-loop works perfectly out of a Tkinter function:
value = []; i = 0
for row in df.itertuples():
i = 1 + i
if i == 10:
value_app = row.A
value.append(value_app)
i=0
However within Tkinter function I have the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Users/anaconda/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "<ipython-input-1-38aed24ba6fc>", line 4174, in start
dfcx = self.mg(a,b,c,d,e)
File "<ipython-input-1-38aed24ba6fc>", line 4093, in mg
value_app = r.A
AttributeError: 'tuple' object has no attribute 'A'
A similar for-loop structure is running in another part of the same Tkinter function and is executed without errors.
If the column A is your first column you can do :
value_app = row[0]
I had the same problem and I think that it only sees it as regular arrays

Python Deap GP Evaluating individual causes error

I am currently experiencing an issue whenever I try to evaluate an individual using the GP portion of DEAP.
I receive the following error:
Traceback (most recent call last):
File "ImageGP.py", line 297, in <module>
pop, logs = algorithms.eaSimple(pop, toolbox, 0.9, 0.1, 60, stats=mstats, halloffame=hof, verbose=True)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/deap/algorithms.py", line 148, in eaSimple
for ind, fit in zip(invalid_ind, fitnesses):
File "ImageGP.py", line 229, in evalFunc
func = toolbox.compile(expr=individual)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/deap/gp.py", line 451, in compile
return eval(code, pset.context, {})
File "<string>", line 1
lambda oValue,oAvg13,oAvg17,oAvg21,sobelVal(v),sobelVal(h),edgeVal,blotchVal: [[[0, 75, 82.2857142857, 83.0, 82.9090909091, 4, 12, 4, 180], ... Proceed to print out all of my data ... [0, 147, 151.244897959, 150.728395062, 150.73553719, 248, 244, 5, 210]]]
^
SyntaxError: invalid syntax
If anyone has any ideas about what could be causing this problem, then I would really appreciate some advice. My current evaluation function looks like this:
def evalFunc(individual, data, points):
func = toolbox.compile(expr=individual)
total = 1.0
for point in points:
tmp = [float(x) for x in data[point[1]][point[0]][1:9]]
total += int((0 if (func(*tmp)) < 0 else 1) == points[2])
print ("Fitness: " + str(total))
return total,
Where the data contains the data being used (the values for the 8 variables listed in the error) and point specifying the x and y co-ordinates from which to get those 8 values. Thank you for your suggestions!

Python type conversion error

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.

Resources