The first error is in the line
ans = raw_input().lower()("This is one of those times when only Yes/No will do!"
"n" "So what will it be? Yes? No?")
The result of lower()
is a string, and parentheses after that mean that the object on the left (the string) gets called. Therefore, you get your error. You want
ans = raw_input("This is one of those times when only Yes/No will do!n"
"So what will it be? Yes? No?").lower()
Also,
if ans() == 'yes' or 'no':
does not what you expect. Again, ans
is a string, and parentheses mean that the object on the left (the string) gets called. Therefore, you get your error.
Also, or
is a logical operator. Even after removing the parentheses after ans
, the code gets evaluated as:
if (ans == 'yes') or ('no'):
Since a non-empty string ('no'
) evaluates to the boolean value True, this expression is always True. You simply want
if ans in ('yes', 'no'):
Additionally, you want to unindent the last lines. All in all, try:
name = raw_input("Welcome soldier. What is your name? ")
print('Ok, ' + name + ' we need your help.')
ans = raw_input("Do you want to help us? (Yes/No)").lower()
while True:
if ans in ('yes', 'no'):
break
print("This is one of those times when only Yes/No will do!n")
ans = raw_input("So what will it be? Yes? No?").lower()
if ans == "yes":
print("Good!")
elif ans == "no":
print("I guess I was wrong about you..." 'n' "Game over.")
Every programming language has certain keywords with specific, prebuilt functionalities and meanings.
Naming your variables or functions after these keywords is most likely going to raise an error. We’ll discuss one of these cases in this article — the TypeError: 'str' object is not callable
error in Python.
The TypeError: 'str' object is not callable
error mainly occurs when:
- You pass a variable named
str
as a parameter to thestr()
function. - When you call a string like a function.
In the sections that follow, you’ll see code examples that raise the TypeError: 'str' object is not callable
error, and how to fix them.
Example #1 – What Will Happen If You Use str
as a Variable Name in Python?
In this section, you’ll see what happens when you used a variable named str
as the str()
function’s parameter.
The str()
function is used to convert certain values into a string. str(10)
converts the integer 10
to a string.
Here’s the first code example:
str = "Hello World"
print(str(str))
# TypeError: 'str' object is not callable
In the code above, we created a variable str
with a value of «Hello World». We passed the variable as a parameter to the str()
function.
The result was the TypeError: 'str' object is not callable
error. This is happening because we are using a variable name that the compiler already recognizes as something different.
To fix this, you can rename the variable to a something that isn’t a predefined keyword in Python.
Here’s a quick fix to the problem:
greetings = "Hello World"
print(str(greetings))
# Hello World
Now the code works perfectly.
Example #2 – What Will Happen If You Call a String Like a Function in Python?
Calling a string as though it is a function in Python will raise the TypeError: 'str' object is not callable
error.
Here’s an example:
greetings = "Hello World"
print(greetings())
# TypeError: 'str' object is not callable
In the example above, we created a variable called greetings
.
While printing it to the console, we used parentheses after the variable name – a syntax used when invoking a function: greetings()
.
This resulted in the compiler throwing the TypeError: 'str' object is not callable
error.
You can easily fix this by removing the parentheses.
This is the same for every other data type that isn’t a function. Attaching parentheses to them will raise the same error.
So our code should work like this:
greetings = "Hello World"
print(greetings)
# Hello World
Summary
In this article, we talked about the TypeError: 'str' object is not callable
error in Python.
We talked about why this error might occur and how to fix it.
To avoid getting this error in your code, you should:
- Avoid naming your variables after keywords built into Python.
- Never call your variables like functions by adding parentheses to them.
Happy coding!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Table of Contents
Hide
- What is typeerror: ‘str’ object is not callable in Python?
- Scenario 1 – Declaring a variable name called “str”
- Solving typeerror: ‘str’ object is not callable in Python.
- Scenario 2 – String Formatting Using %
One of the most common errors in Python programming is typeerror: ‘str’ object is not callable, and sometimes it will be painful to debug or find why this issue appeared in the first place.
Python has a built-in method str()
which converts a specified value into a string. The str()
method takes an object as an argument and converts it into a string.
Since str()
is a predefined function and a built-in reserved keyword in Python, you cannot use it in declaring it as a variable name or a function name. If you do so, Python will throw a typeerror: ‘str‘ object is not callable.
Let us take a look at few scenarios where you could reproduce this error.
Scenario 1 – Declaring a variable name called “str”
The most common scenario and a mistake made by developers are declaring a variable named ‘str
‘ and accessing it. Let’s look at a few examples of how to reproduce the ‘str’ object is not callable error.
str = "Hello, "
text = " Welcome to ItsMyCode"
print(str(str + text))
# Output
Traceback (most recent call last):
File "c:ProjectsTryoutslistindexerror.py", line 4, in <module>
print(str(str + text))
TypeError: 'str' object is not callable
In this example, we have declared ‘str
‘ as a variable, and we are also using the predefined str()
method to concatenate the string.
str = "The cost of apple is "
x = 200
price= str(x)
print((str + price))
# output
Traceback (most recent call last):
File "c:ProjectsTryoutslistindexerror.py", line 3, in <module>
price= str(x)
TypeError: 'str' object is not callable
The above code is similar to example 1, where we try to convert integer x into a string. Since str
is declared as a variable and if you str()
method to convert into a string, you will get object not callable error.
Solving typeerror: ‘str’ object is not callable in Python.
Now the solution for both the above examples is straightforward; instead of declaring a variable name like “str” and using it as a function, declare a more meaningful name as shown below and make sure that you don’t have “str” as a variable name in your code.
text1 = "Hello, "
text2 = " Welcome to ItsMyCode"
print(str(text1 + text2))
# Output
Hello, Welcome to ItsMyCode
text = "The cost of apple is "
x = 200
price= str(x)
print((text + price))
# Output
The cost of apple is 200
Scenario 2 – String Formatting Using %
Another hard-to-spot error that you can come across is missing the %
character in an attempt to append values during string formatting.
If you look at the below code, we have forgotten the string formatting %
to separate our string and the values we want to concatenate into our final string.
print("Hello %s its %s day"("World","a beautiful"))
# Output
Traceback (most recent call last):
File "c:ProjectsTryoutslistindexerror.py", line 1, in <module>
print("Hello %s its %s day"("World","a beautiful"))
TypeError: 'str' object is not callable
print("Hello %s its %s day"%("World","a beautiful"))
# Output
Hello World its a beautiful day
In order to resolve the issue, add the %
operator before replacing the values ("World","a beautiful")
as shown above.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
So you have encountered the exception, i.e., TypeError: ‘str’ object is not callable. In the following article, we will discuss type errors, how they occur and how to resolve them.
What is a TypeError?
The TypeError occurs when you try to operate on a value that does not support that operation. The most common reason for an error in a Python program is when a certain statement is not in accordance with the prescribed usage. The Python interpreter immediately raises a type error when it encounters an error, usually along with an explanation. For instance:
val1 = 100 val2 = "random text" print(val1/val2)
When you try to divide an integer value with a string, it results in a type error.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.