Text Game - if text input isnot "Var1" or "Var2" then - Python 3 - text

This question references info from my previous question:
Text Game - If statement based of input text - Python
So, now I have this:
#Choice Number1
def introchoice():
print()
print("Do you 'Hesitate? or do you 'Walk forward")
print()
def Hesitate():
print()
print("You hesistate, startled by the sudden illumination of the room. Focusing on the old man who has his back turned to you. He gestures for you to come closer. \n ''Come in, Come in, don't be frightened. I'm but a frail old man'' he says.")
print()
#
def Walk():
print()
print("DEFAULT")
print()
#
def pick():
while True:
Input = input("")
if Input == "Hesitate":
Hesitate()
break
if Input == "Walk":
Walk()
break
#
#
pick()
#-#-#-#-#-#-#-#-#-#-#-#-#
#Clean-up
#-#-#-#-#-#-#-#-#-#-#-#-#
Now what I want to do is this;
def pick():
while True:
Input = input("")
if Input == "Hesitate":
Hesitate()
break
if Input == "Walk":
Walk()
break
if Input is not "Walk" or "Hesitate":
print("INVALID")
break
#
#
pick()
#-#-#-#-#-#-#-#-#-#-#-#-#
#Clean-up
#-#-#-#-#-#-#-#-#-#-#-#-#
Now that I have the game determine specific text inputs, I want it to be able to detect if the input was not one of the choices. That way, as typed in the above code, If the input text is not either "Walk" or "hesitate", print Text "INVALID"
How would I do this exactly?

I guess you want to still receiving input if it is "invalid", so the break statements have to be inside the ifs. Otherwise, the loop will only iterate one time.
Also, I would recommend you to use a if-elif-else structure so your code looks more organized.
You can't use is or is not in this case, because these operators are used to check if the objects are the same (same reference). Use the operators == and != to check for equality.
while True:
my_input = input("> ")
if my_input == "Hesitate":
hesitate()
break
elif my_input == "Walk":
walk()
break
else:
print("INVALID")
Notes:
I would recommend you to follow Python naming conventions. Names of variables and methods should start in lowercase.

Related

Functions that include input/print

I'm writing a program where you can play blackjack with a computer. I've implemented a class, a "main" and a bunch of others functions. The problem is that almost all of my them are build to get the proper input from the user. For instance:
def get_the_answer():
while True:
answer = input("Write 'reveal' to reveal cards, 'add' to add one more: ")
if answer in ['reveal', 'add']:
break
else:
continue
return answer
Or this one, which also has some prints in it:
def start_and_greet():
print('', colored('Hi! Shall we play Blackjack?', 'yellow'), '', sep='\n')
print(colored(blackjack()))
print()
while True:
answer = input("Write 'start' / 'exit': ")
if answer in ['start', 'exit']:
break
else:
continue
return answer
If I put all my inputs and prints in "main" function, there will be almost no additional functions besides "main", so this won't be acceptable by the task.
The main reason why I'm worrying about it is that I don't understand how one should test this...
Thank you in advance for your help!
I know that it is not recommended to use a function with print / input, although I saw how David Malan (CS50P course) uses the similar one in lectures:
def get_number():
while True:
n = int(input("What's n? "))
if n > 0:
break
return n

Do I need to look for a key down and up event to avoid double occurrence of my else block?

Wondering why its printing my else statement twice in this scenario. In theory it should just execute it once after an incorrect key is read, and loop back.
the out put I am getting after pressing a non 'enter' key How can I avoid this?
import random
import keyboard
#Constant values to assign as a win or loss
_WIN = 1
_LOSE = 0
#Create and store game hand choices
handChoice = ['Spock', 'Lizard', 'Rock', 'Paper', 'Scissors']
print('\nThis is advanced Rock, Paper, Scissors! Press ENTER to start the automated game->')
while True:
if keyboard.read_key() == 'enter':
break
else:
print('Please press ENTER!')
#Hand choices randomly assigned to player 1
player1 = random.choice(handChoice)
print('Player 1 uses ' + player1 + '!\n')
Looking true the docs you could use this:
keyboard.wait('enter')
It will also use less cpu. But you would need the async library with timeout to also give output.
you could also use this:
while True:
if keyboard.read_key() == 'enter':
break
elif event.event_type == keyboard.KEY_DOWN:
print('Please press ENTER!')

