I don't understand this rock paper scissors game - python-3.x

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!

Related

Is there any way to loop a form in python, while indefinitely store the data?

I'm new in coding and recently I've been practicing Python to use in a script in uni lab.
Basically I'm trying to do a loop over a input loop it self. See:
U_Ant = []
while True:
Sample_ID = input("Sample ID: >>" )
print('Assign the halo diameter according to the previous order, then type "done" when finished')
Ant_Halo = input(">", )
if Ant_Halo == 'done':
break
try:
fAnt_Halo = float(Ant_Halo)
except:
print('Invalid input')
continue
try:
U_Ant.append(int(Ant_Halo))
except:
U_Ant.append(float(Ant_Halo))
But the real thing starts right after that. This single code above allows user to input values for only one sample (halo diameter given to a specific sample), what I want to do is:
print("All fields are correct?")
check_1 = input("Y/N: >")
if check_1 == "Y" or 'y':
pass
else:
return self.mo_antimicrobial()
print("Do you wish to add more samples?")
check_1
if check_1 == "Y" or 'y':
return self.mo_antimicrobial()
else:
pass
And be able to add more samples and inputs without fearing lose them. The point of the whole script is to gather multiple sample data (halo diameters) and plot as a table (where the columns are variable as well), so I must have a way to make every entry unique.
I tried to use dictionaries but I'm not being able to neither add int or str to it. I though of using:
def pilot():
sample_number = int(input("Please, set the number of samples for this experiment:" ))
for i in range(0, sample_number):
while True:
U_Ant = []
Sample_ID = input("Sample ID: >>" )
print('Assign the halo diameter according to the previous order, then type "done" when finished')
Ant_Halo = input(">", )
if Ant_Halo == 'done':
break
try:
fAnt_Halo = float(Ant_Halo)
except:
print('Invalid input')
continue
try:
U_Ant.append(int(Ant_Halo))
except:
U_Ant.append(float(Ant_Halo))
cache_data += {'ID': [Sample_ID], 'Halo': [U_Ant]}
print("Do you wish to add more samples?")
check_1 = input()
if check_1 == "Y" or 'y':
pilot()
else:
pass
but things won't work, since the output is just:
Sample_ID = input("Sample ID: >>" )
print('Assign the halo diameter according to the previous order, then type "done" when finished')
Ant_Halo = input(">", )
Sorry If I was too much vague, it's my first time posting on stack and this is also a reflex of my ignorance in this programming language. Thanks in advance.

How do i get out of this nested loop

I have been trying to get out of this nested loop I coded....please forgive me if the code is a bit too long but the actual important part has been commented at the last but one area of the code please help.
import random
import time
import math
# main
while True:
print('Only a maximum of three players are allowed in this game. A single player plays
with cpu')
print('1. Single Player\n2. Double Players\n3. Triple players')
print("Let's Start")
player_select = input('How many players will be playing ths game?: ')
single_score = [] # keep scores of player
cpu_score = [] # keep scores of CPU
while True:
lst = ['Rock', 'Paper', 'Scissors'] # holding the random three words
if player_select == '1' or player_select.lower() == 'single player':
randomize = random.choice(lst) # create a random choice out of the list
for i in last:
print(i) # display rock paper scissors
time.sleep(1)
print(randomize)
guess = input('guess rock, paper or scissors: ') # demanding for a guess
if guess.lower() == randomize.lower(): # what should happen if guess is right
single_score.append(1) # add 1 to the single_score list
print(f"Scores Player1 {single_score} \nScores Player CPU {cpu_score}")
elif guess.lower() != randomize.lower():
cpu_score.append(1)
print(f"Scores Player1 {single_score} \nScores Player CPU {cpu_score}")
print("Press 'Enter to continue'\n1. Change number of players(p)\n2. Exit(e) ")
question = input('Enter your choice: ')
if question == '':
continue
elif question.lower() in ['change number of players', 'p'] or question == '2':
print('Lets start all over')
#how do i get out of this to the intitial while loop?
elif question.lower() in ['exit', 'e'] or question == '3':
print('Total score of Player1', sum(single_score), '\n Total score of Player CPU',
sum(cpu_score))
The best way to do this is to use boolean check in your while loop :
check1 = True
check2 = True
while check1:
...
while check2:
if some_stop_condition_for_the_iner_loop:
check2 = False
if some_stop_condition_for_the_outer_loop:
check1 = False
check2 = False
In this way you can easily control your execution flow.
You can also use the keyword break that will allow you to stop the current loop you're in, but if there is neested loop, it will only break the deeper one, so boolean check are often the best solution.

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.

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

Random word game python 3.5

Hi i'm completely new to programming and have been trying to teach myself python, I have been trying to create a program that selects a word then shuffles the letters and prompts the user to input their guess within 3 tries. The problem I'm having is when a wrong answer is input it reshuffles the letters of the chosen word or returns a completely different word, here is my code:
import random
import sys
##Welcome message
print ("""\tWelcome to the scrambler,
select [E]asy, [M]edium or [H]ard
and you have to guess the word""")
##Select difficulty
difficulty = input("> ")
difficulty = difficulty.upper()
##For counting number of guesses it takes
tries = 0
while tries < 3:
tries += 1
##Starting the game on easy
if difficulty == 'E':
words = ['teeth', 'heart', 'police', 'select', 'monkey']
chosen = random.choice(words)
letters = list(chosen)
random.shuffle(letters)
scrambled = ''.join(letters)
print (scrambled)
guess = input("> ")
if guess == chosen:
print ("Congratulations!")
break
else:
print ("you suck")
else:
print("no good")
sys.exit(0)
As you can see I've only gotten as far as easy, I was trying to do it piece by piece and managed to overcome other problems but I can't seem to fix the one I'm having. Any help would be appreciated with the problem I'm having or any other issues you may spot in my code.
A few improvements and fixes for your game.
import random
import sys
# Game configuration
max_tries = 3
# Global vars
tries_left = max_tries
# Welcome message
print("""\tWelcome to the scrambler,
select [E]asy, [M]edium or [H]ard
and you have to guess the word""")
# Select difficulty
difficulty = input("> ")
difficulty = difficulty.upper()
if difficulty == 'E':
words = ['teeth', 'heart', 'police', 'select', 'monkey']
chosen = random.choice(words)
letters = list(chosen)
random.shuffle(letters)
scrambled = ''.join(letters)
else:
print("no good")
sys.exit(0)
# Now the scrambled word fixed until the end of the game
# Game loop
print("Try to guess the word: ", scrambled, " (", tries_left, " tries left)")
while tries_left > 0:
print(scrambled)
guess = input("> ")
if guess == chosen:
print("Congratulations!")
break
else:
print("You suck, try again?")
tries_left -= 1
Tell me if you don't understand something, I would be a pleasure to help you.

Resources