Python Forum
Hey guys can you please help me with some basic coding
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Hey guys can you please help me with some basic coding
#1
I am a beginner so please take it easy on me lol. I made a simple rock paper scissor game. I want it to loop until the user or the computer gets to a score of 10. But I can't figure out how to get it to stop at 10. I get why it doesn't I just can't figure out how to fix it. I tried returning comp and user after adding 1 in my if and elif statements but that just broke the loop. I get an error if I set the user and comp outside the game function. I'm thinking I have make a separate function for the score maybe? Would love a fix just so I can see the proper way to do it. Thanks guys!


import random





def game():
    user = 0
    comp = 0
    while (user or comp < 10):
        which = random.randint(1, 3)
        if which == 1:
            which = "rock"
        elif which == 2:
            which = "paper"
        elif which == 3:
            which = "scissor"
        usome = input("rock paper or scissor")
        if usome == 'rock' and which == 'rock':
            print("Computer choose",which)
            print("Tie")
            print("Score is user:",user,"comp:",comp)
        elif usome == 'paper' and which == 'rock':
            print("Computer choose", which)
            print("User wins")
            user = user + 1
            print("Score is user:", user, "comp:", comp)
        elif usome == 'scissor' and which == 'rock':
            print("Computer choose", which)
            print("Computer wins")
            comp = comp + 1
            print("Score is user:", user, "comp:", comp)
        elif usome == 'scissor' and which == 'scissor':
            print("Computer choose", which)
            print("Tie")
            print("Score is user:", user, "comp:", comp)
        elif usome == 'paper' and which == 'scissor':
            print("Computer choose", which)
            print("Computer wins")
            comp = comp + 1
            print("Score is user:", user, "comp:", comp)
        elif usome == 'rock' and which == 'scissor':
            print("Computer choose", which)
            print("User wins")
            user = user + 1
            print("Score is user:", user, "comp:", comp)
        elif usome == 'scissor' and which == 'paper':
            print("Computer choose", which)
            print("User wins")
            user = user + 1
            print("Score is user:", user, "comp:", comp)
        elif usome == 'rock' and which == 'paper':
            print("Computer choose", which)
            print("Comp wins")
            comp = comp + 1
            print("Score is user:", user, "comp:", comp)
        elif usome == 'paper' and which == 'paper':
            print("Computer choose", which)
            print(" Tie")
            print("Score is user:", user, "comp:", comp)
        else:
            print("Invalid input")
game()
Reply
#2
Your while condition is checking user and that comp is less than 10. User will evaluate to True if it is non-zero. So as soon as the user wins a game, the user variable evaluates as True. If either side of the 'or' evaluates as True, the whole thing evaluates as True. So as soon as the user wins a game, the loop will never stop.

If you just want it to end after the computer wins ten games, take out the user and leave it as while comp < 10:.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(Jul-15-2017, 01:33 PM)ichabod801 Wrote: Your while condition is checking user and that comp is less than 10. User will evaluate to True if it is non-zero. So as soon as the user wins a game, the user variable evaluates as True. If either side of the 'or' evaluates as True, the whole thing evaluates as True. So as soon as the user wins a game, the loop will never stop.

If you just want it to end after the computer wins ten games, take out the user and leave it as while comp < 10:.

Thanks for the help! So the 'or' in the while loop messed it up somehow. What I don't get is how though. I know you tried to explain it but I'm not following. So my code reads as 'while user or comp is under 10 run the loop' right. So why wouldn't it stop once user or comp gets to 10? Like you said, it works when you just use 'comp < 10' or 'user < 10'. I'm not understanding why it can't check for either or. Is there a way to set it to check for either or?
Reply
#4
Oh, I see what you were trying to do now. I should have read that more carefully. Less than and or are both operators. Less than has higher precedence than or, so it evaluates first. That leaves user on one side of the or, and the result of comp < 10 on the other. If you want to test either one being less than 10, you need two less thans: while user < 10 or comp < 10:. However, that will run until they both have at least 10 wins (as long as one of them is less than 10, one True will make the whole thing True). I think what you really want is while user < 10 and comp < 10:. Then as soon as either one gets a tenth win, the loop will stop.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
(Jul-15-2017, 08:32 PM)ichabod801 Wrote: Oh, I see what you were trying to do now. I should have read that more carefully. Less than and or are both operators. Less than has higher precedence than or, so it evaluates first. That leaves user on one side of the or, and the result of comp < 10 on the other. If you want to test either one being less than 10, you need two less thans: while user < 10 or comp < 10:. However, that will run until they both have at least 10 wins (as long as one of them is less than 10, one True will make the whole thing True). I think what you really want is while user < 10 and comp < 10:. Then as soon as either one gets a tenth win, the loop will stop.

Ah that makes sense. Thanks!
Reply
#6
Another way to explain it, and the way I finally understood it when first learning logic circuits: Or means "any must be," and means "all must be." In your case, no matter how many are > 10, as long as any is <10, "or" comes out to <10.

