我在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'
'如果height.find( “厘米” 或 “厘米”)' - 这就像'如果height.include? (“厘米”||“厘米”)。 Python很好,但它不是魔术;尝试“厘米”高度或“厘米”高度。相同的公斤。然后,你可以使用相同的正则表达式 - 查看re模块。 – Ryan
我不确定在Ruby中有什么'height = height'和'weight = weight',但是在Python中,你可能不会将它们留在外面 – scohe001
格式化占位符的数量也不符合'(年龄,身高,体重)'你过去了。无论如何,添加错误,你试图解决这个时间将是非常有用的... – Ryan