Difference between a global variable and variable defined in main? - python

I am confused on the difference between creating a global variable vs defining a variable in main. I have a very specific example that I would like explained. Here is the specific code:
def f():
username = input("Please enter your username: ")
print("Thank you for entering your username")
#I want to be able to use the "username" variable outside of the "f" function
#and use it multiple times throughout my code
print(f"Your username is: {username}")
Here is the solution I initially thought was correct:
def f():
global username
username = input("Please enter your username: ")
print("Thank you for entering your username")
f()
print(f"Your username is: {username}")
Here is the solution that I was told was the actual correct/preferred way:
def f():
username = input("Please enter your username: ")
print("Thank you for entering your username")
return username
username = f()
print(f"Your username is: {username}")
The reasoning for the second solution was that it is better to return a variable and creating a global variable using the global keyword is very discouraged/should be avoided, but I'm confused because I thought the second solution also creates a variable that is defined in the global scope since they are defining the variable in main (here is the article I read which confirmed this concept of global vs main variables, if someone can confirm this is correct it would be helpful as well since I have multiple questions regarding this).
I am confused on this Python concept and why the second solution is a better/preferred method of solution. Can someone explain?

The second one does create a global variable. The critical difference, though, is that your function does not rely on it. The user of your function could also write
def f():
username = input("Please enter your username: ")
print("Thank you for entering your username")
return username
name_of_user = f()
print(f"Your username is: {name_of_user}")
Note that there is no dependence on the name your function uses to store the input and the name the caller uses to receive it. Your local variable username does not exist outside your function, and your function knows nothing about how the value it returns will be used, or even it is used at all.

By using a local variable you decrease the dependencies between your components,therefore decreasing the complexity of your code

Related

Printing a variable with the same name as a string in Python

In my project I have user made variables. What I'm trying to do is print the variable if the user gives a string named the same as the variable. Here's what I think it would look like:
variable = 123
userInput = input("Enter a variable to print: ")
print(userInput)
# Instead of printing userInput, it will check if userInput is the name of a variable,
# and print if it is.
The user will input "variable", and will print 123.
Also note that the variables will have their custom names and data. So if the variable name is something different, user entering "variable" won't cause it to be printed.
And yes, I know that having user-made variables can be a bad idea. I know what I'm doing.
You can access your variables dynamically by their name using globals():
print(globals().get(userInput,"No such variable"))
You can replace "No such variable" with any other default value in case the variable doesn't exist
You can create a userspace for each user with their own variables, i.e
def get_userspace(user):
""" Returns current userspace of user. """
# Here may be Postgres, Redis or just global userspaces
global userspaces
return userspaces.setdefault(user, {})
userspaces = {}
userspace = get_userspace(user)
then place all input of specific user in his/her userspace to not interfere with others and to not redefine locals/globals that can be viable for program execution. An then use your code with little improvements to get variable from that userspace:
user_input = input("Enter a variable to print: ")
print(userspace.get(user_input))
Here you go.
variable = 123
userInput = input("Enter a variable to print: ")
print(globals()[userInput])

Assigning a new value to a python variable

