This question already has answers here:
Converting String to Int using try/except in Python

(4个答案)



Asking the user for input until they give a valid response

(21个回答)


上个月关闭。




我开始学习Python。
请对我的程序进行审查:
i = input("input weight = ")

def chicken(i):
    price = 2000
    print('price /kg = ',price)
    totalprice = int(i)*price
    print('total price = ',totalprice)
chicken(i)
如果输入数字,该程序运行良好,但出现字母错误。
如果我给一个字母然后我可以做print("wrong character")怎么办?

最佳答案

试试这个功能
如果所有字符均为数字(0-9),则isnumeric()方法返回True,否则返回False。

i = input("input weight = ")

def chicken(i):
      if not i.isnumeric():
        print("input is not a number")
        return 1
      price = 2000
      print('price /kg = ',price)
      totalprice = int(i)*price
      print('total price = ',totalprice)
chicken(i)

10-08 08:43
查看更多