Trouble with an assignment - python

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!

Related

What's wrong with my use of if / then in this script?

I'm learning if and then statements. I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)
I get an error in line 8
#input integer / test if any decimal number is even or odd
inp2 = input("Please enter a number: ")
the_number = str(inp2)
if "." in the_number:
if int(the_number) % 1 == 0
if int(the_number) % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("You dum-dum, that's not an integer.")
else:
the_number = int(inp2)
if the_number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
I'm just starting with python so I appreciate any feedback.
You have to include a colon at the end of second if statement, like you did in your other conditional statements.
if int(the_number) % 1 == 0:
Next time, give a closer look at the error message. It'll give you enough hints to fix it yourself, and that's the best way to learn a language.
EOL.
You forgot a :. Line 8 should read if int(the_number) % 1 == 0:.
Try putting the : at the end of the if statement
if int(the_number) % 1 == 0:
You can test your input as following code snippet
num = input('Enter a number: ')
if num.isnumeric():
print('You have entered {}'.format(num))
num = int(num)
if num%2:
print('{} is odd number'.format(num))
else:
print('{} is even number'.format(num))
else:
print('Input is not integer number')

While loop spamming output instead of printing output once?

I'm making a regular guess the number game. I'm having problems when I enter the guess and the program spams lower or higher instead of just typing it once, since I'm using a while True loop.
Here I'm just opening the CSV file and picking a random number.
import random
numbers = open('numbers_1-200.csv').read().splitlines()
number = int(random.choice(numbers))
Here I'm importing numbers 1-50 and picking two random numbers which will be what's added and subtracted from the original number. So the computer can write two numbers where the original number is between.
I know I could have just made the program pick two numbers from the first fifty lines in the same CSV that includes numbers from 1-200 but I choose to make another CSV which only had the numbers 1-50.
differences = open('numbers_1-50').read().splitlines()
difference = int(random.choice(differences))
difference2 = int(random.choice(differences))
clue = number + difference
clue2 = number - difference2
This is my welcome screen which also includes the main program on the last row¨
def welcome_screen():
print('The number is between ' + str(clue) + ' and ' + str(clue2))
print('Guess the number: ')
guess_the_number()
This is my loop where you guess the number
def guess_the_number():
guess = int(input())
while True:
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')
I'm getting outputs like these:
The number is between 45 and 97
Guess the number: 72
lower
lower
lower
lower
lower
lower
lower
lower
How can I get a output where it just says "lower" (or "higher") one time and then I can guess again?
Just move the input function inside the while loop:
def guess_the_number():
while True:
guess = int(input())
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')
def guess_the_number():
while True:
guess = int(input())
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')

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.")

Trying to understand my Python guessing game code

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.

Bagel Pico fermi error?

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.

Categories

Resources