My guessing game not functioning correctly - python

It's not selecting the level of difficulty. Did I forget something? For example, I want it to select 3 for hard, which then leads the game to select from 1 to 1000 with 5 tries. and if the user selects 2 for easy they have to guess from 1 to 500 with 10 tries
import random
print('What level would you like to play 1 for easy, 2 for medium, 3 for hard')
print(1,2,3)
number = random.randint(1, 100)
number_of_guesses = 0
print(' Try Guessing a number between 1 and 100:')
while number_of_guesses < 15:
number = random.randint(1, 100)
guess = int(input())
number_of_guesses += 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
while number_of_guesses < 10:
number = random.randint(1, 500)
guess = int(input())
number_of_guesses += 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
while number_of_guesses < 5:
number = random.randint(1, 500)
guess = int(input())
number_of_guesses += 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
print('You guessed the number in ' + str(number_of_guesses) + ' tries!')
else:
print('You did not guess the number, The number was ' + str(number))

level = input("Print your level here")
if int(level) == 1:
# set level to 1
if int(level) == 2:
# set level to 2
if int(level) == 3:
# set level to 3
The problem with your code is that you
Don't take user input.
Even if you had user input you don't act on it.
You also aren't excepting input for the guess.
Here is a link to learn more on how to use the python input() function
https://www.w3schools.com/python/ref_func_input.asp

You forgot the user input for difficulty. Choose maximum guess and highest limit of number based on input as well. Then a single while loop can do the job.
import random
difficulty = int(input('What level would you like to play 1 for easy, 2 for medium, 3 for hard: '))
max_guess = 0
highest_number = 0
if difficulty == 1:
max_guess = 15
highest_number = 100
elif difficulty == 2:
max_guess = 10
highest_number = 500
elif difficulty == 3:
max_guess = 15
highest_number = 100
else:
print("Wrong choice")
number_of_guesses = 0
number = random.randint(1, highest_number)
while number_of_guesses < max_guess:
guess = int(input())
number_of_guesses += 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
print('You guessed the number in ' + str(number_of_guesses) + ' tries!')
else:
print('You did not guess the number, The number was ' + str(number))
Edit: Sorry previous code had some issues. here is the full code that can work

Related

Guess the number program in Python - after typing how many times I want to play, game is not working

I am working on Guess the number program in Python. I had to make some enhancements to it and add:
User has a default limit of 15 guesses (when enter key is hit)
Ask for a limit to the number of guests - this part doesn't work in my code.
import random
def main():
print('\n'*40)
print('Welcome to the Guess number game!')
print('\n'*1)
player_name = input("What is your name? ") print('\n'*1)
try_again = 'y'
number_of_guesses = 0
error = 0
guess_limit = 15
while ((try_again == 'y') or (try_again == 'Y')):
try:
limit = input('You have 15 default guesses to start. Do you like to have different number of guesses? ')
if limit.upper() == 'Y':
limit = input('How many times would you like to play? ') # after I input number of guesses I cannot proceed to the actual game
else:
number = random.randint(1, 100)
while (guess_limit != 0):
guess = int(input("Enter an integer from 1 to 100: "))
if (guess < 1) or (guess > 100):
print("ERROR! Integer must be in the range 1-100! ")
else:
if guess < number:
print ("Guess is low!")
elif guess > number:
print ("Guess is high!")
else:
print('\n'*1)
print ("YOU WIN! You made " + str(number_of_guesses) + " guesses.")
break
number_of_guesses += 1
guess_limit -= 1
print(guess_limit, 'guesses left')
print()
else:
#if guess_limit == 0:
print ("YOU LOSE! You made " + str(number_of_guesses) + " guesses.")
except ValueError:
print('ERROR: Non-numeric data. Please enter valid number!')
print('\n'*1)
try_again = input("Play again? Enter 'Y' or 'y' for yes: ")
print('\n'*1)
main()
OUTPUT: Welcome to the Guess number game!
What is your name? d
You have 15 default guesses to start.
Do you like to have different number of guesses? y
How many times would you like to play? 3 # after this I have
Play again? Enter 'Y' or 'y' for yes: # this result
How can I change that code?
you have to use
guess_limit = input("How many times would you like to play? ")
and then you have to check if it is blank or not by simple if conditions
if guess_limit == "":
guess_limit = 15
Below is the full code with well commented.
# import only system from os
from os import system
import random
def main():
# For clearing the screen
system('cls')
# For adding blank line
blank_line = '\n'*1
print('Welcome to the Guess number game!')
print(blank_line)
player_name = input("What is your name? ")
print(blank_line)
# to start the loop initially try_again = 'y'
try_again = 'y'
# Count number of guesses by player
number_of_guesses = 0
while (try_again.lower() == 'y'):
# Get number of times player want to guess
guess_limit = input("How many times would you like to play? ")
# If player enter nothing and hit enter
# then default value of guess_limit is 15
if guess_limit == "":
guess_limit = 15
# Convert the guess_limit to int data type
guess_limit = int(guess_limit)
# If user inputted number then go inside this try block
# else go inside except block
try:
# Generate random number in betwee 1-99 to be guess by the player
number = random.randint(1, 99)
# Loop untill there is no guesses left
while (guess_limit != 0):
# Player guess
guess = int(input("Enter an integer from 1 to 99: "))
# Check for valid number i.e number should be betwee 1 - 99
while ((guess < 1) or (guess > 99)):
guess = int(
input("ERROR! Please enter an integer in the range from 1 to 99: "))
# Check for High and low guess
if guess < number:
print("Guess is low")
elif guess > number:
print("Guess is high")
# If it is neither high nor low
else:
print(blank_line)
print("YOU WIN! You made " +
str(number_of_guesses) + " guesses.")
# To get out of the loop
break
# decrement the guess_limit by 1 on every iteration
guess_limit -= 1
print(guess_limit, 'guesses left')
# Increment number of guesses by the player
number_of_guesses += 1
print()
# If guess_limit is equal to 0, it means player have not guessed the number
# And player lose
if guess_limit == 0:
print("YOU LOSE! You made " +
str(number_of_guesses) + " guesses.")
except ValueError:
print('ERROR: Non-numeric data. Please enter valid number!')
print(blank_line)
# Ask again to play again
# If player enter anything other than 'Y' or 'y' then exit the game
try_again = input("Play again? Enter 'Y' or 'y' for yes: ")
print(blank_line)
main()

