Typeerror str object is not callable как исправить

В этой строке вы переписываете имя input и теперь в ней будет строка, которую введет пользователь, а не функция input:

input = str(input("Введите Ваш пол по цифре сверху: "))

Поэтому, при последующем вызове input, например в height = str(input("Введите Ваш рост(в сантиметрах): ")) будет та ошибка

Решение. Назовите по другому переменную для input


UPD.

Исправил код из вопроса:

def check():
    global sex, height1, weight1, height2, weight2

    print("1.Мальчик")
    print("2.Девочка")

    sex = input("Введите Ваш пол по цифре сверху: ")
    if sex == "1":
        height1 = input("Введите Ваш рост(в сантиметрах): ")
        weight1 = input("Введите Ваш вес: ")

    elif sex == "2":
        height2 = input("Введите Ваш рост(в сантиметрах): ")
        weight2 = input("Введите Ваш вес: ")

    else:
        print("Введите одну из цифр выше!")


sex, height1, weight1, height2, weight2 = ' ' * 5

check()

print(sex, height1, weight1, height2, weight2)

Typeerror: str object is not callable – How to Fix in Python

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 the str() 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

Cover image for How to fix "‘str’ object is not callable" in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The “TypeError: ‘str’ object is not callable” error occurs when you try to call a string value (str object) as if it was a function!

Here’s what the error looks like:

Traceback (most recent call last):
  File "/dwd/sandbox/test.py", line 5, in 
    print(str + str(age))
                ^^^^^^^^
TypeError: 'str' object is not callable

Enter fullscreen mode

Exit fullscreen mode

Calling a string value as if it’s a callable isn’t what you’d do on purpose, though. It usually happens due to a wrong syntax or overriding a function name with a string value.

Let’s explore the common causes and their solutions.

How to fix TypeError: ‘str’ object is not callable?

This TypeError happens under various scenarios:

  1. Declaring a variable with a name that’s also the name of a function
  2. Calling a method that’s also the name of a property
  3. Calling a method decorated with @property

Declaring a variable with a name that’s also the name of a function: A Python function is an object like any other built-in object, such as str, int, float, dict, list, etc.

All built-in functions are defined in the builtins module and assigned a global name for easier access. For instance, str() refers to the __builtins__.str() function.

That said, overriding a function (accidentally or on purpose) with a string value is technically possible.

In the following example, we have two variables named str and age. To concatenate them, we need to convert age to a string value by using the built-in str() function.

str = 'I am ' # ⚠️ str is no longer pointing to a function
age = 25

# ⛔ Raises TypeError: 'str' object is not callable
print(str + str(age))

Enter fullscreen mode

Exit fullscreen mode

If you run the above code, Python will complain with a “TypeError: ‘str’ object is not callable” error because we’ve assigned str to another value ('I am '). and 'I am ' isn’t callable.

You have two ways to fix the issue:

  1. Rename the variable str
  2. Explicitly access the str() function from the builtins module (__bultins__.str)

The second approach isn’t recommended unless you’re developing a module. For instance, if you want to implement an open() function that wraps the built-in open():

# Custom open() function using the built-in open() internally
def open(filename):
     # ...
     __builtins__.open(filename, 'w', opener=opener)
     # ...

Enter fullscreen mode

Exit fullscreen mode

In almost every other case, you should always avoid naming your variables as existing functions and methods. But if you’ve done so, renaming the variable would solve the issue.

So the above example could be fixed like this:

text = 'I am '
age = 25

print(text + str(age))
# Output: I am 25

Enter fullscreen mode

Exit fullscreen mode

This issue is common with function names you’re more likely to use as variable names. Functions such as str, type, list, dir, or even user-defined functions.

In the following example, we declare a variable named len. And at some point, when we call len() to check the input, we’ll get an error:

len = '' # ⚠️ len is set to an empty string
name = input('Input your name: ')

# ⛔ Raises TypeError: 'str' object is not callable
if (len(name)):
print(f'Welcome, {name}')

Enter fullscreen mode

Exit fullscreen mode

To fix the issue, all we need is to choose a different name for our variable:

length = ''
name = input('Input your name: ')

if (len(name)):
print(f'Welcome, {name}')

Enter fullscreen mode

Exit fullscreen mode

⚠️ Long story short, you should never use a function name (built-in or user-defined) for your variables!

Overriding functions (and calling them later on) is the most common cause of the “TypeError: ‘str’ object is not callable” error. It’s similar to calling integer numbers as if they’re callables.

Now, let’s get to the less common mistakes that lead to this error.

Calling a method that’s also the name of a property: When you define a property in a class constructor, any further declarations of the same name (e.g., methods) will be ignored.

class Book:
    def __init__(self, title):
        self.title = title

    def title(self):
        return self.title

book = Book('Head First Python')

# ⛔ Raises "TypeError: 'str' object is not callable"
print(book.title())

Enter fullscreen mode

Exit fullscreen mode

In the above example, since we have a property named title, the method title() is ignored. As a result, any reference to title will return the property title, which returns a string value. And if you call this string value like a function, you’ll get the “TypeError: ‘str’ object is not callable” error.

The name get_title sounds like a safer and more readable alternative:

class Book:
    def __init__(self, title):
        self.title = title

    def get_title(self):
        return self.title

book = Book('Head First Python')

print(book.get_title())
# Output: Head First Python

Enter fullscreen mode

Exit fullscreen mode

Calling a method decorated with @property decorator: The @property decorator turns a method into a “getter” for a read-only attribute of the same name.

class Book:
    def __init__(self, title):
        self._title = title

    @property
    def title(self):
        """Get the book price"""
        return self._title

book = Book('Head First Python')

# ⛔ Raises "TypeError: 'str' object is not callable"
print(book.title())

Enter fullscreen mode

Exit fullscreen mode

You need to access the getter method without the parentheses:

class Book:
    def __init__(self, title):
        self._title = title

    @property
    def title(self):
        """Get the book price"""
        return self._title

book = Book('Head First Python')
print(book.title)
# Output: Head First Python

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

Alright, I think it does it! I hope this quick guide helped you fix your problem.

Thanks for reading.

❤️ You might like:

  • How to fix “‘float’ object is not callable” in Python
  • How to fix “‘int’ object is not callable” in Python
  • How to fix “Not all arguments converted during string formatting error” in Python

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.

TypeError Example

TypeError Example

Like any TypeError, the ‘str’ object is not callable occurs when we try to perform an operation not supported by that datatype. In our case, here it’s the ‘string’ datatype. Let’s see some examples of where it can occur and how we can resolve them.

Example 1:

str = "This is text number 1"
string2 = "This is text number 2"

print(str(str) + string2)

In the code above, we have deliberately defined the first variable name with a reserved keyword called str. Moreover, the second variable, string2, follows Python’s naming conventions. In the print statement, we use the str method on the str variable, this confuses the Python’s interpreter, and it raises a type error, as shown in the image below.

The output of example 1

The output of example 1

Example 2:

string1 = "This is text number 1"
string2 = "This is text number 2"

print("%s %s" (string1,string2))

Contrary to example 1, where we had defined a variable with the str reserved keyword, which raised an error. In the example 2 code, we are using the ‘ % ‘ operator to perform string formatting. However, there is a minor issue in the syntax. We have omitted the % before the tuple. Missing this symbol can raise a similar error.

The output of example 2

The output of example 2

How to resolve this error?

The solution to example 1:

In Python, the str() function converts values into a string. It takes an object as an argument and converts it into a string. The str is a pre-defined function and also a reserved keyword. Therefore, it can’t be used as a variable name as per Python’s naming conventions.

To resolve the error, use another variable name.

string1 = "This is text number 1"
string2 = "This is text number 2"

print(str(string1) + string2)

Using proper naming convention, error gets resolved.

Using proper naming convention, the error gets resolved.

The solution to example 2:

In example 2, we tried to use string formatting to display string1 and string2 together. However, not using the % operator before the tuples of values TypeError: ‘str’ object is not a callable error that gets thrown. To resolve it, use the % operator in its proper place.

