How to remember previous numbers inputted in loop? - python

What I want to do, is to write a program that given a sequence of real numbers entered by the user, calculates the mean. Entering the sequence should be finished by inputting ’end’. To input more than 1 number I try:
num=input("Enter the number: ")
while num!="end":
num = input("Enter the number: ")
But I don't want the program to "forget" the first 'num', because I'll need to use it later to calculate the mean. What should I write to input and then use more than one value, but not a specific number of values? User should can enter the values until they enter 'end'. All of values need to be use later to calculate the mean. Any tip for me?

First, define an empty list.
numbers = []
Then, ask for your input in an infinite loop. If the input is "end", break out of the loop. If not, append the result of that input() to numbers. Remember to convert it to a float first!
while True:
num = input("Enter a number: ")
if num == "end":
break
numbers.append(float(num))
Finally, calculate the mean:
mean = sum(numbers) / len(numbers)
print("Mean: ", mean)
However, note that calculating the mean only requires that you know the sum of the numbers and the count. If you don't care about remembering all the numbers, you can just keep track of the sum.
total = 0
count = 0
while True:
num = input("Enter a number: ")
if num == "end":
break
total += float(num)
count += 1
print("Mean: ", total / count)

Mean is sum of all nos/total nos. Let's take input from user and add it to list, because we can easily use sum() function to find sum and len() function to find total nos. Your code:
obs=[]
while True:
num=input("Enter number: ")
if num=="end":
break
else:
obs.append(int(num))
print("Mean: ",(sum(obs)/len(obs)))

Related

How can I sum user input numbers whilst in a loop?

I'm trying to get the sum of numbers that a user inputs in a loop, but I can't get it to include the first number input - here's what I have so far
number = int(input("Enter a number"))
total = 0
while number != -1:
number = int(input("Enter another number"))
total += number
else:
print(total)
Probably something easy I'm missing but I'm stumped ( i am a beginner as you can tell)
I have tried changing the name of the first variable number but I end up in a constant loop even when number = -1
number = int(input("Enter a number"))
total = 0
while number != -1:
total += number
number = int(input("Enter another number"))
else:
print(total)
Just move the summation one line above.

Calculating a minimum number input without using sys module

Write a program in Python that reads a sequence of integer inputs (data) from the user and then prints the following results:
the total of all the inputs
the smallest of the inputs
the largest of the inputs
the number of even inputs
the number of odd inputs
the average of all of the inputs
You do not know how many numbers the user will want to type in, so you must ask her each time if she has another number to add to the sequence.
So far this is my code but I want to know if there's a way without using the sys module
import sys
# declare a variable largest which has smallest integer value
# -sys.maxsize gives the smallest integer value,you can also use any smallest value
largest = -sys.maxsize
# declare a variable smallest, that is assigned with maximum integer value
smallest = sys.maxsize
# declare variables total to store the sum of all numbers
total = 0
# option variable is to store the user option Y or N
option = 'y'
# declare variables to count odd, even and totalCount
evenCount = 0
oddCount = 0
totalCount = 0
print("This program will calculate statistics for your integer data.")
# run the loop when the user enters y or Y
while option == 'y' or option == 'Y':
# take input of number
number = int(input("Please type a number: "))
# add the number to total
total = total + number
# increase totalCount
totalCount = totalCount + 1
# calculate smallest
if number < smallest:
smallest = number
# calculate largest
if number > largest:
largest = number
# calculate count of even and odd numbers
if number % 2 == 0:
evenCount = evenCount + 1
else:
oddCount = oddCount + 1
option = input("Do you have another number to enter? ")
# calculate average
average = total / totalCount
# print the output
print("\nThe total of your numbers is:", total)
print("The smallest of your numbers is:", smallest)
print("The largest nof yout numbers is:", largest)
print("The number of even numbers is:", evenCount)
print("The number of odd numbers is:", oddCount)
print("The average of your numbers is:", average)
The answer to "can it be done?" when it comes to programming is almost always "yes."
In this case, you can test if you're on the first loop iteration and set smallest and largest accordingly.
E.g.
option = 'y'
first_loop = True
while option.lower() == 'y':
x = int(input("Please type a number: "))
if first_loop:
smallest = x
first_loop = False
elif x < smallest:
smallest = x
option = input("Do you have another number to enter? ")
print(f"Smallest number entered is {smallest}")
You might also collect the input numbers into a list.
option = 'y'
inputs = []
while option.lower() == 'y':
x = int(input("Please type a number: "))
inputs.append(x)
option = input("Do you have another number to enter? ")
Now if you have all of the input numbers in inputs, then calculating a minimum and maximum is just min(inputs) and max(inputs).
Interesting approach, when I have problems like this I use float('inf') or float('-inf'). Can easily be worked into your approach.