why line 14 is printed two times

import random
random_number = random.randint(1,10) #numbers 1 - 10
guess = None
while True:
guess = input("pick a number from 1 to 10 \n")
guess = int(guess)
if guess < random_number:
print("Too low")
elif guess > 10:
print("pick a number from 1 to 10")
elif guess > random_number:
print("It's high")
else:
print("You won")
play_again = input("Do you want to play again? (y/n) ")
if play_again == "y":
random_number = random.randint(1,10) #numbers 1 - 10
guess = None
else:
print("Thank you for playing!")
break
Because You print "pick a number from 1 to 10" and then follows input label at line 8.
If you type a number greater than 10, it should print at least 3 times
guess = input("pick a number from 1 to 10 \n")
elif guess > 10:
print("pick a number from 1 to 10")
Then the loop repeats
It's not clear why you've hard-coded 10 in the if-else. Rather you can try to continue the loop
while True:
guess = input("pick a number from 1 to 10 \n")
guess = int(guess)
if guess > 10:
continue

I don;t understand what is wrong with this code

Im getting a syntax error for elif option ==2:. I was wondering what I need to do to fix it. I followed the pseudocode my professor gave us but it still won't run. I'm wondering if I shouldn't have used elif or maybe something about the indentation is off.
import random
print("Welcome to the guess my number program")
while True:
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it")
print("3. Exit")
option = int(input("Please enter your number here: "))
if option ==1:
#generates a random number
mynumber = random.randint(1,11)
#number of guesses
count = 1
while True:
try:
guess = int(input("Guess a number between 1 and 10:"))
while guess < 1 or guess > 10:
guess = int(input("Guess a number between 1 and 10:")) # THIS LINE HERE
except:
print("Numbers Only")
continue
#prints if the number you chose is too low and adds 1 to the counter
if guess < mynumber:
print("The number you chose is too low")
count= count+1
#prints if the number you chose is too high and adds 1 to the counter
elif guess > mynumber:
print("The number you choose is too high")
count = count+1
#If the number you chose is correct it will tell you that you guessed the number and how many attempts it took
elif guess == mynumber:
print("You guessed it in " , count , "attempts")
break
elif option == 2:
number = int(input("Please Enter a Number: "))
count = 1
while True:
randomval = random.randint(1,11)
if (number < randomval):
print("Too high")
elif (number > randomval):
print("Too low")
count = count+1
elif (number==randomval):
print("The computer guessed it in" + count + "attempts. The number was" + randomval)
break
else:
break
The problem is simple. There is no continuity between if option == 1 and elif option == 2, because of the in between while loop. What you have to do is remove the el part of elif option == 2 and just write if option == 2.
I haven't tested the whole program myself. But at a glance, this should rectify the problem.
Please comment if otherwise.

