0

I have this python 3 script which should compare two lists and find equal numbers. It'a a Cows and Bulls game. Not going to go too much into details but here is the problem. When I ask for user input as a list it returns list of Strings and not integers, hence I can't compare elements with my given list if integers. Please advise how to cast userinput list into list of digits: Script below:

import random

numtoguess = [random.randrange(0,10,1) for _ in range (4)]
print(numtoguess)

userinput = []

while numtoguess != userinput:
    userinput = list(input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> "))
    print(userinput)
    cows = 0
    bulls = 0
    counter = 0
    for i in userinput:
        if i in numtoguess and i == numtoguess[counter]:
            bulls += 1
        elif i in numtoguess and i != numtoguess[counter]:
            cows += 1
        counter += 1
    print('Cows: ' + str(cows))
    print('Bulls: ' + str(bulls))
Mher Harutyunyan
  • 183
  • 3
  • 12
  • do `userinput = [int(x) for x in input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> ")]` – Jean-François Fabre Apr 06 '18 at 15:14
  • 1
    @Aran-Fey. Close but the duplicate splits the number "words", doesn't iterate on the chars – Jean-François Fabre Apr 06 '18 at 15:16
  • Meh. We can add [this](https://stackoverflow.com/questions/4978787/how-to-split-a-string-into-array-of-characters) to the list, then. – Aran-Fey Apr 06 '18 at 15:18
  • Does this answer your question? [Convert all strings in a list to int](https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) – Georgy Jun 21 '20 at 14:02

4 Answers4

0

You can always use the int() function to cast strings to integers, provided the string can be implicitly converted. Most commonly I see user input as integers in the following format:

num = int(input("enter a number: "))
SamBG
  • 270
  • 4
  • 16
0
userinput = list(input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> "))

creates a list with each char of the input string (the digits, but as string).

Just convert to integer with a list comprehension:

userinput = [int(x) for x in input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> ")]
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

Ok got it this way.

userinput = list(input("Welcome to Cows and Bulls game!!! \nGuess the random 4 digit number :> "))
userinput = [int(i) for i in userinput]
Mher Harutyunyan
  • 183
  • 3
  • 12
0

During each iteration you could append the input to the list as an int...

userinput.append(int(input("enter num")))
Nate Thompson
  • 325
  • 2
  • 12