A problem about a python game guess the number - python-3.x

I am a very beginner in Python, I want to write a number guessing program in which the user thinks of a number which the computer has to guess.
I wrote this it works but there is this problem:
say my secret number is 13. The computer says 45, I enter 'h', then it says a number in range of (0, 45), for example it says 10, after I enter 'l' I don't want it to say a number over 45 (the number I said was too high!) and vice versa about the low number.
import random
print('Please think of a number between 0 and 100!')
input('''Press Enter once you've thought of one...''')
guess = random.randint(0,100)
print('Is your secret number', guess, '?'
'''\nEnter 'h' to indicate the guess is too high'''
'''\nEnter 'l' to indicate the guess is too low'''
'''\nEnter 'c' to indicate the guess is correct''')
hlc = input()
while hlc <= 'h' or 'l' or 'c':
if hlc == 'h':
guess -= 1
guess = random.randint(0, guess)
print('Is your secret number', guess,'?')
hlc = input()
elif hlc == 'l':
guess += 1
guess = random.randint(guess, 100)
print('Is your secret number', guess,'?')
hlc = input()
elif hlc == 'c':
print('Game over. Your secret number was', guess, '!')
break

You should track the highest and lowest numbers your user has rejected so far. Something like the following:
lowest_guess = 100
highest_guess = 100
while ... :
guess = random.randint(lowest_guess, highest_guess)
...
if hlc == 'h':
highest_guess = guess
elif hlc == 'l':
lowest_guess = guess

Related

How can I generate new random numbers each time in my while loop in Python for a number game?

