Python passing return values to functions - python

I'm trying to make a program that will generate a random list, length being determined by user input, that will be sorted. I'm having a problem accessing/passing my randomly generated list to other functions. For example, below, I can't print my list x. I've also tried making a function specifically for printing the list, yet that won't work either. How can I pass the list x?
unsorted_list = []
sorted_list = []
# Random list generator
def listgen(y):
"""Makes a random list"""
import random
x = []
for i in range(y):
x.append(random.randrange(100))
i += 1
return x
def main():
y = int(input("How long would you like to make the list?: "))
listgen(y)
print(x)
main()

x = listgen(y)
def main():
y = int(input("How long would you like to make the list?: "))
x = listgen(y)
print(x)
x should be assigned based on return value of your function

l = listgen(y)
print(l)
The variable x is local to listgen(). To get the list inside of main(), assign the return value to a variable.

In your main, this:
def main():
y = int(input("How long would you like to make the list?: "))
listgen(y)
print(x)
should be:
def main():
y = int(input("How long would you like to make the list?: "))
x = listgen(y) # Must assign the value returned to a variable to use it
print(x)
Does that make sense?

Related

how to use functions and return statement with for loop in python

def calculation(numbers):
for i in range(1,11):
maths = i * numbers
result = print(f"{numbers} x {i} = {maths}")
return result
user_input = int(input('enter a number: '))
x = calculation(user_input)
print(x)
So this is a multiplication program using for loop.
when am returning "result" its doing the calculations but after that its returning NONE
why is it doing that? and what is the fix for it?
I tried returning "maths" but its only returning the last iteration I don't want that,
I want to see all the iterations.
The print() should be removed.

I need to make a generator function that takes *args as an input

I need to make a function which will return successively as a generator,
the square of the difference of each value from the average of all the values given as input.
The function must
A) accept an undefined number of parameters
B) be a generator function
The values will be integers.
To calculate the average of all values I can import statistics.
Have you got any idea?
The code I tried to write:
import statistics
def squares(*args):
for i in args:
a=(args-av)**2
yield a
lst=[]
count = int(input("Give the amount of numbers: "))
for i in range (0,count):
ele=int(input())
lst.append(ele)
av=statistics.mean(lst)
for i in squares(*lst):
print(i)
The only error in your script comes from using args instead of i in your calculations:
import statistics
def squares(*args):
for i in args:
a=(i-av)**2 # <-- There.
yield a
lst=[]
count = int(input("Give the amount of numbers: "))
for i in range (0,count):
ele=int(input())
lst.append(ele)
av=statistics.mean(lst)
for i in squares(*lst):
print(i)
I would also advise using def squares(av, *args) just so that your av does not come out of somewhere. You then have to modify your last but one line to for i in squares(av, *lst). Otherwise everything looks ok!
My suggestion:
import statistics
def squares(average, *items):
for item in items:
yield (item - average)**2
lst = []
count = int(input("Give the amount of numbers: "))
for _ in range(count):
item = int(input())
lst.append(item)
average = statistics.mean(lst)
for square in squares(average, *lst):
print(square)
Your av variable should be computed inside the generator function:
def squares(*args):
av = sum(args)/len(args)
for a in args:
yield (a-av)**2

Adding elements to list after get 2 or more inputs on Python

def take_info(arr2,arr, number):
arr[0] = number
name = input()
arr[1] = name
grade = int(input())
arr[2] = grade
second_grade = int(input())
arr[3] = second_grade
arr2. append(arr)
def main():
number = int(input())
arr = [0] * 4
count =1
arr2 = // ? I dont know how to do it, range must be equal to count but how? Thats the point 1.
while number>0:
take_info(arr2,arr,number)
count +=1
number = int(input())
main()
take_info function must return while ' number >0 ', when the number is 0 or less than 0 loop would end. And I want to add these values and name to a list and the other list's each element should be list. Could anyone can help me ?
Any time you're repeating something, you probably want to use a loop. If you're using a loop to build a list, you probably want to use a list comprehension.
arr = [input() for _ in range(3)]
Given your updated question, I might do it like this:
def take_info(number):
return [number, input(), int(input()), int(input())]
def main():
return [take_info(number) for number in range(int(input()))]
print(main())
If it's important that the numbers count down instead of up, you can do that by modifying the range call so that it goes from N-1 to 0 instead of 0 to N-1.
Alternatively, if you want to have space separated inputs in one line, you can use this:
my_list = list(map(str,input().split()))
for i in range(len(my_list)):
if (isinstance(my_list(i), int)):
temp = int(my_list(i))
my_list.pop(i)
my_list.insert(i, temp)
Input: Car Hockey Cricket
my_list = ['Car', 'Hockey', 'Cricket']
Ofcourse, the data type would be the same here. You'd need to make changes after appending incase of int, float, etc.
The stereotype of Python is that “everything is a dict”. Your application might be such a case.
One way to organize the data you have coming in might be a dict where each entry is also a dict.
def take_info():
record = dict()
record['name'] = input('Name: ')
record['grade'] = int(input('Grade: '))
record['second_grade'] = int(input('Second grade: '))
return record
def main():
course_records = dict()
count = 0
number = int(input('ID number: '))
while number > 0:
course_records[number] = take_info()
count +=1
number = int(input('ID number: '))

How to add elements to a List in python?

