-1

我用 Ruby 编写了一个程序,将用户的体重/身高作为输入。我坚持将其转换为 Python。这是我的 Ruby 代码,效果很好:

print "How tall are you?"
height = gets.chomp()
if height.include? "centimeters"
     #truncates everything but numbers and changes the user's input to an integer
    height = height.gsub(/[^0-9]/,"").to_i / 2.54
else
    height = height
end

print "How much do you weigh?"
weight = gets.chomp()
if weight.include? "kilograms"
    weight = weight.gsub(/[^0-9]/,"").to_i * 2.2 
else
    weight = weight 
end

puts "So, you're #{height} inches tall and #{weight} pounds heavy."

有人对我如何翻译这个有任何提示或指示吗?这是我的 Python 代码:

print "How tall are you?",
height = raw_input()
if height.find("centimeters" or "cm")
    height = int(height)  / 2.54
else
    height = height

print "How much do you weight?",
weight = raw_input()
if weight.find("kilograms" or "kg")
    weight = int(height) * 2.2
else
    weight = weight

print "So, you're %r inches tall and %r pounds heavy." %(height, weight)

它没有运行。这是我得到的错误:

MacBook-Air:Python bdeely$ python ex11.py
How old are you? 23
How tall are you? 190cm
Traceback (most recent call last):
  File "ex11.py", line 10, in <module>
    height = int(height) / 2.54
ValueError: invalid literal for int() with base 10: '190cm'
4

2 回答 2

1

这条线不会做你认为它做的事情:

if height.find("centimeters" or "cm")

除了缺少:(可能是错字)之外,代码无法正常工作有两个原因:

  • str.find()-1如果没有找到,则返回,0如果在开始时找到搜索的字符串。0在布尔上下文中考虑False,您应该改为测试> -1.

  • 您没有测试任何一个'centimeters' or 'cm'。您只是在测试'centimeters'. 首先计算or表达式,然后短路以返回第一个True-ish 值,第一个非空字符串,所以'centimeters'在这种情况下。

您应该改为使用以下方法测试字符串是否存在in

if 'centimeters' in height or 'cm' in height:

演示:

>>> height = '184cm'
>>> height.find("centimeters" or "cm")
-1
>>> 'centimeters' in height or 'cm' in height
True
>>> height = '184 centimeters'
>>> height.find("centimeters" or "cm")
4
>>> 'centimeters' in height or 'cm' in height
True
>>> height = 'Only fools and horses'
>>> height.find("centimeters" or "cm")
-1
>>> 'centimeters' in height or 'cm' in height
False

您的下一个问题是,您int()不喜欢输入文本中的额外文本。您已经确定'centimeter'存在,这就是引发异常的原因。

您可以使用正则表达式,例如 Ruby 代码:

import re

height = int(re.search('(\d+)', height).group(1)) / 2.54

演示:

>>> import re
>>> height = '184cm'
>>> int(re.search('(\d+)', height).group(1)) / 2.54
72.44094488188976
>>> height = '184 centimeters'
>>> int(re.search('(\d+)', height).group(1)) / 2.54
72.44094488188976
于 2013-08-25T22:56:01.987 回答
1

您还有其他问题,但您将遇到的第一个问题是ifandelse语句需要在行尾使用冒号来引入块。

于 2013-08-25T22:29:17.670 回答