So as part of this Python I'm currently taking one of the exercises is to create a guessing game which run in the terminal. Obviously there are multiple ways of doing this and instead of simply watching the solutions video I tried to do it myself first. My code runs with no errors and as far as I can tell it should do the job, however it doesn't. Instead of just looking up a solution on here and rewriting the whole thing the just copies what someone else did I was wondering if someone could help me out with understanding why my code doesn't do what I expected it to?
It's listed below, thank you.
import random
digits = list(range(10))
random.shuffle(digits)
one = digits[0:1]
two = digits[1:2]
three = digits[2:3]
digits = one, two, three
guess = input("What is your guess? ")
g_one = guess[0:1]
g_two = guess[1:2]
g_three = guess[2:3]
while(guess != digits):
print(digits)
if(guess == digits):
print("Congrats, you guessed correctly")
break
elif(g_one == one or g_two == two or g_three == three):
print("One or more of the numbers is correct")
guess = input("Try again: ")
elif(g_one != one and g_two != two and g_three != three):
print("None of those numbers are correct.")
guess = input("Try again: ")
else:
break
It seems you are not updating the values of g_one, g_two and g_three on every iteration.
digits = ([2], [3], [4]) # Assume this is the shuffling result, You are getting a tuple of lists here
guess = input("What is your guess? ") # 123
g_one = guess[0:1] #1
g_two = guess[1:2] #2
g_three = guess[2:3] #3
while(guess != digits): #123 != ([2], [3], [4]) string vs a tuple comparison here
print(digits)
if(guess == digits):
print("Congrats, you guessed correctly")
break
elif(g_one == one or g_two == two or g_three == three):
print("One or more of the numbers is correct")
guess = input("Try again: ") #You are getting the input but the splits are not updated
elif(g_one != one and g_two != two and g_three != three):
print("None of those numbers are correct.")
guess = input("Try again: ") #Same here. Not updating the splits
else:
break
I think that should explain it.
Related
So I'm new to programming and I'm trying to write a program where I have a number in my head and the computer must guess it until I say that it has guessed right!
The computer should choose a random number between 1 to 99 and show it to me, If the number is correct I should type "c" to prove that it's correct, if the number in my head is smaller I should write "s" to make the range smaller and if the number in my head was bigger I should write "b" to make the range smaller and easier for the computer to guess the number.
this is the code I came up with but there's something wrong with it that I can't find out.
import random
first=1
second=99
guess=random.randint(first,second)
print(guess)
answer=input("what is the number in your head(don't enter it, just compare it with the number on the screen)? print c for correct, b for bigger and s for smaller! \n")
while answer!="c":
if answer=="b":
first==guess+1
guess=random.randint(first,second)
print(guess)
elif answer=="s":
second==guess-1
guess=random.randint(first,second)
print(guess)
answer=input("what do you think about the new number? ")
print("you did it!")
You have two mistakes: using == (testing for equality) where you should have used = (assignment), and wrong indentation:
import random
first = 1
second = 99
guess = random.randint(first, second)
print(guess)
answer = input("what is the number in your head(don't enter it, just compare it with the number on the screen)? print c for correct, b for bigger and s for smaller! \n")
while answer != "c":
if answer == "b":
first = guess + 1 # <-- this line
guess = random.randint(first, second)
print(guess)
elif answer == "s":
second = guess - 1 # <-- this line
guess = random.randint(first, second)
print(guess)
answer = input("what do you think about the new number? ") # <-- and this line
print("you did it!")
The final line would only run after the loop ended instead of once every loop the way you wrote it.
See how the spaces I added make it clearer what's going on on each line
You should indent the second input line so that it belongs to the while loop. This way new input is requested after every guess.
Your program is correct, it just needs a few modifications in the while loop. It should look like this:
while answer != "c":
if answer == "b":
first = guess+1
guess = random.randint(first, second)
print(guess)
elif answer == "s":
second = guess-1
guess = random.randint(first, second)
print(guess)
answer = input("what do you think about the new number? ")
I am doing an assignment for school where I need to make a list and assign 4 random integers to the list between 1 and 9. Then, I need to prompt the user for what their guess is for each value. If they get any of the numbers right, I need to say how many, but I've been working on this for like 3 hours and I'm getting nowhere. Currently, all I have is a massive useless nested if/elif statements.
This is the assignment prompt:
Program Specifications:
Computer should generate 4 random numbers from 1 - 9 as the "Secret Code".
User should be prompted for their guess of those four numbers.
After they provide their full guess, the user is told how many are correct.
As long as the user does not get all four correct, they keep getting asked for their guess.
After the user finally gets all of them correct (yes - all four), they are congratulated and then told how many tries it took them.
Technical Requirements:
Use at least one list
Use at least one function with parameters
I'm so confused and I don't know where to start. Here is my current code:
import random
count = 0
guess1 = 1
guess2 = 1
guess3 = 1
guess4 = 1
def getGuess(count,guess1,guess2,guess3,guess4):
while True:
guess1 = input("What is your guess for the first number? ")
guess2 = input("What is your guess for the second number? ")
guess3 = input("What is your guess for the third number? ")
guess4 = input("What is your guess for the fourth number? ")
if str(guess1) == numbers[0] and str(guess2) == numbers[1] and str(guess3) == numbers[2] and str(guess4) == numbers[3]:
print("Your first, second, third, and fourth numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1] and guess3 == numbers[2]:
print("Your first, second, and third numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1]:
print("Your first and second number are correct!")
elif guess1 == numbers[0]:
print("Your first number is correct!")
elif guess2 == numbers[1]:
print("Your second number is correct!")
elif guess2 == numbers[1] and guess3 == numbers[2]:
print("Your second and third numbers are correct!")
elif guess2 == numbers[1] and guess3 == numbers[2] and guess4 == numbers[3]:
print("Your second, third, and fourth numbers are correct!")
elif guess3 == numbers[2]:
print("Your third number is correct!")
elif guess3 == numbers[2] and guess4 == numbers[3]:
print("Your third and fourth numbers are correct!")
elif guess4 == numbers[3]:
print("Your fourth number is correct!")
else:
print("None of your numbers are correct. Try again.")
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
print(numbers)
getGuess(count,guess1,guess2,guess3,guess4)
I see your attempt so I'm going to tell you the problems, as comments said:
Logic flow: your if else statement are serving 4 numbers, what if 10, 100 numbers? It should be generic
You are comparing string with integer, should cast it
Should package your variables inside your function. Which is very ambiguous of guess1 = 1, guess1 function variable, guess1 from input,...
Init random numbers
import random
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
getGuess function, which is getting guess numbers from input string, then split it and convert to int.
def getGuess(numbers):
retryCount = 0
while True:
# You can put try catch here for number validation
guessNums = [int(x) for x in input("Numbers: ").split()]
# To make sure your input must be the same length
if len(guessNums) != len(numbers):
print('Not available numbers')
continue
# Here we just check for incorrect, once it's met, the for loop will be broken and go to the next while loop
isIncorrect = False
for index, num in enumerate(numbers):
if num != guessNums[index]:
isIncorrect = True
retryCount += 1
print('Order of ' + str(index + 1) + ' is incorrect')
break
# When every number is equal, not incorrect occured, return retry count
if isIncorrect == False:
return retryCount
Using:
print('Your retry count: ' + str(getGuess(numbers)))
You can optimize many of the parts of your code.
Assumption: You know how to use lists as you are already using numbers as a list. I am staying away from dictionary. Not sure if you know its use. Also assume you understand list comprehension. If you dont, see this link on list comprehension.
Now let's look at your code. Here are a few things to consider:
You don't need 4 variables to store the 4 input values. You can use a list and store all 4 of them there.
As many have already suggested, you should convert the input value into an integer. When you convert string to integer, there is a potential that the string is not an integer. This can result in code getting broken. So use Try Except to catch the error while converting to int
Your random.randrange(1,9) will create integers. So you dont have to explicitly convert them back to integer.
You have 4 inputs and 4 values to compare. You can map each value to the position and compare. That will reduce the complexity. For the ones that are successful, keep a tab of it. Then print the ones that matched. Again, this can be done using a list or dictionary.
With all that to consider, I have re-written your code as follows. See if this helps you with the solution.
import random
nums = [random.randrange(1,9) for _ in range(4)]
def getGuess():
g = ['first','second','third','fourth']
i = 0
gx = []
while i<4:
try:
x = int(input(f"What is your guess for the {g[i]} number? :"))
gx.append(x)
i+=1
except:
print ('Not numeric, please re-enter')
gwords = [g[i] for i in range(4) if nums[i] == gx[i]]
if gwords:
if len(gwords) == 1:
resp = "Your " + gwords[0] + ' number is correct!'
else:
resp = "Your " + ', '.join(gwords[:-1]) + ' and ' + gwords[-1] + ' numbers are correct!'
print (resp)
else:
print ("None of your numbers are correct. Try again.")
getGuess()
Here's an example run of the above code:
What is your guess for the first number? :1
What is your guess for the second number? :6
What is your guess for the third number? :5
What is your guess for the fourth number? :4
Your second, third and fourth numbers are correct!
I am writing a code for class due tomorrow(sorry for the late notice) but my number filter will not loop or detect the numbers. Could someone help please, also explain thoroughly as possible cause I have to the same when i present as well.
tryagain = True
print("Welcome to Hangman: The Game. Made by Matt, Will and Dom")
while tryagain:
print("To play please have player one input a word for player two to guess")
Input = input("Player one, Please input a word: ").lower()
Answer = Input.lower()
numbers = ("123456789!##$%^&*()_+{}:<>?|/.,';\][")
if numbers in Answer:
print("No numbers or speicals characters please")
continue
game = "_" * len(Answer)
alreadySaid = set()
mistakes = 7
print("Player two, Your word is", " ".join(game))
guess = False
while not guess and mistakes > 0:
attempt = input("Player two, please guess a letter: ")
if attempt in Answer:
alreadySaid.add(attempt)
game = " ".join([char if char in alreadySaid else "*" for char in Answer])
if game == Answer:
guess = True
else:
mistakes -= 1
print ("Wrong letter", "You have", mistakes, "left")
if mistakes == 0:
print("You have lost player Two")
break
print(" ".join(Answer))
tryagain = (input("Again [y/n]: ").lower() == 'yes')
if tryagain == "yes":
continue
The expression numbers in Answer will evaluate to True only if Answers contains the entire String numbers. It doesn’t return True if Answers only contains one or more characters in numbers.
A regular expression would be useful to you in this context.
Current code may have more bugs than I see at the moment, but what I am trying to fix is the get_guess() function. At the moment I have coded it to print i in the "for i in range..." because whenever I input a guess, it automatically assumes i = 0 and prints "You can only guess numbers." I'm not sure why, when 0 is part of the list of numbers that it is supposed to check. Any ideas on how to fix this?
Side note, things are indented correctly, I am just not used to the formatting of this website.
import random
def explain_instructions():
print("I am thinking of a number with nonrepeating digits. You will have 10 attempts to try and guess my number.")
print("'Bagel' will be displayed if no digits are correct.")
print("'Pico' will be displayed if a digit is correct but in the wrong place.")
print("'Fermi' will be displayed if a correct digit is in the correct place.")
def generate_number(length):
num_list = [0,1,2,3,4,5,6,7,8,9]
random.shuffle(num_list)
secret_num = num_list[0:length]
secret_num = "".join(str(digit) for digit in secret_num)
return secret_num
def give_clues(secret_num, guess):
clues = []
for i in range(len(str(guess))):
if guess[i] == secret_num[i]:
clues.append("Fermi")
elif guess[i] in secret_num and guess[i] != secret_num[i]:
clues.append("Pico")
if clues == []:
clues.append("Bagel")
return(clues)
print(clues)
def get_guess(length, guess):
for i in range(int(length)):
if guess[i] in guess[:i] or guess[i] in guess[i+1:]:
print("Repeating numbers don't work in this game.")
return
elif len(guess) != len(secret_num):
print("You don't have the correct number of digits.")
return
elif guess[i] not in num_list and guess != "":
print(i,"You can only guess numbers.")
return
else:
return int(guess)
def play_again():
print("Would you like to play again? (Yes/No)")
answer = input()
if answer.lower()== "yes":
return True
else:
print("That wasn't a firm 'yes' so.... goodbye :( ")
print("Welcome to Bagel, Fermi, Pico!")
explain_instructions()
num_list = [0,1,2,3,4,5,6,7,8,9]
game_is_done = False
while True:
print("How long would you like your number to be?")
length = input()
secret_num = generate_number(int(length))
print(secret_num)
max_guess = 0
while max_guess < 10:
print("Enter a", length, "digit guess:")
guess = input()
if guess == "411":
print(explain_instructions())
elif get_guess(length,guess):
max_guess += 1
clue = give_clues(secret_num,guess)
print(clue)
if clue == ['Fermi'] * len(secret_num):
print("Congrats! You guessed the correct number!")
break
if max_guess == 10:
print("Oh no! You have run out of guesses. The secret number was:", secret_num)
if not play_again():
break
I think it might be because you are declaring num_list inside the function
generate_number(length)
So when you ask for num_list outside the function, python has no idea what num_list is. Declaring it as a global variable could solve your problem (haven't tested it, though)
And yes, i = 0 because it's the iterator, not the number you've guessed. If you want to see your guess, write
print(guess[i],"You can only guess numbers.")
I would be careful with a couple things, nontheless
1. Specify that the input has to be a string. If you input an int without the quotes, it crashed (at least for me it crashed), or cast it to string before passing it to the function. It crashed when trying to access the array guess[i]
2. Be careful with digits that start with 0 (e.g. 02). Casting to int will transform it to 2 if you don't specify otherwise.
I am a new programmer with experience with Visual Basic for Applications and have recently changed to python.
I'm working on a number guessing game and so far progress has been great. The user enters 4 digits into the program. The program also generates a 4 digit number and the program returns Ys or Ns to show whether any digits are correct or not. EG 1357 as a user guess and 1358 as the programs number shows YYYN as output.
I'm trying to rework the program to make it simpler for users by showing H or L to suggest that they need to guess higher or lower IF the digit guessed is incorrect. If it's correct, then a Y should be shown as per normal. I am aware that it's a condition in the loop I need to change or another loop I need to add but I am struggling to see where to add this and how to write it. Does anybody have a solution for this?
Here is part of my code for the section of the program which returns the result for the guesses.
lives = 10
while lives > 0:
number = input("Enter your guess: ")
letter = ''
for i in range(len(numToGuess)):
letter += 'Y' if int(number[i]) == numToGuess[i] else 'N'
if letter == 'Y' * len(numToGuess):
print("Good job!")
break
print(letter)
lives -= 1
else:
print("Game over! You used up all of your tries.")
Does anybody have a solution for this?
I prefer to use lists for this. Meaning, I'd convert both the correct answer and the user guess into separate digits saves in two lists and then compare them.
Let's say the correct answer is '1234':
lives = 10
correct_answer = 1234
correct_answer = [int(char) for char in str(correct_answer)]
while lives > 0:
letter = ''
number = input("Enter your guess: ")
number = [int(char) for char in str(number)]
if number == correct_answer:
print("Correct!")
break
for i in range(len(correct_answer)):
if correct_answer[i] == number[i]:
letter += 'Y'
elif correct_answer[i] > number[i]:
letter += 'H'
else:
letter += 'L'
print("Your guess is wrong: ", letter)
lives -= 1
print("Game over!")
Now for example:
Enter your guess: 1111
Your guess is wrong: YHHH
Enter your guess: 1235
Your guess is wrong: YYYL
Enter your guess: 1234
Correct!
Game over!
>>>
You can use zip function for compare the letters :
>>> a='1357'
>>> b='1358'
>>> l=[]
>>> for i,j in zip(a,b):
... if i==j :l.append('Y')
... else :l.append('N')
...
>>> ''.join(l)
'YYYN'
And for check the answer you can use a generator expression within all :
>>> all(i=='Y' for i in l)
False
You don't need to change your loop condition. Just change the logic of your if expression.
letter = ''
for i in range(len(numToGuess)):
if int(number[i]) == numToGuess[i]:
letter += 'Y'
elif int(number[i]) > numToGuess[i]:
letter += 'H'
else:
letter += 'L'
Or, in one line:
letter = ''
for i in range(len(numToGuess)):
letter += 'Y' if int(number[i]) == numToGuess[i] else ('H' if int(number[i]) > numToGuess[i] else 'L')