I've created a number game where it asks the user if they want to play again and then the loop continues. My program uses import random but I want to know how I'd generate new random numbers without having to make variables each time. (I'm a beginner and I don't know what solution to use pls help)
My code works for the most part it's just that when the loop restarts the same number from the last playthrough repeats so the player ends up getting the same results. Here's my code:
`
import random
random_number_one = random.randint (0, 100)
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
print(random_number_one)
user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
if user_guess == 'H' or user_guess == 'h' :
print("You guessed higher. Let's see: ")
import random
random_number_two = random.randint (0, 100)
print(random_number_two)
if random_number_two > random_number_one :
print("You are correct! It was higher!")
play_again_h = input("Would you like to play again? ('Yes'/'No') ")
if play_again_h == 'Yes' or play_again_h == 'yes' :
continue
else:
break
else:
play_again = input("You were wrong, it was lower. Would you like to play again? ('Yes'/'No') ")
if play_again == 'Yes' or play_again == 'yes' :
continue
else:
break
elif user_guess == 'L' or user_guess == 'l':
print("You guessed lower. Let's see: ")
print(random_number_two)
if random_number_two < random_number_one :
print("You are correct! It was lower!")
play_again_l = input("Would you like to play again? ('Yes'/'No') ")
if play_again_l == 'Yes' or play_again_l == 'yes' :
continue
else:
break
else:
play_again_2 = input("You were wrong, it was higher. Would you like to play again? ('Yes'/'No') ")
if play_again_2 == 'Yes' or play_again_2 == 'yes' :
continue
else:
break
else:
print("Invalid response. You Lose.")
break
elif start_game == 'No' or start_game == 'no':
print("Okay, maybe next time.")
break
else:
print("Invalid response. You Lose.")
break
`
You have to initialize the random number generator with a seed.
See here: https://stackoverflow.com/a/22639752/11492317
and also: https://stackoverflow.com/a/27276198/11492317
(You wrote, you're a beginner, so I give you some hints for cut a few things short...)
import random
#import time #redundant
def get_random(exclude: int = None):
next_random = exclude
while next_random is exclude:
next_random = random.randint(0, 100)
return next_random
#random.seed(time.time())
random.seed() # uses system time!
username = input("Greetings, what is your name? ")
start_game = None
while start_game is None:
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes'/'No') ".format(username))
if start_game.lower() in ("yes", "y", ""):
print("Let's begin!")
number_for_guess = get_random()
running = True
elif start_game.lower() == "no":
print("Ok, bye!")
running = False
else:
start_game = None
while running:
print(number_for_guess)
next_number = get_random(exclude=number_for_guess)
user_guess = ""
while user_guess.lower() not in list("lh"):
user_guess = input("Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: ")
if user_guess.lower() == "h":
print("You guessed higher. Let's see: ")
print(next_number)
if next_number > number_for_guess:
print("You are correct! It was higher!")
else:
print("You were wrong, it was lower.", end=" ")
else:
print("You guessed lower. Let's see: ")
print(next_number)
if next_number < number_for_guess:
print("You are correct! It was lower!")
else:
print("You were wrong, it was higher.", end=" ")
play_again = "-"
while play_again.lower() not in ("yes", "y", "", "no"):
play_again = input("Would you like to play again? ('Yes'/'No') ")
if play_again.lower() == "no":
running = False
print("Well played, bye!")
You are creating random_number_one only once, when the program starts.
import random
random_number_one = random.randint (0, 100)
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
print(random_number_one)
...
So this number is used all the time:
Greetings, what is your name? a
Welcome to the number game, a! Would you like to play a game? (Type 'Yes/No') Yes
Let's begin!
8
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
86
You are correct! It was higher!
Would you like to play again? ('Yes'/'No') Yes
Let's begin!
8
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
82
You are correct! It was higher!
Would you like to play again? ('Yes'/'No')
You have to create new random number each time the while loop repeats:
import random
username = input("Greetings, what is your name? ")
start_game = input("Welcome to the number game, {0}! Would you like to play a game? (Type 'Yes/No') ".format(username))
while True:
if start_game == 'Yes' or start_game == 'yes' :
print("Let's begin!")
random_number_one = random.randint (0, 100) # <-- MOVED HERE
print(random_number_one)
...
Then it will work as you except:
Greetings, what is your name? a
Welcome to the number game, a! Would you like to play a game? (Type 'Yes/No') Yes
Let's begin!
96
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: H
You guessed higher. Let's see:
7
You were wrong, it was lower. Would you like to play again? ('Yes'/'No') Yes
Let's begin!
67
Do you think the next number will be higher or lower? Type 'H' for Higher and 'L' for Lower: L
You guessed lower. Let's see:
7
You are correct! It was lower!
Would you like to play again? ('Yes'/'No')
Some other small things:
Looks like you missed randint call within the lower option:
...
elif user_guess == 'L' or user_guess == 'l':
print("You guessed lower. Let's see: ")
random_number_two = random.randint (0, 100) # missing in your code
print(random_number_two)
if random_number_two < random_number_one :
print("You are correct! It was lower!")
...
You don't need to import random module each time you want to use function from it:
...
if user_guess == 'H' or user_guess == 'h' :
print("You guessed higher. Let's see: ")
import random # line not needed
random_number_two = random.randint (0, 100)
print(random_number_two)
...
You may change the line:
if user_guess == 'H' or user_guess == 'h':
into:
if user_guess.lower() == 'h':
or:
if user_guess in ('H', 'h'):
Try to split your code into smaller parts with functions.

i doesnt do what i want it to doo .i am making a guess the num game

from random import *
name = input("what is your name:")
options = input('what difficulty do you want to play on [ easy , normal , hard ]:').lower
random_num = 0
if options == 'easy':
print('ok, you will get numbers between 0 - 7')
random_num = randint(0, 7)
elif options == 'normal':
print('ok, you will get numbers between 0 - 10')
random_num = randint(0, 10)
elif options == 'hard':
print('ok, you will get numbers between 0 - 15')
random_num = randint(0, 15)
else :
print('sorry I am not able to understand please choose one from [ easy , normal , hard ]')
guess = input('ok i am ready guess a number in your range :')
if random_num == guess :
print('Yictory!!! , you won ,your guess was correct')
elif random_num == guess :
print('You lost!!! ,your guess was wrong')
else:
print('unable to interpret')
can some one help me with this as it doesnt go to else at the end and it goes to the second elif
and i am a biggainer so plz help me as soon as possible . its python 3.9.
The main problem is that guess is a string when it comes from input; you'll need to cast it to an integer, as that's what randint gets you.
guess = int(input('ok i am ready guess a number in your range :'))
This will, of course, crash horribly if you input something that's not a number, but that's a different issue.
There are a number of other issues too, such as the if and elif branches at the end being the same (i.e. you'd never get to "You lost"), and that you never call .lower().
To add proper error handling (and let the player guess more than once), I'd maybe reformulate this as
from random import randint
name = input("what is your name:")
option_ranges = {
"easy": 7,
"normal": 10,
"hard": 15,
}
while True:
options = input("what difficulty do you want to play on [ easy , normal , hard ]:").lower()
max_range = option_ranges.get(options)
if max_range: # found a correct option
break
print("sorry I am not able to understand please choose one from [ easy , normal , hard ]")
print(f"ok, you will get numbers between 0 - {max_range}")
random_num = randint(0, max_range)
while True:
try:
guess = int(input("ok i am ready guess a number in your range :"))
except ValueError:
print("unable to interpret")
continue # Go back to the loop
if random_num == guess:
print("Yictory!!! , you won ,your guess was correct")
break
print("You lost!!! ,your guess was wrong")
The code is okay, except for the logic condition: This line
elif random_num == guess :
print('You lost!!! ,your guess was wrong')
is the same as
if random_num == guess :
print('Yictory!!! , you won ,your guess was correct')
Change the elif logic from == to not equal !=;
elif random_num != guess :
print('You lost!!! ,your guess was wrong')
You should be good to go

I don't understand this rock paper scissors game

I found this code, and I'm having trouble understanding the lines 'user_hand = rps[int(user_input) - 1]' , 'com_hand = choice(rps)' , ' if rps_dict[user_hand]['strong'] == com_hand:' , 'print_result(**game_result)' , '
Why should I subtract 1 from user_input? Why put rps inside brackets next to choice? Why do you win 'if rps_dict[user_hand]['strong'] == com_hand ? Why if user_hand equal to com_hand? It doesnt make sense to me.. I know '**game_result' means it's a kwark, but I dont know why I need to declare it as a kwarg. I'm sorry if these questions seem stupid, but I'm frustrated.
from random import choice
rps = ('rock', 'paper', 'scissors')
rps_dict = {
'rock': {'strong': 'scissors', 'weak': 'paper'},
'paper': {'strong': 'rock', 'weak': 'scissors'},
'scissors': {'strong': 'paper', 'weak': 'rock'}
}
def print_result(user_score, com_score, win, lose, tie):
print('Result:', end=' ')
if user_score > com_score:
print('You win!')
elif user_score < com_score:
print('You lose...')
else:
print('Draw.')
print('--------------------')
# Print scores
print(f'Your score: {user_score}')
print(f'Computer score: {com_score}')
print('--------------------')
# Print statistics
print(f'Win: {win}')
print(f'Lose: {lose}')
print(f'Tie: {tie}')
def play(rounds):
game_result = {
'user_score': 0,
'com_score': 0,
'win': 0,
'lose': 0,
'tie': 0
}
while rounds > 0:
user_input = input(
'Enter your choice (1: Rock, 2: Paper, 3: Scissors, 0: Quit): ')
# Check whether the input is in the options
if user_input in ('1', '2', '3'):
rounds -= 1
user_hand = rps[int(user_input) - 1]
com_hand = choice(rps)
# user_hand is strong against com_hand
if rps_dict[user_hand]['strong'] == com_hand:
game_result['user_score'] += 1
game_result['win'] += 1
result = 'You win!'
# user_hand is weak against com_hand
elif rps_dict[user_hand]['weak'] == com_hand:
game_result['com_score'] += 1
game_result['lose'] += 1
result = 'You lose...'
# Tie
else:
game_result['tie'] += 1
result = 'Tie.'
print(
f'You -> {user_hand}. Computer -> {com_hand}. {result}')
elif user_input == '0':
break
else:
print('Invalid input!')
print()
print_result(**game_result)
if __name__ == "__main__":
print('Welcome to Rock-Paper-Scissors Game!')
try:
rounds = int(input('How many rounds you want to play? '))
play(rounds)
except ValueError:
print('Please input a valid number!')
This is an interesting question, and I'll do my best to discuss the lines that you said you have trouble with:
user_hand = rps[int(user_input) - 1]
The user_hand variable is used to store the choice the user inputs. user_input is the text the user directley entered. This will be saved as a string, so the code stransforms it into an integer with the int class. Next, it subtracts one from the user input (computers count from zero rather than 1). Then, it grabs the element from the list that has that index. For example, if I entered one, it would grab the list item at index 0 ("rock").
com_hand = choice(rps)
This line here is used to gather the computer's choice. As you can see from the first line, the choice function from the random module is imported directly. This allows you to use the function without specifying the module it came from. The choice function selects a random item from the specified list, which is the same rps list as before.
if rps_dict[user_hand]['strong'] == com_hand:
The if statement here gathers data from the rps_dict and compares it to the computer's hand. The rps_dict is a dictionary that contains data on which hand beats or loses to another. To translate the if statement into simpler english, it means if the hand the user's hand would beat (which can be found with rps_dict[user_hand]["strong"]), is the computer's hand, the user will win. In addition, to avoid confusion, the == operator check's for equality, and doesn't assign the variable to com_hand.
print_result(**game_result)
Here you said that you don't understand why the parameters are passed in this way. You don't really need to do it in this format, but the person who created the script decided to (possibly as it is simpler to read).
Thank you, and if you have any other questions, please comment and I'll do my best to answer them!

How do i make my input take all int and str type of data

I'm trying to get a guessing game with the user input as an answer and if the user type exit the game will show the amount of time the player tried but the program won't run because it can only take either interger or string type.
import random
while True:
number = random.randint(1,9)
guess = int(input('guess the number: '))
time = 0
time += 1
if guess == number:
print('you guessed correct')
elif guess < number:
print('your guessed is lower than the actual number')
elif guess > number:
print('your guessed is higher than the actual number')
elif guess == 'exit':
print(time)
break
something like this
import random
time = 0
number = random.randint(1,9)
while True:
guess = input('guess the number: ')
time += 1
if guess == "exit":
print(time)
break
elif int(guess) < number:
print('your guessed is lower than the actual number')
elif int(guess) > number:
print('your guessed is higher than the actual number')
elif int(guess) == number:
print('you guessed correct')
print(time)
break
note that time and number have to be initializate outside the while loop, because if not, we would get different random numbers for each iteration, and also time would be initializate to 0 each time.
You can test the input as a string first before converting it to an integer:
while True:
response = input('guess the number: ')
if response == 'exit':
break
guess = int(response)
# the rest of your code testing guess as a number

Problem with my small dictionary quiz. can someone explain this error please

d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
userinput == (input(color_key))
if userinput == (d[color_key]):
print("correct")
else:
print("wrong")
Hi everyone, i am trying to simulate a quiz with this dictionary. I want to iterate through the dictionary and prompt the user for the questions (which is the key) (i.e what is the number for the colour: color_key). I then want the user to put the value for the key that corresponds to the right colour.
I am getting this error:
userinput == input(color_key)
NameError: name 'userinput' is not defined
Can anyone help me please.
Based on assumptions that you want to make kind of "memory" game with colors and integers, code proposal for your game would be something like this:
import random
d = {'Red': 1, 'Green': 2, 'Blue': 3}
while 1==1:
rand1 = random.choice(list(d))
user_input = input("Please guess the code of "+rand1+" color:\n")
try:
int(user_input)
if(int(user_input) == d[rand1]):
print("Color code is correct!")
else:
print("Color code is incorrect!")
except ValueError:
if(user_input.lower() == "quit"):
print("Program will terminate now")
else:
print("Invalid input provided.")
Take in consideration few things important for these kind of exercises:
Despite python is not strictly typizied language, you have to take
care of exceptions in the user input
"While 1==1" generates something
called "dead loop". Make sure you always have exit condition for this
one - In our case out here, that is keyword "quit" on the input.
In case of keyword "quit" on the input, it has to be validated for both
upper and lowercase
EDIT:
According to your newest update, I am providing you the example of simple 3-operations based game:
import random
def detect_string_operation(elem1, elem2, operator):
result = ""
if(operator == "+"):
result = str(elem1 + elem2)
elif(operator == "-"):
result = str(elem1 - elem2)
elif(operator == "*"):
result = str(elem1 * elem2)
elif(operator == "/"):
result = str(elem1/elem2)
return result
operators_list = ["+", "-", "*"]
while 1==1:
elem1 = random.randint(0, 10)
elem2 = random.randint(0, 10)
operator_index = random.randint(0, len(operators_list)-1)
result_operation = detect_string_operation(elem1, elem2, operators_list[operator_index])
user_input = input("Please calculate following: "+str(elem1)+str(operators_list[operator_index])+str(elem2)+"=")
try:
int(user_input)
if(user_input == result_operation):
print("Result is correct!")
else:
print("Result is incorrect!")
except ValueError:
if(user_input.lower() == "quit"):
print("Program will terminate now")
break
else:
print("Invalid input provided.")
Note that I didn't implement division for a reason: for division totally random choice of values is not an option, since we need an integer as a result of division. Algorithm for generating divisor and divider pair is quite simple to be implemented in iterative way, but it is out of scope of your initial question.

Resources