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.2k6 gold badges64 silver badges82 bronze badges

3

To fix the TypeError: Unsupported operand type(s) for *: float and decimal.Decimal in Python. I will do the object conversion, use the Decimal module and check the object type. Post details below.

The error happens when you multiply a float object by a decimal object.

Example: 

from decimal import Decimal

valueFloat = 1.2
decimalObj = Decimal('1.2')
print(valueFloat * decimalObj)

Output:

Traceback (most recent call last):
  File "./prog.py", line 5, in <module>
TypeError: unsupported operand type(s) for *: 'float' and 'decimal.Decimal'

How to solve this error?

Converting float to decimal

To avoid the error, all you need to do is converting the float object to a decimal number.

Example:

  • Converting float to the decimal object using the Decimal() function.
  • Multiplying 2 decimal objects will not throw an error.
from decimal import Decimal

valueFloat = 1.2

# Float object converts to decimal.
valueFloat = Decimal(valueFloat)

decimalVar = Decimal(1.2)
print('Multiplication result:', valueFloat * decimalVar)

Output:

Multiplication result: 1.439999999999999893418589636

Or you can convert Decimal objects to floats using the float() function and multiply them together.

Example:

from decimal import Decimal

valueFloat = 1.2
decimalVar = Decimal(1.2)

# Decimal object converts to float.
decimalVar = float(decimalVar)
print('Multiplication result:', valueFloat * decimalVar)

Output:

Multiplication result: 1.44

Using the Decimal Module

Example:

  • Import the Decimal module.
  • Implement the decimal object using the Decimal() function from the Decimal module.
  • Perform rounding to 2 digits after the decimal point using the getcontext() function.
from decimal import Decimal, getcontext

firstDecimalFactor = Decimal(1.2)
secondDecimalFactor = Decimal(2.4)

# The getcontext() function rounds the math.
# Get 2 numbers after the decimal point.
getcontext().prec = 2
print('Multiplication result:', firstDecimalFactor * secondDecimalFactor)

Output:

Multiplication result: 2.9

When you enclose numbers in single quotes, the results are automatically rounded.

Example:

from decimal import Decimal

firstDecimalFactor = Decimal('1.2')
secondDecimalFactor = Decimal('2.4')
print('Multiplication result:', firstDecimalFactor * secondDecimalFactor)

Output:

Multiplication result: 2.88

Checking the decimal object

To check if an object is a decimal object, use the isinstance() function or the type() function.

Example:

from decimal import Decimal

firstDecimalFactor = Decimal('1.2')

# Use the isinstance() function to check.
print('Here is the decimal object:', isinstance(firstDecimalFactor, Decimal))

# Use the type() function to check.
print('What object is this?', type(firstDecimalFactor))

Output:

Here is the decimal object: True
What object is this? <class 'decimal.Decimal'>

Summary

The topic TypeError: Unsupported operand type(s) for *: float and decimal.Decimal done. You can use the Decimal module to solve this problem. It is pretty convenient. If you have any comments on the article, please leave a comment below.

Maybe you are interested:

  • TypeError: unsupported operand type(s) for -: str and int
  • TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘str’

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

  • #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))

azat123

0 / 0 / 0

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

Сообщений: 29

1

11.05.2013, 17:50. Показов 196940. Ответов 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



by: DJ Craig |
last post by:

I keep getting this error:
Fatal error: Unsupported operand types in
/usr/local/etc/httpd/htdocs/djtricities/kat/bpmchart/chart.php on line
58

I’ve looked for hours for some type of error, and…

by: Martin Koekenberg |
last post by:

Hello,

Ik get the following error when I install a new Python software
package such as Zope or PIL.

This is what I get whem I ‘make’ Zope :

running build_ext
Traceback (most recent call…

by: Rakesh |
last post by:

In my Python code fragment, I want to write a code fragment such that
the minimum element of a tuple is subtracted from all the elements of a
given
tuple.

When I execute the following python…

by: H. S. |
last post by:

Hi,

I am trying to compile these set of C++ files and trying out class
inheritence and function pointers. Can anybody shed some light why my
compiler is not compiling them and where I am going…

by: yaffa |
last post by:

hey folks i get this error: Python interpreter error: unsupported operand
type(s) for |:

when i run this line of code:

for incident in bs(‘tr’, {‘bgcolor’ : ‘#eeeeee’} | {‘bgcolor’ :…

by: tanusreesen |
last post by:

Hi All,
I am completely new to python programming language.I was trying to write a program on class.But I am getting this error.Can someone please help me to solve the error I am facing.I…

by: somenath |
last post by:

Hi All,
I am trying to undestand «Type Conversions» from K&R book.I am not
able to understand the
bellow mentioned text
«Conversion rules are more complicated when unsigned operands are…

by: Gilbert Fine |
last post by:

This is a very strange exception raised from somewhere in our program.
I have no idea how this happen. And don’t know how to reproduce. It
just occurs from time to time.

Can anyone give me some…

by: Jordan Harry |
last post by:

I’m trying to write a simple program to calculate permutations. I created a file called «mod.py» and put the following in it:

def factorial(n):
a = n
b = n
while a>0 and b>1:
n = (n)*(b-1)…

by: WisdomUfot |
last post by:

It’s an interesting question you’ve got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don’t have the specific technical details, Gmail likely implements measures…

by: Carina712 |
last post by:

Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important…

by: Rahul1995seven |
last post by:

Introduction:
In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts…

by: jack2019x |
last post by:

hello, Is there code or static lib for hook swapchain present?

I wanna hook dxgi swapchain present for dx11 and dx9.

DizelArs

by: DizelArs |
last post by:

Hi all)

Faced with a problem, element.click() event doesn’t work in Safari browser.
Tried various tricks like emulating touch event through a function:

let clickEvent = new Event(‘click’, {…

by: antdb |
last post by:

Ⅱ. Download AntDB Community Version
Download at: http://www.antdb.net/download, choose X86 version under Open Euler
https://img1.imgtp.com/2023/06/14/hn1P9Kz2.png

Ⅲ. Deploy AntDB Community…

ADezii

by: ADezii |
last post by:

What is the best, comprehensive Reference for programming Windows Applications in VB.NET. I have experience in programming in general, but not VB.NET. Thanks in advance.

isladogs

by: isladogs |
last post by:

I have been asked to publicise the next meeting of the UK Access User Group which will be on Thur 22 June from 16:00 to 17:30 UK time (UTC+1)
The meeting is free and open to all (both members and…

by: antdb |
last post by:

B.Distributed Deployment

1). Deploy the distributed software
sh antdb_install.sh ### the difference between distributed and centralized software deployment is as follows…

  • Unsupported command 7 zip ошибка
  • Unrouteable address ошибка почты
  • Unresolved reference python ошибка
  • Unresolved reference android studio ошибка
  • Unrecognized upnp response ошибка upnp wizard