I would like to generate a random number (1,100), however, the random number is bigger than the user idea changes the range of random EX: computer random =36 but users answer is 87 so tell the computer my answer is bigger than your guess, the computer change its range (36,100) and vice versa.
this program runs just one time and doesn't repeat asking for select more randomly.
Thank you so much
from random import randint
a = int(1)
b = int(100)`enter code here`
guess = randint(a,b)
print(guess)
answer = input ("your idea:")
while answer != "done":
if answer == "big":
a = int(guess)
guess = randint(a,100)
print(guess)
if answer == "small":
b = int(guess)
guess = randint(1, b)
print(guess)
else:
answer == "done"
print("your guess number ", guess, "is right")
break
else:
answer == "done"
print("your guess number ", guess, "is right")
break
The break is indented outside the else. So it'll break regardless of the value of the answer. Just indent the break inside the else and it'll be fine
Related
I am trying to write a program as follows:
Python generates random multiplications (factors are random numbers from 1 to 9) and asks to the users to provide the result
The user can quit the program if they input "q" (stats will be calculated and printed)
If the user provides the wrong answer, they should be able to try again until they give the correct answer
if the user responds with a string (e.g. "dog"), Python should return an error and ask for an integer instead
It seems I was able to perform 1) and 2).
However I am not able to do 3) and 4).
When a user gives the wrong answer, a new random multiplication is generated.
Can please somebody help me out?
Thanks!
import random
counter_attempt = -1
counter_win = 0
counter_loss = 0
while True:
counter_attempt += 1
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
guess = input(f"How much is {num_1} * {num_2}?: ")
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
elif guess == result:
print("Congratulations, you got it!")
counter_win += 1
elif guess != result:
print("Wrong! Please try again...")
counter_loss += 1
Hi my Idea is to put the solving part in a function:
import random
counter_attempt = -1
counter_win = 0
counter_loss = 0
def ask(num1, num2, attempt, loss, win):
result = str(num1 * num2)
guess = input(f"How much is {num1} * {num2}?: ")
if guess == "q":
print(
f"Thank you for playing, you guessed {win} times, you gave the wrong answer {loss} times, on a total of {attempt} guesses!!!")
return attempt, loss, win, True
try:
int(guess)
except ValueError:
print("Please insert int.")
return ask(num1, num2, attempt, loss, win)
if guess == result:
print("Congratulations, you got it!")
win += 1
return attempt, loss, win, False
elif guess != result:
print("Wrong! Please try again...")
loss += 1
attempt += 1
return ask(num1, num2, attempt, loss, win)
while True:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
counter_attempt, counter_loss, counter_win, escape = ask(num_1, num_2, counter_attempt, counter_loss, counter_win)
if escape:
break
Is that what you asked for?
Note that everything withing your while loop happens every single iteration. Specifically, that includes:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
So you are, indeed, generating new random numbers every time (and then announcing their generation to the user with guess = input(f"How much is {num_1} * {num_2}?: "), which is also within the loop).
Assuming you only intend to generate one pair of random numbers, and only print the "how much is...?" message once, you should avoid placing those within the loop (barring the actual input call, of course: you do wish to repeat that, presumably, otherwise you would only take input from the user once).
I strongly recommend "mentally running the code": just go line-by-line with your finger and a pen and paper at hand to write down the values of variables, and make sure that you understand what happens to each variable & after every instruction at any given moment; you'll see for yourself why this happens and get a feel for it soon enough.
Once that is done, you can run it with a debugger attached to see that it goes as you had imagined.
(I personally think there's merit in doing it "manually" as I've described in the first few times, just to make sure that you do follow the logic.)
EDIT:
As for point #4:
The usual way to achieve this in Python would be the isdigit method of str:
if not guess.isdigit():
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
An alternative method, just to expose you to it, would be with try/except:
try:
int(guess) # Attempt to convert it to an integer.
except ValueError: # If the attempt was unsuccessful...
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration.
And, of course, you could simply iterate through the string and manually ensure each of its characters is a digit. (This over-complicates this significantly, but I think it is helpful to realise that even if Python didn't support neater methods to achieve this result, you could achieve it "manually".)
The preferred way is isdigit, though, as I've said. An important recommendation would be to get yourself comfortable with employing Google-fu when unsure how to do something in a given language: a search like "Python validate str is integer" is sure to have relevant results.
EDIT 2:
Make sure to check if guess == 'q' first, of course, since that is the one case in which a non-integer is acceptable.
For instance:
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
elif not guess.isdigit():
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
elif guess == result:
...
EDIT 3:
If you wish to use try/except, what you could do is something like this:
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
try:
int(guess)
except ValueError:
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
if guess == result:
...
You are generating a new random number every time the user is wrong, because the
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
Is in the while True loop.
Here is the fixed Code:
import random
counter_attempt = 0
counter_win = 0
counter_loss = 0
while True:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
while True:
guess = input(f"How much is {num_1} * {num_2}?: ")
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
input()
quit()
elif guess == result:
print("Congratulations, you got it!")
counter_win += 1
break
elif guess != result:
print("Wrong! Please try again...")
counter_loss += 1
Implement the GuessNumber game. In this game, the computer
- Think of a random number in the range 0-50. (Hint: use the random module.)
- Repeatedly prompt the user to guess the mystery number.
- If the guess is correct, congratulate the user for winning. If the guess is incorrect, let the user know if the guess is too high or too low.
- After 5 incorrect guesses, tell the user the right answer.
The following is an example of correct input and output.
I’m thinking of a number in the range 0-50. You have five tries to
guess it.
Guess 1? 32
32 is too high
Guess 2? 18
18 is too low
Guess 3? 24
You are right! I was thinking of 24!
This is what I got so far:
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput>randomNumber:
print(randomNumber + "is too high.")
elif userInput < randomNumber:
print(randomNumber + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
I've been getting a syntax error and I don't know how to make the guess increase by one when the user inputs the wrong answer like, Guess 1?, Guess 2?, Guess 3?, Guess 4?, Guess 5?, etc...
Since you know how many times you're going through the loop, and want to count them, use a for loop to control that part.
for guess_num in range(1, 6):
userInput = int(input(f"Guess {guess_num} ? "))
if userInput == randomNumber:
# insert "winner" logic here
break
# insert "still didn't guess it" logic here
Do you see how that works?
You forgot to indent the code that belongs in your while loop. Also, you want to keep track of how many times you guessed, with a variable or a loop as suggested. Also, when giving a hint you probably want to print the number guessed by the player, not the actual one. E.g.,
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
count = 0
while guessed is False and count < 5:
userInput = int(input("Guess 1?"))
count += 1
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + randomNumber + "!")
elif userInput > randomNumber:
print(str(userInput) + " is too high.")
elif userInput < randomNumber:
print(str(userInput) + " is too low.")
if count == 5:
print("Your guess is incorrect. The right answer is" + str(randomNumber))
print("End of program")
You are facing the syntax error because you are attempting to add an integer to a string. This is not possible. To do what you want you need to convert randomNumber in each print statement.
import random
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
guessed = False
while guessed == False:
userInput = int(input("Guess 1?"))
if userInput == randomNumber:
guessed = True
print("You are right! I was thinking of" + str(randomNumber) + "!")
elif userInput>randomNumber:
print(str(randomNumber) + "is too high.")
elif userInput < randomNumber:
print(str(randomNumber) + "is too low.")
elif userInput > 5:
print("Your guess is incorrect. The right answer is" + randomNumber)
print("End of program")
import random
arr=[]
for i in range(50):
arr.append(i)
answer=random.choice(arr)
for trial in range(5):
guess=int(input("Please enter your guess number between 0-50. You have 5
trials to guess the number."))
if answer is guess:
print("Congratulations....You have guessed right number")
break
elif guess < answer-5:
print("You guessed too low....Try again")
elif guess > answer+5:
print("You guessed too high..Try again")
else:
print("Incorrect guess...Try again please")
print("the answer was: "+str(answer))
Just a three things to add:
The "abstract syntax tree" has a method called literal_eval that is going to do a better job of parsing numbers than int will. It's the safer way to evaluate code than using eval too. Just adopt that method, it's pythonic.
I'm liberally using format strings here, and you may choose to use them. They're fairly new to python; the reason to use them is that python strings are immutable, so doing the "This " + str(some_number) + " way" is not pythonic... I believe that it creates 4 strings in memory, but I'm not 100% on this. At least look into str.format().
The last extra treat in this is conditional assignment. The result = "low" if userInput < randomNumber else "high" line assigns "low" of the condition is met and "high" otherwise. This is only here to show off the power of the format string, but also to help contain conditional branch complexity (win and loss paths are now obvious). Probably not a concern for where you are now. But, another arrow for your quiver.
import random
from ast import literal_eval
randomNumber = random.randrange(0,50)
print("I’m thinking of a number in the range 0-50. You have five tries to guess it.")
win = False
for guess_count in range(1,6):
userInput = literal_eval(input(f"Guess {guess_count}: "))
if userInput == randomNumber:
print(f"You are right! I was thinking of {randomNumber}!")
win = True
break
else:
result = "low" if userInput < randomNumber else "high"
print(f"{userInput} is too {result}")
if win:
print ("YOU WIN!")
else:
print("Better luck next time")
print("End of program")
from random import randint
guessed = randint(0,2)
user_guess = input("What do you think the number I'm thinking of is?")
if user_guess == guessed:
print("Correct!")
else:
print("Incorrect!")
I'm looking for a way for the code to repeat or a way to print different messages until user_guess is the same as guessed.
If the person guesses incorrectly, I want to be able to tell them that, and then give them another chance.
Thanks, sorry for beginner question.
Stay in a while loop as long as the guess is wrong.
You need the first guess to "prime" the loop.
# get the first user guess
while user_guess != guessed:
print "Incorrect"
# Get next user guess
Note that the code for "next user guess" will be very similar to "first user guess".
Use a while loop.
from random import randint
correct = False
while (not correct):
guessed = randint(0,2)
user_guess = int(input("What do you think the number I'm thinking of is?"))
if user_guess == guessed:
print("Correct!")
correct = True
else:
print("Incorrect!")
In the process of learning Python using the book 'Python Programming for the Absolute Beginner Third Edition' and struggling with a challenge that has been set.
I have to create a Number Guessing program where the player picks a number and the program tries to guess it by picking a random number then using higher or lower questions to get closer to the number. I've got most of it figured out but I'm struggling with the higher or lower loop. The trouble I'm having is that i can't get the program to not go above or below it's second to last guess i.e.
My number is 78
computer picks 50
i say higher
computer picks 80
i say lower
computer can then pick 12 (when i don't want it going below 50.
I'm using Python 3.1
Here is a copy of the code.
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(higher, 101)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(0, lower)
else:
print("Please choose either higher or lower.")
input("\n\nPress the enter key to exit")
Thanks in advance for any help you folks can give.
Ally
I see the following problems with your code:
your random number generators are bound only on one side of the number spectrum, e.g. random.randint(0, lower) - so it's ignoring the higher bound. Similarly for computer_guess = random.randint(higher, 101).
I suggest you initialise higher and lower.
Some debug helps :)
Here's the working code:
import random
computer_tries = 0
player_number = None
computer_guess = random.randint(1, 100)
print(
"""
Welcome Player to the fabulous number guessing game.
Please allow me to show you my incredible deduction skills
""")
question = None
lower = 0 # initial lower guess
higher = 101 # initial higher guess
while question != ("yes"):
question = input("Has the player picked a number? ")
question = question.lower()
if question == "yes":
print("\nI will now guess your number!!!\n")
while player_number == None:
computer_tries += 1
print(computer_guess, "\n")
confirmation = input("Is this the correct number? ")
confirmation = confirmation.lower()
if confirmation == "yes":
player_number = computer_guess
if computer_tries < 2:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"try to get it right!")
else:
print("I did it! I guessed your number was", computer_guess,
"and it only \ntook me", computer_tries,
"tries to get it right!")
else:
higher_lower = None
while higher_lower not in ("higher", "lower"):
higher_lower = input("Is my guess higher or lower"
+ " than your number? ")
higher_lower = higher_lower.lower()
if higher_lower == "higher":
higher = computer_guess
computer_guess = random.randint(lower+1, higher-1)
elif higher_lower == "lower":
lower = computer_guess
computer_guess = random.randint(lower+1, higher-1)
else:
print("Please choose either higher or lower.")
print("DEBUG: number must be " + str(lower) + " < x < " + str(higher))
input("\n\nPress the enter key to exit")
You have to store something like min_comp_guess and max_comp_guess
Then, when you are about to "guess" number you have to generate it for a valid range (obviously min_comp_guess up to max_comp_guess).
I'm always second! :)
You are never storing the upper and lower bounds to the possible numbers. In your example, as soon as your program picks 50 and you say "higher", you need to store somewhere the information that "the number is definitely higher than 50". The same goes for when you answer "lower".
I may be completely wrong but whilst testing your code I found that by choosing the programs number was higher than my chosen number it would increase the number instead or a presumable decrease, not making it any closer to the number I had guessed. A similar higher/lower program I created had the same problem, to fix the problem I simply switched the more than and less than signs around, hopefully you find this helpful and could apply this to your program.
New to Python and trying to figure out what went wrong here. Making a simple game in which I have to guess the number that was randomly generated by the computer. Thanks for your help.
Here's what I have:
guessed == random.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while entered != guessed
entered = raw_input("Enter your suggestion:")
entered = int(guessed_number)
if entered > guessed
print('Try less')
else
print('Try more')
print('You win!')
You're missing colons at the end of your conditionals and loops, aka while entered != guessed:. Add them to the end of the if and else lines as well. Also you are using the comparison (==) operator when assigning guessed instead of the assignment operator (=).
Also you will notice it prints "Try more" even when they guess the correct number, and then it will print "You win!". I'll leave this as an exercise to the new developer to fix.
entered = int(guessed_number)
makes no sense because you don't have a guessed_number variable. I think you meant to do
entered = int(raw_input("Enter your suggestion:")
Also, you're missing colons after your block starts at while, if, and else.
Welcome to Python 3.x! Here's the fixed code for you.
#Import Random
import random as r
#Create a random Number!
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
#Initiate variable --entered--
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
#Fixed your if/else tree with correct indents and an elif.
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
To add to the list:
guessed == random.randint(1,100)
should be
guessed = random.randint(1,100)
I'm sure you'd rather assign to guessed than compare it random.randint(1,100) and then throw the result of that comparison away.
entered = int(guessed_number)
It doesn't make any sense. There is no variable for 'guessed_number'.
I have edited your code to make it work:
import random
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
Hope that helps!
~Edward