Reputation: 31
How do you write a program to count up and down from a users integer input, using only one while loop and no for or if statements?
I have been successful in counting up but can't seem to figure out how to count down. It needs to look like a sideways triangle also, with spaces before the number (equal to the number being printed).
this is my code so far;
n = int(input("Enter an integer: "))
i = " "
lines = 0
while lines <= n-1:
print(i * lines + str(lines))
lines += 1
Upvotes: 3
Views: 3448
Reputation: 92440
You can solve this by making good use of negative numbers and the absolute value: abs()
which will allow you to "switch directions" as the initial number passes zero:
n = int(input("Enter an integer: "))
s = " "
i = n * -1
while i <= n:
num = n - abs(i)
print(s * num + str(num))
i += 1
This will produce:
Enter an integer: 3
0
1
2
3
2
1
0
Upvotes: 3
Reputation: 900
Move the print line to after the while
loop. Form a list of lists (or an array) in the while
loop using the content from your current print statement. Then create a second statement in your single while
loop to count down, which creates a second list of lists. Now you can sequentially print your two lists of lists.
Upvotes: 0