Error: 'str' object is not callable python [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have been stuck dealing with an error in python and have been searching for a while to fix it but to no avail.
Here is the error I am getting
Traceback (most recent call last):
File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 62, in <module>
main()
File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 23, in main
displayOutput(letterCount,middleCharacter,spaceAmount,aReplace)
File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 56, in displayOutput
print('Number of letters:'(letterCount))
TypeError: 'str' object is not callable
Here is the code I have written so far.
def main():
while True:
sentence= userInput()
letterCount= characterCount(sentence)
middleCharacter= middleLetter(sentence)
spaceAmount= spaceCount(sentence)
aReplace= letterReplace(sentence)
displayOutput(letterCount,middleCharacter,spaceAmount,aReplace)
def userInput():
sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:'))
if sentence == 'STOP':
quit()
return sentence
def characterCount(sentence):
letterCount = len(sentence) - sentence.count(' ')
if letterCount < 10:
print('Sorry that is less than 10 letters')
def middleLetter(sentence):
sentence = len(sentence)/2
middleCharacter = [sentence +1]
def spaceCount(sentence):
spaceAmount = sentence.count(' ')
def letterReplace(sentence):
aReplace= sentence.replace("a", "&")
def displayOutput(letterCount,middleCharacter,spaceAmount,aReplace):
print('Number of letters:'(letterCount))
print('Middle letter:'(middleCharacter))
print('Spaces counted:'(spaceAmount))
print('Sentence with letter replaced:'(aReplace))
main()
The solution is probably something simple that I am overlooking but any help would be appreciated.

The error states str object not callable which meant you were treating strings like functions or anything which is callable () in your code.
The issue is in the print statements in displayOutput() function
Corrected code
def displayOutput(letterCount,middleCharacter,spaceAmount,aReplace):
print('Number of letters:',letterCount)
print('Middle letter:',middleCharacter)
print('Spaces counted:',spaceAmount)
print('Sentence with letter replaced:',aReplace)
main()

Related

What is the problems with my code and how to fix it? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
def ask_a():
a = input("""Please enter a:
a = """)
a = eval(a)
if a == 0:
print("Please input the correct number! \n")
ask_a()
elif isinstance(a, str):
print("Please input the correct number! \n")
ask_a()
else:
print(a)
return a
ask_a()
I'm making a quadratic equation solver by python 3 and that is what i write for asking for a (a is not 0 and a is not a string)
This is what the error message:
Please enter a:
a = sgafdf
Traceback (most recent call last):
File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 15, in <module>
ask_a()
File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 4, in ask_a
a = eval(a)
File "<string>", line 1, in <module>
NameError: name 'sgafdf' is not defined
PS C:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects> & C:/Users/jbtua/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/jbtua/OneDrive/Desktop/wut is this/Personal Folder/Programming Projects/Python/blank-1.py"
Please enter a:
a = a
Please input the correct number!
Please enter a:
a = w
Traceback (most recent call last):
File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 15, in <module>
ask_a()
File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 10, in ask_a
ask_a()
File "c:\Users\jbtua\OneDrive\Desktop\wut is this\Personal Folder\Programming Projects\Python\blank-1.py", line 4, in ask_a
a = eval(a)
File "<string>", line 1, in <module>
NameError: name 'w' is not defined
What should I do to avoid this? I will appreciate all the answer.
Problem (1.)
You're calling eval().
Don't do that.
It opens too many doors to remote exploits.
Specify the business problem you're trying to solve,
and propose a solution that doesn't involve eval.
Problem (2.)
You never assigned a value to sgafdf, nor to w,
yet you tried to evaluate them.
That won't work.
Stick to defined variables in the expressions
you try to evaluate.
You are using the eval() function which will evaluate the string that is passed to it as code. For example, if you enter the input print(9) your code will print 9:
Please enter a:
a = print(9)
9
None
When you pass it invalid code as input it will throw that exception.
Here you are using eval which evaluates the input as integer or float while the data that you entered is string so it won't work.

global variable python, doesn't run [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I try to run this code in python 3.6
def Arrange(num):
global sec
sec=0
def Digit(nmb):
return nmb%10
def WithoutTheLastDigit(nmb2):
return nmb2//10
def IsEven(even):
if even%2==0:
return True
else:
return False
def AddDigit(number,dig):
number=number*10+dig
while num>0:
Digit(num)
if IsEven(Digit(num))==True:
sec=sec+AddDigit(sec,Digit(num))
WithoutTheLastDigit(num)
print(sec)
and it shows this error:
>>> Arrange(500)
Traceback (most recent call last):
File "", line 1, in
Arrange(500)
File "C:\Users\Yair\Desktop\hw3.py", line 56, in Arrange
sec=sec+AddDigit(sec,Digit(num))
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Your problem is that the function AddDigit() returns None:
def AddDigit(number,dig):
number=number*10+dig
# this return None by default. mussing `return number`
while num>0:
Digit(num)
if IsEven(Digit(num))==True:
sec=sec+AddDigit(sec,Digit(num)) # This is 0 + None
WithoutTheLastDigit(num)
Note that you code can be simplify greatly with a few things. I didn't change the logic, so you might have some errors here.
def Digit(number):
return number % 10
def WithoutTheLastDigit(number):
return number // 10
def IsEven(number):
return number % 2 == 0:
def AddDigit(number, digit):
return number*10 + digit
while number > 0:
digit = Digit(number)
if IsEven(digit):
sec += AddDigit(sec, digit)
print(sec)

AttributeError: 'function' object has no attribute 'save' - Python PIL QR Code not saving [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm a newcomer to programming so i apologize for my lack of technical ability.
I'm trying to create a qrcode generator in python, however, when i try to increment the number on the filename save, i get this error.
Traceback (most recent call last):
File "/home/sam/Desktop/QR Code Gen/run.py", line 52, in <module>
purchase_code_fn()
File "/home/sam/Desktop/QR Code Gen/run.py", line 32, in purchase_code_fn
qr_code_fn()
File "/home/sam/Desktop/QR Code Gen/run.py", line 41, in qr_code_fn
im.save("filename"+ count + ".png")
AttributeError: 'function' object has no attribute 'save'
>>>
Is there anyway to rectify this?
(see below for my full code - it's still a WIP)
from qrcode import *
import csv
import time
active_csv = csv.writer(open("active_codes.csv", "wb"))
void_csv = csv.writer(open("void_codes.csv", "wb"))
active_csv.writerow([
('product_id'),
('code_id'),
('customer_name'),
('customer_email'),
('date_purchased'),
('date_expiry')])
void_csv.writerow([
('code_id'),
('customer_email'),
('date_expiry')])
count = 0
def purchase_code_fn():
global count
count =+ 1
customer_email = raw_input("Please enter your email: ")
product_id = raw_input("Which product would you like (1 - 5): ")
qr_code_fn()
def qr_code_fn():
qr = QRCode(version=5, error_correction=ERROR_CORRECT_M)
qr.add_data("asaasasa")
qr.make() # Generate the QRCode itself
# im contains a PIL.Image.Image object
im = qr.make_image
im.save("filename"+ count + ".png")
def restart_fn():
restart_prompt = raw_input("Would you like to purchase another code? : ").lower()
if restart_prompt == "yes" or restart_prompt == "y":
purchase_code_fn()
elif restart_prompt =="n" or restart_prompt == "no":
print("exit")
purchase_code_fn()
The error is here : im = qr.make_image. You are storing into im the function make_image of object qr. As you can store functions in variables in Python, this is a valid syntax.
So, you are not calling the function make_image, just storing it. It should be im = qr.make_image().
After you'll implement T. Claverie answer - it is likely that you'll fail in .save() as you are concating string and integer.
Can you try to change the following line:
im.save("filename"+ count + ".png")
to be:
im.save("filename"+ str(count) + ".png")

max() arg is an empty sequence [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have written a program for Radix Sort in Python. But when I execute the code I get following error message max() arg is an empty sequence.
Here is my code:
class RadixSort:
num=0
array=[]
def getData(self):
print 'Enter the number of elements you want to enter: '
num=int(input())
print 'Now enter the elements: '
for i in range(0,self.num):
print 'Element ',i+1,': '
value=int(input())
self.array.append(value)
def radixSort(self):
bin=[[],[],[],[],[],[],[],[],[],[]]
r=1
m=max(self.array)
while m>r:
for ele in self.array:
bin[(ele/r)%10].append(ele)
r=r*10
self.array=[]
for i in range(10):
self.array.extend(bin[i])
bin[i]=[]
def displayArray(self):
print ''
for ele in self.array:
print ele
RObject=RadixSort()
RObject.getData()
RObject.radixSort()
RObject.displayArray()
I get this error before entering values in array. How can I solve this?
I think you should replace:
num = int(input())
to
self.num = int(input())
Not superfluous will be to check that the array is not empty:
m = max(self.array) if self.array else 0
You should show the complete traceback. When I run your code I get this:
Enter the number of elements you want to enter:
3
Now enter the elements:
Traceback (most recent call last):
File "radix.py", line 35, in <module>
RObject.radixSort()
File "radix.py", line 17, in radixSort
m=max(self.array)
ValueError: max() arg is an empty sequence
so m=max(self.array) fails because you can't do a max function on an object that doesn't exist. You need to have an init method to create self.array
Why are you using input and not raw_input? You are using python 2.7

TypeError: unsupported operand type(s) for %: 'Text' and 'tuple' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to make a program that calculates how much it costs to miss a class. I take in variables tuition, number of courses, and number of weeks in a semester; it then plots the results (using python 2.7). Here's the code I've been working on:
import matplotlib.pyplot as plot
def calculations(t, c, w, wk):
two_week = (((t/c)/w)/2)*wk
three_week = (((t/c)/w)/3)*wk
return two_week, three_week
def main():
tuition = float(raw_input('Tuition cost (not including fees): '))
courses = int(raw_input('Number of courses: '))
weeks = int(raw_input('Number of weeks in the semester: '))
x_axis = range(0,10)
y_axis = []
y_axis2 = []
for week in x_axis:
cost_two, cost_three = calculations(tuition, courses, weeks, week)
y_axis += [cost_two]
y_axis2 += [cost_three]
plot.plot(x_axis, y_axis ,marker='o', label='course meets 2x a week', color='b')
plot.plot(x_axis, y_axis2,marker='o', label='course meets 3x a week', color='g')
plot.xlabel('number of missed classes')
plot.ylabel('cost ($)')
plot.title('Tuition: %.2f Courses: %d Weeks in a semester: %d\n Created by <MyName>') %(tuition, courses, weeks)
plot.legend()
plot.xticks(x_axis)
plot.xlim(0,x_axis[-1]+1)
plot.yticks(y_axis)
plot.ylim(0, y_axis[0]+1)
plot.grid()
plot.show()
plot.savefig('missing-class-cost.pdf')
main()
However, whenever I run my program, I receive the following error:
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 36, in <module>
File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 26, in main
TypeError: unsupported operand type(s) for %: 'Text' and 'tuple'
Line 26 is in reference to this line of code:
plot.title('Tuition: %.2f Courses: %d Weeks in a semester: %d\n Created by <MyName>') %(tuition, courses, weeks)
I'm assuming it's due to some math, but I didn't use a tuple in the whole program, so I'm kind of at a loss.
Any help is appreciated, thanks.
Your parentheses are in the wrong place. You probably want
plot.title('Tuition: [...]' %(tuition, courses, weeks))
instead. Right now, you're doing
plot.title('Tuition: [...]') %(tuition, courses, weeks)
so you're calling plot.title, which is returning a Text object, and then you're trying to call % on that, which gives rise to the error message:
TypeError: unsupported operand type(s) for %: 'Text' and 'tuple'
which hopefully should make more sense now. Even though you say "I didn't use a tuple in the whole program", that's exactly what (tuition, courses, weeks) is.

Categories