How do i get out of this nested loop - python-3.x

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.

Related

python simple help (NameError: name is not defined)

Whenever I run this is get:
Traceback (most recent call last):
File "main.py", line 130, in <module>
while is_playing_cg:
NameError: name 'is_playing_cg' is not defined
I want the user to be able to press 1 or 2 to select which game mode to use and then once pressed it starts. I don't know why it's doing this. Whenever it's fixed it should run through just fine.
New edit
Now it just loops and says 1 or 2 over and over again.
import random
is_playing_cg = False
is_playing_hg = False
def game_select_screen():
#Game Select Screen
print("""
._________________________________.
| |
| ~ Welcome To Guess-A-Number ~ |
| ~~~ |
| ~ Press 1 OR Press 2 ~ |
| You ^ Guess | PC ^ Guess |
|_________________________________|""")
selecting = True
while selecting:
print()
game_mode = input("1 OR 2: ")
try:
int(game_mode)
except ValueError:
print("This is not a Number.")
else:
game_mode = int(game_mode)
if game_mode == 1:
is_playing_hg = True
elif game_mode == 2:
is_playing_cg = True
#Defining Random Number for human guess
def play_human_guess():
num = random.randint (1,10)
print()
print("Im Thinking of a Number 1 Through 10.")
print("You Have 3 Chances.")
chances = 3
game_fisnished = False
#Game is playing (Human Guesses)
while not game_fisnished:
guess = input("> Take A Guess: ")
#Accept only numbers
try:
int(guess)
except ValueError:
print("This is not a Number.")
else:
guess = int(guess)
if guess < num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
elif guess > num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
else:
print()
print("Congradulations, You Won!")
game_fisnished = True
#Game Ended
def end():
print()
print("Thanks For Playing!")
#Setting up for computer guess
def play_computer_guess():
print()
print("Pick a Number 1 Through 10")
print("I Have 3 Chances to Guess Your Number.")
chances = 3
game_fisnished = False
#Game is playing (Computer Guess)
while not game_fisnished:
guess1 = input("Is your number 5?")
#Show Game Select Screen
game_select_screen()
while is_playing_cg:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while is_playing_hg:
#Start Game
selecting = False
play_human_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_hg = False
end()
The variable is_playing_cg is only available in the "block" that creates it.
Block is function / loop / if statement / etc.
In your program you need to initialize the variable globally so you can call them in multiple functions.
Good luck!
You are defining is_playing_cg inside of a conditional statement at the top of your code. So if that option is not selected, then when you get to the latter conditional statement, it has never heard of that variable.... and it is not defined in the namespace. So you could either define it at the top and give it a default (False) or more better, because you only have 2 options, just use one variable to control the computer / human.
Here is a toy example:
selection = int(input('enter 1 for human, 2 for computer: '))
if selection == 1:
human_play = True
elif selection == 2:
human_play = False
else:
# make some loop that asks for input again or such...
pass
# later on...
if human_play:
# ask human for input...
else:
# have AI make turn
#if needed, you can also handle special cases like this:
if not human_play:
# do something unique to computer turn ...
Additional info...
So you got bit by the scope of the variables in your update. You are defining these variables inside of a function and when you put the defaults outside of the function, they are not in the same scope, so whatever you do inside the function is lost. So, you need to change your function into something that returns the mode you want, and catch that in the function call like such:
def ... :
# input ...
if game_mode == 1:
human_playing = True
selecting = False
elif game_mode == 2:
human_playing = False
selecting = False
return human_playing # this will return T/F back to the function call
And then later:
#Show Game Select Screen
human_playing = game_select_screen()
while not human_playing:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while human_playing:
#Start Game
This (above) works for me, but there are still other logic errors popping up! :) Have fun
This particular error is probably there because you have not defined is_playing_cg as global before using it in your function game_select_screen. Simply put global is_playing_cg at the start of your game_select_screen function to tell python you want to use the global variable instead of creating a scoped variable.

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 to write a python code to append data to json list

I want to create a python script which will have user input to enter a word and its definitions (multiple definitions) and append them to a JSON file
For some word there will be only one definition but others might have multiple ones.
JSON Example:
{'acid': ['A compound capable of transferring a hydrogen ion in solution.',
'Being harsh or corrosive in tone.',
'Having an acid, sharp or tangy taste.',
'A powerful hallucinogenic drug manufactured from lysergic acid.',
'Having a pH less than 7, or being sour, or having the strength to '
'neutralize alkalis, or turning a litmus paper red.'],
'acoustic filter': ['A device employed to reject sound in a particular range '
'of frequencies while passing sound in another range of '
'frequencies.'],
'acoustic insulation': ['The process of preventing the transmission of sound '
'by surrounding with a nonconducting material.']}
Code:
import json
while True:
Word = input('Enter Word:')
Definition1 = input('Definition 1: ')
Definition2 = input('Definition 2: ')
Definition3 = input('Definition 3: ')
Definition4 = input('Definition 4: ')
Definition5 = input('Definition 5: ')
Definition6 = input('Definition 6: ')
with open("files/data.json", "r+") as data:
information = {Word, Definition1, Definition2, Definition3, Definition4, Definition5}
data.write(json.dumps(information))
data.close()
I would advice the structure like this:
import json
words_dict = {}
while True:
tmp_list_of_definitions = []
word = input('Enter Word:')
if word in words_dict:
print('You already entered definitions for such word!')
answer = input('Is the procedure over? [y/n]')
if answer == 'y':
break
continue
def_counter = 0
print('In case you want to stop entering the definitions print "stop"')
while True:
definition = input('Definition {}: '.format(def_counter))
def_counter += 1
if definition == 'stop':
break
tmp_list_of_definitions.append(definition)
words_dict[word] = tmp_list_of_definitions
answer = input('Is the procedure over? [y/n]')
if answer == 'y':
break
And you don't have to use close when using with open().
Hope this helps,
import json
if __name__ == '__main__':
information = dict()
while True:
key = input("Enter word or 'q' to quit:")
if key is 'q':
break
definition_list = list()
while True:
definition = input("Enter definition or 'n' to next word:")
if definition is 'n':
break
definition_list.append(definition)
information[key] = definition_list
with open("data.json", "r+") as data:
data.write(json.dumps(information))
exit(0)

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