I am extremely new to python and this is one of the first things I have tried. There are 3 criteria that I want this game to meet. First is to use the number 0-10 and guess the number 3 which it does correctly. Next is 0-25 when 11 is chosen. This also works correctly.
However this last part has been giving me trouble. When picking from 0-50, it should guess 1 which it does. It should also print the "I'm out of guesses" line when another input is placed as it cannot go higher than one now. What am I doing wrong here?
import random
import math
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
maxTry = math.log(larger - smaller)
count = 0
guess = int((smaller+larger)/2)
while count != maxTry:
count += 1
guess = int((smaller+larger)/2)
print("Your number is ", guess)
help = input("Enter =, <, or >: ")
if help == ">":
smaller = guess +1
elif help == "<":
larger = guess -1
elif help == "=":
print("Hooray, I've got it in", count, "tries")
break
elif count == maxTry:
print("I'm out of guesses, and you cheated")
break
Your maxTry is a log so it is not an integer, therefore it can never be equal to count.
You can either use an int for maxTry (cast it to int maxTry = int(math.log(larger - smaller))) or compute it with something different than log that will return an int.
Alternatively, your condition could be count > maxTry instead of equal. It would actually be a bit better conceptually.
Note: you should not use capital letters in variable names in python but all lowercase with _ max_try. It is only a convention though so won't affect your program directly. You can find more info on conventions in the PEP8 documentation
Related
My assignment requires me to take in an input, determine how many digits are in said input, then spit it back out. we are not allowed to use string conversion in order to determine the length of the input. I've managed to get that to work properly. My issue is that I'm supposed to have it repeat in a loop until a sentinel is reached. Here's my code so far.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = 1
final = 0
num = int(input("Enter a number: "))
while num != 0:
num = num //10
count += 1
print("There are", count, "digits in", num)
I'm also seeming to have trouble with having my input integer print properly, but it might just be my ignorance there. I've cut out what my attempts at looping it were, as they all seemed to just break the code even more. Any help is welcome, even criticism! Thank you in advance!
Firstly, that is a strange way to get the digits in the number. There's no need to modify the actual number. Just cast the int back to a string and get the length (don't just keep the original string, it could have spaces or something in it which would throw off the count). That is the number of digits.
Secondly, you can do all the work in the loop. There's no need for setup variables, incrementing, a second loop, or anything like that. The key insight is the loop should run forever until you break out of it, so you can just use "while True:" for the loop, and break if the user inputs "0".
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
def find_digits(num):
count = 0
while num != 0:
num = num //10
count += 1
return count
count += 1
# loop forever
while True:
# hang onto the original input
text_input = input("Enter a number: ")
# cast to int - this will throw an exception if the input isn't int-able
# you may want to catch that
num = int(text_input)
# the number of digits is the length of the int as a string
num_digits = find_digits(num)
if num == 0:
print("Goodbye.")
# "break" manually ends the loop
break
# if we got to this point, they didn't input 0 and the input was a number, so
# print our response
print(f"There are {num_digits} digits in {num}.")
The problem with printing the input integer correctly is, that you first save it in the num variable and then constantly change it in your while loop. So the original input is lost of course and in the end it always prints the 0, that ends up in num after the while loop finishes.
You can easily fix it, by saving the input value to another variable, that you don't touch in the loop.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = int(input("Enter a number: "))
numcopy = num
while numcopy != 0:
numcopy = numcopy // 10
count += 1
print("There are", count, "digits in", num)
Counting is better done with Python builtin functions.
len(str(num))
will give you number of digits in your number.
I created a number guessing game and its code is as follows but the problem is that when I input the number which is warm (look at the code)(for eg 70) and then the warmer number(say 69) and then finally the secret number(i.e. 65) instead of showing 'you won!!:)' it again asks the user to input value but if I directly input the secret number or input the secret number followed in any manner accept this one it works fine. I'm new to python so please help in as easy manner as possible.
guesses = 0
number = 65
while guesses < 30:
guess = int(input())
close = abs(number - guess)
if guess == number:
print("You won!!:)")
break
elif close < 10:
print("Warm")
guesses += 1
guess = int(input())
if abs(guess - number) < close:
print("Warmer")
guess = int(input())
guesses += 1
elif close > 10:
print("Cold")
guesses +=1
if abs(guess - number) < close:
print("Colder")
guesses += 1
Remove the guess = int(input()) from under the if abs(guess-number) < close:. The problem was that after input() is called there, it is called again at the beginning of the loop on its way to be checked for equality.
guesses = 0
number = 65
while guesses<30:
guess = int(input())
close = abs(number - guess)
if guess == number:
print("You won!!:)")
break
elif close<10:
print("Warm")
guesses += 1
guess = int(input())
if abs(guess-number) < close:
print("Warmer")
guesses += 1
elif close>10:
print("Cold")
guesses +=1
guess = int(input())
if abs(guess-number)<close:
print("Colder")
guesses += 1
It's like that because you ask for a number after print("Warmer") and you do nothing with this guess - you do not check if it's correct or not. The iteration of loop finishes and it starts again asking for a new guess.
Remove guess = int(input()) from
print("Warmer")
guess = int(input())
guesses += 1
and it should work just fine.
remove guess = int(input()) . on line number #15
it's a repeated call for input, because you are calling it on line number #4 which makes it ask for input than give you the result.
The others have pointed out the cause for your specific problem.
I would like to recommend that you should try to avoid code duplication in general. Besides calling input() multiple times, you also increment guesses at multiple places.
This is so important, it has a cool acronym: DRY, which stands for "Don't Repeat Yourself".
Code duplication causes your code to be harder to maintain, because you have to apply the same change in multiple places. DRY code, on the other hand, is usually more readable and easier to maintain.
Think about how to rewrite your code to reduce code duplication.
I am trying to create a game where i think of a number in my head. And then the computer guesses the number through me telling it if its guess is too low or high.
This is what I've come up with but i am pretty lost tbh.
maxguess = 100
minguess = 1
count = 0
print("Think of a number between {} and {}".format(minguess,maxguess))
def midpoint(maxguess, minguess) :
z = ((maxguess + minguess)/2)
def guessing(x) :
print("Is you number greater (>) , equal (=) ,or less (<) than" ,z,)
print("please answer <,=, or >! >")
x = input()
if x == (">") :
minpoint = z
count += 1
continue
elif x == ("<") :
maxpoint = z
count += 1
continue
elif x == ("=") :
print ("I have guessed it!")
count += 1
break
print("I needed {} steps!".format(count))
Purposely not a complete solution, but some hints for you:
I'd recommend avoiding the global variables like count, maxguess, and minguess. Instead, make a function that holds all these variables.
Change your midpoint function to return z instead, then call it inside your guessing function.
Your continue and break functions would need to be inside a for or while loop. Since you aren't sure how many iterations you need to guess the number, I think a while loop would make sense here
Your functions are never run. On a style point, bring all your 'main' statements down to the bottom so they're together. After the prompt to think of a number, you need to call the guessing() function. When you call it, you should pass the minguess and maxguess values to it.
I can see what you're trying to do with the if...elif statements, but they need to be in a while True: block. So should the three statements preceding them so the script repeatedly asks for new advice from you.
Either bring the content of the midpoint() function into guessing() or make it return the value of z.
You also offer the user a choice of '>1' but don't handle it - and you don't need it as far as I can tell.
You never use minpoint or maxpoint - and you dont need them. Call the midpoint function instead and pass it the appropriate values, e.g., if '>', z = midpoint(z, maxguess).
Also, you're going to spend forever trying to get it to guess as you are using floats. Make sure everything is an integer.
Finally, you should add some code to manage input that isn't expected, i.e., not '<', '>' or '='.
Good luck!
minguess=1
maxguess=100
z=50
count=0
print("Think of a number between 1 and 100")
condition = True
while condition:
z=((maxguess + minguess)//2)
print("Is your number greater (>) , equal (=) ,or less (<) than" ,z,)
print("Please answer <,=, or >! >")
x = input()
if x == (">"):
minguess=z
count += 1
elif x == ("<") :
maxguess=z
count += 1
elif x == ("=") :
print ("I have guessed it!")
count += 1
condition=False
So I'm creating this game where the computer guesses a number, and based on the reply, it splits and re-selects a number. I've had little problems so far, but now I'm quite stuck on the loop. I know what I have to do, I just can't figure out how to do it properly, and have it function.
lowest = int(input( "What is the lowest number you will think of?: "))
highest = int(input( "What is the highest number you will think of?: "))
print("So you're thinking of a number between",lowest,"and",highest)
x=[]
for number in range(lowest,highest):
x.append(number)
middleIndex = (len(x))//2
print ("is it "+str(x[middleIndex])+"?")
answer = input("")
if answer == "lower":
x = (x[:len(x)//2])
else:
x = (x[len(x)//2:])
I know it has to go after the
x.append(number)
but I can't get it to work using for or while loops.
The entire for loop is kind of pointless, with the x.append line especially so. range() gives you a list anyway (in Python 3 it gives you a range object which can be converted to a list using the list function).
You could replace that with:
x=list(range(lowest, highest))
Also, this is more convention than anything technically incorrect, but in Python I think camel case is generally reserved for class names; for this reason, I would rename middleIndex to middle_index.
And finally, you don't have anything for the case when the computer guesses the right number!
What you're looking for is basically an interactive binary search algorithm that runs over a range of numbers. You don't actually need to use range or a list, because you can calculate the average of your min and max values instead of finding the middle_index.
Here is an example implementation:
def main():
print("What range will your guessed number fall within?")
min = int(input("Min: "))
max = int(input("Max: "))
print("Ok; think of a number between {0} and {1}.".format(min, max))
while min <= max:
mid = (min + max) // 2
if input("Is it {0}? (Y/N) ".format(mid)) == "Y":
print("It is!? Well, that was fun.")
return
elif input("Darn. Is it higher than {0}? (Y/N) ".format(mid)) == "Y":
min = mid + 1
else:
max = mid - 1
print("Well, it looks like you were dishonest somewhere along the line.")
print("I've exhausted every possibility!")
main()
I am new to python, sorry about a basic one.
The code works fine but it guesses same number twice or maybe more number of times. I want to guess an unique number every time.
import random
print("Hey human guess a number between 1 to 50 and i will try guessing what it is ! \n ")
input("Press enter when you have done the first step \n")
print("after my guess if its correct then hit y, if i need to guess higher than hit g and if i need to guess lower then hit l\n")
answer = ""
m = 1
n = 50
while(answer!='y'):
guess = random.randint(m,n)
print(guess)
reply = input("Is my guess correct ?")
if reply == 'y':
print("GG")
answer = 'y'
elif reply == 'l':
n = guess
print("\n Okay let me try again")
elif reply == 'g':
m = guess
print("\n aaah let me try again please \n")
else:
print("\n Seriously man what did i tell you before ?")
Thank you in advance.
As stated in the docstring of random.randint, this method "returns a random integer in range [a, b], including both end points". That means that when you assign the guess to either m or n the guess is going to be included for the range of the random.
Thus, to fix your code you could modify the following lines:
m = 0
n = 51
guess = random.randint(m+1,n-1)
In this way, you never include the guess in the range of the random. Hope this helps.
Create a list of guessed numbers guessed_numbers = []
Then whenever save the guess guessed_numbers.append(guess)
And before setting guess, check that guess is not in guessed numbers.
So you wind up with:
n = 50
guessed_numbers = []
while (answer != 'y'):
guess = random.randint(m, n)
while (guess in guessed_numbers):
guess = random.randint(m, n)
guessed_numbers.append(guess)
print(guess)
The problem is likely that random.randint produces a number between m and n inclusive. If the range is 1-50, and the program guesses 50, it sets the upper bound to 50 again, which means it could guess that number twice. It will be more likely to happen as the range narrows.
I think if you change the line
n=guess
to read
n=guess-1
and similarly add one for m when it guesses too low, you'll get the result you're looking for.