The Sum of Consecutive Numbers in Python - python

What I have to do is get the user input and add consecutive numbers starting with one using a loop until the sum equals or exceeds the input. It's an exercise, so I'm trying to do this without using the condition True or importing any functions. Just a simple while loop.
This is what I've got.
num = int(input("Limit:"))
base = 0
while base < num:
base += base + 1
print(base)
When I input 21, the printout is 1
3
7
15
31
No idea how to fix. Any advice is greatly appreciated.
Edit: Sorry for not specifying, the expected output should only be the final number, that which exceeds or equals the input. So for instance, if input is 10, output should be 10. If input is 18, output should be 21.

You should calculate consecutive numbers in dedicated variable
Try this
limit = int(input("Limit:"))
base = 0
number = 1
while base < limit:
base += number
number += 1
print(base)

Step through what your code is doing, when given 21 as an input.
num = int(input("Limit:"))
base = 0
while base < num:
base += base + 1
print(base)
We know our initial state is:
num = 21
base = 0
base is less than 21, so we'll add base to 1, then add all of that to base with +=.
num = 21
base = 1
Now, let's keep going:
num = 21
base = 1
num = 21
base = 1 + 1 + 1 = 3
num = 21
base = 3 + 3 + 1 = 7
num = 21
base = 7 + 7 + 1 = 15
number = 21
base = 15 + 15 + 1 = 31
If you want to sum a range of numbers, well... Python makes that really straightforward using a while loop. We need a counter (which we'll update on each loop), the end number, and a sum variable (the name sum is already a built-in function).
num = int(input("Limit:"))
counter = 0
sumNums = 0
while counter < num:
sumNums += counter
count += 1
print(sumNums)
Or we can just sum a range.
print(sum(range(1, num)))

Just because I like math:
num = int(input("Limit:"))
for n in range(1,num):
s = n * (n + 1) / 2
if s >= num:
break
print(int(s))

If you want your expected output to only be the final number, simply unindent the print statement:
limit = int(input("Limit:"))
base = 0
num = 1
# Each time base is less than limit, add base by num (At the first iteration num is 1), and add num by 1
while base < limit:
base += num
num += 1
print(base)
Sample output:
>>> Limit: 18
21
>>> Limit: 10
10

It has to stop before it prints.
number = int(input("Limit: "))
x = 1
y = 1
while y < number:
x +=1
y +=x
print(y)

You must do or base = base + 1 or bas += 1 not both otherwise you sum base + (base + 1) that is wrong.
But you can do it also quickly in the same way:
sum(range(1, num + 1))

Related

I have a double while loop, and it does not seem to be working because of some logic I'm doing incorrectly

I have a double while loop, and it does not seem to be working because of some logic I'm doing incorrectly. I'm not sure what is wrong exactly, but I feel the code may be too complicated and somewhere, there is an error.
enter code here
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
for j in range(count):
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
while i <= len(list):
while t != 0 :
initial_guess = 10
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
i = i + 1
break
initial_guess = better_guess
i = i + 1
There are some errors in your code, #x pie has pointed out some of them but not all. The most important is that you are need to initalize t for every number in the list, so you can get the iterations for the numbers separately. Also, t needs to be incremented in the while loop, not inside the if block.
You can also clean up the code considerably, for example the j variable is not being used, list comprehension can be used to shorten the code (pythonic way), and iterating over lists can be done with for num in list.
Putting this altogether produces this:
count = int(input('How many numbers am I estimating John? \nCOUNT> '))
print("Input each number to estimate.")
list = [float(input(f'NUMBER {i+1}> ')) for i in range(count)]
print("The square roots are as follows:")
for num in list:
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + num/initial_guess) / 2
t += 1
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {num}^0.5 = {better_guess}")
break
initial_guess = better_guess
Sample run:
How many numbers am I estimating John?
COUNT> 4
Input each number to estimate.
NUMBER 1> 1
NUMBER 2> 9
NUMBER 3> 16
NUMBER 4> 4
The square roots are as follows:
OUTPUT After 9 iterations, 1.0^0.5 = 1.0
OUTPUT After 7 iterations, 9.0^0.5 = 3.0
OUTPUT After 7 iterations, 16.0^0.5 = 4.0
OUTPUT After 8 iterations, 4.0^0.5 = 2.0
#viggnah is right, and I just ignored the num of iterations. But I think #viggnah 's num of iterations are 1 bigger than the actual num of iterations. E.g., if input is 4 and initial guess is 2, the iteration should be 0 rather than 1. Also I add except in case of illegal input.
I suppose the following code works as you expect.
import math
print("How many numbers am I estimating John?")
count = int(input("COUNT> "))
print("Input each number to estimate.")
better_guess = 0
initial_guess = 10
i = 0
j = 0
t = 1
list = []
while True:
try:
num = float(input("NUMBER> "))
list.append(num)
j = j + 1
if j == count:
print("The square roots are as follows:")
break
except:
print("Invalid input! Try again.")
while i < len(list):
initial_guess = 10
t = 0
while True:
better_guess = (initial_guess + (list[i])/initial_guess) / 2
if initial_guess == better_guess:
print(f"OUTPUT After {t} iterations, {list[i]}^0.5 = {better_guess}")
break
t = t + 1
initial_guess = better_guess
i = i + 1
You need to understand:
We only need initialize guess once for each number. So do it in the first while loop;
tneeds to be updated when initial_guess==better_guess rather than i, I believe this is a clerical error;
initial_guessneeds to be updated in the second loop;