string1 = "This is text number 1"
string2 = "This is text number 2"

print("%s %s" %(string1,string2))

Using the % operator at its right place resolves the error

Using the % operator in its right place resolves the error

TypeError: ‘str’ object is not callable Selenium

This error is likely due to accidentally invoking a function() which is actually a property. Please check your code for this.

TypeError ‘str’ object is not callable BeautifulSoup/Django/Collab

Irrespective of the library used, this error can creep in if you have used some reserved keyword as a variable or redefined some property or a function of the library. Please check your code for such things.

TypeError ‘str’ object is not callable matplotlib

Somewhere in the code, you might have used plt.xlabel = “Some Label”. This will change the import of matplotlib.pyplot. Try to close the Notebook and restart your Kernel. After the restart, rerun your code, and everything should be fine.

FAQs

How do I fix the str object that is not callable?

To fix this error, you need to ensure that no variable is named after the str reserved keyword. Change it if this is the case.

What does str object is not callable mean?

TypeError generally occurs if an improper naming convention has been used, in other words, if the str keyword is used as a variable name.

TypeError ‘str’ object is not callable pyspark

This error is likely due to accidentally overwriting one of the PySpark functions with a string. Please check your code for this.

Conclusion

In this article, we discussed where the ‘str’ object is not callable error can occur and how we can resolve it. This is an easy error to fix. We must ensure we don’t use the reserved keywords for naming variables. In addition, we also have to avoid redefining default methods.

Trending Python Articles

  • Efficiently Organize Your Data with Python Trie

    Efficiently Organize Your Data with Python Trie

    May 2, 2023

  • [Fixed] modulenotfounderror: no module named ‘_bz2

    [Fixed] modulenotfounderror: no module named ‘_bz2

    by Namrata GulatiMay 2, 2023

  • [Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

    [Fixed] Cannot Set verify_mode to cert_none When check_hostname is Enabled

    by Namrata GulatiMay 2, 2023

  • Prevent Errors with Python deque Empty Handling

    Prevent Errors with Python deque Empty Handling

    by Namrata GulatiMay 2, 2023

This error occurs when you try to call a string as if it were a function. This error can occur if you override the built-in str() function or you try to access elements in a string using parentheses instead of square brackets.

You can solve this error by ensuring you do not override the str() function or any function names. For example:

my_str = 'Python is fun!'

my_int = 15

my_int_as_str = str(15)

If you want to access elements in a string, use square brackets. For example,

my_str = 'Python is fun!'

first_char = my_str[0]

This tutorial will go through the error in detail, and we will go through an example to learn how to solve the error.

Table of contents

  • TypeError: ‘str’ object is not callable
    • What is a TypeError?
    • What does Callable Mean?
  • Example #1: Using Parenthesis to Index a String
    • Solution
  • Example #2: String Formatting Using
    • Solution
  • Example #3: Using the Variable Name “str”
    • Solution
  • Summary

TypeError: ‘str’ object is not callable

What is a TypeError?

TypeError tells us that we are trying to perform an illegal operation for a specific Python data type.

What does Callable Mean?

Callable objects in Python have the __call__ method. We call an object using parentheses. To verify if an object is callable, you can use the callable() built-in function and pass the object to it. If the function returns True, the object is callable, and if it returns False, the object is not callable.

Let’s test the callable() built-in function with a string:

string = "research scientist"

print(callable(string))
False

We see that callable returns false on the string.

Let’s test the callable() function with the square root method from the math module:

from math import sqrt

print(callable(sqrt))
True

We see that callable returns True on the sqrt method. All methods and functions are callable objects.

If we try to call a string as if it were a function or a method, we will raise the error “TypeError: ‘str’ object is not callable.”

Example #1: Using Parenthesis to Index a String

Let’s look at an example of a program where we define a for loop over a string:

string = "research scientist"

for i in range(len(string)):

    print(string(i))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      1 for i in range(len(string)):
      2     print(string(i))
      3 

TypeError: 'str' object is not callable

To index a string, you have to use square brackets. If you use parentheses, the Python interpreter will treat the string as a callable object. Strings are not callable. Therefore you will raise the error “TypeError: ‘str’ object is not callable”.

Solution

We need to replace the parentheses with square brackets to solve this error.

string = "research scientist"

for i in range(len(string)):

    print(string[i])
r
e
s
e
a
r
c
h
 
s
c
i
e
n
t
i
s
t

The code runs with no error and prints out each character in the string.

Example #2: String Formatting Using

The TypeError can also occur through a mistake in string formatting. Let’s look at a program that takes input from a user. This input is the price of an item in a store with a seasonal discount of 10%. We assign the input to the variable price_of_item. Then we calculate the discounted price. Finally, we can print out the original price and the discounted price using string formatting.

price_of_item = float(input("Enter the price of the item"))

discount_amount = 0.1

discounted_price = price_of_item - (price_of_item * discount_amount)

rounded_discounted_price = round(discounted_price,2)

print('The original price was %s, the price after the discount is %s'(price_of_item, rounded_discounted_price))

With string formatting, we can replace the %s symbols with the values price_of_item and rounded_discounted_price. Let’s see what happens when we try to run the program.

Enter the price of the item17.99

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print('The original price was %s, the price after the discount is %s'(price_of_item, rounded_discounted_price))

TypeError: 'str' object is not callable

The code returns an error because we forgot to include the % operator to separate the string and the values we want to add to the string. The Python interpreter tries to call ‘The original price was %s, the price after 10% discount is %s‘ because the string has parentheses following it.

Solution

To solve this error, we need to add the % between the string

‘The original price was %s, the price after the discount is %s‘ and (price_of_item, rounded_discounted_price)

price_of_item = float(input("Enter the price of the item"))

discount_amount = 0.1

discounted_price = price_of_item - (price_of_item * discount_amount)

rounded_discounted_price = round(discounted_price,2)

print('The original price was %s, the price after the discount is %s'%(price_of_item, rounded_discounted_price))
Enter the price of the item17.99

The original price was 17.99, the price after the discount is 16.19

The code successfully prints the original price and the rounded price to two decimal places.

Example #3: Using the Variable Name “str”

Let’s write a program that determines if a user is too young to drive. First, we will collect the current age of the user using an input() statement. If the age is above 18, the program prints that the user is old enough to drive. Otherwise, we calculate how many years are left until the user can drive. We use the int() method to convert the age to an integer and then subtract it from 18.

Next, we convert the value to a string to print to the console. We convert the value to a string because we need to concatenate it to a string.

str = input("What is your age? ")

if int(str) >= 18:

    print('You are old enough to drive!')

else:

    years_left = 18 - int(str)

    years_left = str(years_left)

    print('You are not old enough to drive, you have ' + years_left + ' year(s) left')


Let’s see what happens when we run the program:

What is your age? 17

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
      3 else:
      4     years_left = 18 - int(str)
      5     years_left = str(years_left)
      6     print('You are not old enough to drive, you have ' + years_left + ' year(s) left')
      7 

TypeError: 'str' object is not callable

We raise the error “TypeError: ‘str’ object is not callable” because we tried to use the str() method to convert the integer value years_left. However, earlier in the program we declared a variable called “str“. From that point on, the Python interpreter sees “str” as a string in the program and not a function. Therefore, when we try to call str() we are instead trying to call a string.

Solution

To solve this error, we need to rename the user input to a suitable name that describes the input. In this case, we can use “age“.

age = input("What is your age? ")

if int(age) >= 18:

    print('You are old enough to drive!')

else:

    years_left = 18 - int(age)

    years_left = str(years_left)

    print('You are not old enough to drive, you have ' + years_left + 'year(s) left')

Now we have renamed the variable, we can safely call the str() function. Let’s run the program again to test the outcome.

What is your age? 17

You are not old enough to drive, you have 1 year(s) left

The code runs and tells the user they have 1 year left until they can drive.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on the ‘not callable’ TypeError, go to the article: How to Solve Python TypeError: ‘module’ object is not callable.

Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Добавить комментарий