I decided that I would devote myself fully to learning Python, since it seems to be a good introductory language to learn. I have a hard copy of "Introduction to Computation and Programming using Python" by John V. Guttag, and I plan to work through this book in order to fully learn how to program in Python.
You are welcome to join me on my journey as I document my way through being a code newbie.
I have completed the first two chapters of this book. Here are the second exercise and my solution thus far:
2.2 Finger Exercise, Pg. 16
Write a program that examines three variables --- x, y and z --- and prints the largest odd number among them. If none of them are odd, it should print a message to that effect.My Solution:
""" Write a program that examines three variables --- x, y, and z --- and
prints the largest odd number among them. If none of them are odd, it should
print a message to that effect. """
def largest_odd_number(x, y, z):
print x, y, z
if x % 2 != 0 and y % 2 != 0 and z % 2 != 0:
if x > y and x > z:
print x
elif y > x and y > z:
print y
elif z > x and z > y:
print z
elif x == y and y == z:
print x
elif x % 2 != 0 and y % 2 != 0 and z % 2 == 0:
if x > y:
print x
else:
print y
elif x % 2 == 0 and y % 2 != 0 and z % 2 != 0:
if y > z:
print y
else:
print z
elif x % 2 != 0 and y % 2 == 0 and z % 2 != 0:
if x > z:
print x
else:
print z
elif x % 2 != 0 and y % 2 == 0 and z % 2 == 0:
print x
elif x % 2 == 0 and y % 2 != 0 and z % 2 == 0:
print y
elif x % 2 == 0 and y % 2 == 0 and z % 2 != 0:
print z
else:
print "none of these are odd numbers"
Notes:
I know that my solution to this problem is probably not the most efficient, but it is what I produced as a newbie to programming. It seems to work fine, but it seems kinda long and clunky. Alas, I hope to get better with time. :)
I should say that I downloaded Python 2.7.9, as stated in the book, and I am using the standard IDLE program to write and debug my code. It seems fairly easy to use thus far.
I did use some info that I learned from Codecademy's Python track in this solution, how to create a function. I wanted to use a function in this problem because it seemed more proper. But I really am not sure.
I am gonna write another blog post later to document my solution of the next exercise.
No comments:
Post a Comment