作者yeuan (心要夠堅定)
看板Python
標題Re: [問題] 負數如何進迴圈判斷?
時間Thu Feb 14 08:47:54 2019
s = input("Enter a number: ")
try:
print(float(s) * -1)
except:
print("Your input should be a number.")
※ 引述《shentotto (無名火)》之銘言:
: 各位高手好小弟菜雞在練習習題時碰壁了
: 書裡的題目是這樣:
: 當你輸入正數時輸出負數,輸入負數時轉成正數,如果你輸入非數字時輸出"必須為數字"
: http://i.imgur.com/lLGL13w.jpg
: 圖片
: ss = input("請輸入數字")
: if ss.isdigit():
: if ss > 0:
: print(int(ss) * -1)
: elif ss < 0:
: print(int(ss) * -1)
: else:
: print("0")
: else:
: print("必須為數字")
: 書上並沒有教如何分字串和數字判斷的語法
: 所以在網路上找到.isdigit指令(單純抓數字)
: 可是這指令連負號都擋,這一擋造成我負數直接被踢掉
: 求解鈴人解惑
: -----
: Sent from JPTT on my HTC_M9u.
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 67.249.65.90
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1550105277.A.FD7.html
推 talltallyo: float的地方改用eval會不會比較好呢? 02/14 10:38
→ uranusjr: 不會 02/14 11:49
→ djshen: user隨便輸入的東西你敢eval? 02/14 11:50
推 Raymond0710: 別亂用 eval, user輸入個rm -rf / 就慘了 02/15 09:44
推 talltallyo: 感謝各位大大! 02/15 10:53
推 shentotto: 襪靠 大大妳這指令好猛喔,我想了好幾個小時打出來的 02/18 17:04
→ shentotto: 標點符號還會發生錯誤 02/18 17:04
推 shentotto: 只有基本的字母和正負數字判斷的功能而已 02/18 17:12