用户输入值计算中的TypeError [英] TypeError in calculations with user-input values
问题描述
我知道已经回答了,但是我是个超级菜鸟.我知道这与男性/女性是字符串有关,但我认为我已经定义了它?如何使计算生效?
I realize this has been answered but Im a super noob. I know it has to do with male/female being a string but I thought I had it defined? How can I get the calculation to work?
num = int(input('Please enter number of standard drinks consumed:'))
while num <= 0:
print ('Error: The number cannot be negative or zero.')
num = int(input('Please enter number of standard drinks consumed:'))
weight = int(input('Please enter weight in pounds:'))
while weight <= 0:
print ('Error: The weight cannot be negative or zero.')
weight = int(input('Please enter weight in pounds:'))
time = int(input('Please enter number of hours since first drink:'))
while time <= 0:
print ('Error: The time cannot be negative or zero.')
time = int(input('Please enter number of hours since first drink:'))
gender = input('Please enter the sex male or female:')
male = 0.68
female = 0.55
B = -0.015 * time(2.84 * num / weight * gender)
print ('The BAC is', format(B, ',.2f'))
推荐答案
别忘了,在Python中,缩进用于定义代码块.如果不缩进,则while
之后的行仅执行一次.其次,在计算BAC之前,需要将gender
变量转换为正确的数值(取决于用户输入).最后,我相信您想更改计算方式,以便实际上将乘以与time
变量.
Don't forget, in Python indentation is used to define a block of code. If not indented, the lines following while
are executed only once. Secondly, you will need to convert the gender
variable into the correct numerical value (depending on the user input) before calculating the BAC. Finally, I believe you want to change the calculation so that you are actually multiplying with thetime
variable.
这是一个演示如何解决这些问题的示例.请注意,此脚本允许用户输入一些不同的选项,并在检查gender
之前将所有内容转换为小写:
Here's an example that demonstrates how to fix these problems. Notice that this script allows a few different options for the user input, and converts everything to lower-case before checking gender
:
gender = input('Please enter the sex male or female:').lower()
while gender not in ['m', 'f', 'male', 'female']:
print ("Error: Gender must be male or female.")
gender = input('Please enter the sex male or female:').lower()
if gender in ['male', 'm']:
gender = 0.68
else:
gender = 0.55
B = -0.015 * time * 2.84 * num / weight * gender
print ('The BAC is {0:.6f}'.format(B))
我还自由地更改了格式化输出.注意,在Python 2.x中,您需要将input
替换为raw_input
以自动获取gender
值作为字符串.
I also took the liberty of changing the formatted output a bit. Note, with Python 2.x you need to replace input
with raw_input
to automatically get the gender
value as a string.
这篇关于用户输入值计算中的TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!