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

标签 python python-3.x

两周以来,我一直被一个非常基本且简单的问题困扰。我想在我想要使用的模块中创建一个非常简单的程序(例如,我正在开发 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'>

现在您将能够对高度执行数学运算。

编辑

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

heightSq = (height)**2

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

编辑2

为了在函数外部获取 bmi 的值,您需要返回该值:

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

关于python - 如何使用我在 python 中创建的简单模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46669326/

相关文章:

python - “实体”对象没有值 'Width'

python-3.x - 如何向 Pandas 数据框列添加尾随零?

python - 如何在完整验证示例上评估 Tensorflow 模型

python - 如果它不是函数,则将项目添加到列表中

python - 使用按钮更新 Matplotlib 中的注释

python - 如何将原始字节数组作为二进制文件写入谷歌云存储

python - 如何使用 paramiko 启动后台作业?

python - Sklearn语法错误?

python - 如何在python 3中发送post文件(图像)

python - 如何在 python 类的 init 中自动设置 self 属性?