How to loop in a function, and keep taking inputs in python - python

So I was making a simple rock paper scissors game, and I wanted to put it as a function. I also wanted it to loop 10 times before deciding if the user won or lost. But the code just doesn't work and keeps giving random errors.
#code for rock paper scissors
import random
l = ["rock","paper","scissors"]
def rps():
q = 0
wincount = 0
while q < 10:
w = random.choice(l)
x = input("Choose rock paper or scissors all lowercase: ")
if w == "rock":
if x == "rock":
print("It's a draw")
if x == "paper":
print("You lost :(")
if x == "scissors":
print("You win!")
wincount += 1
elif w == "paper":
if x == "rock":
print("You lost :(")
if x == "paper":
print("It's a draw")
if x == "scissors":
print("You win!")
wincount += 1
elif w == "scissors":
if x == "rock":
print("You win!")
wincount += 1
if x == "paper":
print("You lost :(")
if x == "scissors":
print("It's a draw")
q += 1
if wincount >= 5:
print("You won the game!")
The error is
PS D:\project percy> & C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe "d:/project percy/cogs/asiufysduifhi.py"
PS D:\project percy> rps()
At line:1 char:5
+ rps()
+ ~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordE
xception
+ FullyQualifiedErrorId : ExpectedExpression```

The error seems not because of python. It should be because of Powershell.
PowerShell needs the ampersand to interpret the string as a filename.
As you are already using ampersand so not sure but try to run your command within proper quotes.
Like
& "C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe" "d:/project percy/cogs/asiufysduifhi.py"
Or if above wont works then give a try to this:
& "C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe" d:/project percy/cogs/asiufysduifhi.py

As others have said already, he error does not come from python but rather from powershell. I don't have windows to test but I think the problem is that you are trying to call rps() which is a python function, from the powershell prompt:
PS D:\project percy> & C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe "d:/project percy/cogs/asiufysduifhi.py"
Call your python file that defines the function BUT NEVER CALLS IT
PS D:\project percy> rps()
Try to execute a powershell command named rps, which might exist but should be called differently.
Proposed solution
Try to add rps() at the end of your python file:
def rps():
.....
if wincount >= 5:
print("You won the game!")
rps()

The problem is you forgot to pass the list to the function as well as calling the function.
try this:
# code for rock paper scissors
import random
l = ["rock", "paper", "scissors"]
def rps(l):
q = 1
wincount = 0
while q < 11:
w = random.choice(l)
print()
print(q, "time")
x = input(f" Choose rock paper or scissors all lowercase: ")
if w == "rock":
if x == "rock":
print("It's a draw")
if x == "paper":
print("You lost :")
if x == "scissors":
print("You win!")
wincount += 1
elif w == "paper":
if x == "rock":
print("You lost :")
if x == "paper":
print("It's a draw")
if x == "scissors":
print("You win!")
wincount += 1
elif w == "scissors":
if x == "rock":
print("You win!")
wincount += 1
if x == "paper":
print("You lost :")
if x == "scissors":
print("It's a draw")
q += 1
if wincount >= 5:
print("You won the game!")
calling = rps(l)

Related

Tricks and tips for beginners to shorten and simplify code

I am looking for ways to shorten and simplify my python code. Here is one example of one small rock/paper/scissors game I wrote earlier. The code kinda looks too long to me and I want to try to learn how to shorten my code.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
if game_limit == 5 and comp_wins > user_wins:
print("The game is over, YOU LOST!")
elif game_limit == 5 and comp_wins < user_wins:
print("The game is over, YOU WON!")
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "rock":
print("its a draw")
elif user_input == "rock" and comp_input == "paper":
print("You lose!")
comp_wins += 1
if user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "scissors" and comp_input == "scissors":
print("its a draw")
elif user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
if user_input == "paper" and comp_input == "rock":
print("You win")
user_wins += 1
elif user_input == "paper" and comp_input == "paper":
print("its a draw")
elif user_input == "paper" and comp_input == "scissors":
print("You lose!")
comp_wins += 1
Yes. You could simplify your logic by having compound and/or tests for the player and user. Following is a revised version of your code with some simplified logic.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
if game_limit >= 5: # Tweak
if comp_wins > user_wins:
print("The game is over, YOU LOST!")
break
if comp_wins < user_wins:
print("The game is over, YOU WON!")
break
else:
print("We go to sudden death!")
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors" or user_input == "paper" and comp_input == "rock" or user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "paper" or user_input == "paper" and comp_input == "scissors" or user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
else:
print("It's a draw")
This way all of the scenarios where the user can win are in one logical test and all of the scenarios where the computer can win are in another logical test. If neither test is true, then the default would have to be a draw.
Also, I tweaked game limit test because if the computer and user have the same score when the game limit is reached, the test result would be false and the game would then continue on and not stop. So there is a bit of additional code to handle a tie after five rounds.
Give that a try.

The terminal says that computer_choice doesn’t exist even though it does

WHile I was attempting a simple rock, paper scissors, I ran into this proble. When I execute the file and input the user_input, it says to me that the variable computer_choice doesn’t exist, even though it does exist. I would appreciate if someone could help me, thank you.
import random
user_wins = 0
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)
computer_choice = options[random_number]
print ("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors" :
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper" :
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_pick == "rock" :
print("You Won!")
user_wins += 1
continue
else:
print("You Lost!")
computer_wins += 1
continue
print("You won", user_wins,"times and the computer won", computer_wins, "times.")
print("Goodbye")
You have to be careful with indentation when using python:
import random
user_wins = 0
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
# not at this level
# at this level
random_number = random.randint(0, 2)
computer_choice = options[random_number]
print("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors":
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper":
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_choice == "rock": #not computer_pick
print("You Won!")
user_wins += 1
continue
Also you wrote computer_pick in line 31, probably you mean computer_choice

I have a bug in my program that I cannot figure out

So, I just recently started coding and decided to make a rock paper scissors game; However, my program has a bug where if the user enters "rock" the correct code block doesn't run. Instead it runs an else statement that's only meant to run when the user enters, "no". I tried using a while loop instead of just if else statements but it didn't make a difference.
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
user = str(input("Great, select Rock Paper or Scissors:"))
if q_1 != "yes":
if q_1 == comp:
print("Oh No, a Tie!")
elif q_1 == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif q_1 == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
else:
print("Ok :(")
There are a few issues with your code.
First of all your code only plays the game if the user doesn't enter "yes". You need to change if q_1 != "yes": to if q_1 == "yes":.
Secondly, your code asks the user to choose rock, paper or scissors regardless of whether they have said they want to play or not. Fix this by moving user = str(input("Great, select Rock Paper or Scissors:")) to under the if q_1 == "yes": if statement.
Thirdly, your code uses q1 instead of user as it should.
Here is how your code should look:
import random
q_1 = str(input("Hello, want to play Rock Paper Scissors?:"))
print()
# ^^adds an indent
rpc_list = ["rock", "paper", "scissors"]
comp = random.choice(rpc_list)
# ^^randomly selects r, p, or s
if q_1 == "yes":
user = str(input("Great, select Rock Paper or Scissors:"))
if user == comp:
print("Oh No, a Tie!")
elif user == "rock":
if comp == "paper":
print("I Win!")
else:
print("You Win!")
elif user == "paper":
if comp == "rock":
print("You Win!")
else:
print("I Win!")
else:
if comp == "rock":
print("I Win!")
else:
print("You Win!")
print("I played:",comp)
else:
print("Ok :(")

my rock paper scissors gives me nothing in output (python)

I am new to python and as a practice I'm trying to write a rock paper scissors with it.
I triple checked eth but i can't find the problem.
I'm using visual studio code console. the msvcrt is for "getch" and I'm not sure about about the random function syntax
problem: when you give it the input number, It doesn't do or write anything despite the program.
help me pleaaaaase.
import random
import msvcrt
##################################################
player_move = " "
system_move = " "
##################################################
def rand(system_move):
rn = random.randint(1, 3)
if rn == 1:
system_move = "Rock"
elif rn == 2:
system_move = "Paper"
elif rn == 3:
system_move = "Scissors"
else:
rand()
return system_move
##################################################
print("!!! Rock, Paper, Scissors !!!\n\n\n")
###################################################
def playermove(player_move):
print("What do you want to go with?\n1-Rock\n2-paper\n3-scissors\n")
temp = msvcrt.getch()
if temp == '1' or 1:
player_move = 'Rock'
elif temp == '2' or 2:
player_move = 'Paper'
elif temp == '3' or 3:
player_move = 'Scissors'
else:
print(f"invalid input {player_move}. Try again\n")
playermove()
return player_move
###################################################
pm = ' '
sm = ' '
rand(sm)
playermove(pm)
if pm== 'Scissors':
if sm == "Scissors":
print(f"System move: {sm}\nIt's a tie!\n")
elif sm == "Rock":
print(f"System move: {sm}\nSystem won!\n")
elif sm == "Paper":
print(f"System move: {sm}\nYou won!\n")
else:
print("Oops! Something went wrong.\n")
elif pm == "Paper":
if sm == "Scissors":
print(f"System move: {sm}\nSystem won!\n")
elif sm == "Rock":
print(f"System move: {sm}\nYou won!\n")
elif sm == "Paper":
print(f"System move: {sm}\nIt's a tie!\n")
else:
print("Oops! Something went wrong.\n")
elif pm == "Rock":
if sm == "Scissors":
print(f"System move: {sm}\nYou won!\n")
elif sm == "Rock":
print(f"System move: {sm}\nIt's a tie!\n")
elif sm == "Paper":
print(f"System move: {sm}\nSystem won!\n")
else:
print("Oops! Something went wrong.\n")
print("Press any key to exit...")
xyz = msvcrt.getch()
Well, the reason your code doesn't work is because you are not assigning the return value of your functions to any variable. To fix your code you need to do the following:
sm = rand(sm)
pm = playermove(pm)
In Python, passing an immutable object like string means that you cannot make any changes to it. As you're not using the passed value, your function's signature should actually look like this.
def rand()
def playermove()
After you do this, you'll see there are other things you need to fix in your code.
Try this code. Just replace snake, water, gun by rock, paper, scissors.
print(" \t\t\t Welecome to Snake , Water , Gun game\n\n")
import random
attempts= 1
your_point=0
computer_point=0
while (attempts<=10):
lst=["snake","water","gun"]
ran=random.choice(lst)
print("what do you choose snake, water or gun")
inp=input()
if inp==ran:
print("tie")
print(f"you choosed {inp} and computer guess is {ran}")
print("No body gets point\n")
elif inp=="snake" and ran=="water":
your_point=your_point+1
print(f"you choosed {inp} and computer guess is {ran}")
print("The snake drank water\n")
print("You won this round")
print("you get 1 point\n")
elif inp=="water" and ran=="snake":
computer_point = computer_point + 1
print(f"you choosed {inp} and computer guess is {ran}")
print("The snake drank water\n")
print("You Lost this round")
print("computer gets 1 point\n")
elif inp=="water" and ran=="gun":
print(f"you choosed {inp} and computer guess is {ran}")
your_point = your_point + 1
print("The gun sank in water\n")
print("You won this round")
print("you get 1 point\n")
elif inp == "gun" and ran == "water":
print(f"you choosed {inp} and computer guess is {ran}")
computer_point = computer_point + 1
print("The gun sank in water\n")
print("You Lost this round")
print("computer gets 1 point\n")
elif inp == "gun" and ran == "snake":
print(f"you choosed {inp} and computer guess is {ran}")
your_point = your_point + 1
print("The snake was shoot and he died\n")
print("You Won this round")
print("you get 1 point\n")
elif inp == "snake" and ran == "gun":
print(f"you choosed {inp} and computer guess is {ran}")
computer_point=computer_point+1
print("The snake was shoot and he died\n")
print("You Lost this round")
print("computer gets 1 point\n")
else:
print("invalid")
print(10 - attempts, "no. of guesses left")
attempts = attempts + 1
if attempts>10:
print("game over")
if computer_point > your_point:
print("Computer wins and you loose")
if computer_point < your_point:
print("you win and computer loose")
print(f"your point is {your_point} and computer point is {computer_point}")

My input sometimes takes multiple times for it to go in the if statements

I am attempting to make a basic rock, paper, scissors game. When I input either rock, paper, or scissors, I sometimes have to enter the same thing multiple times for it to continue to the if statements. See code below:
# Rock, Paper, Scissors
player_total = 0
computer_total = 0
def get_computer_hand():
choice = randint(1, 3)
if choice == 1:
return "scissors"
elif choice == 2:
return "paper"
else:
return "rock"
def ask_user():
global player_total
global computer_total
player = input("Enter your hand (stop to stop): ")
if player == "stop":
print("Computer had ", computer_total, "points, you had ", player_total, " points.")
exit(0)
computer = get_computer_hand()
if player == "rock":
if computer == "paper":
return "win"
elif computer == "scissors":
return "lose"
else:
return "tie"
elif player == "paper":
if computer == "paper":
return "tie"
elif computer == "scissors":
return "lose"
else:
return "win"
elif player == "scissors":
if computer == "scissors":
return "tie"
elif computer == "paper":
return "win"
else:
return "lose"
def count_winner():
global player_total
global computer_total
player_total = 0
computer_total = 0
while True:
outcome = ask_user()
if outcome == "win":
print("You won that one.")
player_total += 1
elif outcome == "lose":
print("Computer won that one.")
computer_total += 1
count_winner()
I expect it to work the first time and to continue as usual, but I can't seem to figure out why it just asks "Enter your hand (stop to stop): " instead sometimes when I enter either rock, paper, or scissors.
This is happening because there is a tie happening between the computer and the user. This could be fixed by adding the end with the code of
else outcome == "tie":
print("You have tied with the Computer!")
computer_total += 1
player_total += 1
This would add a point to both sides and if you don't want that just delete the last two lines of my code

Categories