大家好,
想請問下面的程式碼,設計理念是,
當輸入字串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')
因為你變動的 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')