python如何保證輸入鍵入數字


要求:用python寫一個要求用戶輸入數字,如果不是數字就一直循環要求輸入,直到輸入數字為止的代碼
 
錯誤打開方式:
 
while True:
    ten=input('Enter a number:')
    if type(eval(ten))==type(int):
   break

 

用這個輸入字母可以可是輸入字母就直接報錯中斷了
主要出在eval上。

  • 第一個方案:
while True:
    ten=input("x:")
    try:
        x=eval(ten)
        if type(x)==int:
            break
    except:
            pass

 


然后輸入asf,沒有提示。輸入344就退出了
x:asf
x:344
  • 第二個方案
while True:
    ten=None
    try:
        ten=int(input("x:"))
    except:
        pass
    if type(ten)==int:
        break

 


這個在python3.0上調試通過
  • 第三個方案:python2.x的方案
while True:
    ten=raw_input("Enter a number:")
    if ten.isdigit():
        break
    ten=int(ten)  #或者是ten=eval(ten)

 

都調試過。可以用
打個廣告: https://www.cnblogs.com/marsggbo/p/9425279.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM