Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
franco cramer
Python Development Techdegree Student 2,433 Pointscan anyone help me on Practice Creating and Using Functions in Python activity THATS ODD . stuck ...
can someone do it and explain it step by step? i found this https://teamtreehouse.com/community/practice-creating-and-using-functions-in-python-task-two It is not clear the explanation and even after following what he suggest Its still not right
1 Answer
Kailash Seshadri
3,087 PointsTo define this function, we start off with def. This tells the interpreter shows that you are going to define a function.
"is_odd" is the name of this function, so well put that afterwards, with a pair of parenthesis : is_odd()
Inside the parenthesis, we specify the parameter that we are going to test. In this case, it can be any number so we use a varaible. It can be any variable and in this case, I'll use the variable 'num'. We finish off with a full colon (:) to show that we are now going to define the functionis_odd(num).
def is_odd (num):
Now we want to test if the number in num is odd. How do we do that? We divide it by 2. If we get a remainder, it is odd. If we don't, it is even. To find the remainder when you divide two numbers in python, we use the %. This is called a modulo operator. a%b is the remainder when we divide a by b.
def is_odd(num):
num%2
We can check if this reminder is actually 1 using an if statement: If the remainder is 1, then the number is odd.In this case we will print the string "Number is odd".
def is_odd(num):
if num%2 == 1:
print('Number is odd')
If it is not odd, we will print "Number is not odd"
def is_odd(num):
if num%2 == 1:
print('Number is odd')
else:
print('Number is not odd')
Note that the we use else here, as the remainder when divided by 2 can only be 1 or 0. So the else does the exact same thing as if num%2 == 0. However, it is much shorter so we can just use else instead.
You can then call this function for any value for num by just doing is_odd(3) for example which will print "Number is odd". Doing is_odd(4) for example will cause "Number is not odd" to be printed.
franco cramer
Python Development Techdegree Student 2,433 Pointsfranco cramer
Python Development Techdegree Student 2,433 PointsThank you so much for the explanation Kailash Seshadri , this helped me a lot :)