The question:

# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.

# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string ’89’

# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.

# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)

My answer:
x = 27.83
rounded = round(x)
convert_to_string = str(rounded)
before_decimal = convert_to_string.find(‘.’)
print convert_to_string[0:before_decimal]

… Okay, okay, this probably isn’t that impressive, given that I’d already gone through most of Learn Python the Hard Way before I decided to revisit Udacity, and at this point I’m comfortable enough to google and understand Python documentation when I need to.

However, I *do* remember struggling with this last year when I first went tried out Udacity. So — yay for being self-aware about how I’m improving, I guess!

One very simple python function I used that the official Udacity answer didn’t use (they just manually added 0.5 to x):


blog comments powered by Disqus
  • Hi, I'm Linda! I enjoy going to tech meetups, learning web development, and blogging about the learning path. Follow me @LPnotes

Subscribe to The Coding Diaries