#๐Ÿ”’ subroutine variable

320 messages ยท Page 1 of 1 (latest)

vapid helmBOT
#

@shut flint

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

leaden portal
#

calling a function doesn't bring the variables of its scope forward

shut flint
#

what can i do

leaden portal
#

!e

def foo():
    x = 5

foo()
print(x)
vapid helmBOT
leaden portal
#

this isn't how python works

shut flint
#

is there any wqay to bring variables from a function

leaden portal
#

You're asking the wrong question here. There's a few things I would modify about this.

shut flint
#

alr

leaden portal
#

Have you learned about loops yet?

shut flint
#

my teacher for programming quit half way through the year

#

and my new teacher is going over my 2nd paper

#

which doesnt cover programming

leaden portal
#

That's unfortunate, but fortunately there's a ton of resource online

shut flint
#

any tips of what to use?

leaden portal
#

You need some sort of loop to re-prompt the user to enter their data if they don't respond with "Yes"

#

have you seen while before?

shut flint
#

yh

leaden portal
#

That's a loop

shut flint
#

i get while loops

#

but not the for loops

leaden portal
#

you wouldn't need a for loop here

#

while is used when the amount of cycles is unknown

#

we don't know how many attempts it will take for the user to input their data correctly

#

it could be first try

#

it could take 100 tries

#

so the number of cycles is tied to a condition. "while the user has not entered yes"

shut flint
#

alr

leaden portal
#

So that solves the repeating issue

#

but as for the variables in the function, you will need to use return here

shut flint
#
print("Welcome, please register your account")
answer = "No"