I'm working on this task in python, but I'm not sure if I'm adding the elements to a list the right way. So basically I'm suppose to create a create_list function the takes the size of the list and prompt the user for that many values and store each value into the list. The create_list function should return this newly created list. Finally the main() function should prompt the user for the number of values to be entered, pass that value to the create_list function to set up the list, and then call the get_total function to print the total of the list. Please tell me what I'm missing or doing wrong. Thank you so much in advance.
def main():
# create a list
myList = []
number_of_values = input('Please enter number of values: ')
# Display the total of the list elements.
print('the list is: ', create_list(number_of_values))
print('the total is ', get_total(myList))
# The get_total function accepts a list as an
# argument returns the total sum of the values in
# the list
def get_total(value_list):
total = 0
# calculate the total of the list elements
for num in value_list:
total += num
#Return the total.
return total
def create_list(number_of_values):
myList = []
for num in range(number_of_values):
num = input('Please enter number: ')
myList.append(num)
return myList
main()
In main you created empty list, but didn't assign create_list result to it. Also you should cast user input to int:
def main():
number_of_values = int(input('Please enter number of values: ')) # int
myList = create_list(number_of_values) # myList = function result
total = get_total(myList)
print('the list is: ', myList)
print('the total is ', total)
def get_total(value_list):
total = 0
for num in value_list:
total += num
return total
def create_list(number_of_values):
myList = []
for _ in range(number_of_values): # no need to use num in loop here
num = int(input('Please enter number: ')) # int
myList.append(num)
return myList
if __name__ == '__main__': # it's better to add this line as suggested
main()
You must convert inputs to integer. input() returns a string object. Just do
number_of_values = int(input('Please enter number of values: '))
And with every input you want to use as integer.
First Problem is you are not passing myList to create_list function, so myList inside of main is not going to get updated.
If you want to create a list inside the function and return it, and then get a total for that list, you need to first store the list somewhere. parse the inputs as integer, also, always do if __name__ == '__main__':. The Following code should work and print the correct result :)
def main():
number_of_values = int(input('Please enter number of values: '))
myList = create_list(number_of_values)
print('the list is: ', myList)
print('the total is ', get_total(myList))
def get_total(value_list):
total = 0
for num in value_list:
total += num
return total
def create_list(number_of_values):
myList = []
for num in range(number_of_values):
num = int(input('Please enter number: '))
myList.append(num)
return myList
if __name__ == '__main__':
main()
An alternative method to the posted solutions could be to have one function that creates your said list and finds the total of that list. In the solution, the map function goes through all the values given to it and only keeps the integers (The split method is used to remove commas and spaces from the values). This solution will print your list and values, but will not return any said value, so it will produce a NoneType, if you were to examine the function at the end.
def main():
aListAndTotal()
#Creates list through finding the integers and removing the commas
#For loop iterates through list and finds the total
#Does not return a value, but prints what's stored in the variables
def aListAndTotal():
myList = map(int, input("Please enter number of values: ").split(","))
total = 0
for num in myList:
total += num
print ("The list is: ", myList)
print ("The total is: ", total)
if __name__ == "__main__":
main()
List is one of the most important data structure in python where you can add any type of element to the list.
a=[1,"abc",3.26,'d']
To add an element to the list, we can use 3 built in functions:
a) insert(index,object)
This method can be used to insert the object at the preferred index position.For eg, to add an element '20' at the index 1:
a.index(1,20)
Now , a=[1,20,'abc',3.26,'d']
b)append(object)
This will add the object at the end of the list.For eg, to add an element "python" at the end of the list:
a.append("python")
Now, a=[1,20,'abc',3.26,'d','python']
c)extend(object/s)
This is used to add the object or objects to the end of the list.For eg, to add a tuple of elements to the end of the list:
b=(1.2, 3.4, 4.5)
a.extend(b)
Now , a=[1,20,'abc',3.26,'d','python',1.2, 3.4, 4.5]
If in the above case , instead of using extend, append is used ,then:
a.append(b)
Now , a=[1,20,'abc',3.26,'d','python',(1.2, 3.4, 4.5)]
Because append takes only one object as argument and it considers the above tuple to be a single argument that needs to be appended to the end of the list.
You need to assign the return value of create_list() to a variable and pass that into get_total()
myList = create_list()
total = get_total(myList)
print("list " + str(myList))
print("total " + str(total))
Adding an element to an existing list in python is trivial.
Assume who have a list names list1
>>> list1 = ["one" , "two"]
>>> list1 = list1 + "three"
this last command will add the element "three" to the list. This is really simple, because lists are objects in python. When you print list1 you get:
["one" , "two" , "three"]
Done

Making a list in sentinel loop (beginnger) PYTHON

after much google'ing and note searching I have yet to come upon an answer for making this List of mine work, if you do answer could you explain what I was doing wrong because this problem is determined to not let me work.
code:
def main():
x = int(input("Enter a number (0 to stop) "))
y = x
l = []
while x != 0:
x = int(input("Enter a number (0 to stop) "))
l = [x]
print(l[x])
main()
I thought I was supposed to initialize the list outside of the loop, and in the loop I thought it would take whatever X is inputted as and store it to later be printed out after it, but that wasn't the case. Any pointers?
You would need to append to the list each time:
def main():
x = int(input("Enter a number (0 to stop) "))
l = [x] # add first x, we will add to the is list not reassign l inside the loop
while x != 0:
x = int(input("Enter a number (0 to stop) "))
l.append(x) # append each time
print(l) # print all when user enters 0
l = [x] reassigns l to a list containing whatever the value of x is each time through the loop, to get all numbers you have to append to the list l initialised outside the loop.
You could also use iter with a sentinel value of "0":
def main():
l = []
print("Enter a number (0 to stop) ")
for x in iter(input,"0"):
print("Enter a number (0 to stop) ")
l.append(int(x))
print(l)

Categories

Resources