Variable become string even though value assigned is 0 - python

This is a guessing game, the variable ans here become type str at the while loop and cause an error. TypeError: '<' not supported between instances of 'str' and 'int'. Why is ans a str
import random
def guess(x):
ansnum = random.randint(1,x)
ans = 0
chance = 0
limit = 4
while ans!= ansnum and chance < limit :
ans = input(f"Guess between 1 and {x}: ")
chance += 1
if ans < ansnum:
print("close,too low")
else:
print ("close,too high")
else:
print("You Guess IT")
guess(10)

At first indeed you initialize it with 0, but it overlapped with the input() inside the loop thats returns a string, so the initialization doesn't mean anything. To solve it you have to cast the input to integer
import random
def guess(x):
ansnum = random.randint(1,x)
ans = 0
chance = 0
limit = 4
while ans!= ansnum and chance < limit :
ans = int(input(f"Guess between 1 and {x}: "))
chance += 1
if ans < ansnum:
print("close,too low")
else:
print ("close,too high")
else:
print("You Guess IT")
guess(10)

Related

print statement only when the condition is CONSECUTIVELY met 3 times in a row

I'm currently making a guessing game where user can get a congrats statement if they guess correctly 3 times in a row or a hint statement if they guesses incorrectly 3 times in a row. If user makes two correct guesses and one incorrect guess the count will reset and vice versa for incorrect guesses. the goal is for the right/wrong guess to be 3 times in a row for the statement to print
Here is what I have
count = 0
rightGuess = 0
wrongGuess = 0
die1 = random.randint(1,6)
guess = int(input('Enter guess: '))
if guess == die1:
rightGuess += 1
print('Good job')
if rightGuess == 3:
print('You guessed three times in a row!')
if guess != die1:
wrongGuess += 1
print('Uh oh wrong answer')
if wrongGuess == 3:
print("Hint: issa number :)")
This works but it displays the text whenever the user reaches 3 wrong or right guesses even if it's not in a row. Please help
You can reset the rightGuess variable using rightGuess = 0 when you add 1 to the wrongGuess variable.
You just have to reset the opposite variable to 0 when incrementing either of them.
count = 0
consecutiveRightGuess = 0
consecutiveWrongGuess = 0
die1 = random.randint(1, 6)
guess = int(input('Enter guess: '))
if guess == die1:
consecutiveWrongGuess = 0
consecutiveRightGuess += 1
print('Good job')
if consecutiveRightGuess == 3:
print('You guessed three times in a row!')
if guess != die1:
consecutiveRightGuess = 0
consecutiveWrongGuess += 1
print('Uh oh wrong answer')
if consecutiveWrongGuess == 3:
print("Hint: issa number :)")
You could also do it like this only using one variable for counting guesses:
import random
count = 0
while True:
die1 = random.randint(1,6)
guess = int(input("Enter guess: "))
if guess == die1:
count = count + 1 if count >= 0 else 1
print('Good job')
if guess != die1:
print('Uh oh wrong answer')
count = count - 1 if count <= 0 else -1
if count == 3:
print('You guessed three times in a row!')
break
if count == -3:
print("Hint: issa number :)")
break

Why am I running into this simple If loop error?

