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()
Related
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
def program(n):
name = input("What is your name? >")
return name
print(name)
I have a code that i am trying to execute very similar to this. When executing it, it will not return the variable 'name' i used in the function in order to use that variable outside the function. Why is this?
I am super new to coding by the way so please excuse me if i made a stupid mistake.
When you run your program, you need to assign the result (i.e. whatever is returned in your program, to another variable). Example:
def get_name():
name = input('Name please! ')
return name
name = get_name()
print('Hello ' + name)
Pssst.. I took your function parameter n away since it was not being used for anything. If you're using it inside your actual program, you should keep it :)
For a bit of a more in-depth explanation...
Variables that are declared inside your neat little function over there can't be seen once you come out of it (though there are some exceptions that we don't need to get into right now). If you're interested in how this works, it's known as "variable scope."
To execute the content of a function you need to make a call to the function and assign the return value to some variable. To fix your example, you would do:
def get_name():
name = input("What is your name? >")
return name
name = get_name()
print(name)
I have changed the function name from program() to get_name() seeing as program() is a ambiguous name for a function.
This snippet will make a call to the get_name() function and assign the return value to the variable name. It is important to note, that the name variable inside the function is actually a different variable to the one that we are assigning to outside the function. Note: I have removed the argument n from get_name() since it was not being used.
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)
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.
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)