2013-08-25 107 views
-1

我在Ruby中编写了一个程序,它将用户的体重/身高作为输入。我坚持将其转换为Python。这是我的Ruby代码,它工作正常:翻译If/Else && RegEx - Ruby翻译为Python

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

'如果height.find( “厘米” 或 “厘米”)' - 这就像'如果height.include? (“厘米”||“厘米”)。 Python很好,但它不是魔术;尝试“厘米”高度或“厘米”高度。相同的公斤。然后,你可以使用相同的正则表达式 - 查看re模块。 – Ryan

+2

我不确定在Ruby中有什么'height = height'和'weight = weight',但是在Python中,你可能不会将它们留在外面 – scohe001

+0

格式化占位符的数量也不符合'(年龄,身高,体重)'你过去了。无论如何,添加错误,你试图解决这个时间将是非常有用的... – Ryan

回答

1

你有其他的问题,但你会遇到的第一个问题是,ifelse语句需要冒号在该行的末尾引入块。

1

此行不会做你认为它的作用:

if height.find("centimeters" or "cm") 
从丢失 :(想必这是一个错字),代码将无法原因有二

除了:

  • str.find()返回-1如果找不到任何内容,0如果在开始处找到搜索字符串。 0在布尔上下文中被认为是False,您应该测试> -1

  • 您没有测试任何'centimeters' or 'cm'。您只在测试'centimeters'。首先对or表达式进行求值,然后短路返回第一个非空字符串值,即'centimeters'。在这种情况下,该值为'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