So , the compiler returns a syntax error for my if loop in this code, I am very new to Python any & all help will greatly be appreciated.
enter code lower_number = int(input('Enter the lower number'))
higher_number = int(input('Enter the higher number'))
r = random.randint(higher_number,last_number)
print("you have got only ", round(math.log(upper - lower + 1, 2)) ," chances")
count = 0
while count < math.log(upper - lower + 1, 2) :
count = count + 1
guess = int(input("Type your guess here")
#the next line is the line that returns the error
if r == guess :
print("wow you genius")
break;
elif guess < x :
print("not high enough")
elif guess > x :
print("too high ")
if count > math.log(upper - lower + 1, 2):
print("sorry, try next time")
As #Gulzar correctly suggested, you have several indentation errors and your code is not complete, so it's difficult for us to reproduce your use case.
Nevertheless this might help you:
count = 0
while count < math.log(upper - lower + 1, 2) :
count = count + 1
guess = int(input("Type your guess here"))
#the next line is the line that returns the error
if r == guess :
print("wow you genius")
break
elif guess < x :
print("not high enough")
elif guess > x :
print("too high ")
if count > math.log(upper - lower + 1, 2):
print("sorry, try next time")
The problems in your while loop were:
indentation (pay attention, it is fundamental in python)
a missing parenthesis in the line guess = int(input("Type your guess here"))

Learning Python - Number game

I'm new to Python. I'm trying to write a small game that asks the end user to pick a number from 1 to 1000 and keep it in their head (the number is not provided to the program). The program should be able to find the number within 10 guesses. As I typically do, I went down the wrong path. My program works most of the time, but there are occasions where it does not find the number in under 10 guesses. Here is my code:
# script to guess a user's number between 1 and 1000 within 10 guesses
# import random so we can use it to generate random numbers
from random import randint
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
failed = False
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# if the lower and upper bounds match we've found the number
if lowerBound == upperBound:
print(f"\nYour number is {str(lowerBound)}. It took me '{str(numGuesses)} guesses!")
break
print(f"\nIs the number {str(myGuess)}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
# uncomment for var output
# print(f"\nGuesses = {str(numGuesses)}\nLower bound = {str(lowerBound)}\nUpper bound = {str(upperBound)}")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{str(numGuesses)} was too high")
if numGuesses == 10:
failed = True
break
upperBound = myGuess - 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'LOW':
print(f"\nGuess #{str(numGuesses)} was too low")
if numGuesses == 10:
failed = True
break
lowerBound = myGuess + 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'CORRECT':
print(f"\nYour number is {str(myGuess)}! It took me {str(numGuesses)} guesses!")
break
numGuesses += 1
if failed:
print(f"\nMy final guess of {str(myGuess)} was not correct. I wasn't able to guess your number in 10 tries.")
It seems clear (now) that the way I'm whittling down the numbers is not going to work. I had originally thought to ask if it was 500 and, if lower, ask if it was 250. If lower again, ask if it was 125, and so on. If higher, ask if it was 750, 875 and so on. Is that the correct approach here?
I've been thinking about this too long and I believe I've cooked my brain. Thanks!
myGuess = int(math.ceil((myGuess) / 2))
is not correct.
If you have narrowed down the range to between 6 and 8 and you were guessing 7, your previous code would call 4 instead which is outside your search range.
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess - 1
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess + 1
myGuess = int(lowerBound + ((upperBound - lowerBound) / 2))
I've updated my code and I think I have it. Thanks for the tips.
# script to guess a number between 1 and 1000 within 10 guesses
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# uncomment next line for var output
# print(f"\nGuesses = {numGuesses}\nLower bound = {lowerBound}\nUpper bound = {upperBound}")
print(f"\nIs the number {myGuess}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess
myGuess = (lowerBound + myGuess) // 2
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess
myGuess = (upperBound + myGuess + 1) // 2
elif userFeedback == 'CORRECT':
print(f"\nYour number is {myGuess}! It took me {numGuesses} guesses!")
break
numGuesses += 1

Function returns None after wrong input

I need a function that excepts wrong input and asks to input once more. But after wrong input it returns None instead of new input. What is wrong with my code and how can I solve this?
def start():
def inputNumber(answer):
try:
number = int(input(answer))
if number <= 100 and number >= 0:
print('%%%',number,'%%%')
return number
else:
inputNumber('Number is wrong, please input number from 0 to 100: ')
except (ValueError):
inputNumber('It is not a number, please input number from 0 to 100: ')
def checkInput(number2):
print('$$$',number2,'$$$')
if number < 50:
return number2
else:
return checkInput(inputNumber('Input number from 0 to 100: '))
number = 0
print('###',checkInput(inputNumber('Input number from 0 to 100: ')),'###')
start()
start()
This is the result:
Input number from 0 to 100: 777
Number is wrong, please input number from 0 to 100: sadf
It is not a number, please input number from 0 to 100: 17
%%% 17 %%%
$$$ None $$$
TypeError: unorderable types: NoneType() < int()
You are calling inputNumber recursively but don't return the result of the recursive call. Better use loops instead of recursion:
def inputNumber(prompt):
while True:
try:
number = int(input(prompt))
if 0 <= number <= 100:
print('%%%',number,'%%%')
return number
prompt = 'Number is wrong, please input number from 0 to 100: '
except ValueError:
prompt = 'It is not a number, please input number from 0 to 100: '
Btw: you should also use loops in your other functions, and don't define nested functions.
run this code it will solve your problem. you just need to catch as extra error (NameError)
def start():
def inputNumber(answer):
try:
number = int(input(answer))
if number <= 100 and number >= 0:
print('%%%',number,'%%%')
return number
else:
inputNumber('Number is wrong, please input number from 0 to 100: ')
except (ValueError, NameError) as e:
inputNumber('It is not a number, please input number from 0 to 100: ')
def checkInput(number2):
print('$$$',number2,'$$$')
if number < 50:
return number2
else:
return checkInput(inputNumber('Input number from 0 to 100: '))
number = 0
print('###',checkInput(inputNumber('Input number from 0 to 100: ')),'###')
start()
start()
The problem is that once you fail a check you call inputNumber again, but don't do anything with the answer. You need to return it.
def start():
def inputNumber(answer):
try:
number = int(input(answer))
if number <= 100 and number >= 0:
print('%%%', number, '%%%')
return number
else:
return inputNumber('Number is wrong, please input number from 0 to 100: ')
except (ValueError):
return inputNumber('It is not a number, please input number from 0 to 100: ')
def checkInput(number2):
print('$$$', number2, '$$$')
if number < 50:
return number2
else:
return checkInput(inputNumber('Input number from 0 to 100: '))
number = 0
print('###', checkInput(inputNumber('Input number from 0 to 100: ')), '###')
start()
start()

Python number game with changing feeback

User guesses four digit number and feedback needs to be 'F' if a number is correct but not in the right place, 'X' if the number is not in the number at all and if the digit is correct and in the right position it displays the digit. Code below shows my attempt but it is giving me the error: expected str instance, list found
from random import randint
def check_char(a, b): #Function making output display F, number and X depending on user input
if a == b:
return randomNumber #Number is displayed when correctly guessed
elif b == randomNumber:
return 'F' #F means number is somewhere in the randomNumber
elif b != randomNumber:
return 'X' #X means number is nowhere in the randomNumber
guessesTaken = 1
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
print(randomNumber)
while guessesTaken < 10:
guesses = list(input("Guess Number: ")) # create list of four digits
check = ''.join([check_char(int(a), int(b)) for a, b in zip(guesses, randomNumber)])
if check == "YYYY": # if check has four Y's we have a correct guess
print("Congratulations, you are correct, it took you", guessesTaken, "guesses.")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
if guessesTaken == 10:
print("You lose")
You will be replacing X with F if the user has guessed a number and it is in randomNumber at another position it will be replaced with an ``F:
from random import randint
guessesTaken = 1
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
def check_char(a, b): #Function making output display F, number and X depending on user input
if a == b:
return b #Number is displayed when correctly guessed
elif a in randomNumber and a != b: # if
return 'F'
elif a != b:
return 'X'
while guessesTaken < 10:
guesses = list(raw_input("Guess Number: ")) # create list of four digits
check = ''.join([check_char(a, b) for a, b in zip(guesses, randomNumber)])
if check.isdigit(): # if check is all digits, number is guessed
print("Congratulations, you are correct, it took you", guessesTaken, "guesses.")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
else:
print("You lose")
You don't need to cast as ints in check_char(a, b) as strings will compare just fine "1" == "1" is True
You are returning the list return randomNumber not the substring b so you get an error trying to join as it expects a string not a list, also b would never be equal to randomNumber .

Categories