Currently working to learn Python 3.5 from scratch and thoroughly enjoying the process. latest thing is to write a basic program that does the following..
Asks user to think of a number between 1 and 100
Guesses what it is
Asks user to enter '1' if too low, '3' if too high and '2' if
correct
Provides a new number based on that user input
Limits itself to 10 tries before quitting in shame
Celebrates when it gets it right
Now I THINK I've got it all working minus the higher / lower feature. My question is this.
Note This differs from other questions on the topic because I do not want to enter any numbers for the PC to work on. Also want to generate pseudo-random numbers that are limited to within given values for subsequent guesses from the PC. Not increment.
"How can I implement a feature that looks at the var 'guess' and modifies it to be higher or lower based on user input while keeping it above 0 and below 100".
Code:
import random
print("\tWelcome to the psychic computer")
print("\nI want you to think of a number between 1 and 100.")
print("I will try to guess it in 10 or less tries.\n")
print("\n Press 1 for a lower guess, 3 for a higher one and 2 if I get it right\n")
tries = int(1)
guess = random.randint(1, 100)
print("\nI guess ", + guess, " Is this correct?")
while tries < 10:
feedback = int (input("\nEnter 1 if too high, 3 if too low or 2 if bang on\n\n"))
tries += 1
if feedback == 1:
print("Balls! Guess I need to go Higher will", + guess, + "do?")
elif feedback == 3:
print("\nSh*te! Lower it is then...")
elif feedback == 2:
print("YEEAAAHH BOYEEEE! Told you I was phychic.")
input("\nHit enter to quit")
end
elif feedback != (1,2,3):
print("Not a valid guess. Try again.")
break
if tries >= 9:
print("\nSh*t, guess I'm not so psychic after all")
input("\nHit enter to exit")
You could do something like a binary search. Use a low_number and a high_number to calculate a guess by taking the middle value of the two. These can initially be set 0 and 100. You should also keep track of your last guess. If you last guess was too low, you can set your low_number equal to that guess+1. If your last guess was too high, you can set your high_number to that guess-1.
OK this is what I have so far. It works in that it will respond with (semi) random higher or lower guesses based on user input but does not yet store the original guess as a reference. I will look at that tomorrow. Thanks again for the suggestions.
BTW once working I plan to use math and come up with a solution that always gets it right inside x amount of tries..
import random
print("\tWelcome to the psychic computer")
print("\nI want you to think of a number between 1 and 100.")
print("I will try to guess it in 10 or less tries.\n")
print("\n Press 1 for a higher guess, 3 for a lower one and 2 if I get it right\n")
tries = int()
guess = random.randint(1, 100)
high_number = int(100 - guess)
low_number = int(1 + guess)
print("\nI guess ", + guess, " Is this correct?")
while tries < 10:
feedback = int (input("\nEnter 1 to go higher, 3 to go lower or 2 if bang on\n\n"))
tries += 1
if feedback == 1:
guess = random.randint(high_number, 100)
print("Balls! Guess I need to go Higher how about", + guess)
elif feedback == 3:
guess = random.randint(1, low_number)
print("\nSh*te! Lower it is then... what about", + guess)
elif feedback == 2:
print("YEEAAAHH BOYEEEE! Told you I was phychic.")
input("\nHit enter to quit")
end
elif feedback != (1,2,3):
input("Not a valid guess. Try again.")
break
if tries >= 9:
print("\nSh*t, guess I'm not so psychic after all")
input("\nHit enter to exit")
Related
I am stuck on a question from my Introduction to Python course. I have to write a code wherein the user keeps an integer in their mind, and the computer guesses. If the user's number is higher than the computer's guess, the user types "+", and the computer guesses higher. If the user's number is lower, the user types "-", and the computer guesses lower numer. If the computer guesses correctly, the user types "y", and the program ends.
Use the builtin function "input" to get a text from the user. If the user types anything other than "+", "-", or "y", the function should throw an exception.
Your function should take no arguments and return nothing.
I have to write the code in python.
The problem I am facing is that after checking for the input the first time, how to change the range and make the user enter their response again. I have just started coding, so please forgive me if it is a very basic question.
I was having the same problem you have and here is my solution for it:
import random
low = 1
high = 100
int(input("Enter the number for computer to guess: "))
while low != high:
guess = low + (high - low) // 2
high_low = input(f"Computer guess is: {guess} \n "
f"Press (H) for higher, (L) for lower and (C) for correct: ").casefold()
if high_low == "h":
low = guess + 1
elif high_low == "l":
high = guess - 1
elif high_low == "c":
print(f"I got it the number is {guess}")
break
else:
print("Please enter h, l or c")
else:
print(f"Your number is {low}")
Here I was using Binary Search algorithm with formula: guess = low + (high - low) // 2. To be more clear, what this formula does it starts of with guessing the mid point between high and low values. If we are told to guess higher that must mean our answer must be between 50 - 100. So the lowest it can be is 51 and that is our new lowest value for the range the mid point now becomes 51+(100-51)//2 (answer from this calculation is 75.5 integer division rounds down) so the result is 75. And If we are told now to guess lower that means answer must be somewhere between 51 and 75, so we know the answer is less than 75, the mid point now becomes 50+(75-51)//2
which is 62 and so on continues with that pattern. You can change H with +, L with -, and C with y and you will get your solution. I hope you find this useful :).
There are several solutions here, and some are more sophisticated than others.
The simplest solution in my opinion would simply be something like this (without validations):
if user_input == "+":
number = number + 1
elif user_input == "-":
number = number - 1
elif user_input = "y":
print("Number guessed correctly.")
Depending on the user input, the program will simply add or subtract 1 from the number. That way, you don't require range checks or anything the like.
Let me know if this approach is acceptable.
I made a simple guessing game for practice. The program is functioning without an error but the output given is a wrong value.
Here is the code:
import random
welcome_phrase = "Hi there. What's your name?"
print("{:s}".format(welcome_phrase))
user_name = input("Name: ")
print("Hey {:s}, I am Crash. Let's play a game. I am thinking of a number between 1 and 20. Can you guess the number?".format(user_name))
attempts = 5
secret_num = random.randint(1,20)
for attempt in range (attempts):
guess = int(input("Guess the number: "))
if guess > secret_num:
print("Your guess is higher than the number. Try again")
elif guess < secret_num:
print("Your guess is lower than the number. Try again.")
else:
print("Well done! {:d} is the right number.".format(guess))
print("It took you {:d} attempts.".format(attempt))
break
if guess != secret_num:
print("Sorry, you have used up all your chances.")
print("The number was {:d}".format(secret_num))
And here is the output:
As you can see in the image above, even though it is clear that 3 attempts were made to guess the right number, Python only counted 2 attempts. Will anyone please let me know how to solve this?
You can change
for attempt in range (attempts):
to
for attempt in range (1,attempts+1):
to solve this, as range starts from 0.
I am relatively new to programming with python (actually programming in general). I am making this 'Guess My Age' program that only has one problem:
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
num = 80
min_num = 6
tries = 1
number = random.randint(min_num, num)
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower()
while guess != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif guess == "higher":
print("Let me think...")
min_num = number + 1 #### Here is my trouble - Don't know how to limit max number
time.sleep(3) # pause
elif guess == "lower":
print("Let me think...")
num = number - 1
time.sleep(3) # pause
number = random.randint(min_num, num) #<- Picks new random number
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower() #<- Lowercases
tries += 1 #<- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)
As you can see, I have 'num' as the max number for the random integer getting picked, but with:
elif guess == "higher":
print("Let me think...")
min_num = number + 1
it can go back up to however high it wants.
I want it to remember the last integer that 'num' was.
Say the program guessed 50 and I said 'Lower'. Then it said 30 and I said 'Higher'
I know I am probably sounding confusing, but please bear with me.
You need to define a maximum number as well as a minimum number. If they say their age is lower than a given age, you should set that age minus 1 as the maximum.
Of course, you also need to set an initial maximal age.
You might find it more useful to look into recursive functions for this kind of problem. If you define a function which takes min_age, max_age and tries_left as parameters, which comes up with a random number with between min_age and max_age and queries the user, you can then rerun the function (within itself) with a modified min_age, max_age and tries_left - 1. If tries_left is zero, concede defeat. This way you might get a better understanding of the logical flow.
I have left code out of this answer because, as you are a beginner, you will find it a useful exercise to implement yourself.
Cant you split out your guess into something like
max_num = 0
min_num = 0
elif guess =="lower":
max_num = number
if min_num!=0:
number = min_num+(max_num-min_num)/2
else:
number = max_num-1
elif guess =="higher":
min_num = number
if max_num!=0:
number=min_num+(max_num-min_num)/2
else:
number=min_num+1
Sorry it's not meant to be fully rigorous, and its a slight change on the logic you have there, but splitting out your variables so you have a higher and lower cap, that should help a lot?
Cheers
Please let me know if you need more elaboration, and I can try to write out a fully comprehensive version
It seems as though I was wrong in the fact that it did not remember the older integers. Before when running the program it would guess a number higher than the 'num' had specified. I don't know what I changed between then and now? But thank you for the help! #.#
This seems to work.
The only changes I really made:
-Variable names were confusing me, so I changed a couple.
-Note that if you try to mess with it (lower than 5, higher than 3... "Is it 4?" if you say it's higher or lower, you'll get an error).
The first time you set min and max numbers, you do it outside of the loop, so this script does "remember" the last guess and applies it to the new min, max inside of the loop. Each time it runs, the min will get higher or the max will get lower, based on the feedback from when the user checks the guess. If you had stuck the "min_num=6" and the "num=80" inside of the loop, the guesses would never get better.
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
max_num = 10
min_num = 1
tries = 1
guess = random.randint(min_num, max_num)
print("\nLet me guess... You are", guess, "years old?")
check = raw_input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower()
while check != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif check == "higher":
print("Let me think...")
min_num = guess + 1
time.sleep(3) # pause
elif check == "lower":
print("Let me think...")
max_num = guess - 1
time.sleep(3) # pause
guess = random.randint(min_num, max_num) # <- Picks new random number
print("\nLet me guess... You are", guess, "years old?")
check = input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower() # <- Lowercases
tries += 1 # <- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)
all. I'm quite new to programming, and I'm trying to figure out why my code isn't working properly. It runs fine up until you tell the computer whether or not its first guess is too high (h), or too low (l). If, say, the guess is too high, and tell the computer that, each guess after will continue guessing lower, regardless of whether or not you enter too low (l). It happens the other way around as well. Hopefully someone can help. Here's the code!
import random
import time
print "Think of a number between 1 and 100 and I'll try and guess it."
time.sleep(2)
print "Let me know if my guess is too (h)igh, too (l)ow, or (c)orrect."
time.sleep(2)
guess = int(raw_input("Pick your number between 1-100: "))
low = 1
high = 100
tries = 0
compguess = random.randrange(low, high)
h = compguess > guess
l = compguess < guess
c = compguess == guess
while compguess != guess:
tries += 1
print "Is it", compguess
if h:
raw_input ()
new_high = (compguess - 1)
compguess = random.randint(low, new_high)
elif l:
raw_input ()
new_low = (compguess + 1)
compguess = random.randint(new_low, high)
elif c:
raw_input ()
print("The computer guessed your number of: ", guess)
Forgive the spacing. I'm not quite sure how to copy it properly.
The raw_input() function returns a value. If you don't assign the return value to a variable or otherwise do something with it, the value returned is simply discarded by Python.
You probably want something like:
print "Is it", compguess
answer = raw_input()
if answer == "h":
...
elif answer == "l":
...
That way, you prompt the user for input, wait for the user to type something, then act upon what the user typed.
You also don't need the h, l, or c local variables. They don't actually serve a purpose in your code.
Finally, why do you ask the user to tell the computer what number the user is thinking of? Isn't the point of this exercise to get the computer to guess the user's number, without knowing what the result is?
I am trying to make a random number game in python where the computer has to generate a number between 1 and 20 and you have to guess it. I have limited the amount of guesses to 6. How do I print how many guesses the user has left when they get a guess wrong? Here is my code:
import random
attempts = 0
name = input("What is your name? ")
random = random.randint(1, 20)
print(name + ",","I'm thinking of a number between 1 and 20, What is it?")
while attempts < 6:
number = int(input("Type your guess: "))
attempts = attempts + 1
int(print(attempts,"attemps left")) #This is the code to tell the user how many attempts left
if number < random:
print("Too low. Try something higher")
if number > random:
print("Too high. Try something lower")
if number == random:
break
if number == random:
if attempts <= 3:
print("Well done,",name + "! It took you only",attempts,"attempts")
if attempts >= 4:
print("Well done,",name + "! It took you",attempts,"attempts. Athough, next time try to get three attempts or lower")
if number != random:
print("Sorry. All your attempts have been used up. The number I was thinking of was",random)
Thanks, Any help is greatly appreciated!
print('attempts left: ', 6 - attempts)
Your attempts variable counts the number of attempts used. Since 6 is the limit, 6 - attempts is the number of attempts left:
print(6 - attempts, "attempts left")
(No need to wrap this in an int call. I don't know why you did that.)
Incidentally, writing 6 for the maximum attempts all the time may obscure what the 6 means and make it hard to find all the places that need changing if you want to change the limit to, say, 7. It may be worth making a variable with a descriptive name:
max_attempts = 6
...
while attempts < max_attempts:
...
print(max_attempts - attempts, "attempts left")
print(6 - attempts, "attempts left")
I would make four suggestions, which work towards making your code cleaner and simpler:
Factor out the "magic number" 6 and count down from it, rather than up to it;
Use for rather than while, so you don't have to increment/decrement the number of guesses manually, and use the else to determine if the loop breaks (i.e. out of guesses);
Use if: elif: else: rather than separate ifs; and
Use str.format.
This would make the code something like:
attempts = 6
for attempt in range(attempts, 0, -1):
print("You have {0} attempts left.".format(attempt))
number = int(input(...))
if number < random:
# too low
elif number > random:
# too high
else:
if attempt > (attempts // 2):
# great
else:
# OK
break
else:
# out of guesses