I'm extremely new to Python and working on my first text-based game. In this game, I would like player to choose from a list of characters. In the course of the game, I would also like to give the player the ability to change the character (which ultimately affects the outcome of the game). I'm unable to understand what I need to do to ensure the new choice of character is saved appropriately. Below is a stripped down version of the code:
def identity_choice():
identity = input("""Your options are:
1. Ordinary Tourist
2. Chef
Please choose a number""")
if identity == "1":
print("You now look like a tourist!")
return identity
elif identity == "2":
print("You are now a chef")
return identity
else:
print("Sorry, I don't understand that.")
return identity_choice()
def action(identity):
if identity == "1":
print("You can't do what you need to as a tourist")
response = input("Would you like to change your disguise?")
if "y" in response:
identity_choice()
else:
print("You have chosen to retain your identity")
identity = identity_choice()
action(identity)
The variable "identity" is used only local to the function(s). If you need the variable global, just declare the variable outside all functions, and inside the functions you enter the line "global identity".
Short Answer
All you need to do is reassign the identity variable, if this is the way you are choosing to keep track of the players identity. For example:
if "y" in response:
identity = identity_choice()
After this you can return identity if you would like, or you may, as the other answer suggested, declare global identity inside the action function description. This way, the identity variable is shared throughout the entire script.
Longer Answer
Actually won't be that long, but this seems like a great place to learn some object oriented programming. You stated that you're just starting, so if it's too early, then don't bother just yet, you'll get there!
However, a nice way to set this up could be to instantiate users as an object of some class, such as user, and then this class could either have a second class identity which inherits from the user class. Or, the user class could simply have a variable called identity, which can be changed with a simple function. Here is a very brief and incomplete example:
class user:
def __init__(self):
pass # here you could call the choose identity function, or just
# initialize with some default identity
def choose_identity():
#the function you wrote above asking the user to choose their identity
Hope this helps a bit, I tried to keep it very simple
I don't exactly understand what you mean.
I assume that the problem is in the "action(identity)" function that the new identity is not saved in case the user chooses "y".
Change it into:
def action(identity):
if identity == "1":
print("You can't do what you need to as a tourist")
response = input("Would you like to change your disguise?")
if "y" in response:
return identity_choice()
else:
print("You have chosen to retain your identity")
return identity
Then, when you call action, do it like this:
identity = action(identity)

Python Beginner Programming

I am still working on the same encryption program before and I am currently stuck.
choice = ""
def program (str,my_fn):
global i
i=0
while i<len(str):
my_fn
i += 1
def encrypt(my_result):
message.append(ord(answer[i]))
while choice != "Exit":
choice = input("Do you want to Encrypt, Decrypt, or Exit?\n")
if choice == "Encrypt":
answer = input("What would you like to encrypt:\n")
message = []
program(answer,encrypt(message))
print (answer)
print (message)
So the first part of the program is simply asking the user if they wish to Encrypt, Decrypt, or Exit the program, this part works perfectly fine. However, my issue is with the functions. Function "program" is intended to serve as a repeater for the inner function for every single letter in the string. However, when I try to run the program, it continues to tell me that "i" isn't defined for the "encrypt" function and does nothing. I am certain I set "i" as a global variable so why isn't this working. In case you are wondering why I chose to make two functions, it is because I will later have to use function "program" multiple time and for this specific assignment I am required to use functions and abstractions. Thanks!
Add one line after your first line
choice = ""
i = 0
The keyword global means you declare an access to a global name.
Also, using a global variable is almost never a good idea. You may want to find another way to design your function.
The line program(answer,encrypt(message)) doesn't do what you want it to do. Rather than passing the function encrypt and its argument message to program (which can call it later), it calls the function immediately. It would pass the return value to program instead, but since encrypt(message) doesn't work without i defined, you get an exception instead.
There are a few ways you could fix this. By far the best approach is to not use global variables in your functions, and instead always pass the objects you care about as arguments or return values.
For instance, you could pass a function that encrypts a single letter to another function that repeatedly applies the first one to a string (this would be very much like the builtin map function):
def my_map(function, string):
result = []
for character in string:
result.append(function(character))
return result
def my_encryption_func(character):
return ord(character)
If you really want to stick with your current architecture, you could make it work by using functools.partial to bind the answer argument to your encrypt function, and then call the partial object in program:
from functools import partial
def program (str,my_fn):
global i
i=0
while i<len(str):
my_fn() # call the passed "function"
i += 1
def encrypt(my_result):
message.append(ord(answer[i]))
choice = ""
while choice != "Exit":
choice = input("Do you want to Encrypt, Decrypt, or Exit?\n")
if choice == "Encrypt":
answer = input("What would you like to encrypt:\n")
message = []
program(answer, partial(encrypt, message)) # pass a partial object here!
print (answer)
print (message)

