2017-10-10 58 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

相關問題