【问题标题】:Picking A Random Option In A Menu在菜单中选择一个随机选项
【发布时间】:2021-07-15 06:41:04
【问题描述】:

当我运行这个程序时,我知道你只能从 1 到 5 中选择一个数字,即使是从 1 到 5 的数字。即使当我运行程序时,它也会打印一个 1-5 的数字(尝试自己运行它。)它选择随机数的部分位于菜单下方。我知道这是一种奇怪的选择数字的方式,但我将它从 choice = random 更改了。 randint(1,5) 之后也失败了。任何帮助表示赞赏

import random
import sys
import time
import os


cls = lambda : os.system('cls')
cls()

def main():
   menu()


def menu():
    print("---------------------- Random Selection ----------------------")
    print ("1. Random AI  1")
    print ("2. Smart AI   2")
    print ("3. View Cards 3")
    print ("4. Credits    4")
    print ("5. Exit       5")
    print ("------------------------------------------------------------------")
    print()

    choices123 = [1,2,3,4,5]
    choice=(random.choice(choices123))
    print(choice)

    if choice == "1" or choice =="one":
        rai()
    elif choice == "2" or choice =="two":
        sai()
    elif choice == "3" or choice =="three":
        VC()
    elif choice == "4" or choice =="four":
        C()
    elif choice=="5" or choice=="five":
        sys.exit
    else:
        print("You must only select from 1 to 5")
        print("Please try again")
        time.sleep(5)
        cls()
        menu()

def rai():
   print("Random AI")
    
def sai():
   print("Smart AI")

def VC():
   print("View Cards")

def C():
   print("Credits")

main()

【问题讨论】:

  • 您的choices123 列表包含ints,而您的if/elif... 块正在寻找字符串。您需要更改其中之一。
  • @MattDMo 我将如何改变让我们说choices123?
  • 使其成为字符串列表 - choices123 = ["1", "2", "3", "4", "5"]
  • @MattDMo 哦,这是一个非常简单的修复,抱歉,我对编码很陌生,但非常感谢,这真的很有帮助!

标签: python


【解决方案1】:

random.choice(choices123) 中选择的choice 是一个整数,而不是您要与之比较的字符串。

a = 1
type(a) # Is type 'int'

b = "1"
type(b) # Is type 'str'

a == b
# Returns False, because they are not the same type and therefore not equal

您希望将一个整数与另一个整数进行比较:

import random

choices = [1, 2, 3]
choice = random.choice(choices)

if choice == 1:
    rai()
elif choice == 2:
    sai()
elif choice == 3:
    VC()
# ... etc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2017-04-30
    • 2011-02-28
    • 2012-01-24
    • 2014-01-18
    相关资源
    最近更新 更多