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
Related
I know how to do this with a while loop and know how to use a for-loop in other languages like Java and C++. I want to use a for-loop in place of where I have written the while loop asking for the user input.
# You are required to use for-loop to solve this and round your answer to 2 decimal places. Write
# a program that takes n ∈ N (i.e., any positive integer including zero) from the user and use the
# input value to compute the sum of the following series:
n = -1
while n < 0:
n = int(input("Enter a value to compute: "))
# keep asking for user input until a whole number (0, 1, 2, 3, etc...) has been entered
k = 0
sum = 0
# To hold the sum of the fraction to be displayed
lastTerm = 0
# This variable represents the last term to be added to the fraction sum before the while loop below terminates
if n == 0:
sum = 0
elif n == 1:
sum = 1
else:
while lastTerm != 1 / n:
lastTerm = (n - k) / (k + 1)
sum = sum + (n - k) / (k + 1)
k += 1
print("{:.2f}".format(sum))
# Print the sum to two decimal places
One option is to catch the exception which is thrown when you cannot convert the input to an int, i.e.
while(True):
try:
# read input and try and covert to integer
n = int(input("Enter a value to compute: "))
# if we get here we got an int but it may be negative
if n < 0:
raise ValueError
# if we get here we have a non-negative integer so exit loop
break
# catch any error thrown by int()
except ValueError:
print("Entered value was not a postive whole number")
Alternative, slightly cleaner but I'm not 100% sure isdigit() will cover all cases
while(true):
n = input("Enter a value to compute: ")
if value.isdigit():
break
else:
print("Entered value was not a postive whole number")
How about this? It uses the for loop and sums all the values in the list.
x=[1,2,3,4] #== test list to keep the for loop going
sum_list=[]
for i in x:
j=float(input("Enter a number: "))
if not j.is_integer() or j<0:
sum_list.append(j)
x.append(1) #=== Add element in list to keep the cyclone going
else:
break
sums=sum(sum_list)
print("The Sum of all the numbers is: ",round(sums,2))
Use this to check for whole numbers -
if num < 0:
# Not a whole number
elif num >= 0:
# A whole number
for a for loop:
import itertools
for _ in itertools.repeat([]): # An infinite for loop
num = input('Enter number : ')
if num < 0:
# Not a whole number
pass # This will ask again
elif num >= 0:
# A whole number
break # break from for loop to continue the program
Easier Way -
mylist = [1]
for i in mylist : # infinite loop
num = int(input('Enter number : '))
if num < 0:
mylist.append(1)
pass # This will ask again
elif num >= 0:
# A whole number
break
i have to write a program with a loop that asks the user to enter a series of positive numbers. the user should enter a negative number to signal the end of the series, and after all positive numbers have been entered, the program should display their sum.
i don't know what to do after this, or whether this is even right (probably isn't):
x = input("numbers: ")
lst = []
for i in x:
if i > 0:
i.insert(lst)
if i < 0:
break
you should use input in the loop to enter the intergers.
lst = []
while True:
x = int(input('numbers:'))
if x > 0:
lst.append(x)
if x < 0:
print(sum(lst))
break
def series():
sum1 = 0
while True:
number = int(input("Choose a number, -1 to quit:"))
if number>=0:
sum1+=number
else:
return sum1
series()
while True means that the algorithm has to keep entering the loop until something breaks it or a value is returned which ends the algorithm.
Therefore, while True keep asking for an integer input , if the given integer is positive or equal to zero, add them to a sum1 , else return this accumulated sum1
You can use a while loop and check this condition constantly.
i, total = 0, 0
while i>=0:
total+=i
i = int(input('enter number:'))
print(total)
Also, don't use:
for loop for tasks you don't know exactly how many times it is going to loop
while loop as while True unless absolutely necessary. It's more prone to errors.
variable names that have the same name as some built-in functions or are reserved in some other ways. The most common ones I see are id, sum & list.
do you want that type of code
sum_=0
while True:
x=int(input())
if x<0:
break
sum_+=x
print(sum_)
Output:
2
0
3
4
5
-1
14
if you want a negative number as a break of input loop
convert string to list; input().split()
convert type from string to int or folat; map(int, input().split())
if you want only sum, it is simple to calculate only sum
x = map(int, input("numbers: ").split())
ans = 0
for i in x:
if i >= 0:
ans += i
if i < 0:
break
print(ans)
My task is to:
"Write a program that will keep asking the user for some numbers.
If the user hits enter/return without typing anything, the program stops and prints the average of all the numbers that were given. The average should be given to 2 decimal places.
If at any point a 0 is entered, that should not be included in the calculation of the average"
I've been trying for a while, but I can't figure out how to make the programs act on anything I instruct when the user hits 'enter' or for it to ignore the 0.
This is my current code:
count = 0
sum = 0
number = 1
while number >= 0:
number = int(input())
if number == '\n':
print ('hey')
break
if number > 0:
sum = sum + number
count= count + 1
elif number == 0:
count= count + 1
number += 1
avg = str((sum/count))
print('Average is {:.2f}'.format(avg))
You're very close! Almost all of it is perfect!
Here is some more pythonic code, that works.
I've put comments explaining changes:
count = 0
sum = 0
# no longer need to say number = 1
while True: # no need to check for input number >= 0 here
number = input()
if number = '': # user just hit enter key, input left blank
print('hey')
break
if number != 0:
sum += int(number) # same as sum = sum + number
count += 1 # same as count = count + 1
# if number is 0, we don't do anything!
print(f'Average is {count/sum:.2f}') # same as '... {:.2f} ...'.format(count/sum)
Why your code didn't work:
When a user just presses enter instead of typing a number, the input() function doesn't return '\n', rather it returns ''.
I really hope this helps you learn!
Try this:
amount = 0 # Number of non-zero numbers input
nums = 0 # Sum of numbers input
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
nums+=int(number)
amount += 1
print(round(nums/amount,2)) # Print out the average rounded to 2 digits
Input:
1
2
3
4
Output:
2.5
Or you can use numpy:
import numpy as np
n = []
while True:
number = input()
if not number: # Breaks out if nothing is entered
break
if int(number) != 0: # Only add to the variables if the number input is not 0
n.append(int(number))
print(round(np.average(n),2)) # Print out the average rounded to 2 digits
A list can store information of the values, number of values and the order of the values.
Try this:
numbers = []
while True:
num = input('Enter number:')
if num == '':
print('Average is', round(sum(numbers)/len(numbers), 2)) # print
numbers = [] # reset
if num != '0' and num != '': numbers.append(int(num)) # add to list
Benefit of this code, it does not break out and runs continuously.
So im new to python and this question should be fairly easy for anybody in here except me obvisouly haha so this is my code
for c in range(0,20):
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
c -=1
so as you may think if the number someone inputs is bigger than 9 or smaller than 0 i just want my c to stay where it is so i get 20 positive numbers from 1-9 instead it doesnt do that and it keeps increasing even tho i have the c-=1 thingy down there
First, do not use range(0,20) but range(20) instead.
Second, range returns an iterator. This means, that when you do c-=1 you do not go back in the iterator, you decrease the number returned by the iterator. Meaning that if c=5 and the number you entered in input is 20, c will become 4, but when returning to the start of the loop, c be be 6.
You probably want something of this sort:
c = 0
while c < 20:
print("number",c+1)
number = input ("Enter number:\n")
number = int(number)
if (number < 1 or number > 9):
print("try again by inputing a positive number < 10")
continue
c += 1
an alternative and simple solution to this would be:
i=20
while(i!=0):
number = input("Enter number:\n")
number = int(number)
if (number <1 or number >9):
print("Invalid no try within 0-9 ")
else
print(number)
i-=1
This code is for asserting values into the list until the user inputs a negative number.
Is there a way better to implement it?
Below is my tried version.
i = -1
while i > -1:
x = raw_input("Enter array limit")
for i in limit(x):
listArr = list()
y = raw_input("Enter number")
y.append(listArr)
print (listArr)
Something like this should meet the requirements:
odds = [] # similiar to `listArr` but we only want odd numbers
limit = 5
for _ in range(limit): # Input 5 numbers into an array
y = int(input('Enter number: '))
if y > -1 and y % 2 !=0: # if odd number
odds.append(y) # add to array
else:
break # break after a negative number as input
if odds:
print(min(odds)) # and display minimum odd number
# and if no negative integer input then also display minimum odd number
else:
print(0) # and if no odd number display zero
If Python2 use raw_input() as used in question code, otherwise use input().