首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择菜单中的随机选项

选择菜单中的随机选项
EN

Stack Overflow用户
提问于 2021-07-14 22:29:50
回答 1查看 62关注 0票数 0

当我运行这个程序,我得到你只能选择一个数字从1-5,即使一个数字从1到5。即使当我运行程序时,它也会从1-5打印一个数字(试着自己运行)。它选择随机数的部分在菜单下面。我知道这是挑选一个数字的一种奇怪的方式,但我改变了它,从选择=随机。在那之后,朗(1,5)也失败了。任何帮助都是非常感谢的。

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2021-07-14 22:41:04

choice中选择的random.choice(choices123)是一个整数,而不是试图与其进行比较的字符串。

代码语言:javascript
复制
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

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

代码语言:javascript
复制
import random

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

if choice == 1:
    rai()
elif choice == 2:
    sai()
elif choice == 3:
    VC()
# ... etc
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68385768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档