i = 0
result = 0
while i < 10 :
result += eval(input("Enter a number: "))
i += 1
if result < 1 :
break
average = result / i
print (average)
I am making a program to calculated average of 10 numbers but it will terminate if a negative number is entered. The problem is that if a negative number is enter the program won't stop until the negative number is greater than all the other numbers that have been entered.
This code doesn't necessarily halt on a negative number. It does this only if that negative number brings the running total to a non-positive amount. For example, if the user enters the following numbers:
4
-2
4
Then the running totals are:
4
2
6
At no point is the running total (result) non-positive. So the condition for that break statement won't be true.
If you want to terminate any time a negative number is entered (or, rather, a non-positive number based on your logic), you need to check that number itself, not the running total. Something like this:
i = 0
result = 0
value = 0;
while i < 10 :
value = eval(input("Enter a number: "))
if value < 1 :
break
i += 1
result += value
average = result / i
print (average)
Related
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
The homework question is: "Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total
and average of the input values (not counting zeros). Your program ends with the
input 0. Display the average as a floating-point number."
positive = 0
negative = 0
total = 0
count = 0
number = eval(input("Enter an integer, the input ends if it is 0:"))
while number != 0:
total += number
count += 1
if number > 0:
positive += 1
elif number < 0:
negative += 1
else:
break
average = total/count
print("The number of positives is", positive)
print("The number of negatives is", negative)
print("The total is", total)
print("The average is", average)
After a number is inputted, the program does not output anything else.
Write a program that reads an unspecified number of integers
That implies that you have to repeatedly take number inputs from the users, but using input() would only really input a single number at a time.
So you should input your number inside the while-loop, example:
while True:
number = int(input("Enter an integer, the input ends if it is 0:"))
total += number
count += 1
if number > 0:
positive += 1
elif number < 0:
negative += 1
elif number == 0:
break
You need to continue prompting for numbers until a zero is entered. An easy way to do this is to put your numbers into a list, which you can then compute the different stats from at the end:
numbers = []
while not numbers or numbers[-1] != 0:
numbers.append(int(input("Enter an integer, the input ends if it is 0: ")))
numbers.pop() # discard the 0
print("The number of positives is", sum(n > 0 for n in numbers))
print("The number of negatives is", sum(n < 0 for n in numbers))
print("The total is", sum(numbers))
print("The average is", sum(numbers) / len(numbers))
I'm currently trying to use simple while loops to count down from a given positive number to zero and then stop. If the number isn't a positive number then it should loop and ask again. I've gotten most of it down, but I can't make it count down to zero. Right now it just stops at 1.
For this problem, zero is not counted as a positive number. If zero is entered, it should loop back to the initial prompt.
This is the code I have so far:
# set loop variable
looking_for_positive_number = True
# get positive number
while (looking_for_positive_number == True):
reply = input("Enter positive number: ")
int_reply = int(reply)
# count down from given positive number to 0, loop back to reply if not
while int_reply > 0:
print(int_reply)
int_reply = int_reply - 1
looking_for_positive_number = False
This is what it returns (I used 5 as the positive number):
Enter positive number: 5
5
4
3
2
1
Ideally, it should return something like this (also used 5 here):
Enter positive number: 5
5
4
3
2
1
0
I don't know what I'm missing/what I'm doing wrong. Any help would be appreciated. Thanks in advance!
EDIT: I figured it out, I just had to include an if statement in the nested while loop. Final code looks like this:
# set loop variable
looking_for_positive_number = True
# get positive number
while (looking_for_positive_number == True):
reply = input("Enter positive number: ")
int_reply = int(reply)
# count down from given positive number to 0, loop back to reply if not
# ZERO DOES NOT COUNT AS POSITIVE NUMBER -- SHOULD LOOP BACK IF 0 IS ENTERED
while int_reply > 0:
print(int_reply)
int_reply = int_reply - 1
# want to print 0 after we get down to 1 (but not include 0 in our initial loop)
if int_reply == 0:
print(0)
# finish and exit loop
looking_for_positive_number = False
# get positive number
while (looking_for_positive_number == True):
reply = input("Enter positive number: ")
int_reply = int(reply)
if int_reply <= 0:
print( "Not a positive number." )
continue
# count down from given positive number to 0, loop back to reply if not
while int_reply > 0:
print(int_reply)
int_reply = int_reply - 1
looking_for_positive_number = False
The Python range function could simplify your logic (slightly). Using a negative step value it will count down instead of counting up.
Example:
while True:
number = int(input("Enter a postive integer value: "))
if number <= 0:
print("Not a positive number.")
continue
for i in range(number, -1, -1):
print(i)
break
Output:
Enter a postive number: 5
5
4
3
2
1
0
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.
I am trying to get average times of the speed skaters with Python and my code will not work. I have searched all over trying to find an answer and I am completely stumped.
print("Enter the skater times in seconds. Input -1 to finish and calculate.")
count = 0
sum = 0.0
number = 1
while number != -1:
number = input("Enter skater time in seconds: ")
if number != 0:
count = count + 1
sum = sum + number
print ("The number of skaters was: ", count)
print ("The average skater time was:", sum / count)
The if clause must be:
if number > 0:
Otherwise you are considering the last one, whose value is -1
Edit
I think it has nothing to do with integer division. It is only the if clause.
You can add from __future__ import division and it will make all divisions be floats.