翻译If / Else&& RegEx - Ruby to Python

时间:2013-08-25 22:18:11

标签: python regex

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

这一行不符合你的想法:

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

除了缺少:(可能是拼写错误)之外,代码不会有两个原因:

    如果找不到任何内容,则
  • str.find()会返回-1,如果在开头找到搜索到的字符串,则00在布尔上下文中被视为False,您应该测试> -1

  • 您没有测试'centimeters' or 'cm'。您只是在测试'centimeters'。首先评估or表达式,并且短路以返回第一个True - ish值,第一个非空字符串,在这种情况下为'centimeters'

    < / LI>

你应该而不是使用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