Jump to content
1 minute ago, Wictorian said:

This little piece of code wont work


var = "no"
def f(var):
    var = "yes"
f(var)
print(var)

 

Now I don't know how Python works exactly, but if it works like any of the programming languages I have used, the line "print(var)" should print out "no".

Does it print out "no"? Or something else?
What are you expecting it to do? 

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to post
Share on other sites

9 minutes ago, minibois said:

Now I don't know how Python works exactly, but if it works like any of the programming languages I have used, the line "print(var)" should print out "no".

Does it print out "no"? Or something else?
What are you expecting it to do? 

Yes I just realized and edited the question

I want it to print "yes"

It prints "no"

Link to post
Share on other sites

Just now, Wictorian said:

Yes I just realized and edited the question

I want it to print yes

Even though all the variables here are called 'var', there are actually two different variables in this piece of code.

image.png.006be6334e90c1a3fed0d38131f72b62.png

When passing along a parameter to a function, you don't pass the actual variable; you only pass along its value. The variable the function changes is a new instance of an int variable, which also happens to be called 'var.' This variable is only existent in the function though.

 

What you are looking for is quite a simple edit, which involves a return statement: https://www.geeksforgeeks.org/python-return-statement/

A return statement allows you to pass back a value from the function, to the original place this function is called from:

var = "no"
def f():
    return "yes"
var = f()
print(var)

Now I am not saying this is flawless perfect code, this is just an example.

By making the f() function return "yes", you are giving a value back, to whatever is calling the function. So where you're calling the function, you also have to setup a place to 'catch' the value that is being sent back.

So by saying "var = f()", you're essentially saying "var should become whatever f() will give me back". 

 

This simple approach nullifies the need for an input parameter in f() too, so I removed it.

 

Take this piece of code as an example of how you can use functions. 

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to post
Share on other sites

2 minutes ago, minibois said:

Even though all the variables here are called 'var', there are actually two different variables in this piece of code.

image.png.006be6334e90c1a3fed0d38131f72b62.png

When passing along a parameter to a function, you don't pass the actual variable; you only pass along its value. The variable the function changes is a new instance of an int variable, which also happens to be called 'var.' This variable is only existent in the function though.

 

What you are looking for is quite a simple edit, which involves a return statement: https://www.geeksforgeeks.org/python-return-statement/

A return statement allows you to pass back a value from the function, to the original place this function is called from:


var = "no"
def f():
    return "yes"
var = f()
print(var)

Now I am not saying this is flawless perfect code, this is just an example.

By making the f() function return "yes", you are giving a value back, to whatever is calling the function. So where you're calling the function, you also have to setup a place to 'catch' the value that is being sent back.

So by saying "var = f()", you're essentially saying "var should become whatever f() will give me back". 

 

This simple approach nullifies the need for an input parameter in f() too, so I removed it.

 

Take this piece of code as an example of how you can use functions. 

Yes I know that I I should use return but I am actually trying to get 2 values from a function so I tried not to use return, is it even possible?

Also does all declaring need to be done outside of functions?

say 

def main(var):
	var = f(var)

would something like this work?

Link to post
Share on other sites

You should read up on global and local objects

 

Functions will not pass on internal values to global objects unless explicitly told to (Which is bad practice)

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 9600X || GPU: RX 9070 XT|| Memory: 32GB || Cooler: Peerless Assassin || PSU: RM850e|| Case: Lian Li A3

Link to post
Share on other sites

2 minutes ago, Wictorian said:

Yes I know that I I should use return but I am actually trying to get 2 values from a function so I tried not to use return, is it even possible?

Also does all declaring need to be done outside of functions?

say 


def main(var):
	var = f(var)

would something like this work?

You should keep functions doing one thing, not multiple things. If you need to two values from a function, you either need to do things like returning an array, running the functions multiple times with different inputs or make two different functions.

 

Without know exactly what you want to do, I can't really judge the snippet of code above. 

5 minutes ago, Wictorian said:

Also does all declaring need to be done outside of functions?

You should declare variables in the most narrow scope it will be used in. Will you only be using a variable in a function? Declare it in the function. Do you need it somewhere else? Declare it in a broader scope, like the class.

This question is too vague to give a singular simple answer. There are many many time where you will want to declare a variable in a function, but also many times you wouldn't want to.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to post
Share on other sites

6 minutes ago, minibois said:

Without know exactly what you want to do, I can't really judge the snippet of code above. 

You should declare variables in the most narrow scope it will be used in. Will you only be using a variable in a function? Declare it in the function. Do you need it somewhere else? Declare it in a broader scope, like the class.

This question is too vague to give a singular simple answer. There are many many time where you will want to declare a variable in a function, but also many times you wouldn't want to.

I need it to use a variable outside of functions.

I have something like this

"
bunch of variables and arrays declared
"
"
functions defined
"


while(True):
	main()

So I guess I cant change the value of a function in main() and use it elsewhere

 

edit: Actually I have two arrays and I append variables to them in a function and I think it will be hard to do with return.

if you are interested here is the source code of What I am trying to do right now but I dont want you to debug my whole code so thats why I simplified my questions.

import os
import pickle
action = "no"
app = "no"
apps = []
locations = []
syntax = "TASKKILL /F /IM "
def Synchronize(apps, locations):
	fh = open("app locations.pkl", "rb")
	apps = pickle.load(fh)
	locations = pickle.load(fh)
def GetAppsAndLocations(apps, locations):
	fh = open("app locations.pkl", "wb")
	fakeApp = input("Type app to register")
	fakeLocation = input("Type app location to register")
	if input("COMMIT?") == "COMMIT":
		apps.append(input())
		locations.append(input())
		pickle.dump(apps,fh)
		pickle.dump(locations,fh)
def GetActionAndApp(action, app): 
	action = input("Type action.\n")
	app = input("Type app.\n")
def CloseApp(app):
	if "." in app:
		os.system(syntax+app)
	elif app == "os":
		os.system("shutdown /s /t 1")
	else:
		os.system(syntax+(app+".exe"))
def OpenApp(app):
	startfile(locations[apps.index(app)])
def Execute(action, app):
	if "c" in action and "l" in action and "o" in action and "s" in action and "e" in action:
		CloseApp(app)
	elif "o" in action and "p" in action and "e" in action and "n" in action:
		OpenApp(app)
	elif  "r" in action and "e" in action and "g" in action and "i" in action and "s" in action and "t" in action:
		GetAppsAndLocations(apps, locations) 
Synchronize(apps, locations)
while(True):
	GetActionAndApp(action, app)
	Execute(action, app)
	

 

Edited by Wictorian
Link to post
Share on other sites

Just now, Wictorian said:

So I guess I cant change the value of a function in main() and use it elsewhere

This is what parameters were made for.

Example: If you know you need to have a way to easily (for example) raise a number to a certain power, you don't make a seperate function for each number and each power, you make a single function which you can call with two parameters to calculate this.

 

So if you know you have a variable outside of a function, but need to do something with this variable (i.e. raise it to a power, see the amount of letters in a word, etc. etc.) you create a function with a parameter (or multiple) to get a dynamic answer from this function.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to post
Share on other sites

1 minute ago, minibois said:

This is what parameters were made for.

Example: If you know you need to have a way to easily (for example) raise a number to a certain power, you don't make a seperate function for each number and each power, you make a single function which you can call with two parameters to calculate this.

 

So if you know you have a variable outside of a function, but need to do something with this variable (i.e. raise it to a power, see the amount of letters in a word, etc. etc.) you create a function with a parameter (or multiple) to get a dynamic answer from this function.

I think you misunderstood me. I am asking if I write

x = 5

def f(var):
	var*=var
def main(var):
	"
	bunch of things

	"
    f(x)
while(True):
	main(x)
    

I cant get 25 , right?

also please see my previous reply, I edited it

Link to post
Share on other sites

1 minute ago, Wictorian said:

I think you misunderstood me.

Yea, I think I really lost you here.

1 minute ago, Wictorian said:

I am asking if I write


x = 5

def f(var):
	var*=var
def main(var):
	"
	bunch of things

	"
    f(x)
while(True):
	main(x)
    

I cant get 25 , right?

also please see my previous reply, I edited it

Going back to my first reply, if you changed the code to this:

x = 5

def f(var):
	return = var*var
def main(var):
	"
	bunch of things

	"
    xSquared = f(x)
while(True):
	main(x)
    

You now have variable xSquared, that is the square of x. Of course nothing is stopping you from naming xSquared to x, now the global variable x will hold the square of (the original) x.

 

I understood your simplified code, but I am unsure if you are either not asking the questions you need answers too, or if you are not understanding how to apply these answers to your code.

Since I am not a Python coder, I unfortunately can't just read the code in question and pick out issues; you would have to point me to the parts you're having problems with.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to post
Share on other sites

2 minutes ago, minibois said:

Yea, I think I really lost you here.

Going back to my first reply, if you changed the code to this:


x = 5

def f(var):
	return = var*var
def main(var):
	"
	bunch of things

	"
    xSquared = f(x)
while(True):
	main(x)
    

You now have variable xSquared, that is the square of x. Of course nothing is stopping you from naming xSquared to x, now the global variable x will hold the square of (the original) x.

 

I understood your simplified code, but I am unsure if you are either not asking the questions you need answers too, or if you are not understanding how to apply these answers to your code.

Since I am not a Python coder, I unfortunately can't just read the code in question and pick out issues; you would have to point me to the parts you're having problems with.

First, I must say that I really appreciate you. This is exactly where I have a problem. so in while(True), if I write print(xSquared) 

will I get 25?

Link to post
Share on other sites

6 minutes ago, Wictorian said:

First, I must say that I really appreciate you. This is exactly where I have a problem. so in while(True), if I write print(xSquared) 

will I get 25?

Since xSquared is a variable made within def main, if while(True) is also contained in def main; yes. print(xSquared) will print out 25.

 

Think about your different section of coats as different tiers.

If you declare something in the highest tier (the top of your code for example), it's visible everywhere. But if you declare a variable in a lower tier, it will only be available there.

 

Simply think if you code structure like this:

image.png.1ea4c42fe2d6c32791bf5eb88fd5794a.png

Where the red bar represent everything in the code, the blue section within that and the green a section within that (the functions for example).

Something you declare in the red portion, will be available anywhere. But something declared in the green section, will be available only there.

So if you have a variable that has to be available in all portions of the code, you need to declare it in a position where it will be a 'tier' higher than where you need it.

 

When you are going to need xSquared in the bottom green part, but will alter its value in the middle green part of the code, you know you will need to declare it in a broader scope/higher tier: the red or blue tiers.

 

In the same idea, if you don't want variables from one of the green parts to be visible anywhere else, you should declare it in there; as that will prevent the variable from being altered by something you don't have control over.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to post
Share on other sites

10 minutes ago, minibois said:

Since xSquared is a variable made within def main, if while(True) is also contained in def main; yes. print(xSquared) will print out 25.

 

Think about your different section of coats as different tiers.

If you declare something in the highest tier (the top of your code for example), it's visible everywhere. But if you declare a variable in a lower tier, it will only be available there.

 

Simply think if you code structure like this:

image.png.1ea4c42fe2d6c32791bf5eb88fd5794a.png

Where the red bar represent everything in the code, the blue section within that and the green a section within that (the functions for example).

Something you declare in the red portion, will be available anywhere. But something declared in the green section, will be available only there.

So if you have a variable that has to be available in all portions of the code, you need to declare it in a position where it will be a 'tier' higher than where you need it.

 

When you are going to need xSquared in the bottom green part, but will alter its value in the middle green part of the code, you know you will need to declare it in a broader scope/higher tier: the red or blue tiers.

 

In the same idea, if you don't want variables from one of the green parts to be visible anywhere else, you should declare it in there; as that will prevent the variable from being altered by something you don't have control over.

ok man again I really appreciate it sorry I wasted your time a little bit (I got it but I insisted because I didnt want to change a lot about my code) I will update you tomorrow if you dont mind it is 2 am here and online edu starts tomorrow so

Link to post
Share on other sites

1 hour ago, Wictorian said:

Yes I know that I I should use return but I am actually trying to get 2 values from a function so I tried not to use return, is it even possible?

You can return two values in Python, for example:

def split_name(name):
    name = name.split()
    return name[0], name[1]

firstname, lastname = split_name("David Souffle")

print(firstname)  # David
print(lastname)   # Souffle

And as the others have said, you should read up on scopes.

Link to post
Share on other sites

8 hours ago, Wictorian said:

I am actually trying to get 2 values from a function

You can either return a tuple

def fun():
  return value1, value2

a, b = fun()

or have your fuction and your values be part of an object so that you can reference them directly inside the method

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to post
Share on other sites

The old "pass by reference" and "pass by value" thing ...

 

Wictorian, read this long article, it should help you understand these things a bit better : https://realpython.com/python-pass-by-reference/

 

You can skip over the c# examples and just read the paragraphs and look at the python code examples.

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×