繁体   English   中英

如何使用我在python中创建的简单模块?

[英]How to use a simple module that I created in python?

我被困在一个非常基本和简单的问题上已经两个星期了。 我想在要使用的模块中创建一个非常简单的程序(例如,我正在使用BMI计算器)。 我写了它,但我仍然不明白为什么它不起作用。 我多次修改它以尝试找到解决方案,所以我遇到了许多不同的错误消息,但是在此程序的此版本中,消息是(在要求输入高度之后):

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

在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'

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

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

现在您将能够在height上执行数学运算。

编辑

您显示的错误表明问题发生在:

heightSq = (height)**2

但是,您提供的代码确实height转换为int。 强制转换为int可以解决您的问题。

编辑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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM