簡體   English   中英

沒有錯誤時出現錯誤代碼

[英]error code comes up when no error

我正在嘗試為我的骰子SIM卡生成錯誤消息

import random
loop=1

while loop == 1:
 dice=input("Choose dice 4,6 or 12 sided")
 if dice =="4":
     n=random.randint(1,4)
     print(dice)
     print(n)
 if dice =="6":
     n=random.randint(1,dice)
     print(dice)
     print(n)
 if dice =="12":
     n=random.randint(1,dice)
     print(dice)
     print(n)

 else:
    print("Error")

4和6出現錯誤,但是當我使用12面時,沒有錯誤出現

Choose dice 4,6 or 12 sided4
4
4
Error

您應該真正說明所使用的編程語言。 我假設這是Python,但是如果不是,我的答案可能是錯誤的。

您的問題是您需要使用elif ,而不是if。 您還試圖在字符串和整數之間進行隱式轉換,這是行不通的。 除非我錯過了其他事情,否則這段代碼應該會。

import random
loop=1

while loop == 1:
 dice=input("Choose dice 4,6 or 12 sided")
 if dice =="4":
     n=random.randint(1,4)
     print(dice)
     print(str(n))
 elif dice =="6":
     n=random.randint(1,int(dice))
     print(dice)
     print(str(n))
 elif dice =="12":
     n=random.randint(1,int(dice))
     print(dice)
     print(str(n))
 else:
    print("Error")

您需要使用elif代替if或switch語句。

您提供的代碼顯示“如果骰子不等於12,則顯示錯誤”。

嘗試類似:

while loop == 1:
 dice=input("Choose dice 4,6 or 12 sided")
 if dice =="4":
     n=random.randint(1,4)
     print(dice)
     print(n)
 elif dice =="6":
     n=random.randint(1,dice)
     print(dice)
     print(n)
 elif dice =="12":
     n=random.randint(1,dice)
     print(dice)
     print(n)
 else:
    print("Error")

這使您可以盡早擺脫循環,而無需評估每個表達式。

暫無
暫無

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

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