while answer != "Yes":
    email = input("Please enter your email")
    age = int(input("Please enter your age"))
    name = input("Please enter your name")
    gender = input("Please enter your gender")
    
    answer = input("Is this information correct? Yes or No")

    if answer == "Yes":
      print(email)
      print(age)
      print(name)
      print(gender)```
#

this seems to work fine

#

is this the best way i can do it then?

leaden portal
#

It depends if you're required to use functions or not

#

but even still, you could modify this loop to be a bit better

shut flint
shut flint
leaden portal
#

It's important to understand how the loop controls the flow of your logic

#
print("Welcome, please register your account")
answer = "No"

while answer != "Yes":
    email = input("Please enter your email")
    age = int(input("Please enter your age"))
    name = input("Please enter your name")
    gender = input("Please enter your gender")




#

just looking at this

#

it's the indented part of code that will repeat

#

we have left the loop once we have unindented code

shut flint
#

yeah i understand that

leaden portal
#
print("Welcome, please register your account")
answer = "No"

while answer != "Yes":
    email = input("Please enter your email")
    age = int(input("Please enter your age"))
    name = input("Please enter your name")
    gender = input("Please enter your gender")
    

print("This is after the loop")
#

this means we can ONLY reach that print statement once "Yes" has been entered

shut flint
#

yeah i get that

leaden portal
#

so we don't need another if to check if the answer is Yes like you have

#
print("Welcome, please register your account")
answer = "No"

while answer != "Yes":
    email = input("Please enter your email")
    age = int(input("Please enter your age"))
    name = input("Please enter your name")
    gender = input("Please enter your gender")
    
    answer = input("Is this information correct? Yes or No")


print(email)
print(age)
print(name)
print(gender)
#

you can simply put your prints after the loop

shut flint
#

kk ty

#

do you know any interactive ways to learn python better

#

i like doing tasks like this

#

instead of just watching videos

leaden portal
#

There's challenge websites

#

I prefer codewars

#

It has a good scale of difficulty

#

but all the challenges expect you to write your answer in a function

#

so if anything, it's a good way to learn functions ๐Ÿ™‚

shut flint
#

okay

#

what is the difference between functions and subroutines

leaden portal
#

subroutine is a type of function that runs asynchronously with the rest of the code. You're unlikely to come across these for a long time

#

They aren't really a key feature of python

#

they require extra libraries

shut flint
#

oh

leaden portal
#

wait sorry

shut flint
#

cuz when my teacher does once in a while cover programming

leaden portal
#

that's coroutine

shut flint
#

he starts talking about subroutines

shut flint
leaden portal
#

sorry subroutine is just another name for a function

#

other languages might use that term

#

but I never see it in python

shut flint
#

k

leaden portal
#

functions are a very important part of python though

#

do you understand return?

shut flint
#

no not really

leaden portal
#

as you saw above, variables created inside a function only exist inside that function

#

they are called "local" variables

#

there's a few important rules about how functions resolve variable names

#
def foo():
    x = 5

foo()
print(x)
#

looking at this again, we saw that this will error

#

x ONLY exists inside the function

shut flint
#

okay

#

what you're saying rn actually helps me with this first challenge on codewars

leaden portal
#

!e

def foo():
    print(x)

x = 10
foo()
vapid helmBOT
leaden portal
#

but have a look at this

#

functions can access variables created outside

#

this is known as the "global" scope

#

outside functions is global scope, inside functions, they each have their own local scope

shut flint
#

alright

#

so a function cant look at the whole code or other functions

#

only at whats inside its own function

leaden portal
#

x is a global variable

shut flint
#

so the main code cant access variables from the function

#

but the function can access variables from the main code

leaden portal
#

yes, but there's some extra rules

shut flint
#

what are thoise rules

leaden portal
#

!e

def foo():
    y = 5
    print(y)

y = 10
foo()
vapid helmBOT
leaden portal
#

now have a look at this

shut flint
#

?

leaden portal
#

local scope has priority over global scope

#

we now have a y variable in the global scope and locally

#

even though they have the same name, they are not related to each other in any way

shut flint
#

so if a variable changes outside of the function, the function will prioritise the value of the variable called inside of it?

#

oh nvm

#

they're 2 seperate variables then?

leaden portal
#

yes exactly

#

we can have the same name in multiple scopes

#

here's what happens when a function has to access a variable

#

so in the example above, it's trying to print y

#

it says "Hey, do I have a local variable named y?"

#

If it does, it prints the value of that y

#

if it doesn't, it then looks into the global scope to see if there's a variable y there instead

#

if there is, then it prints it

shut flint
#

so it will always prioritise the local variable? or is there instances where it wont

leaden portal
#

if there isn't, then it will error

leaden portal
#

this is scope priority

shut flint
#

okay

leaden portal
#

but, there's a funny error that can happen

#
def foo():
    print(y)
    y = 5

y = 10
foo()
#

what do you think will happen here?

shut flint
#

it'll print 10?

leaden portal
#

nope ๐Ÿ™‚

#

a function cannot shift between local or global

#

it won't print the global, then suddenly create a local version

#

what happens is when you define a function, it's actually aware of all variables that will be created, even if it happens later in the function

shut flint
#

so it prints 5?

leaden portal
#

No, because y hasn't been assigned yet inside the function

#

This is a "gotcha" for a lot of python beginners

#

This will error

shut flint
#

so it just errors as it knows the y is going to be called?

leaden portal
#

!e

def foo():
    print(y)
    y = 5

y = 10
foo()
vapid helmBOT
# leaden portal !e ```py def foo(): print(y) y = 5 y = 10 foo() ```

:x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 6, in <module>
003 |     foo()
004 |   File "/home/main.py", line 2, in foo
005 |     print(y)
006 |           ^
007 | UnboundLocalError: cannot access local variable 'y' where it is not associated with a value
leaden portal
#

Yes exactly

shut flint
#

okay

leaden portal
#

It knows there will be a local y, but it has yet to be assigned

shut flint
#

alright

leaden portal
#

so, functions are largely seen as little prewritten packages of code

#

but they're more useful than that

shut flint
#
def are_you_playing_banjo(name):
    # Implement me!
    return name```
#

what does this little return thingy

#

at the bottom mean

leaden portal
#

ok, so, a function is a process

#

we can tell python to provide some sort of result for running that function

#

are you familiar with the term "calling"?

shut flint
#

uh

#

not really

leaden portal
#

