While loop user input? - python

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 ?

Related

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 to remember previous numbers inputted in loop?

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)))

While loop won't terminate

Learning Python. This task is to allow the user to enter numbers as long as the number isn't -99. If the sentinel -99 is entered, the user will no longer be able to enter numbers, and the largest and smallest numbers that have already been entered will be displayed. When I enter the number -99, however, the loop continues to ask for new numbers.
#main module
def main():
#Instructions for user
print ("This program will allow the user to enter several numbers,
positive ")
print ("or negative, and sort the largest and smallest numbers from
them.")
#First number entered by user
inputNum = input ("Enter a number other than -99 to be sorted: ")
#variables
number = inputNum
small=number
large=number
#while loop for getting/sorting numbers
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = input("Enter a number other than -99 to be sorted: ")
lgSm()
#Module for displaying large and small numbers
def lgSm():
print ("The largest number you entered is: ", large)
print ("The smallest number you entered is: ", small)
main()
Edit:
Solved. I forgot to add the variables inside the ()...I'm not sure what these are called, but I do understood their function. Are they called placeholder variables?
#main module
def main():
#Instructions for user
print ("This program will allow the user to enter several numbers, positive ")
print ("or negative, and sort the largest and smallest numbers from them.")
#First number entered by user
inputNum = int (input ("Enter a number other than -99 to be sorted: "))
#variables
number=inputNum
small=number
large=number
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = int (input("Enter a number other than -99 to be sorted: "))
number = inputNum
lgSm(large, small)
#Module for displaying large and small numbers
def lgSm(lg, sm):
print ("The largest number you entered is: ", lg)
print ("The smallest number you entered is: ", sm)
main()
Modify your while loop to update number variable; the value of number is not changing inside the loop
while number != -99:
if number < small:
small = number
elif number > large:
large = number
inputNum = int(input("Enter a number other than -99 to be sorted: "))
number = inputNum ## this line in particular

Deleting numbers from lists.PYTHON

I am creating a python program, to allow a user to input numbers and find the total, average, highest and lowest of the numbers inputted. my teacher has told me to improve the program by removing the first and last number inputted into the list.I am confused on how doing so,as the list does not exist until the user has inputted the numbers into it.
THIS IS MY CODE SO FAR:
totalList=[]
totalList = totalList[1:-1]
TotalNum = int(input("Please enter how many numbers are to be entered:"))
Change=TotalNum
Input=0
Total=0
while TotalNum>0:
TotalNum = TotalNum - 1
Input = int(input("Enter Number: "))
totalList.insert(-1,Input)
Total = Total +Input
print("Total:" ,Total)
print("Average:",Total/Change)
print("Highest:",max(totalList))
print("Lowest:",min(totalList))

Accumulator using For Loop in Python

My teacher wants a program to ask the user for a positive integer number value, which the program should loop to get the sum of all integers from 1 up to the numbered entered. In For Loop using Python.
Here's what I came up with for the For Loop but it is not's not looping when I type in a negative number and it won't display an answer when I input a positive number after inputting a negative number.
x=int(input("Please pick a positive integer"))
sum=0
for i in range(1,x):
sum=sum+1
print(sum)
else:
x=int(input("Please pick a positive integer"))
Help?
How about implementing something like the following. There are a few problems with your program, most notably:1. The sum is being repeatedly printed for every value. 2. You are simply adding 1 to the sum instead of adding the integer i. 3. You are not returning on your function if your user does not enter a positive integer. 4. You have no if statement for if the integer is greater than 0.
def intpicker():
x=int(input("Please pick a positive integer"))
sum=0
if x >= 0:
for i in range(1,x):
sum=sum+i
print(sum)
else:
return intpicker()
This code could be further abbreviated, but for all intents and purposes you should probably just try and understand this implementation as a start.
There are a few fatal flaws in your program. See below:
x=int(input("Please pick a positive integer")) #what if the user inputs "a"
sum=0
for i in range(1,x): # this will not include the number that they typed in
sum=sum+1 # you are adding 1, instead of the i
print(sum)
else:
x=int(input("Please pick a positive integer")) # your script ends here without ever using the above variable x
This is what I might do:
while True: # enters loop so it keeps asking for a new integer
sum = 0
x = input("Please pick an integer (type q to exit) > ")
if x == "q": # ends program if user enters q
break
else:
# try/except loop to see if what they entered is an integer
try:
x = int(x)
except:
print "You entered {0}, that is not a positive integer.".format(x)
continue
for i in range(1, x+1): # if the user enters 2, this will add 1 and 2, instead of 1.
sum += i
print sum

Categories

Resources