'How would I get the results from this to end at a value of 2?
This is a countdown calculator that shows all even numbers from user input to 2. If the user inputs an odd number, it adds 1 to make the number even. I need it to stop at 2, but I'm not sure how.
startVal = int(input("Enter a starting value:"))
loss = 2
if startVal % 2 == 1:
startVal = startVal + 1
for i in range(2, startVal + 1):
startVal -= loss
print(startVal)
Solution 1:[1]
Pythons range has a third arguement which defines step size
range(start: int, end: int, step: int) -> Iterable[int]
And with that you can make decrementing loops
With knowing that you will have the next
start_val = int(input("Enter a starting value:"))
# this can be made much simpler
# if start_val % 2 == 1:
# start_val = start_val + 1
start_val += start_val % 2
for i in range(start_val, 1, -2):
print(i)
Also, you can mention that startVal was renamed to start_val. Avoid using CamelCase in variable namings, as Python's PEP-8 defines naming conventions. Use snake_case for variables and functions and CamelCase for class names.
Solution 2:[2]
range(start, end step)
for i in range(startVal,2,-2): startVal-=loss print(startVal)
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 | sudden_appearance |
| Solution 2 | 80b25a14-11f0-4601-bdf5-fbeea8 |
