How to get this to stop at 20 - python

I would like for this to stop at 20. By which I mean, when it asks you to input another number it should stop after the 20th time.
Currently I have an accumulating counter that when it reaches 20 it prints the "Enter one more number". It does this at the 20th time, but afterwards it keeps going with asking you to input more numbers. I would like it to stop asking for input after the 20th time.
Thanks. This is apart of a larger homework problem.
def main ():
print()
print("Finds the lowest, highest, average, and total to 20 numbers.")
print()
number, count, numberlist = getnumber()
print("Stop.")
def getnumber ():
count = 0
numberlist = []
for count in range(20):
count = count + 1
number = float(input("Please enter another number : "))
numberlist.append(number)
while count != 20:
number = float(input("Please enter one more number : "))
numberlist.append(number)
return number, count
main()

You could do this as follows:
def get_numbers(count=20):
numbers = []
numbers.append(float(input("Please enter a number : "))) # first
for _ in range(count-2):
numbers.append(float(input("Please enter another number : "))) # next 18
numbers.append(float(input("Please enter one more number : "))) # last
return numbers
Note that with a for loop you don't need to manually increment the loop counter. Also, there is no need to return count; you already know how many there will be.

First of all, note that you are not changing value of count inside while loop - that is why it never stops. After for is executed count is exactly 19 and never reaches 20 after that.
Second of all, you do not need while at all - for loop will work for 20 iterations and stop
def getnumber ():
count = 0
numberlist = []
for count in range(20):
count = count + 1
number = float(input("Please enter another number : "))
numberlist.append(number)
return number, count, numberlist

Here is another option (your approach extended)
limit = 5
def main ():
print("Finds the lowest, highest, average, and total to {} numbers.".format(limit))
numbs = getnumber()
print(numbs)
print("lowest:", min(numbs))
print("highest:", max(numbs))
print("avg:", sum(numbs)/len(numbs))
print("total:", sum(numbs))
print("Stop.")
def getnumber ():
numberlist = []
for count in range(limit):
if count == limit-1:
number = float(input("Please enter one more number : "))
numberlist.append(number)
else:
number = float(input("Please enter another number : "))
numberlist.append(number)
return numberlist
main()
Output
Finds the lowest, highest, average, and total to 5 numbers.
[6.0, 3.0, 8.0, 4.0, 2.0]
('lowest:', 2.0)
('highest:', 8.0)
('avg:', 4.6)
('total:', 23.0)
Stop.

There are some problems with the code you posted. First of you should indent the return statement so it is part of getnumber. Secondly you return two values but unpack three values in main. If I fix those two things the code works. The reason that count is 20 after the for loop is that you declare count outside the loop, so on each iteration count will be set to the next integer and then incremented once more by
count = count + 1
If you did not have the extra increment inside the loop, count would be 19 after the for loop terminates because range(N) does not include N.
And you can rewrite the code with a list comprehension to get a very concise version
def getnumber(prompt, n):
return [float(input(prompt)) for _ in range(n)]
This will give you a list of the numbers.

Related

I have just started coding and am stuck solving this python problem

Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.
This is what I have come up with so far
num = int(input("How many number's are there?"))
total_sum = 0
avg = total_sum / num
for n in range (num):
number = float(input("Enter a number"))
while number <0:
print = ("Average is", avg)
number >0
print(number)
total_sum += number
avg = total_sum / num
print = ("Average is", avg)
I need it to stop at -1 one and still give an average of the numbers listed.
Easy.
emp = []
while True:
ques = int(input("Enter a number: "))
if ques != -1:
emp.append(ques)
continue # continue makes the code go back to beginning of the while loop
else:
if len(emp) != 0:
avg = sum(emp) / len(emp) # average is the sum of all elements in the list divided by the number of elements in said list
print(f"Average of all numbers entered is {avg}")
break
else:
print("Give me at least one number that's not -1")
continue # emp is empty we need at least one number to calculate the average so we go back to the beginning of the loop

How do you Multiply numbers in a loop in Python from a list of user inputs

I need to create something that can multiply values no matter how many values there are. My idea is to use a list and then get the sum of the list with the sum function or get the first value of the list and set it as the total and then multiply the rest of the list by that total. Does anyone have a way to do it?
Here was my original idea:
total = 0
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
break
else:
total *= number
print(f"The total is: {total}")
however as you may have guessed it just automatically multiplies it to 0 which equals zero. I would also like the code to work for subtraction and division (Already got Addition working)
thanks!
Thanks to the comments I worked out that the way to do it is by changing the beginning total to a 1 when fixed it is this:
total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
break
else:
total *= number
print(f"The total is: {total}")
Since you are multiplying, you must start with 1 cause anything multiplied by 0 is 0. And idk why you need sum()
total = 1
while True:
number = float(input("Enter a number and I’ll keep multiplying until you enter the number 1: "))
if number == 1:
print(f"The total is: {total}")
break
else:
total *= number

Cannot get += to work properly between functions in python

