This question already has answers here:
Execute function based on function's name string
(4 answers)
Closed 2 years ago.
I want to call the function A() based on the userinput
def main_func():
def A():
print("A")
i = 0
userinput = input(": ")
letter = userinput.split()
number = len(letter)
while (i < number):
letter[i]()
i = i + 1
main_func()
thanks in advance!
First of all, you should put the printing function def A() outside your original function since it runs separately. Furthermore it is better to use a for loop instead of a while loop here. The following more simple code should work for you.
def A(letter):
print(letter)
def main_func():
userinput = input(": ")
for letter in userinput:
A(letter)
main_func()
Here your main function calls your A() function for every letter in the userinput. It also gives the function the specific letter as a parameter. The function A() then receives the parameter and prints it. Hope this helps
Related
this time I'm trying to figure out how can i call a function named listInput that the user will input numbers separated by commas and convert its into a list, the thing is i want instead this list is created call this function in another function that takes as args a list, how can i do it? Thanks for the answers.
def divisibleBy(lista,n):
return [x for x in lista if x % n == 0]
def inputList():
cad = input("Insert a number")
user_cad = cad.split(",")
for i in range(len(user_cad)):
user_cad[i] = int(user_cad[i])
return user_cad
print(divisibleBy(inputList(),4))
Update: Just noticed why lol, fixed code.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I'm trying to make a simple quiz for a project, but I can't get an integer checker to work.
I'm trying to make it so it prints an error for floats and strings, then lets you enter another thing for the same question. My previous one gave a python error and ended the program when entering a float / string.
def int_checker(question):
user = input(question)
passcheck = False
while passcheck is False:
if isinstance(user, int) is True:
passcheck = True
return passcheck
elif isinstance(user, int) is True:
print()
print("Whole numbers only, please.")
passcheck = False
return passcheck
else:
print()
print("Numbers only, please.")
passcheck = False
return passcheck
return user
When I type anything, it gives me the final print statement, then lets me type another input in.
So, is there anyway I can make it say the correct message for each input type, and have it so if I type in an integer, it lets the code use that input?
Thanks in advance.
Since you are using Python 3, user variable will always be a string object, because input function in Python 3 always returns string, so using isinstance function won't help. That's why interpreter won't ever execute if and elif block. If you need to check if user input is a number, then you should implement something like this:
def isValidInt(stringInput):
try:
int(stringInput)
return True
except ValueError:
return False
and use isValidInt(user) instead of isinstance(user, int).
Few things I want to point out:
I noticed that condition in both if and elif are same. Probably, you wanted to do something else and wrote it by mistake.
Having while loop in your function won't make any difference. If you drop it, it will work same.
Refer this implementation if you face any problems:
def intChecker(question):
while True:
userInput = input(question)
if isValidInt(userInput):
return int(userInput)
if isValidFloat(userInput): # Refer isValidInt for implementation of isValidFloat
print("Whole numbers only, please.")
else:
print("Numbers only, please.")
I am trying to call a variable from one function into another by using the command return, without success. This is the example code I have:
def G():
x = 2
y = 3
g = x*y
return g
def H():
r = 2*G(g)
print(r)
return r
H()
When I run the code i receive the following error NameError: name 'g' is not defined
Thanks in advance!
Your function def G(): returns a variable. Therefore, when you call it, you assign a new variable for the returned variable.
Therefore you could use the following code:
def H():
G = G()
r = 2*G
print (r)
You don't need to give this statement:
return r
While you've accepted the answer above, I'd like to take the time to help you learn and clean up your code.
NameError: name 'g' is not defined
You're getting this error because g is a local variable of the function G()
Clean Version:
def multiple_two_numbers():
"""
Multiplies two numbers
Args:
none
Returns:
product : the result of multiplying two numbers
"""
x = 2
y = 3
product = x*y
return product
def main():
result = multiple_two_numbers()
answer = 2 * result
print(answer)
if __name__ == "__main__":
# execute only if run as a script
main()
Problems with your code:
Have clear variable and method names. g and G can be quiet confusing to the reader.
Your not using the if __name__ == "__main__":
Your return in H() unnecessary as well as the H() function.
Use docstrings to help make your code more readable.
Questions from the comments:
I have one question what if I had two or more variables in the first
function but I only want to call one of them
Your function can have as many variables as you want. If you want to return more than one variable you can use a dictionary(key,value) List, or Tuple. It all depends on your requirements.
Is it necessary to give different names, a and b, to the new
variables or can I use the same x and g?
Absolutely! Declaring another variable called x or y will cause the previous declaration to be overwritten. This could make it hard to debug and you and readers of your code will be frustrated.
To better help understand the fundamentals, my professor asked people in our class to write a function to see how many times a character appears in a set of words. I am having trouble integrating ord() into the function. Also, I understand that there are easier ways of getting the outcome.
Here is what I have so far:
def function(char):
word = "yes"
for char in word:
ord(char)
return ord(char)
function('y')
I don't get any errors - but I also don't get anything back
That is because you aren't printing anything!
Also, there are issues in your code, first one being the parameter 'char' and the 'char' in the for loop have the same name, that will cause issues.
A small code to find the count of a given letter can be something like this:
def function(word, char):
count = 0
for c in word:
if c == char:
count = count + 1
return count
print (function("yes", 'y'))
return will automatically end a function, and not keep it going.
there are also a lot of variables that you are not using, like the char parameter you passed to your function. when using the for loop, the variable created after for will be reassigned.
try this:
def function():
word = 'yes'
NewList = []
for char in word:
NewList.append(ord(char))
return NewList
print(function())
however what i think would be better:
def function(word):
NewList = []
for char in word:
NewList.append(ord(char))
return NewList
print(function('blahblah'))
also, when simply calling a function from a file, the returned value is not automatically displayed, you must include a call to print
def areaOfRectangle (length,width):
area = length*width
sqArea = length**2
return area,sqArea
def areaOfSquare (length,):
areaOfRectangle (length,width)
return sqArea
#def radiusOfCircle (radius):
area = 3.14*(radius**2)
return area
#def volumeOfCylinder (radius,height):
volume = 3.14*(radius**2)*height
return volume
length = int(input("Input length: "))
width = int(input("Input width: "))
print()
print(areaOfRectangle (10,20))
print()
print(areaOfRectangle (24.3,6))
print()
print(areaOfRectangle (34.9,17.4))
print()
print(areaOfRectangle (length,width))
print()
print(areaOfSquare (10.3))
I need to make two functions, the first function to calculate the area of a rectangle given the length and width. The second function needs to calculate the area of a square given the length of one of its sides. The second function should call the previous function to perform the calculation. I know how to call a function within another function however I don't know how to bring a variable from the first function to the second.
I don't know how to bring a variable from the first function to the second
Typically, this is done through the use of parameters. Let's say you have a value x:
x = 0
You can pass the value to a function by inserting it into the call itself:
f(x)
Lastly, the function needs to be able to handle the parameter you give it:
def f(y): pass
A working example of what you describe:
def f2(y):
return y + 1
def f1():
x = 2
print(f2(x))
f1()
3 is printed.