How do I transfer varibles through functions in Python - python

I am trying to read from keyboard a number and validate it
This is what I have but it doesn't work.
No error but it doesn't remember the number I introduced
def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)

I think this is what you are trying to achieve.
def IsInteger(a):
try:
a=int(a)
return True
except ValueError:
return False
def read():
global a
a=input("Nr: ")
while (IsInteger(a)!=True):
a=input("Give a number: ")
a=0
read()
print(a)
You need to use global expression in order to overwrite the global variable without a need to create return inside the function and typing a = read().
But I would highly recommend u to use the return and re-assigned the value of 'a', as someone stated below.

a is a local variable to the two functions and isn't visible to the rest of your code as is. The best way to fix your code is by returning a from your read() function. Also, the spacing is off in your IsInteger() function.
def IsInteger(b):
try:
b=int(b)
return True
except ValueError:
return False
def read():
a=input("Nr: ")
while not IsInteger(a):
a=input("Give a number: ")
return a
c = read()
print(c)

It appears as though you are not returning the result of the read() function.
The last line of your read function should be "return a"
And then when you call the read function you would say "a = read()"

Related

Why is the return function not passing the variables to the next function?

I'm trying to get rid of the error without moving the input function out of the userInput function. I expected the return function to remove the NameError. I looked all over stack exchange and in my textbook to figure out this problem.
def userInput():
a = float(input("Enter a: "))
b = float(input("Enter b: "))
return (a,b)
def printFunction(a2,b2):
print(a2)
print(b2)
def main():
userInput()
printFunction(a2,b2)
main()
NameError: name 'a2' is not defined
Functions return values, not variables. The names a and b are only defined in userInput: you need to receive the values returned by userInput in variables defined in main.
def main():
x, y = userInput()
Printfunction(x, y)
You need to assign the return values of userInput to variables if you want to be able to refer to them on the next line:
def main():
a2, b2 = userInput()
Printfunction(a2,b2)
or you could skip a step and pass userInput's output directly to Printfunction as positional arguments with the * operator:
def main():
Printfunction(*userInput())

Are you able in Python to name functions as numbers such as 1 2 3 4 etc

I would like to call functions from the items in my option_list using the first character(index*) in their name which would be 1 or 2
problem is functions don't like being called numbers even if I put "1" or "2"
how would I go about this?
def main():
print(option_list := ["1.data", "2.stratified sampling"])
user_select = input("Type your selection!..\n").lower()
for value in option_list:
if user_select == value[0]:
eval(value)
# functions for specification
def 1():
print("data")
main()
An option would be to create a dictionary that links the number to your function:
dictionary = {
1: data,
2: stratified_sampling
}
Then, you can call it accessing that dictionary and the number:
dictionary[index]()
The whole program woud look like something like this:
def data():
print("data")
def stratified_sampling():
print("stratified sampling")
dictionary = {
1: data,
2: stratified_sampling
}
selection = int(input("Select the option\n"))
if selection in dictionary.keys():
dictionary[selection]()
You can simply add some characters in front of your function and pretty sure you'll still achieve what you want, though not sure what it is
def main():
print(option_list := ["1.data", "2.stratified sampling"])
user_select = input("Type your selection!..\n").lower()
for value in option_list:
if user_select == value[0]:
eval(f"func{value[0]}()")
# functions for specification
def func1():
print("data")
Define your functions with useful names:
def data():
print("data")
def hello():
print("hello")
def say_something():
print("something")
You can put the functions into a list:
functions = [data, hello, say_something]
When asking the user to choose a function, print out all of their names:
print([f.__name__ for f in functions])
Ask for the index of the function they want to use:
i = int(input("Type the index of the function you want\n"))
Then call that function:
functions[i]()
Putting them in a list may be better than a dictionary if you are only numbering them since indexing is inherent to a list.

unction return values only working once in python

The code below runs and prints out the values returned from the two functions test_value(address) and checkRepeatCount(address) when i try to add the two value returned i None as the result. Anyway to fix this?
def check(address):
## define point variables
pass_invalid_char = test_value(address)
pass_repeat_count = checkRepeatCount(address)
if pass_invalid_char == False:
return print("Invalid character")
else:
pass
total = pass_invalid_char+pass_repeat_count
print(total)
check("hello")
Function 1 test_value
def test_value(value):
return print(30)
Function 2 checkRepeatCount
def checkRepeatCount(value):
return print(20)
Thats how im returning the function values
In both functions was returning a print statement with value
def test_value(value):
return print(30)
I was supposed just to return the number on its own like so
def test_value(value):
return 30

Unsure on how to call this function within another function - Python

really sorry if someone has asked this before, i just couldn't find what i was looking for, I'm new to coding and aren't sure why i cant get 'matrice2x2mult' function to be called within 'runcalc'. However i suspect it is to do with me calling the function 'runcalc' at the bottom. Any help will be greatly appreciated. Once again sorry.
-I get the error message:
Traceback (most recent call last):
File "FILE_PATH", line 42, in <module>
query.runcalc(q)
File "FILE_PATH", line 19, in runcalc
matrice2x2mult()
NameError: name 'matrice2x2mult' is not defined
import time
class calculator():
def __init__(self, method):
self.method = method
def matrice2x2mult():
print("Matrix 1:")
a = input("a:")
b = input("b:")
c = input("c:")
d = input("d:")
print(f"({a} {b})\n({c} {d})")
def runcalc(self, method):
if self.method == "1":
print("yes")
matrice2x2mult()
elif self.method == "2":
pass
print ("welcome to matrice Calculator: \nEnter 'HELP' for help menu")
time.sleep(1)
q = input(r"What method is required:")
q = str(q)
help1 = False
while help1 == False:
if r"HELP" in str(q):
print("------help-menu------")
print("ENTER '1' FOR 2X2 MATRIX MULTIPLICATION")
print("ENTER '2' FOR A INVERSE OF A 2X2 MATRIX")
time.sleep(1)
q = str(input(r"What method is required:"))
break
else:
break
pass
query = calculator(q)
query.runcalc(q)```
[1]: https://i.stack.imgur.com/s6jud.png
Since matrice2x2mult is defined within calculator, and you're trying to access it via runcalc which is also defined within the same class, you need to use self.matrice2x2mult to access the function. The only way that using just matrice2x2mult would work is either if it was defined in global scope rather than just in that class, or if you did something like matrice2x2mult = self.matrice2x2mult which would be weird and not recommended.

How can I check if the current string and previous string in Python code?

In this code I want to compare the previous message with the current message. So I created a variable to save the previous message. I wanted to create it as a static variable then manipulate it inside the code. but the outside the x function if I declare the variable it shows an error.
flag = 1
previousMessage = "abc"
def x():
do_something
currentMessage = m #got a string from code
if(currentMessage==previousMessage):
#shows error in flag and previousMessgae
#says create parameter of previousMessage and flag
flag=0
return
else:
do_something
previousNews=currentNews
flag=1
return
def call():
while True:
if(flag==1)
x()
time.sleep(60)
elsif(flag==0)
time.sleep(60) **strong text**
call()
Not sure if this is what you need. Try adding global before flag and previousMessage to make that variable a global variable.

Categories