All Im trying to do is make n a random number, if the user gets it correct it outputs "You got it!" but no matter what is always displays as if I got it wrong, even when I answered n
import random
n = random.randint(1,2)
guess = input("1 or 2?")
if guess == n:
print("You won!")
In python, "10" == 10 is False. You must compare the same type, like 10 == 10 or "10" == "10".
input() returns a str, when random.randint() returns an int, so guess == n will always be False.
This is an easy way to solve your issue :
guess = int(input("1 or 2?"))
or
n = str(random.randint(1, 2))
or
n = random.choice("12")
Related
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 got some homework to do and I got stuck with this code. I have no idea how to continue.
This is what I'm suppose to do:
generate_sequence - Will generate a list of random numbers between 1 to 101. The list
length will be difficulty.
get_list_from_user - Will return a list of numbers prompted from the user. The list length
will be in the size of difficulty.
is_list_equal - A function to compare two lists if they are equal. The function will return
True / False.
play - Will call the functions above and play the game. Will return True / False if the user
lost or won.
(Sorry for copy/pasting. My English is not so good.)
import random
difficulty = 101
secret_number = 6
def generate_number():
global secret_number
secret_number = random.randint(0, difficulty)
def get_guess_from_user():
return input( "Please choose number between 1 to " + str(difficulty))
def compare_results(userInput):
isSame = False
if(secret_number == userInput):
isSame = True
return isSame
def play():
generate_number()
userInput = get_guess_from_user()
isSame = compare_results(userInput)
print("number generated is: " + str(secret_number))
print(isSame)
play()
Your "problem" is, that if(secret_number == userInput): is currently comparing an int to a str, because the result of input() is always a str, even if the input is numeric. An int and a str are never equal, thus isSame will always be False.
You have to cast the user input to int somewhere along the way before or during the comparison.
e.g.:
def get_guess_from_user():
return int(input( "Please choose number between 1 to " + str(difficulty)))
# ^^^
Otherwise, your program seems to do what you are describing.
You could save some lines of code by writing:
def compare_results(userInput):
return (secret_number == userInput)
I took the liberty to rewrite your application w/o global variables:
import random
def generate_number(difficulty):
return random.randint(1, difficulty)
def get_guess_from_user(difficulty):
return int(input( "Please choose number between 1 to {}".format(difficulty)))
def play(difficulty):
secret_number = generate_number(difficulty)
user_input = get_guess_from_user(difficulty)
is_same = (secret_number == user_input)
print("number generated is: {}".format(secret_number))
print("Your guess was {}".format( "correct :)" if is_same else "not correct :(" ))
play(5)
Note: I also changed random.randint(0, difficulty) to random.randint(1, difficulty), because the lower part is also inclusive, meaning that it could return 0. When prompting the user for a number between 1 and 5, the user might be surprised that the correct number was 0 instead.
See the docs:
random.randint(a, b)
Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
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 wrote this script but it always returns the same answer ("Your guess is too high"), no matter what the user inputs. Any insight would be helpful.
import random
number = random.randint(1, 10)
guess = input("Guess a number between 1 and 10: ")
if type(guess == int):
print(number) # this prints the randint to show the code isn't working
while(number != 0):
if(guess > number):
print("Your guess is too high!")
break
elif(guess < number):
print("That's too low.")
break
elif(guess == number):
print("Thats's right!")
break
else:
print("Please enter a number.")
Your while loop is useless, the problem of testing the input as an int is better handled with a try/except.
All together the correct answer is in Python3 :
import random
number = random.randint(1, 10)
found = False
while not found:
try:
guess = int(input("Guess a number between 1 and 10: "))
if guess > number:
print("Your guess is too high!")
elif guess < number:
print("That's too low.")
elif guess == number:
print("Thats's right!")
found = True
except ValueError:
print("Please enter a number.")
if type(guess == int):
This isn't doing what you expect. It always returns True because it's the equivalent to bool(type(False)). First make sure to convert your input to an int
guess = int(input("Guess a number between 1 and 10: "))
and then remove this if statement:
if type(guess == int):
Your problem is that this code:
if(guess > number)
is always comparing a string to an int, so once you correct that your code will be fixed.
I have just copied and pasted your code and it seems to function mostly correctly. There are some issues with it though. First, it appears that this is written for python 2 based on the way you are using the input function. However this is bad practice as the input() function in python 2 includes an implicit call to the eval() function which could allow for arbitrary code to be run.
In python 2 the better practice would be to use guess = int(raw_input("Guess a number between 1 and 10: ")).
In python 3, raw_input() has been removed and input() replaces it. So in python 3 you would use guess = int(input("Guess a number between 1 and 10: ")).
Your final else block is also indented where it should not be, although if you revise your code to make use of the advice given above, your if...else block is no longer necessary.
That's because input returns a string in Python 3. You need to call int() to make it an integer type:
guess = int(input("Guess a number between 1 and 10: "))
You're also using the type() function incorrectly. You probably want the function isinstance(): if isinstance(guess, int):
Also, in Python, we don't need parentheses like you've used. You can simply do if guess > number:
import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if userInput > randomNumber:
print("Guess lower.")
elif userInput < randomNumber:
print("Guess Higher.")
else:
print("You got it!")
break
So this code currently takes the user input and says whether the user guessed the random integer, or if they should guess higher/lower. I want to edit the code to now say whether the user input is within 5,10,15, etc of the random integer.
So if the random integer was 30, and the user inputs 20, the program would say something like "You are within 10; guess higher."
Any advice? I'm extremely new to python, so please respond with more simple methods if possible.
Thanks.
PS: Oh, preferably without the use of modules, mainly because I'm still learning.
I think this does what you want, and it cuts down on the if chains a little:
import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
break # We use break b/c changing correct would still run rest of loop
acceptable_ranges = [5, 10, 15, 20, 25, 30, 25, 40, 45, 50]
guess_error = userInput - randomNumber
i = 0
while abs(guess_error) > acceptable_ranges[i]: # see how close they are
i += 1
if guess_error < 0: # let's figure out where they need to go
next_guess_direction = "higher"
else:
next_guess_direction = "lower"
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
Let's look. at the last if statement a little further and the final print line. We are checking to see if guess_error, defined above (line 15) guess_error = userInput - randomNumber is less than 0 (negative). If it is less than zero, then we make the variable next_guess_direction equal to the string "higher," because the next guess needs to be larger than the last one (randomNumber was larger than userInput. If guess_error is not negative, then it is positive, because we already eliminated the we eliminate the possibility of 0 using:
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
So, if guess_error is positive, we know that userInput was larger than randomNumber and we set next_guess_direction equal to the string "lower." Finally, we print out everything that we have found:
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
I am using an older version of formatting where %i and %s are placeholders for integer and string, respectively. I then define what should be formatted there using %(acceptable_ranges[i], next_guess_direction), which simply means to put acceptable_ranges[i] in for the integer and next_guess_direction in for the string. Keep in mind, we found i in acceptable_ranges[i] right above the if statement.
I know that is all long, but I did not know how much detail you needed!
Update: I see you ask to do it without modules. Here's a solution:
def ceil(xx):
if int(xx) < xx:
return int(xx) + 1
else:
return int(xx)
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / float(interval)
within = ceil(abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
-- original answer:
You can do this with numpy's ceil function.
For instance:
import numpy as np
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / np.float(interval)
within = np.ceil(np.abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
A solution using the modulo operator:
import random
randomNumber = random.randint(0,100)
def guess(divisor = 5):
while 1:
try:
print("Pick a number from 0-100")
userInput = int(input("Insert your number here: "))
except ValueError:
print("That is not a Number!")
continue
delta = randomNumber - userInput
if delta == 0:
print("You got it!")
return
remainder = delta % divisor
# this takes advantage of python truncating non-floating point numbers
rounded_delta = (abs(delta) / divisor) * divisor + divisor * bool(remainder)
high_or_low = 'higher' if delta > 0 else 'lower'
print("You are within %s. Guess %s." % (rounded_delta, high_or_low))