I am trying to tell the program to display insufficient input. unless those 5 are selected

while True:
if users_choice!= ('1','2','3','4','5'):
print ('Insufficient input Method')
break
This is inside my main loop. i dont want to place and if for each one.
Use users_choice not in ('1','2','3','4','5') instead.
while True:
if users_choice not in ('1','2','3','4','5'):
print ('Insufficient input Method')
break
Operator != is actually trying to compare a string with tuple. That's why != wont work here.
To understand clearly, test this code
users_choice = '0'
while True:
print(type(users_choice))
print(type(('1','2','3','4','5')))
if users_choice not in ('1','2','3','4','5'):
print ('Insufficient input Method')
break

Python 3 How to Ask user for specific input and reject invalid inputs

I have a question on how to check a user's input and make sure they are returning a specific string. Currently, the function when called will ask the user for their input. However, if they choose a string that is not part of the function, the else statement will execute and continue the code. I am trying to figure out how to loop this function, until a user inputs one of the strings that the function is looking for. Can anyone help me with this? I am new to python and would appreciate any help.
def dwarf_class_definer(dwarf_class):
if dwarf_class == "Thane":
print("'Ahhh Nobility'")
elif dwarf_class == "Mekanik":
print("'Interesting a Mechanic'")
elif dwarf_class == "Ancestrite":
print("'A spiritualist. I see...'")
elif dwarf_class == "Prisoner":
print("'Never met a gen-u-ine 'Last chancer.'")
elif dwarf_class == "Civilian":
print("'ehhh a civilian? Wut you doing here?'")
else:
print("You aren't choosing a valid class.")
dwarf_class = input("Which Class will you choose?: ")
dwarf_class_definer(dwarf_class)
A while loop will keep going until you tell it not to anymore. You can see when an expected value is supplied, the break command will terminate the while loop. A dictionary can also make your code a lot cleaner and easier to maintain compared to a bunch of if statements.
dwarf_classes = {
"Thane": "'Ahhh Nobility'",
"Mekanik": "'Interesting a Mechanic'",
"Ancestrite": "'A spiritualist. I see...'",
"Prisoner": "'Never met a gen-u-ine 'Last chancer.'",
"Civilian": "'ehhh a civilian? Wut you doing here?'",
}
while True:
dwarf_class = input("Which Class will you choose?: ")
if dwarf_class in dwarf_classes.keys():
print(dwarf_classes[dwarf_class])
break
print("You aren't choosing a valid class.")
example:
$ python3 so.py
Which Class will you choose?: Python!
You aren't choosing a valid class.
Which Class will you choose?: Prisoner
'Never met a gen-u-ine 'Last chancer.'

Unable to get out of loops

I'm trying to write a MasterMind game using classes and objects and I'm currently stuck around some of my loops.
while True:
# create a combination
# test the combination
while game_won == False:
print(scoreboard)
# player input combination
# combination is tested then added to scoreboard
tries_left = tries_left+1
if game_won == True:
print(You Won!)
input = Play Again? Y/N
if tries_left == 10:
print(You Lost!)
input = Play Again? Y/N
How do I do to go back to my while True -> create combination from my last if statement? (if tries_left == 10:)
What's wrong
Your first while True doesn't have anything in it, You need to indent code under it if you want it to be inside the loop.
There is a few typos, missing comment characters, and quotation marks.
What needs to happen
When the nested while loop while game_won == True exits, the code will return looping the parent loop while True, which will replay the game, if the user wishes.
Your code fixed (with a few improvements)
Following is how you can loop the game forever (given the user wishes it).
# Assume user wants to play when the program runs
user_wants_to_play = True
ans = ""
# loop the entire game while the user wishes to play
while user_wants_to_play:
# Create the combination
# Test the combination
# Game isn't done when started
game_done = False
tries_left = 10 # Arbitrary number I chose
while not game_done:
# Play the game
print("Scoreboard")
# Subtract one to tries left
tries_left -= 1
if game_done:
print("You won!")
elif tries_left == 0:
print("You lost!")
game_done = True
# if users answer was 'n'
ans = input("Play again? Y/N \n")
if ans.strip().upper() == 'N':
user_wants_to_play = False
Improvements
Boolean logic is more pythonic using not instead of myBool == False
while True: changed to while user_wants_to_play:
User input is scrubbed to ignore white-space and lower case
Changed game_won to game_done
Made tries_left count down instead

Resources