Unsupported operand type s for float and float ошибка

I wrote this simple program to calculate one’s BMI. But I am unable to execute it complete. Below is my program,

PROGRAM

h = input("Please Enter your height in meters:")
q = raw_input("Do you want to enter your weight in kg or lbs?")

if q=="kg":
         w1 = input("Please Enter your weight in kgs:")
         bmi1 = w1/(h*h) 
         print "Your BMI is", bmi1

         if bmi1 <= 18.5: 
                        print "Your are underweight."
         if bmi1 > 18.5 & bmi1 < 24.9: 
                                     print "Your weight is normal."
         if bmi1 > 25 & bmi1 < 29.9: 
                                   print "Your are overweight"              
         if bmi1 >= 30: 
                      print "Your are obese"                    


if q=="lbs":
          w2 = input("Please Enter your weightin lbs:")
          bmi2 = w2/((h*h)*(39.37*39.37)*703) 
          print "Your BMI is:", bmi2

          if bmi2<= 18.5: 
                        print "Your are underweight."
          if bmi2>18.5 & bmi2<24.9: 
                                  print "Your weight is normal."
          if bmi2>25 & bmi2<29.9: 
                                print "Your are overweight"         
          if bmi2>=30: 
                     print "Your are obese" 

OUTPUT

Please Enter your height in meters:1.52
Do you want to enter your weight in kg or lbs?kg
Please Enter your weight in kgs:51
Your BMI is 22.074099723
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "bmi.py", line 11, in <module>
    if bmi1 > 18.5 & bmi1 < 24.9: 
TypeError: unsupported operand type(s) for &: 'float' and 'float'

Where am I going wrong? Anyone just let me know..

Thanks :).

asked Apr 20, 2012 at 12:39

user1345589's user avatar

& is a bitwise operator, I think you were looking for the boolean and.

But notice that Python also supports the following syntax:

if 18.5 < bmi1 < 24.9:
    # ...

Since you seemed to have trobled with indentation this is how your script might look like:

h = raw_input("Please enter your height in meters: ")
h = float(h)
w_unit = raw_input("Do you want to enter your weight in kg or lbs? ")
w = raw_input("Please enter your weight in {}: ".format(w_unit))
w = int(w)
if w_unit == "kg":
    bmi = w / (h*h)
elif w_unit == "lbs":
    bmi = w / ((h*h) * (39.37 * 39.37) * 703)

print "Your BMI is {:.2f}".format(bmi)
if bmi <= 18.5: 
    print "Your are underweight."
elif 18.5 < bmi <= 25: 
    print "Your weight is normal."
elif 25 < bmi < 30: 
    print "Your are overweight"              
elif bmi >= 30:
    print "Your are obese"

There are a couple of slight improvements:

  • The explicit conversion (since in Python 3 the input function behave like raw_input and there’s nothing like the Python 2 input, it might be a good habit to write your input like that)
  • What really changes is the bmi value, so there’s no need to write two times the same thing.

Something left to do, might be wrap the whole script into functions :)

answered Apr 20, 2012 at 12:41

Rik Poggi's user avatar

Rik PoggiRik Poggi

28.1k6 gold badges64 silver badges82 bronze badges

3

  • #1

1)Windows 10
2) Python 3.8
3) 1607019877424.png — нужно вычислить сумму.
Вот код, я только начал изучать Python, поэтому и не знаю, как решить такую задачу.

Код:

a=float(input("zadayte a="))
x=float(input("zadayte x="))
suma=(a+1/x+a+2/2*x^2+a+3/3*x^3)
print("suma")

4) Ошибка
suma=(a+1/x+a+2/2*x^2+a+3/3*x^3)
TypeError: unsupported operand type(s) for ^: ‘float’ and ‘float’


0

  • #2

в питоне степень это **

Python:

a = float(input("zadayte a="))
x = float(input("zadayte x="))
suma = (a + 1 / x + a + 2 / 2 * x ** 2 + a + 3 / 3 * x ** 3)
print(suma)

но это вашу задачу не решает…


0

  • #3

в питоне степень это **

Python:

a = float(input("zadayte a="))
x = float(input("zadayte x="))
suma = (a + 1 / x + a + 2 / 2 * x ** 2 + a + 3 / 3 * x ** 3)
print(suma)

но это вашу задачу не решает…

Не подскажете, что нужно изменить в коде?


0

  • #4

добавить переменную ‘n’ и в цикле складывать дроби до значения ‘n’…


0

alext


  • #5

Python:

def go(a, x, n):
    return sum((a + i) / (i * x**i) for i in range(1, n+1))

Florian Lindner


  • #1