how to count the number of user inputs in Python

Im having loads of trouble trying to count the number of guesses in this after you find the number.
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
Try this:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+1 #new line
start with a variable to store the number of guesses
...
count = 0
...
then increment it on every guess
...
guess = int(input("Your guess: "))
count += 1
...
You should initialize count as 1 and increment on each loop.
import random
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
An example output:
Enter the upper limit for the range of numbers:
10
I'm thinking of a number from 1 to 10
Your guess: 3
Too low.
Your guess: 7
Too low.
Your guess: 9
Too low.
Your guess: 10
You guessed it in 4 tries.
import random
highest = 10
answer = random.randrange(1,highest)
guess = 0
count = 0
print("please guess a number between 1 and {}".format(highest))
while guess != answer:
guess = int(input())
if count == 4:
exit(print("you exceeded number of chances"))
if guess == answer:
print("well done you have guessed it correctly and the answer is
{}".format(guess))
break
else:
if guess < answer:
print("please guess higher")
else:
print("please guess lower")
count = count +1

Random number guessing game throws error: > or < cannot be used between str and int

I have the following code for a random number guessing game:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = input()
if guess1 == number:
print ("Good job, you got it!")
while guess1 != number:
if guess1 > number:
print ('your guess is too high')
if guess1 < number:
print ('your guess is too low')
which throws the error that > or < cannot be used between str and int.
What should I do so it doesn't trigger that error?
There are two errors in your code.
You need to convert the input for guess1 from a string (by default) to an integer before you can compare it to the number (an integer).
The while loop will never stop since you are not letting the user input another value.
Try this:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try again.')
elif guess1 < number:
print ('your guess is too low. Try again.')
guess1 = int(input()) # asks user to take another guess
print("Good job, you got it!")
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm
The logic should be:
answer_is_correct = False
while not answer_is_correct :
Keep receiving input until answer is correct
I hope this works for you:
import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
guess_number = int(input('Enter a number:'))
guess += 1
if guess_number < number:
print('Your guess is to low')
if guess_number > number:
print('Your guess is to high')
if guess_number == number:
print('Your guess is correct the number is',number)
break
if guess == 4:
break
print('The number i was thinking of is',number)
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
Code in Python 3 for guessing game:
import random
def guessGame():
while True:
while True:
try:
low, high = map(int,input("Enter a lower number and a higher numer for your game.").split())
break
except ValueError:
print("Enter valid numbers please.")
if low > high:
print("The lower number can't be greater then the higher number.")
elif low+10 >= high:
print("At least lower number must be 10 less then the higher number")
else:
break
find_me = random.randint(low,high)
print("You have 6 chances to find the number...")
chances = 6
flag = 0
while chances:
chances-=1
guess = int(input("Enter your guess : "))
if guess<high and guess>low:
if guess < find_me:
print("The number you have entered a number less then the predicted number.",end="//")
print("{0} chances left.".format(chances))
elif guess > find_me:
print("The number you have entered a number greater then the predicted number.",end="//")
print("{0} chances left.".format(chances))
else:
print("Congrats!! you have succesfully guessed the right answer.")
return
else:
print("You must not input number out of range")
print("{0} chances left.".format(chances))
print("The predicted number was {0}".format(find_me))
You can conditions within the while loop to check if its right. It can be done the following way.
import random
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
print "Sorry wrong number , try again"
inputNumber = int(raw_input('Enter the number')
print "Congrats!"
from random import *
def play_game():
print("Let's play a number guessing game")
# Selecting a random number between 1 and 100
number = randint(1, 100)
choice = int(input("I am thinking of a number between 1 and 100. Could you guess what it is? "))
# Guide the user towards the right guess
# Loop will continue until user guesses the right number
while choice != number:
if choice < number:
choice = int(input("Too low. Can you try again? "))
elif choice > number:
choice = int(input("Too high. Can you try again? "))
continue_game = input("You guessed it right! Would you like to play it again? (Y/N) ")
# Restart the game if user wishes to play again
if continue_game == "Y":
print("--" * 42)
play_game()
else:
print("Thanks for playing :)")
exit(0)
play_game()

Categories