Home > database >  Python code to randomly guess user input number
Python code to randomly guess user input number

Time:02-06

import random
tries =0
g = [random.randint(1,9),random.randint(1,9),random.randint(1,9),random.randint(1,9)]
a,b,c,d =input("enter a 4 digit number: ")


r = [a,b,c,d]
while r !=g:
    g = [random.randint(1,9),random.randint(1,9),random.randint(1,9),random.randint(1,9)]
    tries = tries 1
if r==g:
    print("I got it right in ",tries,"tries")
else:
    pass

CodePudding user response:

while True:
    master = int(input("enter a 4 digit number: "))
    if 1000 <= master <= 9999:
        break
    print("That's not a 4-digit number.")

guess = 5500
delta = guess // 2
tries = 0
while guess != master and tries < 10:
    tries = tries 1
    nxt = input(f"My guess is {guess}.  Is your number higher or lower? ")
    if nxt[0] == 'h':
        guess  = delta
    elif nxt[0] == 'l':
        guess -= delta
    else:
        print("Come on, type 'higher' or 'lower'.")
        continue
    delta //= 2
    
if master == guess:
    print(f"My guess is {guess}.  I got it right in {tries} tries")
else:
    print("I didn't get it in 10 tries.")

CodePudding user response:

The main issue here is that you are trying to force input() to split your string input into four variables. Even if you wanted to convert it to integers, you would need to use a for loop or equivalent to separate it into a list. Also, having each digit split is redundant for your case, and you could just compare the integer to a 4 digit random integer (ex: randint(1000, 9999). Below is a simpler and more efficient way of doing this:

import random

userInput = int(input("Please input a 4 digit number: "))
compNumber = random.randint(1000, 9999)


count = 0
while userInput != compNumber:
    compNumber = random.randint(1000, 9999)
    count  = 1
print("Match was created on the", count, "attempt.")

Please comment if you have any questions!

Note: This does not have any user input validation and will break if given a string and will be in a forever loop if the input is a number greater then 9999 or smaller then 1000

  •  Tags:  
  • Related