So my task is simple: I am to make two functions,
one which takes input from a user as a list of integers. (User enters how many entries, then begins entering them individually)
second function reads that list and returns how many times a chosen value was found in that list.
For some reason when combining these functions, the count does not stay at 0 and count whenever x is seen in the list; it just jumps to whatever the initial entry count was.
code is as follows:
def get_int_list_from_user():
list1 = []
numNums = int(input("Enter number count: "))
for x in range(numNums):
nextval = int(input("Enter a whole number: "))
list1.append(nextval)
return list1
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
count += 1
print("Target counted ", count, "time(s)")
return count
Over here is where I've tried different ways of calling the functions, but each time just ends up with the same result.
list1 = my_functions.get_int_list_from_user()
count = my_functions.count_target_in_list(int_list=list1)
I also tried this:
my_functions.count_target_in_list(int_list=my_functions.get_int_list_from_user())
This statement does not do what you think it does:
for target_val in int_list:
That essentially erases the original value passed into the function, and instead runs through the whole list, one element at a time. So, count will always be equal to the length of the list. You wanted:
for val in int_list:
if val == target_val:
count += 1
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for target_val in int_list:
count += 1
print("Target counted ", count, "time(s)")
return count
instead, using this logic, you need to compare the loop values with the target value. in the code above the target value will be overridden by the iteration of the loop.
def count_target_in_list(int_list):
target_val = int(input("Enter target value: "))
count = 0
for value in int_list:
if target_val == value :
count += 1
print("Target counted ", count, "time(s)")
return count

Set total equal to zero when computes the sum of given numbers

I'm a newbie of python and I'm trying to practice some exercises, however I'm stuck with the line "total = 0" in this code. Actually I don't really understand why this value is initialized to 0.
Could anyone please explain it for me ?
def main():
print("This program allows you to total up some numbers")
print()
n = int(input("How many numbers do you have? "))
total = 0
for i in range(n):
num = float(input("Enter a number: "))
total = total + num
print()
print("The sum of the numbers is:", total)
main()
Remove that line and you see you will get an error:
NameError: name 'total' is not defined
This is because both total and num must be initialised before you can use them in total = total + num
You initialise it before the for loop otherwise it would be reset to 0 each time.

Trying to rewrite variables

print("Please enter some integers to average. Enter 0 to indicate you are done.")
#part (a) -- what are the initial values for these variables?
#incomplete
done = 0
mySum = 0
count = 0
while not done:
valid = False #don't yet have a valid input
while not valid: #this loop keeps attempting to get input until the user enters an integer
try:
num = int(input())
valid = True #now the input is valid, and can use it
except ValueError:
print("Input must be an integer.")
if num == 0:
break
mySum = sum(num)
count = len(num)
#part (b) -- fill in the inside of this if statement
#incomplete
else: print num #part (c) -- if num is not zero, then... fill in the code
#incomplete
avg = mySum / count #calculates average
print("The average is", avg) #prints average
Excuse the comments as this is an assignment from an instructor. As you can see, line 28 of the code shows a divide by zero error for variable mySum. In the while loop I overwrote(or at least tried to) mySum, but still got the division error. Am I going about this correctly or is there some syntax I'm not following?
EDIT: New attempt:
#part (a) -- what are the initial values for these variables?
#incomplete
done = 0
mySum = []
count = len(mySum)
while not done:
valid = False #don't yet have a valid input
while not valid: #this loop keeps attempting to get input until the user enters an integer
try:
num = int(input())
valid = True #now the input is valid, and can use it
except ValueError:
print("Input must be an integer.")
if num == 0:
break
#part (b) -- fill in the inside of this if statement
#incomplete
else: mySum.append(num)
count +=1#part (c) -- if num is not zero, then... fill in the code
#incomplete
avg = sum(mySum) / count #calculates average
if len(mySum) == 0:
print "You haven't entered any number"
else: print ("The average is", avg)
The "divide by zero" is a consequence of other problems in your code (or incompleteness of it). The proximate cause can be understood from the message: you are dividing by 0, which means count is 0 at that point, which means you haven't actually tracked the numbers you put in. This, in turn, is - because you don't do anything with the numbers you put in.
In case num == 0, you immediately break the loop; the two statements below do not execute.
In case of not num == 0, you just print the number; there is not storing of a number into an array that you can sum later, there is no += summing in an interim variable, and there is certainly no incrementing of count.
There is two basic ways to do this, hinted to by the above:
List: Make an empty list outside the loop, when 0 is entered just break, otherwise add the new number to the list. After the loop, check the length: if it's zero, complain that no numbers have been entered, otherwise divide the sum by the length. No count required.
Running total: Initialize total and count variables to 0 outside the loop; again, just break on a 0, otherwise add one to the count and the number to the total. After the loop, do the same, just with total and count instead of with sum and len.
Denominator cannot be zero. In this case, count is zero.
You may need to use count += 1 instead of count = len(num).
You should check whether the denominator is zero before you do the division.
Suggestion: study python 3 instead of python 2.7. Python 2 will be finally replaced by python 3.
mySum = 0
count = 0
while True: # this loop keeps attempting to get input until the user enters an integer
try:
num = int(input("input a num "))
except ValueError:
print("Input must be an integer.")
continue
if num == 0:
break
else:
mySum += num
count += 1
print(num)
avg = mySum / count if count else 0
print("The average is", avg) # prints average

Categories