Add all numbers (in a while loop) [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
so Im practicing coding in python. My question is this "So I make program that add all the number that enter by a user but the output of the program is not the sum of all the numbers that the user enter.

first sum_num need a initial value
sum_num = 0
and, change sum_num in loop every time is needed:
sum_num = sum_num + num
all code based at yours:
i = 0
sum_num = 0
while 1 == 1:
num = int(input('enter a number :'))
sum_num = sum_num + num
i = i + 1
if i > 5:
print('Total number is :' + str(sum_num))
break
if it's helpful , pls accept it.

You can do the same job by another code
if you have the count of the numbers that user will enter you can use this code :
#create a variable that store the total value
sum_num = 0
#for loop take a the number in range to repeat the code by it
for i in range(5):
#take the number from user and store it
num = int(input("Enter a number: "))
#add the number to total variable
sum_num += num
#at the end of the loop print the total
print("Total Number Is " + str(sum_num))
If you don't have the count of number that user will enter Use This Way :
#create a variable that store the total value
sum_num = 0
#create flag that tell me if user won't enter any other numbers or he want to
#enter more numbers
flag = True
#while loop take a flag and will be in the loop while flag is true
while(flag):
#take the number from user and store it
num = int(input("Enter a number: "))
#add the number to total variable
sum_num += num
#ask user if he want to continue
ask = input("Do you want to continue : ")
if(ask.lower() == 'no' or ask.lower() == 'n') :
flag = False
#at the end of the loop print the total
print("Total Number Is " + str(sum_num))

Related

Beginner question regard basic loop and totaling positive inputs [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 days ago.
Improve this question
print("Welcome to the number program")
number=input("Please give me a number \n")
number=int(number)
total_number=0
entries=0
while number>0:
total_number=total_number+number
print(total_number)
number=input("Please give me another number! \n")
number=int(number)
entries= int(entries)+1
if number < 0 :
print("Sorry, this value needs to be positive. Please enter a
different number.")
if number == -999:
print(total_number)
print(entries)
print(total_number/entries)
I'm in a beginners programming class, and the book is not very helpful at times. I'm trying to write a basic program that takes positive numbers, totals them, and averages them out at the end. Also rejects negative numbers, and asks if -999 is entered I print the average of all entries, amount of entries, and the value tally. Any advice or tips I can learn from to improve it would be helpful. Thanks!
The program runs ok, it just doesn't write out some things I wanted
From what you wrote and the comments in your code I am guessing that you want the program to continue running and asking for input if you enter a non-positive number. In that case I would rewrite it as:
print("Welcome to the number program")
total_number = 0
entries = 0
while True:
number = input("Please give me a number \n")
number = int(number)
if number == -999:
break
if number <= 0:
print("Sorry, this value needs to be positive. Please enter a different number.")
continue
total_number = total_number + number
entries += 1
print(total_number)
print(total_number)
print(entries)
print(total_number / entries)
Also, you can increment numbers with entries += 1
In most cases you should NOT create variables first, however this case you should. Create number = 0, tally = 0 and total_number = 0 first
Accept your first number inside your while loop and handle all of the logic in there as well.
Your while loop should continue to loop until the final condition is met which seems to be number == -999
Should tally be incremented if you enter a negative number? I assume not. What about a 0? Wrap the increment for tally and the addition to total_number in an if number > -1: condition. Use an if else to check for number == -999, and an else for handling invalid entries.
Finally, move your print statements outside of your while loop. It also doesn't need a condition around it because now, if you've exited your while loop, that condition has been satisfied.
Final note here, and this is just a nice to know/have and purely syntactic sugar, MOST languages support abbreviated incrementing. Theres a better word for it, but the gist is simply this.
total_number += number
# is exactly the same as
total_number = total_number + number
# but way nicer to read and write :)
print("Welcome to the number program")
number = 0
total_number = 0
entries = 0
while number != -999:
number = input("Please enter a number! \n")
number = int(number)
if number >= 0
total_number += number
entries += 1
print("Current sum: " + total_number)
elif number == -999:
break
else
print("Sorry, this value needs to be positive.")
print("Sum of entries: "+str(total_number))
print("Number of entries: " + str(entries))
print("Average entry: " +str(total_number/entries))
I have rewritten your code. But I am not sure what the goal was. Anyways, if the value were ever to be under 0 the loop would have been exited and a new value would have never been accepted from an input.
Also some things I have written more elegant.
print("Welcome to the number program")
number=int(input("Please give me a number \n"))
total_number=0
entries=0
while number > 0:
total_number += number
print(total_number)
number = int(input("Please give me another number! \n"))
entries += 1
if number == -999:
print(total_number)
print(entries)
print(total_number/entries)
break
elif number < 0:
number = input("Sorry, this value needs to be positive. Please enter a different number!")

we need to write a prorgam that asks a user to enter multiple numbers and ends the while loop with -1.then work out the average of numbers provided

we have been tasked with writing a program in python asking a user to enter multiple numbers.
the subject is while loops,so we can only make use of while loops and if statements.
when the user wants to stop the entry of numbers,the user then needs to type '-1'.
once that has been done,the program must return the average of the numbers entered by the user.
this is what i have so far:
#task 13-while.py
#first the program will explain to the user that the user can keep
#entering numbers until -1 occurs.
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program'''))
num_count = 0
while num > -1:
num_count = num_count + 1
average = sum(num)/num_count
if num == -1:
print("the average of the numbers you have entered is"+ average)
extremely inexperienced with python,all help will be greatly appreciated.
You need to put the input into the while and then only when the loop is over calculate the averageLike this:
num = int(input("enter numbers and then -1 to stop: "))
num_count = 1
sum = num
while num!=-1:
num = int(input("another number: "))
num_count+=1
sum+=num
print(sum/num_count)
In order for it to work you need to add an input() call inside the while loop like in the code bellow :
count = 0
sum = 0
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program\n'''))
while num != -1:
sum += num
count +=1
num = int(input('''Give another integer\n'''))
print("the average of the numbers you have entered is", sum/count)
Personal advice : I would suggest for you to read more tutorials or ask your peofessor for more work

My while loop should be running until the user wants to stop it but ends after the 2nd input

I feel like the question is not well worded for a question, but this is what I really want:
I am writing this code where a 'user' can enter as many integers from 1 to 10 as he/she wants. Every time after the user has entered an integer, use a yes/no type question to ask whether he/she wants to enter another one. Calculate and display the average of the integers in the list.
Isn't 'while' supposed to running part of a program over and over and over again until it stops when it is told not to?
num_list = []
len()
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while integer_pushed < 0 or integer_pushed > 10:
print('You must type in an integer between 0 and 10')
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
It stops after the 2nd time even if the user types in 'y'. It then gives me the 'Number List: ".
Once again, you guys have been great assisting my classmates and I. Im in an introduction to Python course and we are learning about loops and lists.
One while loop is sufficient to achieve what you want.
num_list = []
again = 'y'
while again=='y':
no = int(input("Enter a number between 1 and 10: "))
if not 1 <= no <= 10:
continue
num_list.append(no)
again = input("Enter another? [y/n]: ")
print("Average: ", sum(num_list) / len(num_list))
The while loop runs as long as again == 'y'. The program asks for another number if the user inputs an integer not between 1 and 10.
Try this:
num_list = []
again = "y"
while again == "y":
try:
integer_pushed = float(input("Enter as many integers from 1 to 10"))
if integer_pushed > 0 or integer_pushed <= 10:
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print("Number list:", num_list)
else:
print('You must type in an integer between 0 and 10')
except ValueError:
print('You must type in an integer not a str')
I'm not sure why you had two different while loops, let alone three. However, this should do what you want. It will prompt the user for a number, and try and convert it to a float. If it can't be converted, it will prompt the user again. If it is converted it will check to see if it's between 0 and 10 and if it is, it will add it to the list, otherwise, it will tell the user that that's an invalid number.

Add numbers and exit with a sentinel

My assignment is to add up a series of numbers using a loop, and that loop requires the sentinel value of 0 for it to stop. It should then display the total numbers added. So far, my code is:
total = 0
print("Enter a number or 0 to quit: ")
while True:
number = int(input("Enter a number or 0 to quit: "))
print("Enter a number or 0 to quit: ")
if number == 0:
break
total = total + number
print ("The total number is", total)
Yet when I run it, it doesn't print the total number after I enter 0. It just prints "Enter a number or 0 to quit", though it's not an infinite loop.
The main reason your code is not working is because break ends the innermost loop (in this case your while loop) immediately, and thus your lines of code after the break will not be executed.
This can easily be fixed using the methods others have pointed out, but I'd like to suggest changing your while loop's structure a little.
Currently you are using:
while True:
if <condition>:
break
Rather than:
while <opposite condition>:
You might have a reason for this, but it's not visible from the code you've provided us.
If we change your code to use the latter structure, that alone will simplify the program and fix the main problem.
You also print "Enter a number or 0 to quit:" multiple times, which is unnecessary. You can just pass it to the input and that's enough.
total = 0
number = None
while number != 0:
number = int(input("Enter a number or 0 to quit: "))
total += number # Same as: total = total + number
print("The total number is", total)
The only "downside" (just cosmetics) is that we need to define number before the loop.
Also notice that we want to print the total number after the whole loop is finished, thus the print at the end is unindented and will not be executed on every cycle of the while loop.
You should sum the numbers inside the loop even if they aren't zeros, but print the total after the loop is over, not inside it:
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
break
print ("The total number is", total)
If the number is 0, the first thing you are doing is break, which will end the loop.
You're also not adding the number to the total unless it's 0, which is not what you're after.
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
break
print ("The total number is", total)
You were very near, but you had some indentation problem.
Firstly, why all these print statements? I guess you are trying to print it before taking input. For this, the below line will be enough.
number = int(input("Enter a number or 0 to quit: "))
Secondly, differentiate between what you want to do, when only the number==0 and what to do in every iteration.
You want to use the below instruction in every iteration as you want every number to be added with total. So, keep it outside if block.
total = total + number
And when number==0, you first want to print something and then break the loop.
if number == 0:
print ("The total number is", total)
break
Make sure you are adding with total first and then checking the if condition, because once you break the loop, you just can't add the number to total later.
So, the solution could be like that,
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
total = total + number
if number == 0:
print ("The total number is", total)
break
total = 0
while True:
number = int(input("Enter a number or 0 to quit: "))
if number == 0:
break
total = total + number
print("The total number is", total)
If you put break before your other code, then the loop will be ended and your code after that break will not run.
And by the way, you can use try...except to catch the error if user didn't enter a number:
total = 0
while True:
try:
number = int(input("Enter a number or 0 to quit: "))
except ValueError:
print('Please enter a number')
continue
if number == 0:
break
total = total + number
print("The total number is", total)

Python Help, Max Number of Entries

Created a program for an assignment that requests we make a program that has the user input 20 numbers, and gives the highest, lowest etc. I have the main portion of the program working. I feel like an idiot asking this but I've tried everything setting the max number of entries and everything I've tried still lets the user submit more than 20. any help would be great! I tried max_numbers = 20 and then doing for _ in range(max_numbers) etc, but still no dice.
Code:
numbers = []
while True:
user_input = input("Enter a number: ")
if user_input == "":
break
try:
number = float(user_input)
except:
print('You have inputted a bad number')
else:
numbers.append(number)
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
Your question could be presented better, but from what you've said it looks like you need to modify the while condition.
while len(numbers) < 20:
user_input = input("Enter a number:" )
....
Now once you've appending 20 items to the numbers list, the script will break out of the while loop and you can print the max, min, mean etc.
Each time the user enters input, add 1 to a variable, as such:
numbers = []
entered = 0
while entered < 20:
user_input = input("Enter a number: ")
if user_input == "":
break
else:
numbers.append(number)
try:
number = float(user_input)
except:
print('You have inputted a bad number')
continue
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
entered+=1
Every time the while loop completes, 1 is added to the variable entered. Once entered = 20, the while loop breaks, and you can carry on with your program. Another way to do this is to check the length of the list numbers, since each time the loop completes you add a value to the list. You can call the length with the built-in function len(), which returns the length of a list or string:
>>> numbers = [1, 3, 5, 1, 23, 1, 532, 64, 84, 8]
>>> len(numbers)
10
NOTE: My observations were conducted from what I ascertained of your indenting, so there might be some misunderstandings. Next time, please try to indent appropriately.

Categories