Returning value from a function when the function itself called inside PYTHON

My function in python looks like below:
def choose_sepa_reason_code():
# This method is for providing proper sepa reason code
sepa_reason_code = input("\nPlease provide SEPA reason code to reject the payment: ")
if sepa_reason_code in sepa_reason_codes:
return sepa_reason_code
else:
print("Your reason codes doesnt match the list:\n")
pprint(sepa_reason_codes)
choose_sepa_reason_code()
provided_sepa_reason_code = choose_sepa_reason_code()
The if statement is to make sure that user will provide proper code, but if he is wrong at the first time my function later returns None.
Could you please advise how to change it to get final correct user input?
If you really want to call the function recursively, call choose_sepa_reason_code() as return value in your else statement:
sepa_reason_code = input("\nPlease provide SEPA reason code to reject the payment: ")
if sepa_reason_code in sepa_reason_codes:
return sepa_reason_code
else:
print("Your reason codes doesnt match the list:\n")
print(sepa_reason_codes)
return choose_sepa_reason_code()
firstly your code wont run because it isnt indented, secondly you cant call a function inside itself.
this would be a better approach to your task:
def choose_sepa_reason_code():
# This method is for providing proper sepa reason code
while True: #will provide permanent loop
sepa_reason_code = input("\nPlease provide SEPA reason code to reject the payment: ")
if sepa_reason_code in sepa_reason_codes:
return sepa_reason_code #stops loop and returns the reason code
else:
print("Your reason codes doesnt match the list:\n")
print(sepa_reason_codes)

Trouble writing python program?

There's a main function, inside which the entire operation is done. Inside it, there's an if statement. I want to define a function inside that if function only if that if is satisfied. The compiler should proceed to the function defined in it and 3/4 of the program depends on the operations inside the if. When I run the program, the statements above if only is getting executed.
eg:
def manage():
name=raw_input("Enter name")
pass=raw_input("Enter password")
conf=raw_input("Confirm password")
if(pass==conf):
print"You can proceed!!!"
def proceed():
#here rate is calculated
print rate
manage()#at the very end
the statements above the if is getting executed only.the function inside if is not getting executed.i gave the statements in the else,but its not coming. is it possible to define function inside an if? if not,is there any package we should import? or is there some other way?
You can't use pass as variable name:
def manage():
name=raw_input("Enter name: ")
Pass=raw_input("Enter password: ")
conf=raw_input("Confirm password: ")
if(Pass==conf):
print"You can proceed!!!"
proceed()
def proceed():
print rate
manage()
You can't use Python Keywords as variable name
You only declare the method inside the if, you don't execute it. Here is what you should do:
def manage():
name=raw_input("Enter name")
passwd=raw_input("Enter password")
conf=raw_input("Confirm password")
if(passwd==conf):
print"You can proceed!!!"
proceed()
def proceed():
#here rate is calculated
print rate
manage() #at the very end
You should:
declare your method proceed outside the manage method
Call the proceed method when you enter the if
change the pass variable name as it is a Python keyword
And this also assumes that the variable rate is declared and contains something...
I think you might want to review what a function is and does.
A function is defined within a scope, and can be within another function, but that doesn't mean it has to be inside, otherwise there is no real point to a function.
So, in short, you need to define the function(s) in the body, and call the function of interest when needed.
Directly from your code:
def proceed():
#here rate is calculated
print rate
def manage():
name=raw_input("Enter name")
passwd=raw_input("Enter password")
conf=raw_input("Confirm password")
if(passwd==conf):
print"You can proceed!!!"
proceed()
manage()#at the very end
I would suggest you pick up a good book on Python, like this one, and read through it.
As noted below, the pass variable name is a reserved keyword in Python and will break your code. Renamed here as passwd.
It seems you defined the function in the if statement, but didn't call the function.
Try add proceed() after the definition.
Something like this:
if(pass==conf):
print"You can proceed!!!"
def proceed():
#here rate is calculated
print rate
proceed()

Categories

Resources