Mastermind code will not run - python

I created a Mastermind code and when I attempt to run it on my Mac it just says "logout". If anyone knows why, that would be extremely helpful! Here is the code:
def masterMind():
number = random.ranint(10000,99999) #the computer chooses 5 random numbers
userGuess = raw_input("Guess my 5 digit password:") #asking the user to input their guess
tries = 10 # telling the computer number of tries the user is allowed
while tries < 0: # 10 attempts is the maximum amount
if number != userGuess: # if the computer's password does not equal the user's guess then it equals to one attempt
tries += 1
userGuess = input("Guess my 5 digit password:")
else: #if the user and the computer's answers align
print "Win: ", userGuess
print number

tries = 10
while tries < 0:
will never enter the loop.
You may want to reverse the sense of the comparison, using > instead.
You'll also need to decrement tries within the loop rather than incrementing it.

more "pythonic" (2.x) way. fixes answers like "00000", fixes int to str compair.
def masterMind():
number = "%05d" % random.randint(0, 99999) #the computer chooses 5 random numbers
for tries in range(10):
user_guess = raw_input("Guess my 5 digit password:") #asking the user to input their guess
if number == user_guess:
print "Win on the %d try" % (tries + 1)
break
print "answer was:", number

Related

How To Keep Trying New Inputs in Try and Except Format [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 months ago.
I am coding a guessing game where the user inputs an integer between 1 and 100 to try and guess the correct number (26). I have to count the number of guesses the user takes to get the correct number. I want to use try and except blocks to allow the user to keep trying until they guess it right.
Right now, my code only allows the user to input one ValueError. I don't want this, I want to keep inputting until I guess the number. Attached is my code. Any help is greatly appreciated!
ex:
I want to input errors ("a", 4.20, "hello") and still have them count as guesses until I guess the number
"a" > 4.20 > "hello" > 26 => Guessed it in 3 tries
def guess(n):
secret_number = 26
if n < secret_number:
return print("Too low!")
elif n > secret_number:
return print("Too high!")
def try_exp():
try:
n = int(input("What is your guess? "))
return n
except ValueError:
n = int(input("Bad input! Try again: "))
return n
def counter():
print("Guess the secret number! Hint: it's an integer between 1 and 100... ")
n = try_exp()
i = 0
while n != 26:
guess(n)
i += 1
n = try_exp()
print(f"You guessed it! It took you {i} guesses.")
counter()
Instead of making try_exp like that, you can use a while loop that will first ask for input, and if the input is valid, then it will break out of the while loop. This is one way to implement it:
def try_exp():
first_input = True
while True:
try:
if first_input:
n = int(input("What is your guess? "))
return n
else:
n = int(input("Bad input! Try again: "))
return n
except ValueError:
first_input = False
In this, we go through an infinite loop, and we have a flag that designates whether it is the first guess or if they have already guessed before. If it is the first guess, we ask them for input, and if it is the second guess, we tell them that they gave incorrect input and ask for more input. After receiving correct input, the function returns n. If the input is incorrect which is when it is not an integer, we set first_input as false. Then, the while loop loops again. It will keep on waiting for input until they submit an integer.

what is causing reference before assignment errors in below code?

I'm getting this error with refrenced before assignment and im not sure how to fix it.
I havent tried anything at the moment. It would be appreciated if this could be answered. (im just trying to fill up more words so it can be posted)
this is the error code i am getting:
number = int(number)
UnboundLocalError: local variable 'number' referenced before assignment
And this is the rest of my code
import random
import sys
again = True
while True:
myName = input('Hello, Enter your name to get started')
if myName.isdigit():
print('ERROR,Your Name is not a number, please try again')
print('')
continue
break
myName = str(myName.capitalize())
print('')
print('Hi {}, This is Guessing Game, a game where you have a certain amount of attempts to guess a randomly generated number. Each level has a different amount of attempts and a higher range of number. After each guess, press enter and the program will determine if your guess is correct or incorrect.' .format (myName))
print('--------------------------------------------------------------------------------')
while True:
level = input('{}, Please select a level between 1 and 3. Level 1 being the easiest and 3 being the hardest')
if not level.isdigit():
print('Please enter a number between 1 and 3. Do not enter a number in word form')
continue
break
def guessNumber(): # Tells the program where to restart if the user wants to play again
guessesTaken = 0
List = []
if level == 1:
number = random.randint (1, 16)
print('You chose Level 1, Guess a number a between 1 and 16, you have 6 guesses.')
allowedGuesses = 6
boundary = 16
if level == 2: # The code for level 2
number = random.randint (1,32)
print('You chose Level 2, Guess a number between 1 and 32, You have 8 guesses.')
allowedGuesses = 8
boundary = 32
if level == 3:
number = random.randint (1, 40)
print('You chose Level 3, Guess a number between 1 and 40, you have 10 guesses.')
allowedGuesses = 10
boundary = 40
if level == 4:
number = random.randint (1, 50)
print('You chose Level 4, Guess a number between 1 and 50, you have 10 guesses.')
allowedGuesses = 10
boundary = 50
if level == 5:
number = random.randint (1, 60)
print('You chose Level 5, Guess a number between 1 and 60, you have 10 guesses.')
allowedGuesses = 10
boundary = 60
guess = input()
guess = int(guess)
while guessesTaken < allowedGuesses:
guessesTaken = guessesTaken + 1
guessesLeft = allowedGuesses - guessesTaken
if guess < number:
List.append(guess)
print('Your guess is too low, You must guess a higher number, you have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess > number:
List.append(guess)
print('Your guess is too high, You must guess a lower number, you have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess > boundary:
List.append(guess)
print('You must input a number between 1 and 16. You have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess == number:
List.append(guess)
print('Good Job {}!, You guessed my number in {} guesses. You guessed the numbers {}.' .format (myName, guessesTaken, List))
print('Your high score for your previous game was {}' .format(guessesTaken))
else:
number = int(number)
print('')
print('--------------------------------------------------------------------------------')
print('Sorry {}, Your gueses were incorrect, The number I was thinking of was {}. You guessed the numbers {}.' .format(myName, number, List))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
while True:
again = input('If you want to play again press 1, if you want to stop playing press 2')
if not again.isdigit():
print('ERROR: Please enter a number that is 1 or 2. Do not enter the number in word form')
continue
break
if again == 1:
level + 1
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
In your code you are getting level as input and checking that if level is in between 1 to 5.
else you are trying number = int(number)
but you should write number = int(level).
Since level is a string rather than a number, none of the conditions like
if level == 1:
will succeed. So none of the assignments like number = random.randint (1, 16) ever execute, and number is never assigned.
Since if level == 5: doesn't succeed, it goes into the else: block, which starts with
number = int(number)
Since none of the other number assignments took place, this tries to use int(number) before the variable has been assigned, which doesn't work.
I'm not sure why you even have this assignment there. When number is assigned, it's always set to an integer, so there's no need to use int(number).
You need to use
level = int(level)`
after you confirm that it contains digits. And you need to do similarly with again.
There are a number of other problems with your code. For instance, the code that asks for the user's guess and checks it is inside the if level == 5: block, it should run in all the levels.
When you have a series of mutually exclusive tests, you should use elif for each successive test. If you just use if for each of them, and then use else: at the end, that else: will only apply to the last test, so it will be executed even if one of the early tests also succeeded.

IF statement will only consider ELIF? [duplicate]

This question already has answers here:
Numeric comparison with user input always produces "not equal" result
(4 answers)
Closed 4 years ago.
whats up? I'm playing around with my mastermind project for school, only recently started dabbling into Python - and I've ran into a problem I simply cannot figure out? I've looked at other people's questions, who seem to have the same problem as me, but it seems to be more selective, and my code is kind of different. Can anyone tell me why whenever I reply to the question, it immediately skips to "Try again!", even if I know for a fact rnumber == tnumber? (Using Python 3.4.2).
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = input("Guess the four digit number. ")
type(tnumber)
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
elif rnumber != tnumber:
print ("Try again!")
numot = numot+1
you need to make your input an int so it considers it a number, try this
#Generates the random number module
import random
#Creates the variable in which I store my random number
rnumber = random.randint(0,9999)
#Delete this code when complete
print (rnumber)
#Number of tries
numot = 0
#Asks for user input, on what they think the number is
tnumber = int(input("Guess the four digit number. "))
#Compares their number to the random number
if tnumber == rnumber:
print ("You win!")
else rnumber != tnumber:
print ("Try again!")
numot = numot+1

Loops not working in Python 3

I originally wrote this program in python 2, and it worked fine, then I switched over to python 3, and the while loop working.
I don't get any errors when I run the program, but it isnt checking for what the value of i is before or during the run. The while loop and the first if loop will run no matter what.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")
Thanks for any help in advance.
You are comparing something like '6' == 6, since you didn't convert the user input to an int.
Replace user_answer = input("Try to guess the magic number. (1 - 10) ") with user_answer = int(input("Try to guess the magic number. (1 - 10) ")).
user_answer will store the input as string and random.randint(1,10) will return an integer. An integer will never be equal to a string. So you need to convert user_input to integer before checking.
#imports the random module
import random
#Creates variable that is used later
i = 0
#chooses a random number betweeen 1 - 100
randomNumber = random.randint(1,10)
#prints the number
print (randomNumber)
#Creates while loop that runs the program until number is guessed
while i == 0:
#Creates a variable where the answer will be stored, and then
asked the question in the quotes
user_answer = input("Try to guess the magic number. (1 - 10) ")
# better use exception handling here
try:
user_answer = int(user_answer)
except:
pass
print ("\n")
if user_answer == randomNumber:
print("You guessed correct")
break
else:
print("Incorrect. Try again.")

Guess Random Number Why i m not able to enter input - python

Below is my code to generate random number between 0 - 9 and checking with user input whether it is higher lower or equal. When I run the code, it is not taking input and showing
error in 'guessNumber = int(input("Guess a Random number between 0-9")) File "", line 1 '
Can somebody please tell me where I'm making mistake
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
I think guessRandom() was meant to be outside of the method definition, in order to call the method. The guessNumber variable never changes since the inputs are not assigned to be guessNumber, thus it will continuously check the initial guess. Also, the less than / greater than signs seem to conflict with the intended message. Additionally, turn is outside of the scope of the method.
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
EDIT: Assuming you're using input in Python3 (or using raw_input in older versions of Python), you may want to except for ValueError in case someone enters a string. For instance,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
I changed the while loop condition to True and added a break because otherwise it would loop indefinitely (comparing an integer to a string input value).

Categories

Resources