2017-10-10 61 views
1

我已经坚持了两个星期,可能是一个非常基本和简单的问题。我想创建一个非常简单的程序(例如,我正在开发一个BMI计算器),以便使用一个模块。我写了它,我仍然不明白为什么它不起作用。我修改了很多次,试图找到解决办法,所以我有很多不同的错误信息,但在这个版本我的程序中,该消息为(它要求进入高度后):如何使用我在python中创建的简单模块?

Enter you height (in inches): 70 

Traceback (most recent call last): 
File "C:/Users/Julien/Desktop/Modules/Module ex2/M02 ex2.py", line 6, in <module> 
    from modBmi import * 
    File "C:/Users/Julien/Desktop/Modules/Module ex2\modBmi.py", line 11, in <module> 
    modBmi() 
    File "C:/Users/Julien/Desktop/Modules/Module ex2\modBmi.py", line 5, in modBmi 
    heightSq = (height)**2 
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'" 

这是我的代码(信息,我的模块是一个分离的文件“modBmi.py”,但比我的主程序相同的文件夹):

#Python 3.4.3 
#BMI calculator 

def modBmi(): 
#ask the height 
    height = input ("Enter you height (in inches): ") 
    #create variable height2 
    heightSq = int(height)**2 
#ask th weight 
    weight = input ("Enter you weight (in pounds): ") 
#calculate bmi 
    bmi = int(weight) * 703/int(heighSq) 

modBmi() 

#import all informatio from modBmi 
from modBmi import * 

#diplay the result of the calculated BMI 
print("Your BMI is: " +(bmi)) 
+0

谢谢它帮助我走得更远!尽管如此,它还是说我在进入高度和体重之后测试程序时没有定义(在我的主程序中)bmi。 – Pak

+0

查看我的更新回答 – DavidG

回答

2

在Python 3.x中,input()将返回一个字符串。

height = input("Enter you height (in inches): ") 
print (type(height)) 
# <class 'str'> 

因此:

height ** 2 

将导致:

Traceback (most recent call last): 
    File "C:/Python34/SO_Testing.py", line 45, in <module> 
    height ** 2 
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' 

而这正是你所看到的错误。为了解决这个问题,只是投input结果为整数,使用int()

height = int(input("Enter you height (in inches): ")) 
print (type(height)) 
# <class 'int'> 

现在,您将能够在height进行数学运算。

编辑

你显示的错误说,问题出现的:

heightSq = (height)**2 

但是,你的代码提供了确实height为int。投射到一个int将解决你的问题。

EDIT 2

为了获得价值bmi需要return值函数外:

def modBmi(): 
#ask the height 
    height = input ("Enter you height (in inches): ") 
    #create variable height2 
    heightSq = int(height)**2 
#ask th weight 
    weight = input ("Enter you weight (in pounds): ") 
#calculate bmi 
    bmi = int(weight) * 703/int(heighSq) 

    return bmi 

bmi = modBmi() 
+0

好!非常感谢你,我想我开始明白了。但真的很感谢你!我正在感觉自己在墙前......一次又一次地感谢你! – Pak

+0

没问题,如果这回答了你的问题,不要忘了upvote和接受,以便它可以被标记为已解决。 – DavidG

相关问题