when input is asked, I type Rock it loops back as though i did not type the right input.
I've tried retyping the error checking but nothing is working. The only input it will accept is 'q'. Here is the code:
import random
user_wins = 0 #setting default score
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
if user_input not in options:
continue
random_number = random.randint(0, 2) #rock: 0 , paper: 1, scissors: 2
computer_pick = options[random_number] #using computer's pick from a random from the list to be stored.
print('Computer picked:', computer_pick + ".") #printing the result of computer's pick
if user_input == "rock" and computer_pick == "scissors": #setting win or lose conditions
print('Rock Crushes Scissors...You Win!')
user_wins += 1
elif user_input == "paper" and computer_pick == "rock":
print('Paper Covers Rock...You Win!')
user_wins += 1
elif user_input == "scissors" and computer_pick == "paper":
print('Scissors Cuts Paper...You Win!')
user_wins += 1
else:
print("You Lose")
computer_wins += 1
print("You won ", user_wins, "times.")
print("Computer won ", computer_wins, "times.")
print('Goodbye')
It's because you need to break the loop when input is in options, so the loop could be
while True:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
if user_input not in options:
continue
else:
break
Anyways, a better implementation could be creating the empty option and assign it if matches, so
answer = ''
while not answer:
user_input = input('Type Rock/Paper/Scissors or Q to quit: ').lower()
if user_input == "q":
break
elif user_input in options:
answer = user_input
In you case try this code. You will need to have two while loops: one is for checking the input, the other is for continuing the game.
exit = False #this helps you to exit from the main while loop.
while not exit:
options = ['rock', 'scissors', 'paper']
user_input = ""
while True:
user_input = input('pls write paper, rock, scissors, or
q(quit) ').lower()
if user_input in options:
break
elif user_input == 'q':
exit = True
break
#do some calculations
# do some summary calculations and print them
I hope you will find it helpful)
Related
Trying to exit the program by importing sys.exit(), break and ask == False, but nothing works. Full code here
#import sys
def body_cycle(*args):
if option == "/":
error_func_for_zero(first_number, second_number, option)
print(division_option(first_number, second_number))
print()
print(begin)
def error_func_for_zero(*args):
try:
first_number / 0 or second_number / 0
except ZeroDivisionError:
print("YOU CANNOT DIVIDE BY ZERO!")
print(begin)
def division_option(*args):
return first_number / second_number
begin = " "
while begin:
print("Hello, I am calculator. ")
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\nChoose your option (+, -, *, /): ")
print(body_cycle(first_number, second_number, option))
ask = " "
while ask:
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'? \nChoice: ")
if exit_or_continue == "Y" or "y":
print("OK")
elif exit_or_continue == "N" or "n":
#break
ask == False
else:
print("Break program. ")
break
You just want to replace ask == False by ask = False.
In addition, you could really use a simpler code structure. The whole thing before begin can be compacted down to:
def operation(a, b, option):
if option == "+":
return a + b
elif option == "-":
return a - b
elif option == "*":
return a * b
elif option == "/":
try:
return a / b
except ZeroDivsionError
return "YOU CANNOT DIVIDE BY ZERO!"
The rest can be put in a single loop instead of two, like so:
print("Hello, I am calculator. ")
while True:
print("Please, enter your numbers (just integers) ! ")
print()
first_number = int(input("First number: "))
print()
second_number = int(input("Second number: "))
print()
option = input("Remember: you can't divide by zero.\n
Choose your option (+, -, *, /): ")
# Result.
print(operation(first_number, second_number, option))
exit_or_continue = input("If you want continue press 'Y', 'y'. For break press 'N' or 'n'.\n
Choice: ").lower()
if exit_or_continue == "y":
print("OK")
elif exit_or_continue == "n":
break
Its showing"line 42, in
if input_ !='no':
NameError: name 'input_' is not defined" error when i input 'no'
The code is :
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
input_=input(y+z+"?")
if input_ == "no":
return
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
How can i rectify it? (this is just a small part of the entire program but i think this should do...)
Variable input_ is initialised inside function rock_paper_scissors() which means outside of it (function scope) is undefined. So we need to put it inside function or make input_ global.
def rock_paper_scissors():
comp_score = your_score = 0
y, z = "This is a rock paper scissors game. ", "Do you wish to play"
x= ["rock", "paper", "scissors"]
input_=input(y + z + "?")
if input_ == "no":
return
else: # no need for: if input_ != "no"
a = input("Do you wanna play again?")
rock_paper_scissors()
Hope this helps.
Here is my take on it, still needs some work, it functional...
# Tested via Python 3.7.4 - 64bit, Windows 10
# Author: Dean Van Greunen
# License: I dont care, do what you want
####################################
# Some Defines
####################################
# imports
import random
# global vars
comp_score = 0
your_score = 0
input_ = ''
ai_input = ''
# strings
string_1 = 'This is a rockpaper scissors game.'
question_1 = 'Do you wish to play? '
question_2 = 'Enter your move: '
question_3 = 'Do you wanna play again? '
string_4 = 'Valid Moves: '
string_5 = 'Thank you for playing!'
string_6 = 'Scores: Player {0} V.S. AI {1}'
yes = 'yes'
no = 'no'
# vaild moves
moves = ["rock","paper","scissors"]
####################################
# Code Setup
####################################
def displayWinner(player_move_str, ai_move_str):
# Vars
winner = ''
tie = False
# Winner Logic
if player_move_str == ai_move_str:
tie = True
elif player_move_str == 'paper' and ai_move_str == 'rock':
winner = 'Player'
elif player_move_str == 'scissor' and ai_move_str == 'rock':
winner = 'AI'
elif player_move_str == 'rock' and ai_move_str == 'paper':
winner = 'AI'
elif player_move_str == 'scissor' and ai_move_str == 'paper':
winner = 'Player'
elif player_move_str == 'rock' and ai_move_str == 'scissor':
winner = 'Player'
elif player_move_str == 'paper' and ai_move_str == 'scissor':
winner = 'AI'
# display Logic
if tie:
print('It Was A Tie!')
else:
global your_score
global comp_score
if winner == 'AI':
comp_score = comp_score + 1
elif winner == 'Player':
your_score = your_score + 1
print(winner + ' Won!')
def start():
global your_score
global comp_score
print(string_1)
print(string_6.format(your_score, comp_score))
input_ = input(question_1)
if input_ == yes:
print(string_4)
[print(x) for x in moves]# make sure input is valid.
input_ = input(question_2)
ai_input = random.choice(moves) # let AI pick move
print('AI Picked: ' + ai_input)
displayWinner(input_, ai_input)
input_ = input(question_3) # Play Again?
if input_ == yes:
start() # Restart Game (Recursive Call)
else:
print(string_5) # Thank you Message
####################################
# Game/Script Entry Point/Function
####################################
start()
Thanks yall. Fixed my program. Now it goes like:
import time
import random
input_ =""
def rock_paper_scissors():
comp_score = your_score = 0
y,z="This is a rockpaper scissors game. ","Do you wish to play"
x= ["rock","paper","scissors"]
global input_
input_=input(y+z+"?")
if input_ == "no":
return
max_score=("Enter max score : ")
while True:
input_=input("Enter your choice among rock, paper and scissors ('stop' to
quit):")
if input_ not in x and input_!='stop'and input_ != 'enough':
print("Invalid answer. Are you blind? Pick one from the 3.")
continue
n = random.randint(0,2)
k=x[n]
if n<2:
if input_==x[n+1]:
your_score+=1
elif input_==k:
pass
else:
comp_score+=1
else:
if input_=="paper":
comp_score+=1
elif input_=="rock":
your_score+=1
elif input_=="scissors":
pass
else:
pass
if input_!="stop" and input_ != "enough":
print(3)
time.sleep(1.5)
print(2)
time.sleep(1.5)
print(1)
time.sleep(1.5)
print("Your choice : "+input_ +"\nComputers move : "+k)
elif input_=="stop" and input_=="enough":
input_=input("Play again?")
if (your_score == max_score or comp_score==max_score) or (input_=="stop"
or input_=="enough"):
print("Your score is : ",your_score)
print("AI's score is : ",comp_score)
break
rock_paper_scissors()
if input_ !='no':
a=input("Do you wanna play again?")
if a =="yes":
rock_paper_scissors()
print("k.bye! \n :(")
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
play_func()
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append()
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
I think the problem is here:
besides from no
if secret_word[x] == guess:
guess_word[x] == guess
print(guess_word)
if not '-' in guess_word:
print('You Won!')
break
else:
print('The letter is not in the word. Try Again!')
guess_taken += 1
if guess_taken == 8:
print('You Lost, the secret word was: ', secret_word)
change()
guessing()
print('Game Over!')
if secret_word[x] == guess:
guess_word[x] == guess
I think the problem is on these lines of code because they don't actually replace guess_word
This should hopefully get you on the right track. I just created a new method/function to contain all of your other functions, and fixed the append statement. Good Luck!
import random
import sys
word_list = ['zebra', 'memory']
guess_word = []
secret_word = random.choice(word_list)
lenght_word = len(secret_word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
letter_storage = []
def main():
play_func()
change()
guessing()
def play_func():
print('Great moment to play HANGMAN!')
while True:
game_choice = input('Do you want to play? ').lower()
if game_choice == 'yes' or 'y':
break
elif game_choice == 'no' or 'n':
sys.exit('That is a shame! BYE!')
else:
print('Please answer only Yes/y or No/n')
continue
def change():
for character in secret_word:
guess_word.append("-")
print('The word you need to guess has', lenght_word, 'characters')
print('Be aware that you can only enter 1 letter from a-z')
print('If you want to exit type quit')
print(guess_word)
def guessing():
guess_taken = 0
while guess_taken < 8:
guess = input('Pick a letter: ').lower()
if guess == 'quit':
break
elif not guess in alphabet:
print('Enter a letter from a-z')
elif guess in letter_storage:
print('You have already guessed that letter')
else:
letter_storage.append(guess)
if guess in secret_word:
print('You guessed correctly!')
for x in range(0, lenght_word):
print(x)
main()
Here is my code (for hangman game):
import random, os
def main():
print("******THIS IS HANGMAN******")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["school", "holiday", "computer", "books"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, x in enumerate(word):
if x == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print('You won')
elif choice == "2":
os.system("cls")
main()
else:
print("that is not a valid option")
main()
I have tried os.system("clear") but it doesn't clear the screen, I want it to clear the entire screen but instead (cls) makes it print my menu again and (clear) does nothing except clear the 2. If I'm missing something obvious it's probably because I'm new to python.
It prints the menu again because you call main() again instead of just stopping there. :-)
elif choice == "2":
os.system("cls")
main() # <--- this is the line that causes issues
Now for the clearing itself, os.system("cls") works on Windows and os.system("clear") works on Linux / OS X as answered here.
Also, your program currently tells the user if their choice is not supported but does not offer a second chance. You could have something like this:
def main():
...
while True:
choice = input("Please enter option 1 or 2")
if choice not in ("1", "2"):
print("that is not a valid option")
else:
break
if choice == "1":
...
elif choice == "2":
...
main()
I'm practicing conditionals and logical operators.
How do I make the following rock, paper, scissors game print "This is not a valid object selection." immediately after Player 1's input, if Player 1 enters an invalid object? Right now the string is not printed until both players have entered an object.
Also, any suggestions for making the following code more elegant?
player1 = input('Player 1? ')
player2 = input('Player 2? ')
if (player1.lower() == 'rock' and
player2.lower() == 'rock'):
print('Tie.')
elif (player1.lower() == 'rock' and
player2.lower() == 'paper'):
print('Player 2 wins.')
elif (player1.lower() == 'rock' and
player2.lower() == 'scissors'):
print('Player 1 wins.')
elif (player1.lower() == 'paper' and
player2.lower() == 'paper'):
print('Tie.')
elif (player1.lower() == 'paper' and
player2.lower() == 'scissors'):
print('Player 2 wins.')
elif (player1.lower() == 'paper' and
player2.lower() == 'rock'):
print('Player 1 wins.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'scissors'):
print('Tie.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'rock'):
print('Player 2 wins.')
elif (player1.lower() == 'scissors' and
player2.lower() == 'paper'):
print('Player 1 wins.')
else:
print('This is not a valid object selection.')
How about a function to ask each player their choice? Only if the player enters a valid selection will they be allowed to proceed through the code to your logic statements.
def get_choice(Player_number):
print('Player', Player_number, 'please enter your choice: ', end='')
while True:
choice = input().lower() #lower converts input to all lowercase
if choice in ('rock', 'paper', 'scissors'): # check if valid choice
return choice # if valid return choice
else:
print('Incorrect choice, try again: ', end='') # else print this and start loop agan
player1 = get_choice('1')
player2 = get_choice('2')
For the logic part, note that if player1 choice == player 2 choice, this will substitute 3 elif blocks in your code, ie.
if player1 == player2:
print('tie')
Now replaces pl==rock and p2 == rock, p1 == scissors and p2 == scissors, ect.
edit:
1) The problem if you move the print statement in 2 to inside the input in 4 is you can no longer specify the ,end='' parameter, as it does not work with input. As you said it will generate SyntaxError. The code looks much cleaner when run this way in terminal as it all lines up, but do test it for yourself.
2) end='' prints an empty string at the end of the print statement. you are confusing this with end='\n' which prints a new line after print. As my way keeps the cursor on the same line after the print, it lines up with the input to make it look nice, see above question. Note the print statement in python by default passes , end='\n'. This is why
print('hello') #same as print('hello', end='\n')
print('world)
hello
world
print('hello', end='')
print('world', end='')
helloworld
3) The while True loop will alway evaluate to true. So the body of the while loop will constantly cycle - However, it can return out of the entire function with the 'return choice' function. The only way to leave this function if to get down the logical steps required to reach the return statement. In this case unless the choice is in that tuple('rock', 'paper', 'scisors') it will just print invalid entry try again, finishing the block. However, As while is still true the loop will begin again and ask the user to input again. This will repeat until a valid choice is selected.
4) You could concatenate it onto the player_number eg..
print('Player', Player_number + ',' , 'please enter your choice: ', end='')