Basic guessing game not functioning the way I want it to [duplicate] - python

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
I'm trying to get this game to run ad infinitum until the user enters "q" or "quit". For some reason, this isn't quite working out with what I have. I initially tried to do this with two functions but failed miserably, so I consolidated for right now into one function to try to get it going. Still failing, but not as bad.
#Ex9: Guessing game. Generate a number between 1-9 and provide info whether its too high or low
import random
#print("Type q or quit to quit")
#guess = int(input("Please enter a number between 1 to 9: "))
def guessing_function():
while True:
quit1 = print("Type q or quit to quit")
guess = int(input("Please enter a number between 1 to 9: "))
value = random.randint(1,9)
if quit1 == "quit".lower() or "q".lower():
print("Ok we will stop")
break
elif guess > value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too high")
elif guess < value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too low")
elif guess == value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is correct!")
guessing_function()
Basically the issue is that the script just stops after one loop, rather than continue on without the user's input.... Not sure what I'm doing wrong.

Looks like you want to check if the user wanted to quit.
checking "quit".lower() is not correct. "quit" is already lower.
Also the or part of the if statement is incorrect. It will always be True.
Instead you want to check if lowercase of quit1 is either "quit" or "q".
You can do that by giving if quit1.lower() in ("quit","q"). By using in ("quit","q"), the if statement checks against the items in the tuple. This is a much better way to check when you have multiple values to check.
def guessing_function():
while True:
quit1 = print("Type q or quit to quit")
guess = int(input("Please enter a number between 1 to 9: "))
value = random.randint(1,9)
if quit1.lower() in ("quit","q"): #fixed this line
print("Ok we will stop")
break
elif guess > value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too high")
elif guess < value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too low")
elif guess == value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is correct!")

print doesn't prompt for user input(and returns None always), you should replace it with input instead.
The if is also wrong, it should be if quit1 == "quit" or quit1 == "q":. How to test multiple variables against a value? explains it better than I could.

Related

while if statements, am not sure how to use a while statement when a name is not equal to quit

I am learning how to do while if statements and am unsure how to do step 2 in this program, "use a while statement to test when the name is not equal to quit". I tried to assign a variable to "name" but am not sure if that is the right way to go about it.
# Write the statements requested in Steps 1-6 below
# See the examples in the provided code
# Use structured programming and indent your code.
# Programmer Name: *****add your name here****
import random
# uses randrange instead of randint for better results in Python 3.7
# randrange stops just before the upper range, use (1, 11) for 1-10
num = random.randrange(1, 11)
# Step 1: Ask the player to enter a name or quit to exit
print("Hi, please enter your name or type 'quit' to exit.")
# Step 2: use a while statement to test when the name is not equal to quit
a=name
while a
# Step 3: input enter a number from 1 to 10 for the variable your_guess
# display the number guessed
print("Your number is", your_guess)
while num != your_guess:
# Step 4: Write an if statement for your_guess is less than num
print("Your guess is too low.")
your_guess = int(input("Guess another number from 1 to 10: "))
elif your_guess > num:
print("Your guess is too high")
your_guess = int(input("Guess another number from 1 to 10: "))
else:
break
print("The correct number was", num)
# Step 5 display text with your guess and You won, name
print("***************************************************************")
# Step 6 ask the player to enter a name or quit to exit
num = random.randrange(1, 11)
print("Thank you for playing!")
The program is bascially asking you to check whether the user has typed in quit instead of a number.
I don't see you take in the input entered by the user in the program, maybe you should try and do
print("Hi, please enter your name or type 'quit' to exit.")
your_guess = input()
Then you have to check whether your_guess is equal to 'quit' because that should terminate the loop (stop it from running and exit the program).
while your_guess != 'quit':
P.S. Make sure to say your_guess = int(your_guess) to convert it to a string inside the loop, or else it will be evaluated as a string.

How do I prevent a user from entering a previous guess in my python guessing game? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I want to store a list of guesses the user has already made, so that when the user makes the next guess I can check that guess against a list of previous guesses. If the guess the user just made is in that list I want to tell the user to guess again and not count it as a attempt(5 attempts at guessing correct number)
tried using the append method to append the guesses to a blank list but I'm getting a "int obj has no append method" error.
import random
def guess_a_number():
chances = 5
random_number_generation = random.randint(1,21)
while chances != 0:
choice = int(input("Guess a number between 1-20, you only have {} chances left ".format(chances)))
if choice > random_number_generation:
print("Your number is too high, guess lower")
elif choice < random_number_generation:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
if chances == 0:
try_again = input("Do you want to try play again? ")
if try_again.lower() == "yes":
guess_a_number()
else:
print("Better luck next time")
guess_a_number()
Try keeping a list of previous guesses and then check if guess in previous_guesses: immediately after the choice. You can use continue to skip the rest and prompt them again.
Just use a set or a list to hold the previously attempted numbers and check for those in the loop.
I think you already tried something similar but by the sound of it you were attempting to append to an int.
import random
while True:
chances = 5
randnum = random.randint(1, 21)
prev_guesses = set()
print("Guess a number between 1-20, you have {} chances ".format(chances))
while True:
try:
choice = int(input("what is your guess? "))
except ValueError:
print('enter a valid integer')
continue
if choice in prev_guesses:
print('you already tried {}'.format(choice))
continue
if choice > randnum:
print("Your number is too high, guess lower")
elif choice < randnum:
print("Your number is too low, guess higher")
else:
print("You guessed the correct number!!!")
break
chances -= 1
prev_guesses.add(choice)
print("you have {} chances left".format(chances))
if chances == 0:
print("You ran out of guesses, it was {}".format(randnum))
break
try_again = input("Do you want to play again? ")
if try_again.lower() not in ("y", "yes"):
print("Better luck next time")
break

What can I do to fix my simple computer-player game code? Syntax Error

I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break

Python: why is my print statement not running for my else?

import random
number = random.randint(0,10)
#print (number)
guess = int(input("I'm thinking of a number between 1 and 10. \nPlease guess what it is: "))
#print(guess)
while guess != number:
if guess > number:
print("That is too high!")
guess = int(input())
elif guess < number:
print("That is too low")
guess = int(input())
else:
print("Thats it! You win!")
I'm working out a few python coding examples and I am confused why my else statement isn't printing?
The code objective is to generate a random number, and then have the user input a guess and then depending if the guess is lower or higher than the random number for the computer to notify the user and if the user guess correctly, then to tell the user that they won.
I'm tested this out and when I input the correct number the code just ends and doesn't print out "That's it! You win!". Why is this and how can I get it to print it out?
Guess input prior to the loop will most times be different than the number to guess, therefore the loop will not enter.
You also have other more subtle bugs: for instance, input is taken twice in one loop, creating conditions for improper feedback. Further, your win is confirmed by default, that is if guess not too high, and if guess not too low, then it is a win; a positive assertion such as if guess equals number, is probably safer to declare a win.
Here is a design that segregates each actions in one place in the loop, minimizing the risks of a faulty logic.
import random
number = random.randint(0, 10)
guess = None
while guess != number:
guess = int(input())
if guess > number:
print("That is too high!")
elif guess < number:
print("That is too low")
elif guess == number:
print("Thats it! You win!")
else:
print('that was not supposed to happen')

Python 3.6.5. Why does OR not work as i expect it to? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
Why if i use OR at !!! section, does it break even if i type a number 1 - 9 in the guess input. And why do i not need to type BOTH 'q' and 'quit', because thats what i assume AND means... 'q' AND 'quit'...
import random
while True:
print("\nGuess a number between 1 and 9.")
guess = input("I guess: ")
if guess == 'q' !!!or!!! 'quit':
break
number = random.randrange(1, 10)
try:
if int(guess) < number:
print(f"You guess was too low. The number was {number}")
elif int(guess) > number:
print(f"Your guess was too high. The number was {number}")
elif int(guess) == number:
print(f"Your guess was exactly right! The number was {number}")
except ValueError:
print("Please only guess numbers!")
So with OR it doesn't work and with AND it does. This makes no sense to me. Why is this?
if guess == 'q' or 'quit':
This statement will not work because you are trying to use a string as a boolean. The OR doesn't assume you want the exact same thing to happen like before it, you have to fill the condition again.
if guess == 'q' or guess == 'quit':
This will work because you are now getting a boolean out of the right side instead of just trying to use a string.

Categories

Resources