Hello,
I get the exception above when trying to use a float as radix and exponent,
e.g.:
Traceback (most recent call last):
File «<stdin>», line 1, in ?
TypeError: unsupported operand type(s) for ^: ‘float’ and ‘float’

How can I use floats for powers?

Thanks,

Florian

Advertisements

benc


  • #2

Traceback (most recent call last):
File «<stdin>», line 1, in ?
TypeError: unsupported operand type(s) for ^: ‘float’ and ‘float’

That operator… I do not think it means what you think it means.
‘0x1100’

^ is the bitwise XOR operator. For exponentiation, use **.
1301.326396639844

Hope that helps,
—Ben

Want to reply to this thread or ask your own question?

You’ll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.


Ask a Question

azat123

0 / 0 / 0

Регистрация: 26.04.2013

Сообщений: 29

1

11.05.2013, 17:50. Показов 195679. Ответов 2

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Python
1
2
3
4
5
6
7
import math
from math import tan, atan, log10, cos , sin
x=input("Введи х")
v= x-tan(2)
u=4*atan(1)+log10(x)
y=cos(u)+8*sin(3*v)
print (round(y,3))

Почему то выходит ошибка:

Python
1
2
3
4
5
Введи х 3
Traceback (most recent call last):
  File "C:Python33programzadacha1.py", line 4, in <module>
    v= x-tan(2)
TypeError: unsupported operand type(s) for -: 'str' and 'float'

Что нужно сделать?



0



ilnurgi

141 / 141 / 38

Регистрация: 20.02.2012

Сообщений: 597

11.05.2013, 18:08

2

Цитата
Сообщение от azat123
Посмотреть сообщение

Что нужно сделать?

взять переводчик и перевести текст ошибки.

Цитата
Сообщение от azat123
Посмотреть сообщение

Python
1
TypeError: unsupported operand type(s) for -: 'str' and 'float'

не поддерживаемый оператор -, строка и флоат.
следовательно вы хотите из строки вычесть float число.
следовательно строку надо перевести либо в int, int(x), либо в float -> float(x)



1



voxfoot

0 / 0 / 1

Регистрация: 25.01.2013

Сообщений: 4

13.05.2013, 12:57

3

Python
1
x=int(input("Введи х"))



0



As a developer, you may encounter the error message: «TypeError: unsupported operand type(s) for +: ‘float’ and ‘str'» while working on your code. This error message occurs when you try to concatenate a string and a float value, which is not supported in Python. In this guide, we will provide you with valuable information on this error message, its causes, and solutions.

Causes of ‘Unsupported Operand Type(s) for +: ‘float’ and ‘str’ Error

This error message occurs when you try to concatenate a string and a float value using the «+» operator. Python does not support this operation, as it only allows concatenation between strings. Therefore, when you try to concatenate a string and a float value, Python raises a «TypeError: unsupported operand type(s) for +: ‘float’ and ‘str'» error message.

Solutions to ‘Unsupported Operand Type(s) for +: ‘float’ and ‘str’ Error

There are several ways to fix this error message, depending on the context of your code. Here are some solutions you can try:

Convert the float value to a string:

You can convert the float value to a string using the str() function before concatenating it with the string value. Here’s an example:

age = 25
print("My age is " + str(age))

This will output: My age is 25

Use string formatting:

You can use string formatting to concatenate a string and a float value. Here’s an example:

age = 25
print("My age is {}".format(age))

This will output: My age is 25

Use f-strings:

You can use f-strings to concatenate a string and a float value. Here’s an example:

age = 25
print(f"My age is {age}")

This will output: My age is 25

FAQ

Q1. What is the ‘unsupported operand type(s) for +: ‘float’ and ‘str’ error message?

A1. This error message occurs when you try to concatenate a string and a float value using the «+» operator, which is not supported in Python.

Q2. How do I fix the ‘unsupported operand type(s) for +: ‘float’ and ‘str’ error message?

A2. You can fix this error message by converting the float value to a string, using string formatting, or using f-strings.

Q3. Can I concatenate a string and an integer value in Python?

A3. Yes, you can concatenate a string and an integer value in Python using the «+» operator.

Q4. What other Python operators can I use to concatenate strings?

A4. You can use the «+=» operator or the join() method to concatenate strings in Python.

Q5. How can I avoid the ‘unsupported operand type(s) for +: ‘float’ and ‘str’ error message in my code?

A5. To avoid this error message, make sure that you are only concatenating strings with strings and floats with floats in your code.

  • Python String Formatting Guide
  • Python f-strings Guide

Понравилась статья? Поделить с друзьями:
  • Unrecognized upnp response ошибка upnp wizard
  • Unrecognized command line option ошибка
  • Unreal engine ошибка при запуске игры
  • Unreal engine ошибка ls 0019
  • Unreal engine код ошибки e10 0