'Python code to randomly guess user input number
This is the code I have now thank you to Ely Murphy for helping me fix this code :) if you want to see a website i made with html go to bit.ly/famfacts All the people listed in the list on the website are my siblings
import random
userI = "true"
while userI == "true":
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
ex = False
print("Match was created on the", count, "attempt.")
while ex == False:
userAwnser =str( input("Would you like to play again")).lower
if userAwnser =="no":
userI = True
elif userAwnser == "yes":
userI = False
else:
print("Error Not a valid awnser")
ex = False
Solution 1:[1]
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.")
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
| Solution 2 | Eli Murphy |