Write a program that keeps reading positive numbers from the user until the user entered negative numbers

Write a program that keeps reading positive numbers from the user. The program should only quit when the user enters a negative value. Once the user enters a negative value the program should print the average of all the numbers entered.
Here is my code so far
def main():
number = 1
numbers = []
while (number > 0):
number = int(input("Enter a number, put in a negative number to end: "))
if number > 0 :
numbers.append(number)
ratarata = len(numbers)
print ("Average number entered: ", ratarata)
main()
This is the output:
Rather than having an item counter and a running total, use a list as follows:
list_ = list()
while (n := int(input("Enter a number, put in a negative number to end: "))) >= 0:
list_.append(n)
print('Average number entered: ', sum(list_) / len(list_) if list_ else 0)
Note:
This will fail if the input cannot be converted to int
sum_num=0
count=0
while True:
val=int(input())
if val>=0:
sum_num+=val
count+=1
else:
break
try:
print(sum_num/count)
except ZeroDivisionError:
print(0)
ZeroDivisionError will come when your first input in not positive number
while True: is infinite loop which will take infinite input until condition are true.
This is my working answer
number=1
numbers=[]
while number>0:
number=float(input("Enter a positive number. (or a negative number to quit)"))
if number>0:
numbers.append(number)
print("The sum of your numbers is", sum(numbers))
print("The average is", (sum(numbers)/len(numbers)))

How do I calculate the sum of the individual digits of an integer and also print the original integer at the end?

I wish to create a Function in Python to calculate the sum of the individual digits of a given number
passed to it as a parameter.
My code is as follows:
number = int(input("Enter a number: "))
sum = 0
while(number > 0):
remainder = number % 10
sum = sum + remainder
number = number //10
print("The sum of the digits of the number ",number," is: ", sum)
This code works up until the last print command where I need to print the original number + the statement + the sum. The problem is that the original number changes to 0 every time (the sum is correct).
How do I calculate this but also show the original number in the print command?
Keep another variable to store the original number.
number = int(input("Enter a number: "))
original = number
# rest of the code here
Another approach to solve it:
You don't have to parse the number into int, treat it as a str as returned from input() function. Then iterate each character (digit) and add them.
number = input("Enter a number: ")
total = sum(int(d) for d in number)
print(total)
You can do it completely without a conversion to int:
ORD0 = ord('0')
number = input("Enter a number: ")
nsum = sum(ord(ch) - ORD0 for ch in number)
It will compute garbage, it someone enters not a number
number = input("Enter a number: ")
total = sum((int(x) for x in list(number)))
print("The sum of the digits of the number ", number," is: ", total)
As someone else pointed out, the conversion to int isn't even required since we only operate a character at a time.

While loop user input?

Instructions: Create a program that asks a user to enter a series of numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum.
I am using Python 2, Python IDLE
I'm using a while loop for this assignment. So far, I made a program that is saying, while the user enters a positive number under the while loop, collect that number and keep adding it until the user enters a negative number. I am trying to find a way to include the first user input into the program.
print('This program calculates the sum of the numbers entered and ends
after inputting a negative number')
total = 0.00
number = float(input('Enter a number: '))
while number >= 0:
print('Enter another positive value if you wish to continue. Enter a
negative number to calculate the sum.')
number = float(input('Enter a number: '))
total = total + number
print('The sum is', total)
Have reduced your code to the below.
Performs checking of input in while loop and exits upon negative value.
total = 0.00
while True:
print('Enter another positive value if you wish to continue. Enter a negative number to calculate the sum.')
number = float(input('Enter a number: '))
if number >= 0: # Check for positive numbers in loop
total += number
else:
break
print('The sum is', total)
I assume you're a beginner, so firstly welcome to Python! I hope you're having fun. Now, as far as your code goes, there are two things I noticed off the bat:
You can simply put this 'Enter another positive value if you wish to continue.
Enter a negative number to calculate the sum.' inside your input, why bother
with an extra print statement?
You don't have to call the input() function twice.
Here's how I'd do it:
print('This program calculates the sum of the numbers entered and ends
after inputting a negative number')
total = 0.00
while True:
number = float(input("Enter a positive number(Negative number if you wish to terminate program"))
if number >=0:
total += number #equivalent to total=total + sum
else:
break # break out of while loop
print('The sum is', total)
P.S - Why are you using Python 2 btw ?

Categories

Resources