I want to write a python game that knows the number(1-100) taken from a user in 7 steps at most.
2^7>100.
The code below is working but it takes more than 7 steps. I think the problem is guess=guess+-guess//(2^n) part. But I dont know what to replace with.
number=int(input("Enter a number between 1 and 100: "))
guess=50
n=1
if number>100:
number=int(input("Enter a number less than 100: "))
if number<1:
number=int(input("Enter a number greater than 1: "))
while True:
print("Your number is" +' '+ str(guess) +' '+ "?")
ans=str(input("(g)reater,(l)ess or (b)ravo: "))
for n in range(1,10,1):
if ans=="g":
guess=guess+guess//(2^n)
elif ans=="l":
guess=guess-guess//(2^n)
elif ans=="b":
print("Your number is " +' '+ str(guess) +' '+ "Well done for me")
break
You need to keep track of your lowest and highest possible numbers and then make guess that lies halfway between them. Update the lowest and highest numbers based on reply.
number=int(input("Enter a number between 1 and 100: "))
guess = 50
n = 1
if number>100:
number=int(input("Enter a number less than 100: "))
if number<1:
number=int(input("Enter a number greater than 1: "))
lo = 1
hi = 100
while True:
print("Your number is" +' '+ str(guess) +' '+ "?")
ans = str(input("(g)reater,(l)ess or (b)ravo: "))
if ans == "g":
lo = guess
guess=lo + (hi-lo+1)//2
elif ans == "l":
hi = guess
guess=lo + (hi-lo)//2
elif ans == "b":
print("Your number is " +' '+ str(guess) +' '+ "Well done for me")
break
n += 1
Related
It has been a week since I started to self-study python and I tried making a program that adds or multiplies all natural numbers and the problem is I want to only show the final result of all the sum or product of all natural numbers. How do I do it?
repeat = 'y'
a=0
while repeat.lower() == 'y':
result = 0
choice = 0
i=0
product = 1
num = int(input("Enter the value of n: "))
if num < 1 or num > 100 :
print('must be from 1-100 only')
repeat = input("\nDo you want to try again?Y/N\n>>> ")
continue
print('1. Sum of all natural numbers')
print('2. Product of all numbers')
choice = int(input("Enter choice: "))
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
while repeat.lower() == 'n':
print('\nthank you')
break
The program prints you all the numbers because the print statement is in a while loop, so it gets executed with each run of the loop. Just move the print function out of the while.
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
You have two problems. First, your print statements that print the results need to be un-indented by one step, so they are not PART of loop, but execute AFTER the loop. Second, you need to initialize product = 1 after the if choice == 2:. As a side note, you don't need that final while loop. After you have exited the loop, just print('Thanks') and leave it at that.
So the end of the code is:
if choice == 1:
while num > 0 :
result += num
num -= 1
print(' ',result)
if choice == 2:
product = 1
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
print('thank you\n')
I presume you'll learn pretty quickly how to do those with a for loop instead of a while loop.
import random
x = 50
score = 0
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
while True:
if int(input('Guess: ')) == number:
print('You got it')
break
else:
print('Try again!')
What the code does so far is takes a random integer between 1 and whatever number I want. It tells me which numbers it is divisible by between 1-9 and also if it is bigger than half the maximum possible number. It essentially gives you a lot of info to guess.
I want to add a score aspect where after you guess the correct number, you will get 1 added to your score. Then it will loop back to the beginning, get a new number to guess and give all it's information again so you can guess. I'm trying to get the looping part but I'm really lost right now.
When your guess is correct we can add 1 to your current score and print it. You can play till you guess it right. You have to put the whole code in a while loop for looping through the game after every correct answer. You can break the loop if your score is greater than 10 and the game stops.
import random
x = 50
score = 0
while True:
if score >= 10:
break
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
while True:
if int(input('Guess: ')) == number:
print('You got it')
score+=1
print('Your current score',score)
break
else:
print('Try again!')
Haven't worked with Python myself before but I assume you want to encapsulate everything inside a huge while loop and ask at the end of each iteration if you want to keep playing
Something like this (this is more pseudocode than anything, didn't even tested it)
import random
x = 50
score = 0
keepPlaying = True
while keepPlaying:
number = random.randint(1, x)
[print("This number is divisible by ", str(i)) for i in range(1, 10) if number % i == 0]
print('The largest possible number to guess is ' + str(x))
if number < x/2:
print('This number is less than ' + str(int(x/2)))
else:
print('This number is larger than ' + str(int(x/2)))
print(number)
if int(input('Guess: ')) == number:
print('You got it')
score++
break
else:
print('Try again!')
score--
if (input("do want to keep playing?")=="no")
keepPlaying = False
A Python(3.7) beginner here. This guessing game gives range clues:
Cold
Warm
Hot
Depending on how close to answer player is.
Problem: how to add extra 3 incremental clues:
Colder
Warmer
Hotter
Colder is used if the next guess is further from answer.
Warmer is used if the next guess is closer to answer.
Hotter is used instead of Warmer if its in the Hot range.
The first guess produces the range clues Cold, Warm or Hot.
The subsequent guesses will produce incremetal clues Colder or Warmer/Hotter if while they land in same range as previous guess.
If they fall out of the range, the range clues Cold, Warm or Hot will be produced first and then Colder or Warmer/Hotter while in that range. in other words Cold, Warm or Hot range clues have higher priority than incremental Colder or Warmer/Hotter.
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
while user_input is not 41 and count < 4:
count = count + 1
how_close_to_answer = 41 - user_input
if 5 < how_close_to_answer.__abs__() < 20:
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif how_close_to_answer.__abs__() >= 20:
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
if user_input is not 41:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
For example (in case of infinite guesses n):
player guesses = 10 , desired outcome 'Cold. Remaining guesses (n-1) '
next guess = 15 , desired outcome 'Warmer. Remaining guesses (n-2) '
next guess = 12 , desired outcome 'Colder. Remaining guesses (n-3) '
next guess = 36 , desired outcome 'Hot. Remaining guesses (n-4) '
next guess = 37 , desired outcome 'Hotter. Remaining guesses (n-5) '
next guess = 30 , desired outcome 'Warm. Remaining guesses (n-6) '
In 4. example - number 36 is Warmer than previous 12, but it also falls in the Hot range so the Hot clue is given instead.
in 6. example - number 30 is Colder than previous 37, but it also falls in the Warm range so the Warm clue is given instead.
I took num as a random generated number instead of 41.
import random
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
num = random.randint(1,101)
while user_input is not num and count < 4:
#uncomment the line below to see random generated number
#print('Generated Random Number= '+str(num))
count = count + 1
how_close_to_answer = num - user_input
if abs(how_close_to_answer)>5 and abs(how_close_to_answer) <20 :
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif abs(how_close_to_answer) >= 20 :
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
if user_input is not num:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
As far as i understood , the above program generates a random number and you need to guess that number ,
if your guessed number is less then or equivalent to 5 digits closer to that random number it will tell you hot
if its greater than 5 and less than 20 then it will tell you warm
on greater than 20 it will give you cold
Hope this will help you !!
This is the closest I could get to what you asked for. The comments on your original question are worth a read in my opinion but I think this does exactly what you asked for in the question.
print("The secret number is somewhere between 0 and 100. You have 5 guesses.")
user_input = int(input('Make a guess '))
count = 0
last_distance = -1
while user_input is not 41 and count < 4:
count = count + 1
how_close_to_answer = (41 - user_input)
how_close_to_answer = how_close_to_answer.__abs__()
if how_close_to_answer <= 5 and last_distance > 5:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
elif last_distance == -1:
if 5 < how_close_to_answer < 20:
user_input = int(input(f'Warm. Remaining guesses {5 - count} '))
elif how_close_to_answer >= 20:
user_input = int(input(f'Cold. Remaining guesses {5 - count} '))
elif how_close_to_answer <= 5:
user_input = int(input(f'Hot. Remaining guesses {5 - count} '))
else:
if how_close_to_answer < last_distance:
if how_close_to_answer <= 5:
user_input = int(input(f'Hotter. Remaining guesses {5 - count} '))
else:
user_input = int(input(f'Warmer. Remaining guesses {5 - count} '))
elif how_close_to_answer > last_distance:
user_input = int(input(f'Colder. Remaining guesses {5 - count} '))
last_distance = how_close_to_answer
if user_input is not 41:
print('You Lose!')
else:
print('You Win!')
print(f"It took you {count + 1} guesses to get this correct.")
Hope this is what helps
How can you make this program make the user input 5 digits at once, instead of asking separate numbers each time? I know I have to use string.split() but where would I place the code and execute the code.
Heading
from random import randint
n1 = randint(1,9)
n2 = randint(1,9)
n3 = randint(1,9)
n4 = randint(1,9)
c = 1
while True:
print (n1,n2,n3,n4)
guess1 = input("guess the first number")
guess2 = input("guess the second number")
guess3 = input("guess the third number")
guess4 = input("guess the fourth number")
guess1 = int(guess1)
guess2 = int(guess2)
guess3 = int(guess3)
guess4 = int(guess4)
numberswrong = 0
if guess1 != n1:
numberswrong += 1
if guess2 != n2:
numberswrong += 1
if guess3 != n3:
numberswrong += 1
if guess4 != n4:
numberswrong += 1
if numberswrong == 0:
print('Well Done!')
print('It took you ' + str(c) + ' ries to guess the number!')
break
else:
print('You got ' + str(4-numberswrong) + ' numbers right.')
c += 1
You just have to split the numbers in a single input and convert them into integers using a list comprehension. You can also create your random_n using a similar method.
from random import randint
random_n = [randint(1,9) for i in range(4)]
c = 1
while True:
print(random_n)
user_input = [int(i) for i in input("guess the numbers: ").split()]
numberswrong = 0
if user_input[0] != random_n[0]:
numberswrong += 1
if user_input[1] != random_n[1]:
numberswrong += 1
if user_input[2] != random_n[2]:
numberswrong += 1
if user_input[3] != random_n[3]:
numberswrong += 1
if numberswrong == 0:
print('Well Done!')
print('It took you ' + str(c) + ' tries to guess the number!')
break
else:
print('You got ' + str(4-numberswrong) + ' numbers right.')
c += 1
if c > 10:
print('More than 10 failed attempts. End.')
break
>>
[3, 9, 1, 6]
guess the numbers: 1 2 1 6
You got 2 numbers right.
[3, 9, 1, 6]
guess the numbers: 3 9 1 6
Well Done!
It took you 2 tries to guess the number!
Edited: Added break if attempts more than 10, in this case when your counter c is more than 10.
You can try using raw_input:
Guesses= raw_input("Guess 5 numbers (separated by comma)")
Guess_list= Guesses.split(",")
This question already has answers here:
Guessing algorithm does not seem to work, guessing number by Python
(3 answers)
Closed 5 years ago.
The program is supposed to take in an integer from the user and guess what that integer is using binary search.
user_num = (int(input("Please think of a number between 0 and 100! ")))
low = 0
high = 100
ans = (high + low)//2
while True:
print("is your secret number " + str(ans))
check_ans = input("""enter 'h' to indicate if the guess is too high.
enter 'l' to indicate if the guess is too low.
enter 'c' if I guessed correctly.""")
if check_ans == 'h':
high = ans//2
ans = high
elif check_ans == 'l':
low = ans*2
ans = low
elif check_ans == 'c' and check_ans == user_num:
print("Game over. Your secret number was: " + str(ans))
break
else:
print("I do not understand your command")
I believe the issue I am having is occurring in the while loop. I need the program to know when to stop once it reaches the threshold. Say if my integer is 34, once I hit 'h' as input it will drop to 25. Now if I hit 'l' it's going to jump back to being 50.
I guess my question is how do I update the ans variable so the program knows to stay within that range?
Let's go over your conditions. What we want to do is redefine low and high based on the answer the program received.
if check_ans == 'h':
# We know that ans is lower, so we set our higher bound to slightly below ans
high = ans - 1
elif check_ans == 'l':
# We know that ans is higher, so we set our lower bound to slightly above ans
low = ans + 1
Then at the beggining of your loop you want to get ans based on the interval by doing ans = (high + low)//2.
Overall this gives
user_num = (int(input("Please think of a number between 0 and 100! ")))
low = 0
high = 100
while True:
ans = (high + low)//2
print("is your secret number " + str(ans))
check_ans = input("""
enter 'h' to indicate if the guess is too high.
enter 'l' to indicate if the guess is too low.
enter 'c' if I guessed correctly.""")
if check_ans == 'h':
high = ans - 1
elif check_ans == 'l':
low = ans + 1
elif check_ans == 'c' and check_ans == user_num:
print("Game over. Your secret number was: " + str(ans))
break
else:
print("I do not understand your command")
The algorithm is slightly wrong when calculating the new interval. Here is the corrected code:
user_num = (int(input("Please think of a number between 0 and 100! ")))
low = 0
high = 100
ans = (high + low) // 2
while True:
print("is your secret number " + str(ans))
check_ans = input("""enter 'h' to indicate if the guess is too high.
enter 'l' to indicate if the guess is too low.
enter 'c' if I guessed correctly.""")
if check_ans == 'h':
high = ans
ans = (high + low) // 2
elif check_ans == 'l':
low = ans
ans = (high + low) // 2
elif check_ans == 'c' and check_ans == user_num:
print("Game over. Your secret number was: " + str(ans))
break
else:
print("I do not understand your command")