What I'm trying to do:
executing the script, I will have to type in two numbers and it will compare them.
I want to be asked a total of 3 times.
The first time I will type in 10 and 5, second time 5 and 10 and the third time I will type in 10 and 10 to get all three possible answers.
My problem with the first code is: getnumbers() is being called inside of Checknumbers().
I want to create functions and a loop and strictly ONLY execute the functions inside a dedicated loop and not within another function.
I want everything clean cut and no reference of any function inside another function, I don't want to use any global variables either.
I solved this with a class but I'm not really sure if I'm butchering the language or if this is common practice. Also I have to reference the class inside the checknumbers() function.
First solution:
def getnumbers():
x = input("Enter the X number: ")
y = input("Enter the Y number: ")
return x, y
def checknumbers():
x, y=getnumbers()
if x > y:
print(f'x is larger then y: x is {x} and y is {y}')
elif y > x:
print(f"y is larger then x: x is {x} and y is {y}")
elif y == x:
print(f"x is equal to y: x is {x} and y is {y}")
else:
print("Dont know mate")
n = 0
while(n < 3):
checknumbers()
n += 1
This is the variant with the class:
class ui:
x = input("Enter the X number: ")
y = input("Enter the Y number: ")
def checknumbers():
if ui.x > ui.y:
print(f'x is larger then y: x is {ui.x} and y is {ui.y}')
elif ui.y > ui.x:
print(f"y is larger then x: x is {ui.x} and y is {ui.y}")
elif ui.y == ui.x:
print(f"x is equal to y: x is {ui.x} and y is {ui.y}")
else:
print("Dont know mate")
n = 0
while(n < 3):
checknumbers()
n += 1
Ideal solution, so both functions getnumbers() and checknumbers are clean cut independent of each other and they are being called inside the while loop, the problem is that x and y from the getnumbers() function are unknown to checknumbers.
The requirement is: I cant have any reference to any other function inside my functions, how do I pass x and y without referencing them?:
def getnumbers():
x = input("Enter the X number: ")
y = input("Enter the Y number: ")
return x, y
def checknumbers():
if x > y:
print(f'x is larger then y: x is {x} and y is {y}')
elif y > x:
print(f"y is larger then x: x is {x} and y is {y}")
elif y == x:
print(f"x is equal to y: x is {x} and y is {y}")
else:
print("Dont know mate")
n = 0
while(n < 3):
getnumbers()
checknumbers()
n += 1
You're getting confused between classes and instances, and between class attributes and instance attributes. (Read e.g. this)
The OO way to store state variables (like x,y) so you don't have to pass them around between function(/method) calls is to make them instance attributes. (Not class attributes, as you were doing. Don't worry, I did that too when I first learned Python).
So we declare a class UI; we will access its instance attributes as self.x, self.y inside its methods.
Don't try to directly do stuff on class UI. You must instantiate it first: ui = UI(). You should follow the Python convention that class names are Uppercase/CamelCase: UI, instance names are lowercase e.g. ui, ui1, ui2...
You were trying to put code directly into the class definition of UI, not define methods and put the code in that, and your UI class didn't even have an __init__()
Methods are functions inside a class, they always have a first argument self. If they didn't, the method wouldn't be able to access the rest of the class(!)
Now that we cleared that up, there are a couple of ways to decompose the methods to do what you want to do:
Have an empty __init__() (you could just make its body do pass). Have get_numbers() and check_numbers() be separate methods, which you manually call in-order. This is what I show below and is closest to what you said you want ("I want no reference to any function inside another function"), but is bad decomposition - what if the client called check_numbers() before get_numbers()? It would blow up on TypeError since __init__() initializes x,y with None.
Better would be to have __init__() call the method get_numbers() under-the-hood to guarantee the instance gets properly initialized. (We could always call get_numbers() again later if we want to input new numbers). That's easy to change, I leave that to you.
In approach 1., we had to initialize the instance members to something (otherwise trying to access them in check_numbers() will blow up). So we initialize to None, which will deliberately throw an exception if we compare. It doesn't really matter, this is just bad decomposition to not have __init__() properly initialize the instance (and call whatever methods it needs to to get that done). That's why approach 2. is better. Generally you should always have an __init__() that initializes the class into a known state, so that any other method can safely be called.
Code:
class UI:
def __init__(self, x=None, y=None):
self.x = x
self.y = y
def get_numbers(self):
self.x = input("Enter the X number: ")
self.y = input("Enter the Y number: ")
def check_numbers(self):
"""This is bad decomposition because if the client calls check_numbers() before get_numbers(), the NoneType will throw a TypeError"""
if self.x > self.y:
print(f'x is larger then y: x is {self.x} and y is {self.y}')
elif self.y > self.x:
print(f'y is larger then x: x is {self.x} and y is {self.y}')
elif self.y == self.x:
print(f'x is equal to y: x is {self.x} and y is {self.y}')
else:
print("Don't know mate")
# Declare an instance and reuse it three times
ui = UI()
for n in range(3):
ui.get_numbers()
ui.check_numbers()
Also, some minor stylistic points:
you don't need a while-loop for a simple counter: n = 0, while(n < 3) ... n += 1 . A for-loop is a one-liner: for n in range(3):
good Python style (see PEP-8) is to name the methods lower_case_with_underscores, thus get_numbers(), check_numbers()
a great top-down way to design a class is to write its method signatures first, think about what methods and attributes you'll need and how they'll work together. Example: "get_numbers() will get the user input, hence we'll need attributes self.x,y to store the numbers so check_numbers() can access them". And this way you should hit any problems with class design before you've written a wall of code.
If you don't want to call getnumbers() within checknumbers(), the only alternative that makes sense is to pass the numbers as parameters to checknumbers().
def getnumbers():
x = int(input("Enter the X number: "))
y = int(input("Enter the Y number: "))
return x,y
def checknumbers(x, y):
if x > y:
# etc.
...
for _ in range(3):
x,y = getnumbers()
checknumbers(x,y)
That at least has better separation of concerns.
I don't see anything wrong with the first solution (except for the fact that getumbers returns strings in Python 3) . Classes are not the solution for every problem
I cant have any reference of any other function inside my functions, how do I pass x and y without referencing them?
It's impossible to pass something without referencing it. Even if x and y were global variables (which is much worse than your current design) the using function would need to reference them.
I don't understand why you are under the impression that calling a function inside another function is bad or wrong design.
Related
I'm new to python and I want to convert a loop "for" into a function. My loop I created enables me to multiply all the number of a list and print the result. This is my loop:
a=[1,2,3,4,9]
y=1
for x in a:
y=y*x
print(y)
As you can see I tried it with a certain list and I always put y=1 to start my loop and it works very well but when I want to create a function of that loop it fails, so far I tried that:
a=[]
y=1
def produit_entier(a):
for x in a:
y=y*x
return y
a=[1,2,3,4,9]
y=1
print(produit_entier(a))
As you can see I tried it with a certain list and when I run my code it tells me "local variable 'y' referenced before assignment", and when I remove the "y=1" line and put it right after the "for x in a:" this message disappear but the result is always 1.
So I'm lost here, my function is almost exactly the same as my loop, but my loop works very well and not my function, so I would really appreciate help here. Thx in advance
The y needs to be declared inside the function, since it is used by the function.
def produit_entier(a):
y = 1
for x in a:
y=y*x
return y
Karim!
First of all, there is a problem with the return statement. You placed it the wrong way, it should be like this:
def produit_entier(a):
for x in a:
y=y*x
return y
Secondly, if you want to modify a value inside a function, which is not passed or declared inside the function - you gotta specify a global keyword to make it accessible for the modification (if you only want to read it - you do not have to specify global keyword):
def produit_entier(a):
global y
for x in a:
y=y*x
return y
Thirdly, you do not have to return a value of y though it is a global one, just print it after.
And fourthly, using global variables is actually a bad practice (since you might modify if accidentally somewhere you do not want to and it will be difficult to find). I suggest you either declare it inside the function:
def produit_entier(a):
y = 1
for x in a:
y=y*x
return y
Or just pass a value as an argument:
def produit_entier(a, y):
for x in a:
y=y*x
return y
Best of luck!
I'll provide an alternative answer using reduce:
from functools import reduce
def produit_entier(a):
return reduce(lambda x,y: x*y,a)
Or just the built-in reduce(int.__mul__, a)
Take the below code for an example.
import random
class test:
def __init__(self):
x = random.choice([1,2,3])
print(x)
if x == 2:
pass
What I want to do here is that when x equals 2 then run the function again and get the different value of x. Therefore whenever I call the test class it always assigns the x value other than 2.
NOTE: We must run the random.choice() in the __init__ and always get the value other than 2, it's okay to run the __init__ as many times as we want unless we get the different value.
The value of x is random.
What I have tried
class test:
def __init__(self):
x = random.choice([1,2,3])
if x != 2:
self.x = x
else:
test()
Update:
Implementing the while loop sounds a good idea.
Try this:
import random
class test:
def __init__(self):
x = random.choice([1,2,3])
loop = 0
while x == 2:
x = random.choice([1,2,3])
loop += 1
if loop >= 5:
x = False
It is impossible to return any value from the __init__() function, since the function is supposed to return None, therefore I have set the x value to False, if it is something you'd like,
You really don't want to be calling init recursively. If you're using Python 3.8+ there's a neat way to fulfil your requirement.
class test:
def __init__(self):
while (x := random.choice([1,2,3])) == 2:
pass
At some point the while loop will terminate when x is either 1 or 3
I am getting an error when I try to run this simple python script:
def ask_x():
x = int(input('What is X?'))
def ask_y():
y = int(input('What is Y?'))
def result():
print(z)
def count():
if (x>10):
z = x + y
else:
z = 0
print('nono')
#start of program
ask_x()
ask_y()
count()
result()
I am using Python 3. I tried searching the forum and found Stackoverflow - input() error - NameError: name '…' is not defined
but it doesn't work for me.
This is because your variables are in a local scope. You can't access x outside of the ask_x() function.
I would suggest you read up on functions to get a better grasp of this.
def ask_x():
return int(input('What is X?'))
def ask_y():
return int(input('What is Y?'))
def result(z):
print(z)
def count(x, y):
if (x>10):
return x + y
else:
print('nono')
return 0
#start of program
x = ask_x()
y = ask_y()
z = count(x, y)
result(z)
This will grab the values in each function, however, instead of storing them in the local scope, it'll be returned to the main function and stored in the corresponding variable.
You can then send x and y as parameters to count(), take care of your logic, and return the the value to be stored as z.
I hope this makes sense!
One way to get around scoping is to return the variable you need from your function and pass it in where needed. I prefer this to using global variables:
def ask_x():
return int(input('What is X?'))
def ask_y():
return int(input('What is Y?'))
def result(z):
print(z)
def count(x,y):
if (x>10):
z = x + y
else:
z = 0
print('nono')
return z
#start of program
x = ask_x()
y = ask_y()
z = count(x,y)
result(z)
It would be better to use one of the ways presented in How to ask user for valid input to get to your input:
def askInt(text):
"""Asks for a valid int input until succeeds."""
while True:
try:
num = int(input(text))
except ValueError:
print("Invalid. Try again.")
continue
else:
return num
x = askInt("What is X?")
y = askInt("What is Y?")
This way you pass in the changing value (the text) and both profit from the variable parsing and validation.
If you dont want to return then just initialize variable with some default values
x=0
y=0
z=0
def ask_x():
global x
x = int(input('What is X?'))
def ask_y():
global y
y = int(input('What is Y?'))
def result():
global z
print(z)
def count():
global x,y,z
if (x>10):
z = x + y
else:
z = 0
print('nono')
#start of program
ask_x()
ask_y()
count()
result()
Python follows function scoping unlike some other languages like c which follows block scoping. This implies variables defined inside a function cannot be accessed outside. unless they are defined global.
Solution to your problem:
You can either return them in your functions and store them in variables in global scope or put all the input statements inside a single function.
below is my an example of what i am trying to do in my code...
def func():
x = int (input ('enter x: '))
return x
def func2():
y = int (input( 'enter y: '))
return y
def func3(x,y):
print(randomint(x,y))
def main():
func()
func2()
func3()
main()
What i am wondering is, why cant i use the x and y variables that i have defined via input and returned at the end of my functions? When this program tries to run it says the functions are missing required arguments. Silly i know, i am new to python.
furthermore, how can i use variable in one function i am creating, that were defined within another separate function? thanks!
You stated that you know how to indent so I'm not going to discuss that, the problem at hand is that you will need to catch the return value from func and func2 after they are caught.
You can do so like this:
def func():
x = int (input ('enter x: '))
return x
def func2():
y = int (input( 'enter y: '))
return y
def func3(x,y): # there's two positional value so you will need to pass two values to it when calling
print(randomint(x,y))
def main():
x = func() # catch the x
y = func2() # catch the y
func3(x,y) # pass along x and y which acts as the two positional values
# if you're lazy, you can directly do:
# func3(func(), func2()) which passes the return values directly to func3
main()
Another method is to use the global statement, but that isn't the best way for your case.
Just a hint: if you are using the random module, the random integer is called by: random.randint(x,y)
Your variables only live within the functions, there is no way for func3 to get x and y, but you have defined x and y as parameters. So far you're just not passing them in. The following should do.
def func():
x = int (input ('enter x: '))
return x
def func2():
y = int (input( 'enter y: '))
return y
def func3(x,y):
print(randomint(x,y))
def main():
x_val = func()
y_val = func2()
func3(x_val, y_val)
main()
Or just like this, if you don't want to use variables.
Just remember, same name doesn't mean it's the same variable. The scope can be different (method, function, elsewhere), and the name makes the variable unique ("the same") withhin the same scope. That is similar across all higher programming languages, but also, scopes can intersect, and in different ways. So that reuse example above, might, for example work in JavaScript.
This is probably closest to what you attempted to achieve:
def inX():
return int (input ('enter x: '))
def inY():
return int (input( 'enter y: '))
def PrintRand(x,y):
print(randomint(x,y))
def main():
PrintRand(InX(),InY()) # is probably closest to what you attempted to do.
main()
note that those slight renames do not have an effect other than understanding the code, but good names of methods telling what they actually do, are very important. You read the code many more times. You write it once.
I have set a string called 'charge' within a function but when I call 'charge' in the main body I get a traceback call saying that 'charge' is not defined. I would like to know if it is possible to call the string from outside of the function and if it is not, is there another way to get the data held within charge?
def service (x, y, z):
print ('How many animals are being provided for?')
nodogs = input ('-----> ')
if nodogs == '1':
charge = 'x'
elif nodogs == '2':
charge = 'y'
elif nodogs == '3':
charge = 'z'
x = int (x)
y = int (y)
z = int (z)
# the call for the string is later on but I think that part is irrelevant.
#If it is not, please say and I will post it.
I am a novice and am only trying out simple code. if an advanced feature is required, please explain the feature as I am unlikely to know it already,
Thanks in advance - TGSpike
You should put the line
return charge
at the end of the function, and then when you call the function, do
charge = service(x, y, z)
(with x y z set however you're using them). This will return the value of charge to your main program, and put it in the variable charge. If you want to do this with multiple variables, you can do
return x, y
and
x, y = service(x, y, z)
This is called tuple unpacking.