簡體   English   中英

#Python 新手。 我正在嘗試使用 While 循環從用戶那里獲取輸入后打印數字

[英]#Python newbee. I am trying to print number after taking input from user using While loop

Python 新手。 我試圖在使用 while 循環獲取用戶輸入后打印數字。

我的代碼從用戶那里獲取 int 然后運行循環。 在打印第一個數字后,代碼要求繼續,然后循環將繼續。

我的代碼如下:

 i = 1
 ans = 'n'
 x = int(input("enter a number to loop: " ))

 while(i<x):
   print('\n')
   print(i, end= " ")
   ans = input('\ndo you want to print the next number? ')
   if ans == 'y':
     i += 1
   else:
    print('thanks')

代碼正在執行額外的循環,然后在得到答案后終止循環。 最重要的是在最后一個循環中,如果答案是“n”,它就會繼續運行。

您只需在代碼中的print("thanks")行之前添加一個break語句。 這將退出循環。

else:
    break
    print('thanks')

除非被告知中斷或變為假,否則所有循環都會繼續。 Break 和 Continue 在編程中非常重要。 我建議你閱讀這個https://www.tutorialspoint.com/python/python_loop_control.htm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM