Why am I running into this simple If loop error? - python

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

Related

Variable become string even though value assigned is 0

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)

How can I check if a number is negative?

I tried to check if the number is negative or not:
x = int(input('Enter any number:'))
bumble = x+1
shumble = x-1
if shumble>x:
print('Your number is a negative number')
elif bumble>x:
print('Your number is a positive number')
elif x == 0:
print('Your number is 0')
but the problem is python won't consider a negative number its mathematical value
and I checked that by running this block of code
x = -2
y = 1
if x>y:
print('-2 is greater that 1')
elif y>x::
print('1 is greater than -2')
and the output says:
-2 is greater than 1
so can someone pls help me find a solution?
I would really appreciate it!
I'm not sure whether or not you're not allowed to use zero with you inequality operator. But surely the following should work pretty well. You can omit the exception handling if not needed.
try:
x = int(input('Enter any number:'))
if x < 0: print('Your number is a negative number')
elif x > 0: print('Your number is a positive number')
elif x == 0: print('Your number is 0')
except ValueError:
print("That was not a valid number...")
You're overcomplicating this so much. To check if its a negative number check if its less than, equal to, or greater than zero
try:
x = int(input("Enter a number"))
except:
print("invalid number")
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Equal to 0")
num = float(input("Enter a number: "))
if num > 0:
print("{0} is a positive number".format(num))
elif num == 0:
print("{0} is zero".format(num))
else:
print("{0} is negative number".format(num))

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

check if a number combination is found in a list of combinations

I am creating a program in Python simulating multiplication flash cards. I've gotten pretty far but I can't figure out how to not repeat combinations of numbers. How do I check if a pair of numbers has already been presented?
from __future__ import division
from itertools import combinations
import random
amountCorrect = 0
amountMissed = 0
comb = combinations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 2)
print("Type 0 at any time to exit and see your score.")
while True:
firstNumber = random.randint(1,12)
secondNumber = random.randint(1,12)
ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
if ans == 0:
break
elif ans == firstNumber * secondNumber:
amountCorrect += 1
else:
amountMissed += 1
totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems
if .9 < percentCorrect <= 1:
print("Great job, you are doing awesome!")
elif .7 <= percentCorrect <= .89:
print("You are doing well,keep it up.")
elif .5 <= percentCorrect <= .69:
print("You are half way to becoming a master.")
else:
print("Keeping practicing, you will be a master one day.")
In short, use a set to store the pairs of numbers you have already used. Here is some code. You never use combinations in your code so I removed it.
from __future__ import division
import random
amountCorrect = 0
amountMissed = 0
highestNumber = 12
print("Type 0 at any time to exit and see your score.")
used = set()
while True:
if len(used) == highestNumber ** 2:
break
while True:
firstNumber = random.randint(1,highestNumber)
secondNumber = random.randint(1,highestNumber)
pair = (firstNumber, secondNumber)
if pair not in used:
used.add(pair)
break
ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
if ans == 0:
break
elif ans == firstNumber * secondNumber:
amountCorrect += 1
else:
amountMissed += 1
totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems
if .9 < percentCorrect <= 1:
print("Great job, you are doing awesome!")
elif .7 <= percentCorrect <= .89:
print("You are doing well,keep it up.")
elif .5 <= percentCorrect <= .69:
print("You are half way to becoming a master.")
else:
print("Keeping practicing, you will be a master one day.")
I just created an empty set called used, and added a new inner loop. That loop test if the pair of numbers has already been used. If so, it just loops again and tries a new pair of numbers. I also added a variable to store the highest possible number, and test of the used set is full. I end the quiz if it is full. Without this, when all possibilities are tried the program will go into an infinite loop.
Note that this code will allow both 1,2 and 2,1. If you want to allow only one of those, add both (firstNumber, secondNumber) and (secondNumber, firstNumber) to the used set.

Why does my count function only count as high as one when I have multiple integers?

Q: Why does my count function only count as high as one when I have multiple integers?
CODE:
import random
while True:
value = 0
count = 0
right_counter = 0
value = int(input("Enter the amount of questions would you like to answer: "))
AVG = right_counter / value
if 0<=value<=10:
for i in range(value):
numb1 = random.randint(0, 12)
numb2 = random.randint(0, 12)
answer = numb1 * numb2
AVG = right_counter / value
problem = input("What is " + str(numb1) + " * " + str(numb2) + "? ")
right_counter =+ 1
if int(problem) == answer:
print("You are Correct! Great Job!".format(right_counter))
elif int(problem) > answer:
print("Incorrect, Your answer is too high!")
elif int(problem) < answer:
print("Incorrect, your answer is too low!")
print("You got",right_counter,"out of",value,"correct, giving you an average of ",AVG,"")
break
else:
print(" Error, Please type a number 1-10 ")
This is what the output looks like:
Enter the amount of questions would you like to answer: 3
What is 1 * 8? 8
You are Correct! Great Job!
What is 11 * 11? 122
Incorrect, Your answer is too high!
What is 1 * 7? 7
You are Correct! Great Job!
You got 1 out of 3 correct, giving you an average of 0.3333333333333333
I found some help on Tutorial, but I couldn't answer my question.
bug:
right_counter =+ 1
This is (insidiously) equivalent to
right_counter = 1
you probably meant
right_counter += 1
You probably also want to address the logic issue that right_counter is incremented regardless of the correctness of the answer.

Categories