Lexar
Lexar

Reputation: 1

Picking A Random Option In A Menu

When I run this program I get you must only select a number from 1-5 even though a number from one to five. Even though when I run the program It will print a number from 1-5 (try and run it yourself.) The part where it chooses the random number is underneath the menu. I know it's a strange way of picking a number but I changed it from choice = random. randint(1,5) after that had failed too. Any help is appreciated

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()

Upvotes: 0

Views: 149

Answers (1)

blake-g
blake-g

Reputation: 96

The choice selected from the random.choice(choices123) is an integer, and not a string that you're trying to compare it to.

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

You want to instead be comparing an integer with another integer:

import random

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

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

Upvotes: 1

Related Questions