Ruby
#!/usr/bin/ruby
# The Dog year calculator program called dogyears.rb
def dogyears
# get the original age
puts “Enter your age (in human years): "
age = gets # gets is a method for input from keyboard
puts # is a method or operator for screen output
#do some range checking, then print result
if age <0
puts "Negative age?!? I don't think so."
elsif age > 110
puts "Frankly, I don't believe you."
else
puts "That's", age*7, "in dog years."
end
dogyears
Python
#!/usr/bin/python
# The Dog year calculator program called dogyears.py
def dogyears():
# get the original age
age = input("Enter your age (in human years): ")
print # print a blank line
# do some range checking, then print result
if age <0
print "Negative age?!? I don't think so."
elif age > 110:
print "Frankly, I don't believe you."
else:
print "That's", age*7, "in dog years."
### pause for Return key (so window doesn't disappear)
raw_input('press Return>')
def main():
dogyears()
main()
Answer:
The codes of Ruby and Python are very similar. They first accepts the input from keyboard. The input represents year-old. Then, they verify the input to see whether the input is in reasonable range. If so, they will calculate and print the result.
The difference of the codes is ....
1. Ruby uses "puts" to output on screen when Python uses "print" to output.
2. Ruby uses the reserved words "elsif" buy Python uses "elif"
3. Ruby needs "end" to complete the if-then-else, whereas, Python does not need.
4. Ruby uses "def dogyears" to define the dog years class while Python uses "def dogyears()"
5. Ruby does not need main() class when Python needs main() class
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment