Home > Back-end >  How to matched random number using input function
How to matched random number using input function

Time:09-28

How can i matched the random generated number in input function? my if and else statement don't run because even i inputted the random number, they don't match. here is my code below.

import random
randomNumber=[]
length_randomNumber = 6

for i in range(length_randomNumber):
    randomNumber.append(random.randint(0,9))
print(randomNumber)

x = input("Enter the 6 generated number :")
if x == randomNumber:
    print("x and random number matched!")
else:
    print("x don't matched with the random number!")

CodePudding user response:

Here the problem occurs due to x = input("Enter the 6 generated number :"). The x here is of string type.

What you can do instead is this:

for i in range(length_randomNumber):
    randomNumber.append(random.randint(0,9))
print(randomNumber)

x = input("Enter the 6 generated number, seperated by commas :")
x = [int(y) for y in x.split(",")]
if x == randomNumber:
    print("x and random number matched!")
else:
    print("x don't matched with the random number!")

Here you convert the input to an integer array and compare. Above we used a list comprehension to do that.

CodePudding user response:

Try this... Your x is by default string, so needed to convert into integer first... & 2nd thing is randomNumber is a list, so condition should be x in randomNumber;

import random
randomNumber=[]
length_randomNumber = 6

for i in range(length_randomNumber):
    randomNumber.append(random.randint(0,9))
print(randomNumber)

x = input("Enter the 6 generated number :")
if int(x) in randomNumber:
    print("x and random number matched!")
else:
    print("x don't matched with the random number!")

CodePudding user response:

randomNumber variable is a list not an integer , if you are trying to check if an entered value is present in that list of random numbers then change if condition to : if int(x) in randomNumber

if you are trying to form a 6 digit random number , this is not the right way to generate.

CodePudding user response:

your randomNumber is list, you can use operator in to check it. and also convert the x first to integer. like below:

import random
randomNumber=[]
length_randomNumber = 6

for i in range(length_randomNumber):
    randomNumber.append(random.randint(0,9))
print(randomNumber)

x = input("Enter the 6 generated number :")
if int(x) in randomNumber:
    print("x and random number matched!")
else:
    print("x don't matched with the random number!")
  • Related