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

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.

Related

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.

How to print only the last result of an array of sum in python

I want to calculate the sum of the natural numbers from 1 up to an input number. I wrote this code:
number=int(input("enter a natural number"))
if number<0:
print("The number is not positive")
else:
n=0
for i in range (1,number+1):
n+=i
print(n)
But it prints multiple numbers instead. For example, if the user puts five, the program should print 15, but I get this:
1
3
6
10
15
How can I fix the code so that only 15 appears?
You have all the steps because your print statement is in your for loop.
Change it like this:
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
result = 0
for i in range(1, number + 1):
result += i
print(result) # We print after the calculations
There's also a mathematical alternative (see here):
number = int(input("Enter a positive natural number: "))
if number < 0:
print("The number needs to be positive")
exit() # Stops the program
print(number * (number + 1) / 2)
As I've pointed out and suggested earlier in comments, you could move the print statement out of for-loop to print the final sum.
Or you could try to use generator expression to get all number's total (sum), because we don't care the intermediate sums.
This simple sum of all up to the number in one shot.
number=int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
# exit or try again <---------
else:
print(sum(range(1, number + 1))) # given 5 -> print 15
Something like this?
number = int(input("enter a natural number"))
if number < 0:
print("The number is not positive")
else:
n = 0
for i in range (1,number + 1):
n += i
print(n)
The answer to your question is that you are printing the n every time you change it. You are looking for the last answer when you run the code. This code should solve it.
number = int(input("enter a natural number"))
if number < 0:
print("The num < 0")
else:
n = 0
l = []
for i in range (0, number+1):
n+=i
l.append(n)
print(l[len(l)-1])

How to find the smallest number using a while loop?

I cannot use min, boolean or any other keyword or function.
they can enter positive or negative number, so the smallest value will be set as their first number. If they enter 0 as the first number, a program aborted message will appear. Otherwise, they can enter number and then, hit 0. Then a message will pop up stating the smallest number.
def main():
smallest = 0
while smallest == 0 :
num = int(input("Please enter a number "))
if num==0:
print("Program aborted")
elif smallest == 0:
smallest = num
elif num < smallest:
num = smallest
num = int(input("Please enter a number "))
print("Your smallest number was", smallest)
main()
so with this code, it will print two numbers and it will give the smallest. but it shouldn't automatically stop after two numbers, it should stop after 0 is entered.
You don't need to take seperate input for the smallest.
Please use the below code. It will find you the smallest number.
def main():
smallest = None
while True :
num= int(input("Please enter a number "))
if num == 0:
print("Program aborted")
break
elif smallest is None:
smallest = num
elif num < smallest:
smallest = num
print("Your smallest number was", smallest)
main()
Output:
Please enter a number 5
Please enter a number 3
Please enter a number 2
Please enter a number -10
Please enter a number 6
Please enter a number 0
Program aborted
Your smallest number was -10
you can do something like this:
nums = [int(i) for i in input("Enter the numbers seperated by a space:\n" ).split()]
smallest = nums[0]
for num in nums:
if num < smallest:
smallest = num;
print(f"The smallest number out of {nums}, is {smallest}");
what the code does is first it allows you to input a string of numbers, (separated by a space of course), and then takes each number and puts it in a list. Then it temporarily sets the smallest number to the first number in the list, and iterates through the list one by one to check the numbers in the list against the smallest number. If the current number that it is checking is smaller than the smallest number variable, then it becomes the new smallest number. At the end, it prints out the smallest number in a print statement.
oops sorry forgot it had to use a while loop

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.

Write a program that accepts a positive integer from the user and prints the first four multiples of that integer. Use a while loop

I am trying to write as the question is stated, Write a program that accepts a positive integer from the user and print the first four multiples of that integer; Use while loop (Python)
total = 0
number = int(input("Enter integer: "))
while number <= 15:
total = total + number
print(number)
SAMPLE
Enter integer: 5
0
5
10
15
this is the example my professor wanted
This is what i have so far, but i'm a bit lost...
You should loop over a counter variable instead of a hard coded limit
counter = 1
while counter <= 4:
counter += 1
total = total + number
print(number)
The loop condition should be set on total, not number, and total should be incremented by 1, not number (assuming total is used as a loop counter):
total = 0
number = int(input("Enter integer: "))
while total <= 3:
print(total * number)
total = total + 1
Sample:
Enter integer: 5
0
5
10
15
A normal while loop that counts upto 4:
count, total = 0, 0
number = int(input("Enter integer: "))
while count < 4:
print(total)
total = total + number
count += 1
Python for loop is more pythonic than while:
number = int(input("Enter integer: "))
for i in range(4):
print(number * i)
Although you have the right idea from the example there's still a couple of things the sample is missing.
1. You don't check whether the input is positive or not
2. The while loop is dependent on knowing the input
Try the following:
# Get Input and check if it's positive
number = int(input('Enter positive integer: '))
if number <= 0:
number = int(input('Not positive integer, enter positive integer: '))
# This increments i by one each time it goes through it, until it reaches 5
i=1
while i < 5:
new_number = number*i
i = i + 1
print(new_number)
Note: This does not take into account if the input is a letter or string. If so, it'll throw an error.

Categories

Resources