简体   繁体   中英

How to loop in a function, and keep taking inputs in 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 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.

<\/blockquote>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM