How to call an action from def function - Python - python

I have python code as below
def call():
input1 = input('Bot1:')
input2 = input('Bot2:')
call()
input1
How to call 'input1' action only. I want after call it, the input1 action will start for inputting data on the screen.
But on above code... when I run, it show warning 'input1 not defined'
Thanks you!

You can't access the local variables of a function from outside of it. One way to workaround that limitation would be to do something like this:
ACTION1, ACTION2 = 1, 2
def get_input(action):
if action == ACTION1:
return input('Bot1:')
elif action == ACTION2:
return input('Bot2:')
else:
raise RuntimeError('Unknown action')
input1 = get_input(ACTION1)

Related

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.

How can I increase code readability in python for this?

I am running my script in Flask and to catch and print the errors on the server I have made functions that either return None if succeeded else return an error message.
The problem is I have many functions which runs one after another and uses global variable from earlier function, this makes the code unorganized. What can I do?
App.py
from flask import Flask
from main import *
app = Flask(__name__)
#app.route('/')
def main():
input = request.args.get('input')
first_response = function1(input)
if first_response is None:
second_response = function2() # no input from hereon
if second_response is None:
third_response = function3() # functions are imported from main.py
if third_response is None:
...
if ...
else ...
else:
return third_response
else:
return second_response
else:
return first_response
main.py
def function1(input):
global new_variable1
if input is valid:
new_variable1 = round(input,2)
else:
return "the value is not integer"
def function2():
global new_variable2
if new_variable1 > 8:
new_variable2 = new_variable1 / 8
else:
return "the division is not working, value is 0"
def function3():
...
This is just a demo of what's going on. The last function will return a value either side. So if everything goes right I would be able to see the right output as well as I will see error on any given function.
The code works fine, but I need better alternative to do this.
Thanks!
Ah...you have (correctly) determined that you have two things to do:
Process your data, and
Deal with errors.
So let's process the data replacing global with parameteters (and come back to the error handling in a bit). You want to do something like this.
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
def function2(a_rounded_number):
if a_rounded_number > 8:
return a_rounded_number / 8
So each function should return the results of its work. Then the calling routine can just send the results of each function to the next function, like this:
app.py
# [code snipped]
result1 = function1(the_input_value)
result2 = function2(result1)
result3 = function3(result2)
But...how do we deal with unexpected or error conditions? We use exceptions, like this:
main.py
def function1(some_number):
if some_number is valid:
return round(some_number, 2)
else:
raise ValueError("some_number was not valid")
and then in the calling routine
app.py
try:
result1 = function1(some_input_value)
except (ValueError as some_exception):
return str(some_exception)

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 do I pass input to click.confirm without running CLIrunner.invoke()

I have a use case where a function seeks user confirmation to proceed. This is basically:
def abc()
response = click.confirm("Do you want to continue?")
Based on this response, it either aborts or proceeds.
The problem is to test this function abc.
#click.option('--yes', prompt=True)
def test_abc():
with mock.patch.object(click.confirm, input="n"):
click.echo("Aborted")
Old question but I had the same issue, I decided to mock the click.confirm which allowed me to simulate someone selecting [y/N]
lets say your abc() looked like this:
def abc():
if click.confirm("do you want to continue?", abort=True):
return "Confirmed"
return "Aborted"
and then your tests mock the click.confirm to y/n
#mock.patch("click.confirm")
def test_abc_aborted(mock_click):
mock_click.return_value = False
assert abc() == "Aborted"
#mock.patch("click.confirm")
def test_abc_confirmed(mock_click):
mock_click.return_value = "y"
assert abc() == "Confirmed"

Python: Have an action happen within every single function of a python file

Sorry the title isn't very clear but it is kind of hard to explain. So I am wondering how you can have a certain action happen within every single function of a python file. I want a user to type 'paper' inside any function in the entire python file and I cannot figure out how to do it. Here is an example:
def a():
raw_input()
print "Test"
def b():
raw_input()
print "Test 2"
How can I have it setup so a user can type 'paper' in these two functions (realistically more than 30+) and then it would print the statement "you have a paper"
Thank you so much for the help!
If you have something you want to apply to every function, you should use a decorator. I'm not exactly sure what you're trying to accomplish, but this should demonstrate:
>>> def youhaveapaper(function):
def wrapper(*args):
response = input('whatchu got?\n>>> ')
if response == 'paper':
print('you have a paper')
return function(*args)
import functools
functools.update_wrapper(wrapper, function)
return wrapper
>>> #youhaveapaper
def somefunction(x):
"""return the square of x"""
return x**2
>>> y = somefunction(5)
whatchu got?
>>> paper
you have a paper
>>> y
25
As you can see, somefunction did not need to be changed, it just needed #youhaveapaper placed before the definition.
Please see the good comments and questions above. Do you mean this:
#!/usr/bin/python
def paper(prompt):
response = raw_input(prompt+' ')
print('you have a {}'.format(response))
def a():
paper('Test')
def b():
paper('Test2')
a()
b()

Categories