#๐ subroutine variable
320 messages ยท Page 1 of 1 (latest)
@shut flint
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.
calling a function doesn't bring the variables of its scope forward
what can i do
!e
def foo():
x = 5
foo()
print(x)
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | print(x)
004 | ^
005 | NameError: name 'x' is not defined
this isn't how python works
is there any wqay to bring variables from a function
You're asking the wrong question here. There's a few things I would modify about this.
alr
Have you learned about loops yet?
my teacher for programming quit half way through the year
and my new teacher is going over my 2nd paper
which doesnt cover programming
That's unfortunate, but fortunately there's a ton of resource online
any tips of what to use?
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?
yh
That's a loop
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"
alr
So that solves the repeating issue
but as for the variables in the function, you will need to use return here
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?
It depends if you're required to use functions or not
but even still, you could modify this loop to be a bit better
nah i dont have to
can u show me how
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
yeah i understand that
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
yeah i get that
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
kk ty
do you know any interactive ways to learn python better
i like doing tasks like this
instead of just watching videos
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 ๐
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
oh
wait sorry
cuz when my teacher does once in a while cover programming
that's coroutine
he starts talking about subroutines
oh okay
sorry subroutine is just another name for a function
other languages might use that term
but I never see it in python
k
no not really
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
!e
def foo():
print(x)
x = 10
foo()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
10
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
alright
so a function cant look at the whole code or other functions
only at whats inside its own function
well no, this shows that the function can look at what's happening in the global scope
x is a global variable
so the main code cant access variables from the function
but the function can access variables from the main code
yes, but there's some extra rules
what are thoise rules
!e
def foo():
y = 5
print(y)
y = 10
foo()
:white_check_mark: Your 3.12 eval job has completed with return code 0.
5
now have a look at this
?
here's one of those important rules
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
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?
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
so it will always prioritise the local variable? or is there instances where it wont
if there isn't, then it will error
yes, always
this is scope priority
okay
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?
it'll print 10?
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
so it prints 5?
No, because y hasn't been assigned yet inside the function
This is a "gotcha" for a lot of python beginners
This will error
so it just errors as it knows the y is going to be called?
!e
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
Yes exactly
okay
It knows there will be a local y, but it has yet to be assigned
alright
so, functions are largely seen as little prewritten packages of code
but they're more useful than that
def are_you_playing_banjo(name):
# Implement me!
return name```
what does this little return thingy
at the bottom mean
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"?
"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"
yes exactly
so foo is the function's name, and foo() is a call to the function
foo and foo() are very different things
that's one way we can add a bit of variety and reusability to the function
and yes, parameter is the correct term
can i quickly like tell u what i think it does
!e
def say_hello(name):
print("Hello", name)
say_hello("IvyJam")
say_hello("Fashoomp")
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Hello IvyJam
002 | Hello Fashoomp
and u tell me if im right
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"
So here I call the function twice, each with a different argument
but within the function, we simply refer to the argument data as name
yes ๐
and IvyJam is the argument being used in place of name
yes exactly
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
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
!e
result = print(5)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
5
What do you think will happen if I do print(result) on the next line?
error?
nope ๐
but isnt that basically print(print(5))
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?
isnt that checking the length of a string
yes exactly
idk how it works but ive heard of it
it returns the length of the string
!e
name = "Fashoomp"
num_letters = len(name)
print(num_letters)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
8
yes
is it in python or psuedocode where it starts at 0
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
only reason i somewhat know lua is cuz of roblox
it's just explaining code in more plain language
okay
name = "Fashoomp"
num_letters = len(name)
print(num_letters)
so after i get the length of my name
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
alr
ohhh
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
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)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
8
num_letters isn't going to change just because name changed
each line is evaluated and stored on its own
alr
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
wait so rq
any function without a return will default to returning a value of None
k
!e
x = 5
y = print(5)
print(y)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 5
002 | None
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
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
it's honestly not doing anything meaningful
it's simply returning the parameter that it was given
without it would the result differ in anyway?
yes, the return would be None
!e
def are_you_playing_banjo(name):
length = len(name)
return name
are_you_playing_banjo("Fashoomp")
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
it would appear nothing is happening
just because there's nothing printed
but also, nothing meaningful is happening
so if there was a print in the end
with or without returning it would still print what was supposed to
!e
def are_you_playing_banjo(name):
length = len(name)
return name
result = are_you_playing_banjo("Fashoomp")
print(result)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
Fashoomp
!e
def are_you_playing_banjo(name):
length = len(name)
result = are_you_playing_banjo("Fashoomp")
print(result)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
None
a function without a print will always return None
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
!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"))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
ray plays banjo
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
k
rq
when i put the code u sent
none of this was showing up
why are these 2 differnet
you're returning name
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
oh okay
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
in vsc?
my pc is like really bad so i dont like using stuff like vsc
makes everything else really slow
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!
alright ty
would it be possible for me to contact you at a different time if i do need help tho
I'm usually around if you open a help thread
but going into the weekend I won't be as available
np!
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.