Why is my function returning `None`? [duplicate] - python

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 5 years ago.
I built a calculation and it works:
num = input("How many numbers would you like to add? ")
list = []
for x in range(num):
list.append(input('Number: '))
a = 0
for x in list:
a=a+x
print a
But when I try to make a function on of this, simply doesn't work. Can you please direct me?
list = []
def adding():
num = input("How many numbers would you like to add? ")
for x in range(num):
list.append(input('Number: '))
a = 0
for x in list:
a=a+x
print adding()

Functions without explicit returns or empty returns will return None.
>>> def foo():
... print("Hello")
...
>>> f = foo()
Hello
>>> f is None
True
If you don't want this, use a return at the end of your function to return some value.
Some other tips.
Make your function only do one thing:
Currently your function is getting input, creating a list, and summing everything. This is a lot. You'll find that if you make your functions smaller, you'll get some nice benefits. You might consider something like this:
def prompt_for_number_of_inputs():
return int(input("How many elements are there in the list? ")
def prompt_for_elements(num_elements):
return [int(input("Enter a number: ")) for _ in range(num_elements)]
def sum_elements_in_list(li):
return sum(li)
so you might use it like this:
num_elements = prompt_for_number_of_inputs()
my_list = prompt_for_elements(num_elements)
print("The sum of all the elements is {0}".format(sum_elements_in_list(my_list))
Don't shadow Python built-ins:
If you call your variables the same thing as Python builtins, you'll find yourself in trouble. See here:
>>> a = list()
>>> a
[]
>>> list = [1,2,3]
>>> a = list()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Normally list() would create an empty list (as seen above), but this is impossible because you've bound an object to the name list. Look at other builtins which could be shadowed here.

You are not returning anything.
Your indentation is incorrect.
You shouldn't use python builtins as variable names (list).
(Note: _ is often used as a disposable variable)
def adding():
num = int(raw_input("How many numbers would you like to add? "))
lst = []
for _ in range(num):
lst.append(int(raw_input('Number: ')))
a = 0
for x in lst:
a += x
return a
You don't really need the second loop as return sum(lst) would do the same thing.
Alternatively, you don't need lst at all:
def adding():
num = int(raw_input("How many numbers would you like to add? "))
a = 0
for _ in range(num):
x = int(raw_input('Number: '))
a += x
return a

I changed your variable name for the list as it shadows the built-in name and added the return statement. Works as you intended it to.
sumlist = []
def adding():
num = input("How many numbers would you like to add? ")
for x in range(int(num)):
sumlist.append(int(input('Number: ')))
a = 0
for x in sumlist:
a=a+x
return a
print(adding())

Related

How can I find the amount of duplicates an element has within a list?

In this code, I have a user-generated list of numbers and have to find the amount of duplicates a specific element has within that list. I am getting an error in the function. How do I fix this?
def count(list,y):
new_list = []
for j in range(0,x):
if(list[j]==y):
new_list.append(list[j])
else:
pass
print(new_list)
length = len(new_list)
print("The number {} appears {} times in the list".format(y,length))
list = []
x = int(input("Please enter the size of the list you want to create: "))
for i in range(0,x):
value = input("Please enter value of list : ")
list.append(value)
print("The list of the values you entered : {}".format(list))
y = int(input("Which element do you want to find the number? : "))
count(list,y)
There were multiple issues in your code.
In the loop in function count instead j you are using i as index.
initiation of loop index till range(0,x) => x is not defined as the variable is not assigned in this scope, instead use len of the list.
All the inputs added to the list were strings and the one that was searched was an integer.
Other suggestions:
do not use list as a variable name as it is a keyword.
Below this code I am also providing a shorter version of the function count.
def count(mylist,y):
new_mylist = []
for j in range(0,len(mylist)):
print(mylist[j])
if(mylist[j]==y):
new_mylist.append(mylist[i])
else:
pass
length = len(new_mylist)
print("The number {} appears {} times in the mylist".format(y,length))
mylist = []
x = int(input("Please enter the size of the mylist you want to create: "))
for i in range(0,x):
value = int(input("Please enter value of mylist : "))
mylist.append(value)
print("The mylist of the values you entered : {}".format(mylist))
y = int(input("Which element do you want to find the number? : "))
count(mylist,y)
Shorter version
def count(mylist,y):
length = mylist.count(y)
print("The number {} appears {} times in the mylist".format(y,length))
one issue, you're trying to acces the i'th element in list, but i is not initialized. Try replacing i with j
for j in range(0,x):
if(list[i]==y):
new_list.append(list[i])
If you don't mind me taking liberties with your code, here's an example using the Counter from collections. Note that it doesn't do exactly the same thing as your code, as Counter doesn't use indexes as you were using before.
from collections import Counter
input_counter = Counter()
while True:
value = input("Please enter a value (or nothing to finish): ")
if value == '':
break
input_counter[value] += 1
print(input_counter)
y = input("Which number do you want to count the instances of? ")
print(input_counter[y])

What is this "studentrecord"?

I based my code on Duncan Betts' codes for my assignment but I don't understand it and it seems like it has been 3 years since he last logged on so I can't ask him.
Can you please explain where did the "studentrecord" code come from? What is it?
num = int(input("How many students?: "))
physics_students = [[input("Input student name: "),float(input("Input grade: "))] for studentrecord in range(num)]
physics_students.sort(key=lambda studentrecord: float(studentrecord[1]))
lowest_grade = physics_students[0][1]
ind = 0
while physics_students[ind][1] == lowest_grade:
ind += 1
second_lowest_grade = physics_students[ind][1]
second_lowest_students = []
while physics_students[ind][1] == second_lowest_grade:
second_lowest_students.append(physics_students[ind][0])
ind += 1
if ind == num:
break
second_lowest_students.sort()
print(*second_lowest_students, sep="\n")
Thank you so much for your help!
The two occurrences of studentrecord refer to 2 different things
In the list comprehension, studentrecord is used to hold each element of the range range(num). It's basically an index, but it's never used anyways.
Edit: I don't think the list comprehension should call it studentrecord because the elements of that range are indices and not lists representing a student's name and grade. It's a little confusing, and the variable should probably be renamed to something like i or _.
That list comprehension is like doing this:
physics_students = []
for studentrecord in range(num):
physics_students.append([input("Input student name: "),float(input("Input grade: "))])
or this:
physics_students = []
for studentrecord in range(num):
physics_students[studentrecord] = [input("Input student name: "),float(input("Input grade: "))]
In the lambda expression, studentrecord is the name of the parameter to your anonymous function. It's like saying this:
def my_lambda(studentrecord):
return float(studentrecord[1]
physics_students.sort(key=my_lambda)

I'm trying to make a piece of code where a user inputs 5 numbers and the code will remove the 5th number. What is wrong with my code?

Here is what I've done so far:
def remove_five ():
list = []
for x in range(0, 4):
number = input("Enter a number")
list.append(number)
end
fifth = list[4]
list.remove(fifth)
remove_five()
I get a 'TypeError when I run the program. This is what it says:
Traceback (most recent call last):
File "G:fivealive.py", line 6, in
list.append(number)
TypeError: descriptor 'append' requires a 'list' object but received a 'str'
Keep indentation correct.
range(0, 4) will generate 0..3. You want range(5).
If you want numbers, convert the input to integers.
Delete elements using the del operation.
Return the created list.
Do not use list as variable name, as it is built-in type
Fixing it should result like that:
def remove_five ():
my_list = []
for x in range(5):
number = int(input("Enter a number"))
my_list.append(number)
del my_list[4]
return my_list
my_list = remove_five()

try except structure don't work. user input integers and if not give an error.how to fix?

print ("please enter values as check([x,y,z])to find min and max")
def check(iterable):
try:
(iterable) = int(iterable)
except:
print("please Enter number")
else:
print("************************")
it = iter(iterable)
first = next(it) # Raises an exception if the input is empty
minimum = maximum = cumsum = first
n = 1
for x in it:
n += 1
cumsum += x
if x < minimum:
minimum = x
if x > maximum:
maximum = x
return "min:" + str(minimum), "max:" + str(maximum)
From what I can break down from what you wrote, the first thing you should be doing is prompting the user to input a list as such:
1,2,3,4
So your code should be written like this to accept this input:
user_input = input("please enter values as #,#,# to find min and max ")
From there, what you want to do is then call your check method with user_input:
check(user_input)
Inside your try/except for your check method, you must now determine how to convert your string which now looks like this:
# pure string
"1,2,3,4"
In to this:
# list of ints
[1, 2, 3, 4]
So, if you simply do this:
# Convert to a list of strings by splitting on comma
iterable = iterable.split(',')
# Iterate over array and convert each element to an int
for i, v in enumerate(iterable):
iterable[i] = int(iterable[i])
To simplify the above, you use what is called a list comprehension, and do this all in one line as such:
iterable = [int(x) for x in iterable.split(",")]
You will end up getting your list of ints. Now, if you end up providing an input like this:
1,a,5
The logic to convert to a list of ints will fail because 'a' is not a int and it will enter your except.
After that, you should be able to continue with the rest of your logic to determine how to get the max and the min.
So, your code should look something like this:
def check_user(user_input):
# code stuff
user_input = input("blah blah")
check_user(user_input)

Python return a value from my function

I am currently trying to figure out how to extract the list of numbers created by this function.
def getInput():
numlist = []
while True:
z = float(input("Enter a number (-9999 to quit): "))
if z == -9999:
print(numlist)
return numlist
else:
numlist.append(z)
print(numlist)
getInput()
Right now the print commands are just for me to confirm that I'm adding numbers to the list, but when the user quits, I need to be able to use new numlist in other functions (I'm going to find the averages of these numbers), and when I try to print the numlist after the function is done, I get an error, which leads me to believe the numlist is disappearing. Could I have some help please?
You are not capturing the numlist being returned.
def getInput():
numlist = []
while True:
z = float(input("Enter a number (-9999 to quit): "))
if z == -9999:
print(numlist)
return numlist
else:
numlist.append(z)
print(numlist)
numlist = getInput()
#do processing here
Your function uses return to return the list object to the caller. You'd store that return value of the function in a new name:
result = getInput()
Now result will be a reference to the same list you built in the function.
You can give it any name you like; it can even be the same name as what was used in the function, but because this name isn't part of the function namespace, that name is entirely separate from the one in the function.
your problem is essentially that any data acquired during a function call is put on the stack, and at the end of the function the stack is cleared. so as mentioned above, result = getInput() would do. or you could pass in a variable to the function as an argument and use that.

Categories