天天看點

Python學習-一些讓人頭疼的小bug(新手更新的日常)

Python學習-一些讓人頭疼的小bug(新手更新的日常)

1.卡在一些看起來不會出錯的地方,系統也沒有報錯。

來看一下這個程式:

這個程式的目的是想讓使用者輸入數字,如果輸入不是數字,那麼就傳回,要求使用者重新輸入。

while True:
    t = input('plz enter a number:')
    try:
        t == int(t)
        t = int(t)
        print('You are clever! Your number is ' + t)
        break
    except:
        print('You are wrong, man')
        continue
           

運作的話,你會發現,的确可以篩選出非數字的情況,系統完全沒有報錯。但是結果是這樣的:

plz enter a number:what
You are wrong, man
plz enter a number:hello
You are wrong, man
plz enter a number:g
You are wrong, man
plz enter a number:10
You are wrong, man
plz enter a number:5
You are wrong, man
           

咋回事呢?原因也很簡單,因為你在程式裡,重新定義了 t 變量的類型為整數(int),一般為了接下來的計算都會這麼做。但是!定義之後,print函數裡,沒有加上str(t),導緻print函數無法執行,接下來的break也被跳過了,因為本身的函數在try循環中,而try循環會跳過所有報錯。而如果單獨運作這段print,你會得到:

t = 6
print('You are clever! Your number is ' + t)
           

結果:

Traceback (most recent call last):
  File "C:\Users\lenovo\Desktop\py\11.py", line 2, in <module>
    print('You are clever! Your number is ' + t)
TypeError: can only concatenate str (not "int") to str
           

正常報錯,是以在使用try函數時,一定要多測試一下。

2.循環的問題

看看這一段:

order = 1
while order:
    while True:
        t = input('plz enter a number:')
        try:
            t == int(t)
            t = int(t)
            print('You are clever! Your number is ' + str(t))
            break
        except:
            print('You are wrong, man')
            continue
    order = int(input('plz enter 1 to reload, 2 to quit.'))
    if order == 1:
        continue
    else:
        break
    break

           

我們給代碼加了一段循環,可以讓使用者選擇是否重新輸入數字。這一段看起來沒什麼問題,甚至運作起來也沒什麼問題。運作結果如下:

plz enter a number:8
You are clever! Your number is 8
plz enter 1 to reload, 2 to quit.1
plz enter a number:7
You are clever! Your number is 7
plz enter 1 to reload, 2 to quit.2
           

但是其實,這裡面多了一個結束循環的 break :

if order == 1:
        continue
    else:
        break
    break    #這個break 是多餘的

           

雖然感覺好像是兩個循環,但是continue和break都含有,先結束本層循環,然後至上層循環,continue就是跳到上層開頭,break就是直接到上層結束。因為如果隻有一層意思,那麼continue之後也需要加入一個break了,但是這樣的話:

if order == 1:
        continue
    break     #新添加的break
    else:
        break
    break

           

無情報錯:

Python學習-一些讓人頭疼的小bug(新手更新的日常)

這個也是我在學習Python過程中遇到的一個小問題,希望大家都能避免。

希望大家都能事事順意,本篇是個人學習總結,僅供記錄參考。