Where to create avoid global variables when creating objects in Python - python

I have written a simple menu function that i want to call from my main_program() function. The code also includes a class called Writing which I'm trying to make an object of inside the main_program(). The reason for this is that I've heard that it's preferable to avoid global variables. However this doesn't work and I get the answer: NameError: name 'writing_obj' is not defined
When I create the object outside the main_program() everything works fine so I guess is that I have to return my object writing_obj from the main_function() somehow?
Here is the code I wrote:
class Writing:
def writing_something(self):
print("I'm learning Python ")
def menu():
while True:
val = int(input("1. Write a sentence 2. Quit "))
if val == 1:
writing_obj.writing_something()
elif val == 2:
print("The program shuts down. See ya! ")
break
else:
print("Sorry, I din't get that! ")
continue
def main_program():
writing_obj = Writing()
menu()
main_program()

writing_obj is defined within the main_program() function and is not declared to be global. I would suggest using function arguments:
...
def menu(writing_obj):
...
def main_program():
writing_obj = Writing()
menu(writing_obj)
You could instead put global writing at the beginning of the main_program() definition, but as you said, global variables are not recommended.

Related

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)

How to print function on if statement?

How do I print the function 'play' in the if statement on line 5?
print("Deal 'Em\nby Imago Games")
print("1. Play\n2. Credits")
select = input()
if select == 1:
def play()
elif select == 1:
print("Bye")
def play():
print("Welcome to Deal 'Em\nLet me teach you the basics!")
There are three major problems in your code:
play() is defined before usage. You have to define the function earlier in your code.
to call the function use play() without def
your elif has the same condition as the if and will never be executed
You can put either just play() on line 5 (remove the def) or change the play function to return the string instead of printing it. def is only used when you define the function, not when you call it.
Just leave it as play(), the print is already inside the function
Instead of def play() on line 5, use play() to simply call the function. Also, you should work on the structure of your code and place all the function definitions before calling them.

Passing parameters error

I am trying to create a program and get user data then pass it on to another function, but I keep getting a NameError, even though I (appear) to be passing the parameters properly and calling the function with that parameter too.
here is an example of my code:
#Define prompt to get player name
def welcomePrompt():
print("Welcome to my beachy adventure game!")
name=(input("Before we start, you must check-in, what is your name?:"))
return name
#Define dictionary to access all player data
def dataDict(name):
name=name
print(name)
def main():
welcomePrompt()
dataDict(name)
main()
could someone please help? thanks
You don't use the name value returned from welcomePrompt(); a local variable in a function is not going to be visible in another function, so the only way to pass on the result is by returning and then storing that result:
def main():
name = welcomePrompt()
dataDict(name)
Note the name = part I added. This is a new local variable. It may have the same name as the one in welcomePrompt(), but because it is a different function, the two are independent. You can rename that variable in main() to something else and not change the function of the program:
def main():
result = welcomePrompt()
dataDict(result)

Repeating A Function From Within A Function In Python 3

My question is that I was writing a program in Python 3 trying to think of a way to repeat a function from within a function, when on StackOverflow I found I can do this with the else statement:
def program():
var = (input('Pick A Car: BMW Or Nissian'))
if var == 'BMW':
print('You Picked BMW \n')
if var == 'Nissian':
print('You Picked Nissian \n')
else:
print('That's Not An Option')
program()
return
But I just do not understand how calling back a function from within a function can happen considering that the full function has not been defined yet? I appreciate the help if possible!
The function is defined. You define it right there. Assuming the indentation in your actual code is correct, your code should mostly work (you should use elif var == 'Nissian': instead of if var == 'Nissian').
Repeating a function within a function is called "recursion." There is a wealth of information about it online.

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