简体   繁体   中英

How to use continue in while loop?

I tried to use continue in a while loop to skip print number but it doesn't work.

 num = int(input())

 while int(num) > 0 :
     num-=1
    print(num)
    if num == 6:
        continue
    elif num ==1:
     print("8 Numbers Printed Successfully.")
     break
#i want to remove number six

Try this

num = int(input())

while num > 0 :
    num -= 1
    if num == 6: 
        continue

    elif num == 1:
        print("8 Numbers Printed Successfully.")
        break
    
    print(num)

Your print line should be after the if-else block

num = int(input())

while int(num) > 0:
    num -= 1
    # print(num) => if you print here, it does not check the condition
    if num == 6:
        continue
    elif num == 1:
        print("8 Numbers Printed Successfully.")
        break
    # print number here
    print(num)

First of all, how do you know it's been 8 numbers? The input can be any number. Secondly, if you want to print every number but 6 you need to move the num -= 1 too. Being there, it won't print the first number.

Try this if you don't insist on using continue :

num = int(input())

printed_numbers = 0
while int(num) > 0 :
    if num != 6:
        print(num)
        printed_numbers += 1
    num -= 1
print("{} Numbers Printed Successfully.".format(printed_numbers))

Or this, if you want to test continue :

num = int(input())

printed_numbers = 0
while int(num) > 0 :
    if num == 6:
        num -= 1
        continue
    print(num)
    printed_numbers += 1
    num -= 1
print("{} Numbers Printed Successfully.".format(printed_numbers))

Finally, If you're ok with the num -= 1 there:

num = int(input())

printed_numbers = 0
while int(num) > 0 :
    num -= 1
    if num == 6:
        continue
    print(num)
    printed_numbers += 1
print("{} Numbers Printed Successfully.".format(printed_numbers))

NOTE : I'm using printed_numbers because if the input is less than 6 you will print all the numbers else you'll have one less. You can use this condition instead.

You are print the number before the condition. chnage the code as follows.

num = int(input())

while int(num) > 0 :
    num-=1
    if num != 6:
        print(num)
    elif num == 1:
      print("8 Numbers Printed Successfully.")
      break
#i want to remove number six

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM