iT邦幫忙

0

python的while迴圈,無法停止

  • 分享至 

  • xImage

大家好,
想請問下面的程式碼,設計理念是,
當輸入字串exit時,就結束while迴圈。不然就繼續執行文章搜尋。

但是為什麼我輸入exit時,雖然有印出stop
但依然會跳出input讓我輸入?無法停止程式碼?
感謝

import pip._vendor.requests as requests
times = 1
def fn() : 
    name = input("please enter your name : ")
    if name == 'exit' : 
        times = 0
        print('stop')
    else :
        r = requests.post('https://forecasting.hk/name/?p=stroke_count', data = { 'char': name })
        r.encoding = 'utf-8'
        r1 = r.text.split('字的姓名學筆劃數為')
        r2 = r1[1].split('。')
        print(r2[0])

while times > 0:
    fn()

print('done')
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
hokou
iT邦好手 1 級 ‧ 2022-09-28 14:13:36
最佳解答

因為你變動的 times 只存在 fn() 內
可以把 times 變成全域變數試試

import pip._vendor.requests as requests
times = 1
def fn() : 
    global times # 改全域
    name = input("please enter your name : ")
    if name == 'exit' : 
        times = 0
        print('stop')
    else :
        r = requests.post('https://forecasting.hk/name/?p=stroke_count', data = { 'char': name })
        r.encoding = 'utf-8'
        r1 = r.text.split('字的姓名學筆劃數為')
        r2 = r1[1].split('。')
        print(r2[0])

while times > 0:
    fn()

print('done')
greenriver iT邦研究生 5 級 ‧ 2022-09-28 14:20:19 檢舉

謝謝~

我要發表回答

立即登入回答