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'
Related
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)
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.
The code :
x=0
def ex():
u= input (': ')
if u =='a':
print ('okay')
x = x + 1
ex()
The error :
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
ex ()
File "<pyshell#2>", line 5, in ex
x = x + 1
UnboundLocalError: local variable 'x' referenced before assignment
This is what I get. I have no idea what's wrong. Thanks in advance
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.
I have a problem with the following code:
inputf = open('test.dat', 'r')
lines = inputf.readlines()
rico_clus_e = []
for line in lines:
line.split()
print line
if (line[0] != '#'):
rico_clus_e.append(float(line[4]))
inputf.close()
My test.dat file is:
# specn rico_all rico_all_e rico_clus rico_clus_e rico_farclust rico_far_e extin
a119 1.07038692 0.11109547 0.61473431 0.15063627 0.32590239 0.14777812 0.207
And this gives the following output in my terminal:
# specn rico_all rico_all_e rico_clus rico_clus_e rico_farclust rico_far_e extin
a119 1.07038692 0.11109547 0.61473431 0.15063627 0.32590239 0.14777812 0.207
Traceback (most recent call last):
File "test.py", line 8, in <module>
rico_clus_e.append(float(line[4]))
ValueError: could not convert string to float:
I'm quite confused by this. It had nothing to do with spaces, I checked them all. And if you change 4 by 1, 2 or 3 this works, so it must have something to do with the test.dat file, but I can't seem to figure out how. I'm using python 2.7.3.
line.split() on its own does nothing to line. You must store the result of the method call and use that instead.