Меню

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

27.7k6 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’

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

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

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

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

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

  • #4

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

alext


  • #5

Python:

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

I’m attempting to compute the class_weights for an highly imbalanced set of 9 classes based on the examples discussed in How to set class weights for imbalanced classes in Keras?. Here is the code:

import numpy as np
import math

# labels_dict : {ind_label: count_label}
# mu : parameter to tune 

def create_class_weight(labels_dict,mu=0.15):
    total = np.sum(labels_dict.values())
    keys = labels_dict.keys()
    class_weight = dict()

    for key in keys:
        score = math.log(mu*total/float(labels_dict[key]))
        class_weight[key] = score if score > 1.0 else 1.0

    return class_weight

# random labels_dict
labels_dict = {0: 3400, 1: 1700, 2: 4700, 3: 6800, 4: 3400, 5: 2300, 6: 8300, 7: 1000, 8:9600}

create_class_weight(labels_dict)

I’m getting an error log like this:

 File "<ipython-input-34-7a9feda1053b>", line 20, in <module>
    create_class_weight(labels_dict)

  File "<ipython-input-34-7a9feda1053b>", line 11, in create_class_weight
    score = math.log(mu*total/float(labels_dict[key]))

TypeError: unsupported operand type(s) for *: 'float' and 'dict_values'

I’m running the code with Python 3.6.3. What modifications am I supposed to make?

& — это побитовый оператор, я думаю, вы искали логическое значение and.

Но обратите внимание, что Python также поддерживает следующий синтаксис:

if 18.5 < bmi1 < 24.9:
    # ...

Поскольку вы, похоже, столкнулись с отступами, вот как может выглядеть ваш скрипт:

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"

Есть пара небольших улучшений:

  • Явное преобразование (поскольку в Python 3 input функция ведет себя как raw_input и нет ничего лучше Python 2 input, это может быть хорошей привычкой писать свой вклад таким образом)
  • Что действительно меняется, так это bmi значение, поэтому нет необходимости писать два раза одно и то же.

Осталось кое-что сделать, возможно, весь скрипт завернуть в функции 🙂

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Unidrive m300 коды ошибок
  • Unrouteable address ошибка почты