The Sum of Consecutive Numbers

I have to write a program which asks the user to type in a limit. The program then calculates the sum of consecutive numbers (1 + 2 + 3 + ...) until the sum is at least equal to the limit set by the user.
In addition to the result it should also print out the calculation performed. I should do this with only a while loop, no lists or True conditionals.
limit = int(input("Limit:"))
base = 0
num = 0
calc = " "
while base < limit:
base += num
num += 1
calc += f" + {num}"
print(base)
print(f"The consecutive sum: {calc} = {base}")
So for example, if the input is 10, the output should be 10 and underneath that should be "The consecutive sum: 1 + 2 + 3 + 4 = 10." If the input is 18, the output should be 21 and underneath that should be "The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21."
Right now I can get it to print the final result (base) and have gotten it to print out the calculation, but it prints out one integer too many. If the input is 10, it prints out 1 + 2 + 3 + 4 + 5 when it should stop before the 5.
I would avoid the while loop and use range instead. You can derive the value of the last term with arithmetic.
If the last term is 𝑛, then the sum will be 𝑛(𝑛+1)/2, which must be less or equal to the input limit. Resolving this equation to 𝑛 given the limit, we get that the 𝑛 is ⌊√(1 + 8β‹…limit) βˆ’ 1) / 2βŒ‹
So then the program can be:
limit = int(input("Limit:"))
n = int(((1 + 8 * limit) ** 0.5 - 1) / 2)
formula = " + ".join(map(str, range(1, n + 1)))
total = n * (n + 1) // 2
print(f"The consecutive sum: {formula} = {total}")
One way that came to my mind is concatenating values for each iteration:
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
calculation = 'The consecutive sum: '
while base < limit:
calculation += f"{num} + "
base += num
num += 1
print(f"{calculation[:-3]} = {base}")
print(base)
#> Limit:18
## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
## 21
The other way is printing value on each iteration without new line in the end (but you have additional + sign in the end here):
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
print('The consecutive sum: ', end='')
while base < limit:
print(f"{num} + ", end='')
base += num
num += 1
print(f"= {base}")
print(base)
#> Limit:18
## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 + = 21
## 21
There's probably a more efficient way to write this but this was what came to mind...
sum = 0
long_output = []
for i in range(limit + 1):
sum += i
long_output.append(str(i))
print("The consecutive sum: {} = {}".format(' + '.join(long_output), sum))
Keep putting stuff in an list and then join them afterwards. i has to be casted to a str type since join is just for strings
NOTE: the output starts at 0 to account for limit being potentially 0 (I don't know what your constraints are, if any)
EDIT: made updates based on #Copperfield's recommendation
You are/were very close. Try rearranging the follow of execution in your while statements. I also find this assignment hard. Try moving you calc line as the first statement after your 'while'.
One other way is to add an if statement:
if base< num :
calc += f" + {num}"
Here is a example to print the calculation
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
msg = ""
while base < limit:
msg = msg + str(num) + "+"
base += num
num += 1
msg = msg[:-1] + "=" + str(limit)
print(msg)
if limit = 21 then the output would be
1+2+3+4+5+6=21

Finding even numbers with while as

I'm doing this assignment:
Write a program that prints all even numbers less than the input
number using the while loop.
The input format:
The maximum number N that varies from 1 to 200.
The output format:
All even numbers less than N in ascending order. Each number must be
on a separate line.
N = int(input())
i = 0
while 200 >= N >= 1:
i += 1
if i % 2 == 0 and N > i:
print(i)
and its output like:
10 # this is my input
2
4
6
8
but there is an error about time exceed.
The simple code would be:
import math
N = int(input(""))
print("1. " + str(N))
num = 1
while num < math.ceil(N/2):
print (str(num) + ". " + str(num * 2))
num += 1
The problem is that the while loop never stops
while 200 >= N >= 1 In this case because you never change the value of N the condition will always be true. Maybe you can do something more like this:
N = int(input())
if N > 0 and N <= 200:
i = 0
while i < N:
i += 2
print(i)
else
print("The input can only be a number from 1 to 200")

How can you sum these outputs in Python?

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

How to make loop repeat until the sum is a single digit?

Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum 2+3+4+5 = 14 which is not a single digit so repeat with 1+4 = 5 which is a single digit.
This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another while statement
n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
this is a sample output of the code
Input an integer: 98765678912398
8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88
8 + 8 = 16
1 + 6 = 7
This should work, no division involved.
n = int(input("Input an integer:"))
while n > 9:
n = sum(map(int, str(n)))
print(n)
It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.
You could utilize recursion.
Try this:
def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
if s > 9:
return sum_of_digits(s)
return s
n = int(input("Enter an integer: "))
print(sum_of_digits(n))
you can try this solution,
if n=98 then your output will be 8
def repitative_sum(n):
j=2
while j!=1:
n=str(n)
j=len(n)
n=list(map(int,n))
n=sum(n)
print(n)
You don't need to convert your integer to a float here; just use the divmod() function in a loop:
def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
return newnum
By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:
n = int(input("Input an integer:"))
while n > 9:
n = sum_digits(n)
print(n)
def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
A simple, elegant solution.
I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.
n = int(input("Input an integer:"))
def sum_int(num):
numArr = map(int,str(num))
number = sum(numArr)
if number < 10:
print(number)
else:
sum_int(number)
sum_int(n)
Again I am unsure about the recursion within a function in Python, but hey, it works :)
If you like recursion, and you must:
>>> def sum_digits_rec(integ):
if integ <= 9:
return integ
res = sum(divmod(integ, 10))
return sum_digits(res)
>>> print(sum_digits_rec(98765678912398))
7
def digit_sum(num):
if num < 10:
return num
last_digit = num % 10
num = num / 10
return digit_sum(last_digit + digit_sum(num))
input_num = int(input("Enter an integer: "))
print("result : ",digit_sum(input_num))
This may help you..!
Try with strings comprehension:
new = input("insert your number: ")
new = new.replace(" ","")
new =sum([int(i) for i in new])
if new not in range (10):
new = str(new)
new = sum ([int(i) for i in new])
print (new)
Note that the answers which convert int to str are relying on the python conversion logic to do internally the divmod calculations that we can do explicitly as follows, without introducing the non-numeric string type into an intrinsically numerical calculation:
def boilItDown(n):
while n >= 10:
t = 0
while n:
d, m = divmod(n, 10)
n, t = d, t + m
n = t
return n
n = 98765678912398
print(boilItDown(n))
Output:
7

Categories