'Increment user's input
The program asks a user three questions:
- Enter the number you want me to start counting in;
- Enter the number you want me to end in; and
- How much do you want to increment by?
From the questions, you can see what I want the program to do.
My problem is that I can manually increment the start number by putting it inside the while loop, but I cannot incorporate this as a user's input.
#Demonstrates user's input and increment.
start = int(input("Enter the number you want me to start counting in: "))
end = int(input("Enter the number you want me to end in: "))
increment = int(input("How much do you want to increment by? "))
while start < end:
start += 1
print(start)
input("Press the enter key to exit..")
I know that the third question in the program is useless because it has no connection to the actual loop, but I've put it in there because that would be part of my final program.
Solution 1:[1]
If you want to print the numbers from start to end including the extremes, the condition on your while is not correct, because when the number start that you are going to print is exactly equal to stop, the condition start<stop is False and so the body of the while is not executed.
A correct condition is either
while not start > end:
...
or
while start !> end:
...
or eventually
while start <= end:
...
All these three ways of writing the test evaluate to True when start equals end.
As a side note, in my opinion you better don't use start for the while loop, rather introduce an auxiliary variable, like in
incr = 1
current = start
while current <= end:
print(current)
current = current + incr
Post Scriptum
There are more idiomatic ways (more pythonic ways, someone will tell you) to get your job done, but for now let's keep simple things as simple as possible... Further, I hope that you have not missed the implicit hint on the use of an increment...
Solution 2:[2]
Try this:
while start < end:
start += increment
print(start)
Solution 3:[3]
Use the Python range() function. It takes three arguments:
- starting point
- ending point
- increment each time
For example:
def increment(start, end, increment):
for i in range(a, b, increment):
print(i)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Muhammad Bilal |
| Solution 3 | jonrsharpe |
