stuck on "return"

0 Velimir Topolovacki · June 13, 2015
So I've tried to improvise a little on Bucky's code for return value like this:

def allowed_dating_age():                                 ----step 1: creating function
my_age = input("How old are you?")               -----step 2:creating var. that should store whatever my input would be
girls_age = my_age/2 + 7                                  -----step 3:setting up the var. that will calculate girls age
return girls_age

allowed_dating_age()                                         ----step4: calling a function

if int(girls_age) > 18:                                            ----step5: "trying" to use it "later" on
print("Cool, I can date with you.")
else:
print("Sorry, you are way to young for me.")



and afterwards I get an error saying "girls_age is not defined" or  something like that, so basically I'm stuck cause my logic sucks. any help?


Post a Reply

Replies

Oldest  Newest  Rating
+1 alex constantin · June 13, 2015
girls_age is a local variable to the allowed_dating_age() function, meaning you can only use it there.
As you are returning girls_age, you can do this:

if int( allowed_dating_age() ) > 18:

    print("Cool, I can date with you.")
else:
    print("Sorry, you are way to young for me.")


That should work
0 Velimir Topolovacki · June 13, 2015
P.S. Those steps you see are not in my code...
0 Velimir Topolovacki · June 13, 2015
This is my new code:

def allowed_dating_age():
my_age = input("How old are you?")
girls_age = int(my_age)/2 + 7
return girls_age



limit = allowed_dating_age()

if limit > 18:
print("Cool, I can date with you.")
else:
print("Sorry, you are way to young for me.")

And .....it WORKS! But still unclear about RETURN. : (
0 Velimir Topolovacki · June 13, 2015
Already did it, it works.  Thanks anyway. I'm just not sure if it's by the book to use function after IF regardless of being converted to an integer....
0 Halcyon Abraham Ramirez · June 14, 2015

def func():
    a = 1 + 2
    return a

print(func())

this outputs 3

return is when you need to use the output of whatever it is you returned from the function
consider this


def func():
    a = 1 + 2
    print(a)

func()

I didn't print it like the first one because the function when called already prints something
now what if I wanted to use "a" for something


def func():
    a = 1 + 2
    return a

def multiply():
    b = 1 + 1
    result = b * func()
    return result

print(multiply())


here we returned the value of func which is 3. it's almost as if func became  a variable because it stores 3 now, We
defined another function named multiply and used what the function func returns to multiply returned the result of multiply and printed it. 
  • 1

Python

107,294 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator