How am I supposed to check the value of answer?


#1

Question

How am I supposed to check the value of answer?

Answer

answer is a variable that we’re able to use because it’s provided to the function when the function is used. You’ll learn about the syntax of functions in due time, but you already know how to use variables!
It’s totally fine that we don’t know the value of answer ahead of time - that’s what makes functions so useful and reusable!
If we wanted to check if answer was equal to 5, we could write if answer == 5:. All we need to do, then, is compare answer to 5 using the operators we’ve learned about so far for greater and less than.
If we had a separate but similar problem where we had a function that was given a variable called targets_hit and wanted to check for two different values to assign an accuracy rating, we might do that like this:

def accuracy_rating(targets_hit):
    if targets_hit > 90:
        return "Super accurate!"
    elif targets_hit < 60:
        return "Work on your aim!"
    else:
        return "Aw, shux."

Even though we have no idea what the value of targets_hit is beforehand, we can still write our conditions because we do know what we want the value to be for certain responses.


FAQ: Learn Python - Conditionals & Control Flow - I Got 99 Problems, But a Switch Ain't One
#2

can anyone explain to me why does the answer is -1, 0, and 1?


#3

Could you provide the link/url to exercise? Then i can write a better answer


#4

Hi! this is the link
https://www.codecademy.com/courses/learn-python/lessons/conditionals--control-flow/exercises/i-got--problems-but-a-switch-aint-one?modal=pro-trial-welcome


#5

I think this is the exercise:

https://www.codecademy.com/courses/learn-python/lessons/conditionals--control-flow/exercises/i-got--problems-but-a-switch-aint-one?action=resume_content_item&modal=pro-trial-welcome


#6

the arguments at function call:

# function calls with different arguments (4, 5 and 6)
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)

are passed to the parameter:

# defining a function with answer parameter
def greater_less_equal_5(answer):

so for the first function call, we have answer = 4, which will return -1 (elif), given 4 is lesser then 5.


#7

I don’t think its a logical answer, as in a mathematical answer or one based in reason, its just what they used. It could have been A, B, and C if they wanted to…


#8

Can you please explain me in detail how -1, 0 and 1 are being displayed in the console?


#9

they are the values returned by the function.

if you think away the function:


answer = 4
if answer > 5:
  print 1
elif answer < 5:
  print -1
else:
  print 0

does the 1, -1 and 0 make sense then? The great thing about the function is that we don’t have to copy and paste the condition twice


#10

What are some common uses of elif?


#11

if you need to check for multiple conditions, elif is very useful