Sum of n natural numbers using while loop in python [duplicate] - python

This question already has answers here:
Sum of the integers from 1 to n
(11 answers)
Closed 6 months ago.
The question was tp :write a program to find the sum of n natural numbers using while loop in python.
n = int(input("Enter a number: "))
i = 1
while i<n:
print(i)
i = i + 1
this is what I have done s far...
can not understand what to do next.

n = int(input("enter a number: "))
i = 1
sum = 0
while (i <= n):
sum = sum + i
i = i + 1
print("The sum is: ", sum)

with a while loop the sum of natural numbers up to num
num = 20
sum_of_numbers = 0
while(num > 0):
sum_of_numbers += num
num -= 1
print("The sum is", sum_of_numbers)

You can either follow Alasgar's answer, or you can define a function with the formula for this particular problem.
The code's gonna be something like this:
def natural(n):
sumOfn = (n * (n + 1))/2
terms = int(input("Enter number of terms: "))
natural(terms)

number = int(int(input("Enter the number: "))
if number < 0:
print("Enter a positive number: ")
else:
totalSum = 0
while (number > 0):
totalSum += number
number -= 1
print ("The sum is" , totalSum)

num = int(input('Enter the number : '))
sum = 0
while 0<num:
sum += num
num -= 1
print(f'The sum of the number is {sum}')

Related

Transform iterative function into recursive function

Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
def solowayAverage():
number = int(input("Enter a number: "))
sum = 0
count = 0
while number != 99999:
if (number >= 0):
sum += number
count += 1
number = int(input("Enter a number: "))
print("The average is: ", sum / count)
#iterative code
solowayAverage()
def solowayaveragerec(n, sum, count):
if n !=99999 and n>0:
sum += n
count += 1
else:
return solowayaveragerec(n, sum, count)
number = int(input("Give me a number: "))
solowayaveragerec(number, 0, 0)
#recursive code non completed
I would need help to make the recursive code work. The problem is that I don't know where to insert the call for the function in the recursive part
You should make the recursive call with the new number added to the sum and the count added with 1:
def solowayaveragerec(sum=0, count=0):
number = int(input("Enter a number: "))
if number == 99999:
print("The average is: ", sum / count)
else:
solowayaveragerec(sum + number, count + 1)
solowayaveragerec()
Demo: https://replit.com/#blhsing/PrimeSadClosedsource

Can someone help me loop this script (Python)?

I have this Python assigment to complete where I need to write a program that reads in X whole numbers and outputs (1) the sum of all positive numbers, (2) the sum of all negative numbers, and (3) the sum of all positive and negative numbers. The user can enter the X numbers in any different order every time, and can repeat the program if desired. This is what I've got so far:
x = int(input('How many numbers would you like to enter?: '))
sumAll = 0
sumNeg = 0
sumPos = 0
for k in range (0,x,1):
num = int(input("please enter number %i :" %(k+1)))
sumAll = sumAll + num
if num < 0:
sumNeg += num
if num > 0:
sumPos += num
if k == 0:
smallest = num
largest = num
else:
if num < smallest:
smallest = num
if num > largest:
largest = num
print("The sum of negative numbers is: " , sumNeg)
print("The sum of positive numbers is: " , sumPos)
print("The sum of all numbers is: " , sumAll)
count = 0
repeat = input('Would you like to repeat? y/n: ')
repeat = 'y'
while y == 'y':
I'm just a little stuck after this point. Any ideas on what I should do?
A simple while loop would suffice.
run = True
while run is True:
x = int(input('How many numbers would you like to enter?: '))
sumAll = 0
sumNeg = 0
sumPos = 0
for k in range (0,x,1):
num = int(input("please enter number %i :" %(k+1)))
sumAll = sumAll + num
if num < 0:
sumNeg += num
if num > 0:
sumPos += num
if k == 0:
smallest = num
largest = num
else:
if num < smallest:
smallest = num
if num > largest:
largest = num
print("The sum of negative numbers is: " , sumNeg)
print("The sum of positive numbers is: " , sumPos)
print("The sum of all numbers is: " , sumAll)
repeat = input('Would you like to repeat? y/n: ')
if repeat != 'y':
run = False
Example of the output:
How many numbers would you like to enter?: 4
please enter number 1 : 3
please enter number 2 : 2
please enter number 3 : 4
please enter number 4 : 5
The sum of negative numbers is: 0
The sum of positive numbers is: 14
The sum of all numbers is: 14
Would you like to repeat? y/n: y
How many numbers would you like to enter?: 3
please enter number 1 : 2
please enter number 2 : 4
please enter number 3 : 3
The sum of negative numbers is: 0
The sum of positive numbers is: 9
The sum of all numbers is: 9
Would you like to repeat? y/n: n
You just need to place your code inside an outer loop, that might start it all over again if the user wants to repeat.
while True:
# all your current code until the prints
repeat = input('Would you like to repeat? y/n: ')
if repeat is not 'y':
break

How do I use while function to complete this question

For example, if user keys in 6, the output is 21 (1+2+3+4+5+6)
sum = 0
num = int(input("Enter number: "))
…..
….
This is my code below:
x=0
sum = 0
nums = int(input("enter num "))
while sum <= nums:
sum+=1
x= x + sum
y = x - nums -1
print(y)
First of all, I suggest not to use sum as variable name, this will shadow the built-in sum() function.
There are two ways to do it using while loop, the first one is close to yours but turn <= to < in the condition so you don't need extra - num - 1 at the end.
n = 0
total = 0
num = int(input("enter num "))
while n < num:
n += 1
total += n
print(total)
Second one adds number in descending order, it also change the value of num. If you need num for later use, use the first one.
total = 0
num = int(input("enter num "))
while num:
total += num
num -= 1
print(total)
If loop is not needed, as you are going to obtain a triangular number, just use the formula.
num = int(input("enter num "))
print(num * (num + 1) // 2)
If you don't have use a loop you could do it in a single line:
print(sum(range(1, int(input('Enter a number: ')) + 1)))
Test:
Enter a number: 6
21

Finding magic numbers in python [duplicate]

This question already has answers here:
Sum the digits of a number
(11 answers)
Closed 2 years ago.
I am trying to find the magic number in this program but I got stuck on this part and am not sure where to go next. I have searched up many ways on the internet but they are all using more complex code that I have not learned yet.
Example
input 45637
4+5+6+3+7 = 25
2+5 = 7
7 = magic number
num = int(input("Enter a positive number : "))
ans = 0
while num > 0 or ans > 9:
digit = num % 10
num = num//10
print(digit)
Using statements and operators you have already learned as demonstrated in your code, you can use a nested while loop to aggregate the digits from the division remainders into a total as the number for the next iteration of the outer while loop:
num = 45637
while num > 9:
total = 0
while num > 0:
digit = num % 10
num = num // 10
total = total + digit
num = total
print(num)
This outputs:
7
One way:
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
Full code:
num = int(input("Enter a positive number : "))
ans = num
while len(str(ans))>1:
ans = sum(map(int, str(ans)))
print(ans)
Output for input 45637:
7

Wrong results for calculator subtraction and division

My addition and multiplication work just fine. However, for subtraction, if I input 2 numbers, 3 and 1, the answer would be -2, which is obviously incorrect. Division is also not functioning properly.
I can input 2 numbers, 8 and 4, and it would tell me the answer is 0.5, which is also incorrect.
What went wrong in my code?
print("Welcome to Calculator!")
class Calculator:
def addition(self,x,y):
added = x + y
return added
def subtraction(self,x,y):
subtracted = x - y
return subtracted
def multiplication(self,x,y):
multiplied = x * y
return multiplied
def division(self,x,y):
divided = x / y
return divided
calculator = Calculator()
print("1 \tAddition")
print("2 \tSubtraction")
print("3 \tMultiplication")
print("4 \tDivision")
operations = int(input("What operation would you like to use?: "))
x = int(input("How many numbers would you like to use?: "))
if operations == 1:
a = 0
sum = 0
while a < x:
number = int(input("Please enter number here: "))
a += 1
sum = calculator.addition(number,sum)
print("The answer is", sum)
if operations == 2:
s = 0
diff = 0
while s < x:
number = int(input("Please enter number here: "))
s += 1
diff = calculator.subtraction(number,diff)
print("The answer is", diff)
if operations == 3:
m = 0
prod = 1
while m < x:
number = int(input("Please enter number here: "))
m += 1
prod = calculator.multiplication(number, prod)
print("The answer is", prod)
if operations == 4:
d = 0
quo = 1
while d < x:
number = int(input("Please enter number here: "))
d += 1
quo = calculator.division(number, quo)
print("The answer is", quo)
if operations == 4:
d = 0
quo = 1
while d < x:
number = int(input("Please enter number here: "))
d += 1
quo = calculator.division(number, quo)
print("The answer is", quo)
The first time through quo becomes 8. Then it goes through again with 4 as number and 8 as quo. 4 / 8 = .5
Here's an alternative solution using reduce from the functools library.
if operations == 4:
quo = 1
numbers = list()
while len(numbers) < x:
number = int(input("Please enter number here: "))
numbers.append(number)
quo = reduce(calculator.division, numbers)
print("The answer is", quo)
I'd like to know why this was downvoted when it is indeed the answer why division wasn't working...
Issue is with these lines..
diff = 0
while s < x:
number = int(input("Please enter number here: "))
s += 1
diff = calculator.subtraction(number,diff)
print("The answer is", diff)
Lets say input is 2 line number 3 of the above snippet, The difference in the first iteration of the loop, number (input) is 2 and diff is already 0
2-0 = 2 diff becomes 2 now
Input is 1 in the second iteration,
1 -2 = -1 number is 1 and 1 - diff will become diff. that is -1.
Since in the loop you mentioned, (number,diff) - subtraction happens in the same order

Categories