"calling" is just a fancy name for saying "run the code inside the function"

#

but this is what we say, we are "calling the function"

shut flint
#

is that like

#

doing the foo()

#

after the variable was made

leaden portal
#

yes exactly

shut flint
#

function*

#

not variable

leaden portal
#

so foo is the function's name, and foo() is a call to the function

#

foo and foo() are very different things

shut flint
#

why does the function i sent have a parameter iirc

#

is that what they're called?

leaden portal
#

that's one way we can add a bit of variety and reusability to the function

#

and yes, parameter is the correct term

shut flint
#

can i quickly like tell u what i think it does

leaden portal
#

!e

def say_hello(name):
    print("Hello", name)


say_hello("IvyJam")
say_hello("Fashoomp")
vapid helmBOT
shut flint
#

and u tell me if im right

leaden portal
#

oh sorry

#

still explain what you think it does ๐Ÿ™‚

shut flint
#

i was gonna say can i use name as a variable to send to the function

#

and use within

leaden portal
#

yes, in this example, name still acts like a local variable within the function

#

The value that is provided when you call the function is called the "argument"

leaden portal
#

but within the function, we simply refer to the argument data as name

shut flint
#

so "IvyJam" is an argument

#

name is a parameter

leaden portal
#

yes ๐Ÿ™‚

shut flint
#

and IvyJam is the argument being used in place of name

leaden portal
#

yes exactly

shut flint
#

in ur code u dont return name

#

does it matter

leaden portal
#

It entirely depends what you're trying to do

#

as a beginner, a lot of your exercises revolve around trying to print something out

#

but as you write more complex programs, rarely is printing the goal

shut flint
#

it wants me to check if the letter begins with an upper or lower case r

#

and print if they play the banjo if it does or doesnt play the banjo if it doesnt

#

im completely lost when it comes to checking the first letter of a string

leaden portal
#

!e

result = print(5)
vapid helmBOT
leaden portal
#

What do you think will happen if I do print(result) on the next line?

shut flint
#

error?

leaden portal
#

nope ๐Ÿ™‚

shut flint
#

but isnt that basically print(print(5))

leaden portal
#

no, and here's where a lot of beginners get tripped up

#

we are not storing the function call in the variable result

#

we are storing the RETURNED value

#

have you learned about len yet?

shut flint
#

isnt that checking the length of a string

leaden portal
#

yes exactly

shut flint
#

idk how it works but ive heard of it

leaden portal
#

it returns the length of the string

#

!e

name = "Fashoomp"
num_letters = len(name)
print(num_letters)
vapid helmBOT
shut flint
#

wait rq

#

do yk psuedocode

leaden portal
#

yes

shut flint
#

is it in python or psuedocode where it starts at 0

leaden portal
#

just about every language starts at 0

#

except lua because it is weird

#

I don't think there's any rules for what index you need to start at in pseudocode

shut flint
#

only reason i somewhat know lua is cuz of roblox

leaden portal
#

it's just explaining code in more plain language

shut flint
#

okay

leaden portal
#
name = "Fashoomp"
num_letters = len(name)
print(num_letters)
shut flint
#

so after i get the length of my name

leaden portal
#

so looking at these 3 lines

#

the first line simply assigns some string data to the name variable

#

remember that the right side of the = is always handled first

#

so we call len on name

#

len is a function

#

so we're calling it

#

name is the argument

shut flint
#

alr

leaden portal
#

it returns 8

#

and then 8 gets assigned to num_letters

shut flint
#

ohhh

leaden portal
#

after line 2, num_letters has no memory of len being called

#

whenever we call a function, we are storing the result in the variable that we assign to it

shut flint
#

so len(name) doesnt really exist

#

num_letters is only known as 8

leaden portal
#

yes

#

we aren't storing len(name) in num_letters

#

we are storing the result of calling that function

#

and return is how we tell a function what its result should be

#

!e

name = "Fashoomp"
num_letters = len(name)
name = "IvyJam"
print(num_letters)
vapid helmBOT
leaden portal
#

