In this example I want python to print the last number again if I say yes the code:
for i in range(1,11):
print(i)
a=input("back?")
#if a=="yes":
#want to do the last number again
if a=="no":
None
for example I want to print 2 again here
not from the beginning just the last one
CodePudding user response:
Use while
loop instead of for
and increase i
only on the 'no'
answers
i = 1
while i < 11:
print(i)
a = input("back?")
if a == "yes":
continue
else:
i = 1
Output
1
back?no
2
back?no
3
back?yes
3
back?yes
3
back?no
4
back?yes
4
CodePudding user response:
I think this is what you want:
for i in range(1,11):
print(i)
a=input("back?")
if a=="yes":
#want to do the last number again
print(i)
Example output:
1
back?no
2
back?yes
2
3
back?no
4
back?yes
4
5
back?
CodePudding user response:
- You don't need the
else
withNone
and keep in mind that no-op in Python ispass
(and notNone
). - Just print in the if and you are good to go imho.
for i in range(1,11):
print(i)
a=input("back?")
if a=="yes":
print(i)
CodePudding user response:
The key is to avoid advancing to the next iteration of the for
loop until the user answers 'no'
to the question. For that you can use a while
loop to keep printing the same number until the break
condition is met:
for i in range(1, 11):
while True:
print(i)
if input('back?') == 'no':
break
Demo: https://replit.com/@blhsing/CoordinatedSpecializedFolders