Error message reads, that number is not defined in line 5:
if number < int(6):
Using Qpython on android.
looper = True
def start() :
names = ["Mari", "Muri", "Kari"]
number = input("Whoms name to you want to know?")
number = int(number)
if number < int(6):
print(names[number])
else:
print("There arent that many members")
while looper :
start()
First of all, 6 is already an integer. There's no reason to type-cast it as one.
Next, you call start() after your if statement. Python reads code top-down, so the first thing it reads is your function definition, and then your if statement. Given that start() needs to be called for number to be defined, number represents nothing and cannot be compared to 6.
Well besides how you need to call the function before using the variable, you also have a simple issue of global and local variables.
Number is a local variable in the start() function and can only be used within it.
If you want to use the number variable outside the function, you can use the 'global' keyword in front of it, which should allow you to use it externally.
For example:
def func ():
global var
var = 10
func ()
print (var)
outputs 10
Related
As per my previous question here, my question today is related to it. I have a constantly updating global variable, and I pass that variable to a function. That function consists of a loop and conditional statements. I want the loop to end when the condition is satisfied, but it keeps on looping.
Here is my code.
class LetterAScreen:
def identity(self):
global where
lol=Identifier()
lol.fn_compare()
print where
def verifier(self):
global where
verify=where
if verify != 1:
while (count>0):
print ("try again")
run=LetterAScreen()
run.identity()
run.verifier
print ("try again")
count += 1
else:
print ("correct")
The "Correct" is when the variable turns to one. Otherwise, it is not correct and the user should try again. The output ends up looking like this.
#incorrect inputs
19
try again
try again
19
try again
try again
19
try again
try again
19
try again
try again
19
try again
try again
#correct inputs but loop doesn't end
1
try again
try again
1
try again
try again
1
try again
try again
1
try again
try again
The essential part about Identifier class is only the updating variable. I believe the problem is with the class I've shared. I'm really unfamiliar how this works. I hope you could help me.
There are some things to note here:
Why are your creating a new LetterAScreen object in your loop?
Be carefull when using a global variable, usually there are other ways to solve this cleaner.
I don't know what the Identifier class does but guess the fn_compare function of that class will change the where variable? Also, creating a new Identifier on every call of the identity function seems something you should change.
That being said, the verifier method needs to be adjusted as followed:
def verifier(self):
global where
count = 1
while (count>0 and where != 1):
print ("try again")
self.identity()
count += 1
print ("correct")
You shouldn't assign the global where variable to a local one, this will cause problems because the local one will not be updated in the loop. You can compare to this global where variable directly. Also I removed the run variable, you are executing in an instance of the LetterAScreen class so you can call the identity method on the self object (similar to a this in JS).
first of all you probably don't need to create new instance inside a method "verifier" (methods are already called when the instance is created, you can access the instance using "self" variable.
So instead of
run=LetterAScreen()
run.identity()
write
self.identity()
also instead of of using complex "global" approach
you can create instance variable like self.verify and change it inside "identify"
class LetterAScreen:
def __init__(self):
self.verify = 0
also infinitive loop usually created like this
while True:
Always be careful using "global" is tricky and in most of cases you can do anything in simples and readable way, so I would recommend you remove all globals from this script, you can return params from functions, use mutable objects etc.
While writing a program in python i noticed that if one puts a function like print("hello world") inside a variable it will not be stored like expected, instead it will run. Also when i go and call the variable later in the program it will do nothing. can anyone tell me why this is and how to fix it?
If mean something like:
variable = print("hello world")`
then calling the function is the expected result. This syntax means to call the print function and assign the returned value to the variable. It's analogous to:
variable = input("Enter a name")
You're surely not surprised that this calls the input() function and assigns the string that the user entered to the variable.
If you want to store a function, you can use a lambda:
variable = lambda: print("hello world")
Then you can later do:
variable()
and it will print the message
I thought that using the return function would cause the variable placed after it to be passed outside of my function (returned?). It appears not, why not?
I am trying to write some code that requires me to compile a list of 5 items inside a function, and then pass that list outside of the function and do some work with it. Right now I only have a print statement written outside of it, just trying to see if it's getting passed outside of my function but ill need to do more later on. It is telling me variable is undefined so I am assuming that it is not getting passed.
Why would a list variable placed after the return command not be passed outside of the function and be free to use, and what do I need to do to make it so that I can in fact call my list variable outside of the function?
#Gather data about elements and turn into a list to check agsint function list later
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/elements1_20.txt -o elements1_20.txt
elements_20 = open("elements1_20.txt","r")
elements_20.seek(0)
elements = elements_20.readline().strip()
element_list = []
while elements:
element_list.append(elements)
elements = elements_20.readline().strip()
print(element_list)
# define function to get user input and compile it into a list
def get_name():
user_list = []
while len(user_list) < 5:
user_input=input("Name one of the first 20 items please kind sir: ")
#check to make sure the input is unique
if user_input.lower() in user_list:
print("please don't enter the same word twice")
else:
user_list.append(user_input.lower())
return user_list
get_name()
print(user_list)
A side note I need the function to not take any arguments so I can't use that method as a solution.
You need to save the returned value from get_name() to a variable named user_list outside of the scope of the function in order to print it:
#Storing the returned value from the function:
user_list = get_name()
print(user_list)
Without storing the return value, the function completes itself, returns the value up the stack where it is captured by nothing, and then it is subsequently dereferenced. The assignment of user_list within the body of the function is only applicable inside of the scope of the function. As soon as it is returned, the program no longer 'sees' any variables named user_list, which causes the print() statement to fail.
All, I have this request but first I will explain what I'm trying to achieve. I coded a python script with many global variables but also many methods defined inside different modules (.py files).
The script sometimes moves to a method and inside this method I call another method defined in another module. The script is quite complex.
Most of my code is inside Try/Except so that every time an exception is triggered my code runs a method called "check_issue()" in which I print to console the traceback and then I ask myself if there's any variable's value I want to double check. Now, I read many stackoverflow useful pages in which users show how to use/select globals(), locals() and eval() to see current global variables and local variables.
What I would specifically need though is the ability to input inside method "check_issue()" the name of a variable that may be defined not as global and not inside the method check_issue() either.
Using classes is not a solution since I would need to change hundreds of lines of code.
These are the links I already read:
Viewing all defined variables
Calling variable defined inside one function from another function
How to get value of variable entered from user input?
This is a sample code that doesn't work:
a = 4
b = "apple"
def func_a():
c = "orange"
...
check_issue()
def check_issue():
print("Something went wrong")
var_to_review = input("Input name of var you want to review")
# I need to be able to enter "c" and print the its value "orange"
print(func_a.locals()[var_to_review ]) # this doesn't work
Could somebody suggest how to fix it?
Many thanks
When you call locals() inside check_issue(), you can only access to the locals of this function, which would be : ['var_to_review'].
You can add a parameter to the check_issue function and pass locals whenever you call it.
a = 4
b = "apple"
def func_a():
c = "orange"
check_issue(locals())
def check_issue(local_vars):
print("Something went wrong")
var_to_review = input("Input name of var you want to review")
print(local_vars[var_to_review])
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)