Related question, while [b](user or comp < 10)[/b] does this create a tuple? and why will it work with or without the ()?
Reply
#7
(user or comp < 10) does not create a tuple. To create a tuple, you need a comma between the parentheses. If you want to create a tuple of length one, you add what looks like an extra comma: (user or comp < 10,) would create a tuple. If it's not a tuple, the parentheses are removed after everything inside it resolves, but before resolving anything else. So they are not necessary like they are in some languages, but if they are there they just go away as the final part of the calculation. If you did make that tuple by putting a comma in there, the loop would never end. It would always be a tuple of length one, either (True,) or (False,), and tuples only resolve to False if they are empty. Even if all they have in them is a False, the tuple still is counted as True.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
Thanks for the clarification on that ichabod. It is very helpful with reading code understanding the syntax and style.

Quote:I get an error if I set the user and comp outside the game function.
def fn1():
   user,comp = 1,2
   print(j)
   return x,y,z

def fn2():
   j = 'outside function'
  return j

fn2()
fn1()
print(user,comp)
If you run this, you will get an error that "j" isn't defined. Even though in fn2() it is. The reason is because variables are only defined in the function. The variable "j" in fn2() is a different variable than the "j" in fn1(). return j means that the value is available to be called in global or different functions. Once you define j in fn1(), the same thing will happen with user and comp since I never defined them at global and never defined them by calling their values from fn1().
If you failed to define user and comp in game() by calling the values ala user, comp = function_where_you_defined() or game(user,comp), you will get a trace back error.

Quote:I tried returning comp and user after adding 1 in my if and elif statements but that just broke the loop
Copied from the Python Doc 7.6. The return statement: "return leaves the current function call with the expression list (or None) as return value... In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised."

From what I understand, it's standard convention to define your primary function as main(). Doesn't mean you have to, but reviewers will understand that is the function that is the main purpose of your program. If you do decide to implement separate functions, it's something you'll want to remember.

I hope someone other than me learned something from this reply.
Reply
#9
You can just run all the other functions after the if __name__ = '__main__': statement but using a main() function allows your system to know the error of your program.
If there's any
def main()
   # the program

if __name__ = '__main__':
   sys.exit(main())
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#10
Hello. I am posting the Python 3 code for a rock, paper, scissors game which I have made, here. Some of you may find the differences interesting. Any questions please ask.

import random
import math
import time

UserChoice = ""
ComputerChoice = ""
mainMenu = 1
mainMenuChoice = ""

while mainMenu == 1 :
    print ("A ROCK, PAPER, SCISSORS GAME BY ME IN PYTHON")
    print ("HIT Y TO START")
    mainMenuChoice = input()
    mainMenuChoice = mainMenuChoice.upper()
    if mainMenuChoice == "Y" :
        mainMenu = 0
    

ComputerChoice = random.randint(1,3)

if ComputerChoice == 1 :
    ComputerChoice = "ROCK"

if ComputerChoice == 2 :
    ComputerChoice = "PAPER"

if ComputerChoice == 3 :
    ComputerChoice = "SCISSORS"

while UserChoice != "ROCK" and UserChoice != "PAPER" and UserChoice != "SCISSORS" :
    print("Please type ROCK, PAPER OR SCISSORS")
    UserChoice  = input()
    UserChoice = UserChoice.upper()

def DiceRolling (ComputerChoice, UserChoice) :
    print("ComputerChoice = " + ComputerChoice)
    Winner = ""
    if ComputerChoice != UserChoice :
        if ComputerChoice == "ROCK" :
            if UserChoice == "PAPER" :
                Winner = "User Won"
            else : Winner = "Computer Won"

        if ComputerChoice == "PAPER" :
            if UserChoice == "SCISSORS" :
                Winner = "User Won"
            else : Winner = "Computer Won"

        if ComputerChoice == "SCISSORS" :
            if UserChoice == "ROCK" :
                Winner = "User Won"
            else : Winner = "Computer Won"
    else : Winner = "Draw"
    return Winner

Winner = DiceRolling(ComputerChoice, UserChoice)
print (Winner)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic Coding Question: Exit Program Command? RockBlok 3 583 Nov-19-2023, 06:31 PM
Last Post: deanhystad
  guys please help me , pycharm is not able to identify my xlsx file CrazyGreenYT7 1 2,024 Jun-13-2021, 02:22 PM
Last Post: Larz60+
  hi guys, i'm back to learning python ! astral_travel 6 2,938 Oct-05-2020, 10:02 AM
Last Post: astral_travel
  Hi Guys, please help me to write SAS macro parameter equivalent code in Python Manohar9589 2 2,612 Jun-14-2020, 05:07 PM
Last Post: Larz60+
  [split] Very basic coding issue aary 4 2,484 Jun-03-2020, 11:59 AM
Last Post: buran
  Very basic coding issue mstichler 3 2,604 Jun-03-2020, 04:35 AM
Last Post: mstichler
  Basic example Coding gudlur46 2 2,065 Dec-19-2019, 01:55 PM
Last Post: gudlur46
  Could you guys help with this bug. I would post on StackOverflow but I got tempbanned ryder5227 2 2,398 Sep-26-2019, 08:01 PM
Last Post: metulburr
  Basic coding question with Python Than999 3 3,125 Jul-17-2019, 04:36 PM
Last Post: jefsummers
  Help Please guys AbuSiraj 2 2,690 Feb-14-2019, 09:29 AM
Last Post: AbuSiraj

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020