Call an input list in a function from another function - python-3.x

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.

Related

Can we change for loop result into list with index?

I am currently learning python, I just have one little question over here.
I used for loop and getting a result below.
Here is my code:
def psuedo_random(multiplier, modulus, X_0, x_try):
for i in range(x_try):
place_holder = []
count = []
next_x = multiplier * X_0 % modulus
place_holder.append(next_x)
X_0 = next_x
for j in place_holder:
j = j/modulus
count.append(j)
print(count)
Result:
[0.22021484375]
[0.75439453125]
[0.54443359375]
[0.47705078125]
Can we somehow change it into something like this?
[0.22021484375, 0.75439453125, 0.54443359375, 0.47705078125]
After you initialized a list, you can use append function in the loop.
initialize a list where you want to list these numbers
mylist = []
use this function in your for loop
for i in .....:
mylist.append(i)
It's simple. Do not initialize your list inside the loop. Just place it outside.

comparing elements of a list from an *args

I have this function that I need to compare the strings in a list to a *args
The reason being is that, the user should be able to type any words in the 2nd argument. However when I try to compare the strings to the *args it doesn't give me any results
def title_case2(title, *minor_words):
for x in title.split():
if x in minor_words:
print(x)
Assuming I ran the function with the parameters below. I was hoping it would display a and of since these words are found on those 2 entries.
title_case2('a clash of KINGS','a an the of')
*args is a tuple of arguments, so you're actually checking if x is in ('a an the of',). So either pass your argument as:
title_case2('a clash of KINGS', *'a an the of'.split())
Or, use this as your test:
if any(x in y for y in minor_words):
In either of the above cases the output is:
a
of
This is one approach.
Ex:
def title_case2(title, *minor_words):
minor_words = [j for i in minor_words for j in i.split()] #Create a flat list.
for x in title.split():
if x in minor_words:
print(x)
title_case2('a clash of KINGS','a an the of', "Jam")
using a for-loop instead of list comprehension
def title_case2(title, *minor_words):
minor_words_r = []
for i in minor_words:
for j in i.split():
minor_words_r.append(j)
for x in title.split():
if x in minor_words_r:
print(x)

how to print the median of a list in python

I've written code to find the median of a list but I'm unsure how to display it when I run the code.
I've tried the print function but I'm not sure what to print.
My code is:
wages = [1,2,3]
def median(wages):
sorted_list = sorted(wages)
length = len(sorted_list)
center = length // 2
if length == 1:
return sorted_list[0]
elif length % 2 == 0:
return sum(sorted_list[center - 1: center + 1]) / 2.0
else:
return sorted_list[center]
Any help would be appreciated.
You can just call your function in the print statement:
print(median(wages))
or
print(median([1,2,3])
You might be confused because you labelled wages as the array and put it in the definition of your function, but there is no connection between the two wages in your code. The line
wages = [1,2,3]
creates a variables called wages but it doesn't impact the wages in the line:
def median(wages):
or inside your function definition. To read more have a look into variable scopes in python.
For example, you could call your function on any array such as,
test_array = [1,2,3,4]
print(median(test_array))
You can just print the return value of your median method.
def median():
your code here
print(median())
PS : There are some indentation errors in your code.

Problem with calling a variable from one function into another

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.

Passing a list from one function to another

I need help understanding this instruction.
Your main program code should call the “getData” function. Pass the list returned from the “summer” function to “getData” and save the sum that function returns.
def getData():
fin = open("sample.dat","r")
numbers=[]
for line in fin:
val =line.rstrip()
numbers.append(val)
return numbers
def summer(lst):
sum=0
for n in range(0,13,2):
sum+=powerval(lst[n],lst[n+1])
return sum
If the instruction read,
Pass the list
returned by the getData function to summer and save the sum that
function returns.
then try:
total = summer(getData())
I think this satisfies the requirements.
def getData(lst):
for l in lst:
do something with sum
save sum
return sum
invoke as:
getData(summer(some_other_data))

Resources