簡體   English   中英

檢查輸入是python中的數字

[英]Checking input is a number in python

我需要幫助,我的程序正在模擬骰子的動作。 我想進行錯誤檢查,以檢查輸入字符串是否為數字,如果不是,我想再次詢問該問題,直到他輸入整數

# This progam will simulate a dice with 4, 6 or 12 sides.

import random 

def RollTheDice():

    print("Roll The Dice")
    print()


    NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))

    Repeat = True 

    while Repeat == True:


        if not NumberOfSides.isdigit() or NumberOfSides not in ValidNumbers:
            print("You have entered an incorrect value")
            NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides")

        print()
        UserScore = random.randint(1,NumberOfSides)
        print("{0} sided dice thrown, score {1}".format (NumberOfSides,UserScore))

        RollAgain = input("Do you want to roll the dice again? ")


        if RollAgain == "No" or RollAgain == "no":
            print("Have a nice day")
            Repeat = False

        else:
            NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))

作為評論者,我不喜歡try:第一個答案try: except ValueError和OP詢問如何使用isdigit ,您可以通過以下方式進行操作:

valid_numbers = [4, 6, 12]
while repeat:
    number_of_sides = 0      
    while number_of_sides not in valid_numbers:
          number_of_sides_string = input("Please select a dice with 4, 6 or 12 sides: ")
          if (not number_of_sides_string.strip().isdigit() 
              or int(number_of_sides_string) not in valid_numbers):
              print ("please enter one of", valid_numbers)
          else:
              number_of_sides = int(number_of_sides_string)
    # do things with number_of_sides

有趣的行not number_of_sides_string.strip().isdigit() 為了方便起見,使用strip刪除了輸入字符串兩端的空格。 然后, isdigit()檢查完整的字符串是否由數字組成。

就您而言,您只需檢查一下

 if not number_of_sides_string not in ['4', '6', '12']:
     print('wrong')

但是如果您要接受任何數字,則另一種解決方案更通用。

順便說一句, Python編碼樣式指南建議使用小寫的下划線分隔的變量名。

將字符串捕獲到變量中,例如text 然后執行if text.isdigit()

利用以下功能:

while NumberOfSides != 4 and NumberOfSides != 6 and NumberOfSides != 12:
    print("You have selected the wrong sided dice")
    NumberOfSides = int(input("Please select a dice with 4, 6 or 12 sides: "))

並在需要輸入時調用它。 您還應提供一個退出選項,例如按0。也應嘗試捕獲無效數字。 Python doc中有一個確切的示例 請注意,輸入始終嘗試將其解析為數字,並且將引發其自身的異常。

您可以使用type方法

my_number = 4
if type(my_number) == int:
    # do something, my_number is int
else:
    # my_number isn't a int. may be str or dict or something else, but not int

或更多個«pythonic» isinstance方法

my_number = 'Four'
if isinstance(my_number, int):
    # do something
raise Exception("Please, enter valid number: %d" % my_number)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM