Вопрос по информатике:
Что я не правильно написал? Начал учить Python, как решить ошибку: TypeError: 'str' object is not callable?
Код: profesion = str(input("Ким ви хочете стати? ")) age = int(input("Через скільки років? ")) res = (f"Через {age} років, вы станете {profesion}") print (profesion, age, res)
Трудности с пониманием предмета? Готовишься к экзаменам, ОГЭ или ЕГЭ?
Воспользуйся формой подбора репетитора и занимайся онлайн. Пробный урок - бесплатно!
- 03.06.2023 20:13
- Информатика
- remove_red_eye 93
- thumb_up 2
Ответы и объяснения 1
Ответ:
По умолчанию функция input()
конвертирует всю получаемую информацию в строку.
Возможно здесь не нужно ставить str: profesion = str(input("Ким ви хочете стати? "))
Теория по этой ошибке:
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!
- 04.06.2023 20:17
- thumb_up 0
Знаете ответ? Поделитесь им!
Как написать хороший ответ?
Чтобы добавить хороший ответ необходимо:
- Отвечать достоверно на те вопросы, на которые знаете правильный ответ;
- Писать подробно, чтобы ответ был исчерпывающий и не побуждал на дополнительные вопросы к нему;
- Писать без грамматических, орфографических и пунктуационных ошибок.
Этого делать не стоит:
- Копировать ответы со сторонних ресурсов. Хорошо ценятся уникальные и личные объяснения;
- Отвечать не по сути: «Подумай сам(а)», «Легкотня», «Не знаю» и так далее;
- Использовать мат - это неуважительно по отношению к пользователям;
- Писать в ВЕРХНЕМ РЕГИСТРЕ.
Есть сомнения?
Не нашли подходящего ответа на вопрос или ответ отсутствует? Воспользуйтесь поиском по сайту, чтобы найти все ответы на похожие вопросы в разделе Информатика.
Трудности с домашними заданиями? Не стесняйтесь попросить о помощи - смело задавайте вопросы!
Информатика — наука о методах и процессах сбора, хранения, обработки, передачи, анализа и оценки информации с применением компьютерных технологий, обеспечивающих возможность её использования для принятия решений.