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.
CodePudding user response:
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)
CodePudding user response:
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)))
CodePudding user response:
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))
CodePudding user response:
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
CodePudding user response:
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))