num_letters isn't going to change just because name changed

#

each line is evaluated and stored on its own

shut flint
#

alr

leaden portal
#

so you can see that some functions return meaningful data

#

but with my "gotcha" before with result = print(5)

#

print is merely used for display

#

it doesn't actually return anything meaningful

shut flint
#

wait so rq

leaden portal
#

any function without a return will default to returning a value of None

shut flint
#
x = 5
y = print(5)```
#

x and y are equal?

leaden portal
#

no

#

y is None

#

print ONLY displays

#

it does not return the value it displays

shut flint
#

k

leaden portal
#

!e

x = 5
y = print(5)
print(y)
vapid helmBOT
leaden portal
#

this is where I think there's a lot of confusion for beginners

#

because a lot of basic functions are still just used for printing things

#

and this can be ok if all you care about is printing

#

maybe I'm making a game of tic-tac-toe

#

I could make a function that prints the board in a nice way

#

functions can be really useful when we don't want to have to think about what it's doing and we just want to call it by name to get a result

shut flint
#

rq

#
def are_you_playing_banjo(name):
    length = len(name)
    return name``` can u explain more thoroughly what the return is doing in this specific instance
leaden portal
#

it's honestly not doing anything meaningful

#

it's simply returning the parameter that it was given

shut flint
#

without it would the result differ in anyway?

leaden portal
#

yes, the return would be None

shut flint
#

so if i called the function what would happen?

#

rq let me write sum code

leaden portal
#

!e

def are_you_playing_banjo(name):
    length = len(name)
    return name

are_you_playing_banjo("Fashoomp")
vapid helmBOT
leaden portal
#

it would appear nothing is happening

#

just because there's nothing printed

#

but also, nothing meaningful is happening

shut flint
#

so if there was a print in the end

#

with or without returning it would still print what was supposed to

leaden portal
#

!e

def are_you_playing_banjo(name):
    length = len(name)
    return name

result = are_you_playing_banjo("Fashoomp")
print(result)
vapid helmBOT
leaden portal
#

!e

def are_you_playing_banjo(name):
    length = len(name)

result = are_you_playing_banjo("Fashoomp")
print(result)
vapid helmBOT
leaden portal
#

a function without a print will always return None

shut flint
#
def are_you_playing_banjo(name):
    length = len(name)
    if name[0] == "R" or name[0] == "r":
        result = name + " plays banjo"
    else:
        result = name + " does not play banjo"
    return result

are_you_playing_banjo("ray")
print(result)```
#

why does this not work

#

oh wait

#

the global cant scope in the local

leaden portal
#

!e

def are_you_playing_banjo(name):
    length = len(name)
    if name[0] == "R" or name[0] == "r":
        result = name + " plays banjo"
    else:
        result = name + " does not play banjo"
    return result


print(are_you_playing_banjo("ray"))
vapid helmBOT
leaden portal
#

you can simply do this

#

we're directly printing whatever gets returned

#

this is fine if you don't care about storing the returned value in a variable

shut flint
#

k

#

rq

#

when i put the code u sent

#

none of this was showing up

#

why are these 2 differnet

leaden portal
#

not result

#

you also aren't meant to call the function at the bottom. Codewars handles that for you

#

you only need to write the function

shut flint
#

oh okay

leaden portal
#

Also I don't know if you're doing the same, but I like to work locally so I can better test my function and then once I'm ready to test, I'll paste it into codewars

shut flint
#

in vsc?

#

my pc is like really bad so i dont like using stuff like vsc

#

makes everything else really slow

leaden portal
#

you don't have to use VSC

#

python install comes with IDLE which is a bare bones editor

#

also I'm really sorry but I have to go

#

good luck!

shut flint
#

alright ty

#

would it be possible for me to contact you at a different time if i do need help tho

leaden portal
#

I'm usually around if you open a help thread

#

but going into the weekend I won't be as available

shut flint
#

k

#

ty

leaden portal
#

np!

vapid helmBOT
#
Python help channel closed using Discord native close action

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.