簡體   English   中英

即使if中的第一個命令為true,它也不打印我想要的內容,它只打印else命令

[英]Even if the first command in if is true it doesn't print what i want , it only print the else command

numberchk=(int(input("Enter a Roman numeral or a Decimal numeral:" )))
def int2roman(number):
    numerals={1:"I", 4:"IV", 5:"V", 9: "IX", 10:"X", 40:"XL", 50:"L",
              90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"}
    result=""
    for value, numeral in sorted(numerals.items(), reverse=True):
        while number >= value:
            result += numeral
            number -= value
    return result
if numberchk==int:
    print(int2roman(int(numberchk)))

else:
    print("error")

請使用isinstance(numberchk, int) ,因為int是一種類型,但numberchk是該類型的實例。

因為int(input(...總是盡可能長地返回一個整數,所以你不必使用if-else來檢查它。如果輸入不是整數,請使用try-except作為@poke提到) 。

您還可以使用while-loopbreak來重復請求用戶輸入,直到您獲得合法輸入:

while True:
    try:
        numberchk=int(input("Enter a Roman numeral or a Decimal numeral:" ))
        break
    except ValueError:
        print('error')
print(int2roman(numberchk))
if numberchk==int:

這將檢查numberchk是否等於 int 類型 不會檢查numberchk是否為整數(您可能想要這樣做)。 檢查其類型的正確方法是:

if isinstance(numberchk, int):

但是,這也沒有意義。 獲取numberchk是在字符串上調用int()

numberchk=int(input(…))

所以numberchk 永遠是一個int。 但是,對不是數字的字符串調用int()可能會失敗,因此您可能希望捕獲該錯誤以確定輸入是否為數字:

try:
    numberchk = int(input("Enter a Roman numeral or a Decimal numeral:"))
except ValueError:
    print('Entered value was not a number')

但這將再次成為問題,因為 - 至少從您正在打印的消息判斷 - 您還希望接受羅馬數字,這些數字不能通過int轉換為整數。 所以你還應該編寫一個帶有羅馬數字並將其轉換為int的函數。

檢查整數類型而不是使用int匹配變量。

您可以使用isinstance方法檢查變量的類型。

嘗試使用isdigit()函數。

在代碼中替換此部分

if numberchk==int:

if numberchk.isdigit():

暫無
暫無

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

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