Jump to content

Python Functions Help

Aspect11

Hi, so i am trying to make a code, but it is returning an error, what is wrong with it?

 

import random

user1Score = 0
user2Score = 0
user1Total = 0
user2Total = 0

def rollDieWithPoints():
        user1Roll1 = random.randint(1,6)
        user1Roll2 = random.randint(1,6)
        user2Roll1 = random.randint(1,6)
        user2Roll2 = random.randint(1,6)
        print("user1roll1=", user1Roll1)
        print("user1roll2=", user1Roll2)
        print("user2roll1=", user2Roll1)
        print("user2roll2=", user2Roll2)
        user1Total = user1Roll1 + user1Roll2
        user2Total = user2Roll1 + user2Roll2
        print(user1Total)
        print(user2Total)
        def user1Points():
            if (user1Total % 2 == 0):
                user1Score = user1Score + 10
            elif (user1Total % 2 != 0):
                user1Score = user1Score - 5
            print(user1Score)
        def user2Points():
            if (user2Total % 2 == 0):
                user2Score = user2Score + 10
            elif (user2Total % 2 != 0):
                user2Score = user2Score - 5
        user1Points()
        user2Points()
        
def authentication():
        user1 = input("User one, please enter your password (R£m£dy21): ")
        user2 = input("User two, please enter your password (Pa$$12345!): ")
        if user1 == "R£m£dy21" and len(user1) == 8:
                if user2 == "Pa$$12345!" and len(user2) == 10:
                        rollDieWithPoints()

def start():
        authentication()
        rollDieWithPoints()

start()

The error it returns is:

Traceback (most recent call last):
  File "D:\School Stuff\Work\Year 11\School Work\Computer Science\NEA\NEA Coursework.py", line 46, in <module>
    start()
  File "D:\School Stuff\Work\Year 11\School Work\Computer Science\NEA\NEA Coursework.py", line 43, in start
    authentication()
  File "D:\School Stuff\Work\Year 11\School Work\Computer Science\NEA\NEA Coursework.py", line 40, in authentication
    rollDieWithPoints()
  File "D:\School Stuff\Work\Year 11\School Work\Computer Science\NEA\NEA Coursework.py", line 32, in rollDieWithPoints
    user1Points()
  File "D:\School Stuff\Work\Year 11\School Work\Computer Science\NEA\NEA Coursework.py", line 23, in user1Points
    user1Score = user1Score + 10
UnboundLocalError: local variable 'user1Score' referenced before assignment

Please help me.

 

Thanks!

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

When updating global variables in python you need to declare them as global inside the functions that use them.

 

https://stackoverflow.com/a/423596/4153995

 

Don't use global variables though - just pass the values to the function as a parameter and return the new value. Also, there's no reason to declare user1Points() inside the other function; it's just messy and bad style.

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, Sauron said:

When updating global variables in python you need to declare them as global inside the functions that use them.

 

https://stackoverflow.com/a/423596/4153995

 

Don't use global variables though - just pass the values to the function as a parameter and return the new value. Also, there's no reason to declare user1Points() inside the other function; it's just messy and bad style.

How would i do that if i wanted to add to a variable inside the function, for example at 'user1Score = user1Score + 10'?

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, DerpDiamonds1 said:

How would i do that?

Which part? For the global variables, just read the link to stackoverflow - as for passing arguments to functions and returning values, you just need to declare them like so:

def function(argument1, argument2, argument3):
	...
    return returnvValue

 

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

33 minutes ago, Sauron said:

Which part? For the global variables, just read the link to stackoverflow - as for passing arguments to functions and returning values, you just need to declare them like so:


def function(argument1, argument2, argument3):
	...
    return returnvValue

 

Thanks, I'll look at it tomorrow as I am going out now!

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

You didn't ask for this but I wanted to see how I would tackle something like this and this is what I came up with.

 

Adding new players is simple by adding a new string to the users list, changing the dice size is done by changing the range in rollDice and change the scoring in get score. changing either of these does not affect any other function as the output is the same (assuming you keep it that way) and as @Sauron suggested no global variables.

 

Plus is super neat and easy to read. I didn't do the password part though.

 

You get an dictonary returns from play() that will look something like this

 


{'user1': 5, 'user2': 20}

 

The code

from random import randint 
from functools import reduce

def rollDice():
  return randint(1,6)

def getScore():
  diceRoll = rollDice()
  if(diceRoll % 2 == 0):
    return  10
  else:
    return -5

def calculateScore(x, y): 
  return x + y

def play(users, rolls = 2):
  results = {}
  for user in users:
    results[user] = reduce(calculateScore, [getScore() for n in range(0,rolls)])
  return results


users = ['user1', 'user2']
print(play(users, 2))

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

This is happening due to the redefinition of global variables inside of a function without specifying that they are a global variable first in the function.

e.g.

Quote

def myFunction():

    global var1, var2, var3, var...

    <then your code for the function can hide in here>

sorry for it not being the best example, im just too dead to beable to do anything else right now

Sadness is the one true emotion, and happiness, well, that's just a lie, sadness is all many of us feel, and is all we need to feel, because having it any other way, would just be wrong, why be happy when you can just be miserable like myself. 

Link to comment
Share on other sites

Link to post
Share on other sites

3 hours ago, Shoe_Eater said:

This is happening due to the redefinition of global variables inside of a function without specifying that they are a global variable first in the function.

e.g.

sorry for it not being the best example, im just too dead to beable to do anything else right now

Editing globals is a very bad practise and you should avoid it.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Thanks everyone, i will get back to you if i need any more help!

Specs:

Motherboard: Gigabyte Z97X Gaming 3

CPU: Intel Core I7 4790K

GPU: Gigabyte G1 Gaming GTX 970

RAM: HyperX Fury 16GB

HDD: Seagate ST3000DM001 3TB

SSD: KINGSTON SV300S37A480G 450GB

Cooler: Corsair H100i GTX

Case: NZXT H440 Red

Monitor: DELL U2412M

Keyboard: Gigabyte Force K7

Mouse: Corsair Sabre RGB

 

Link to comment
Share on other sites

Link to post
Share on other sites

On 12/19/2018 at 9:13 AM, DerpDiamonds1 said:

-Snip-

You didn't comment your code! The instructor gonna be mad!

 

As others have stated I feel you are putting way too much into a single function. You need to break it up more and then just call on those functions as needed.

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, AngryBeaver said:

You didn't comment your code! The instructor gonna be mad!

 

As others have stated I feel you are putting way too much into a single function. You need to break it up more and then just call on those functions as needed.

If you get pulled up for no comments you simply say

 

"Code is like a joke, if you have to to explain it it's not very good"

 

The code I posted is perfectly read able and understandable without a single comment 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, vorticalbox said:

If you get pulled up for no comments you simply say

 

"Code is like a joke, if you have to to explain it it's not very good"

 

The code I posted is perfectly read able and understandable without a single comment 

While this may be true... we are still probably talking about a college course here and they teach you to comment code for a reason. Now from the security side of things that can be a major PITA when we have to audit code/comments.

 

I don't do a ton of coding/scripting, but I can if needed. I just don't do it as a profession, but instead to just enhance and automate for my current role. That being said for someone like me if I write something and come back to it 4+ months later it will take me much longer than I want to admit to remember wtf I was doing and how I did it. So for me that commented code helps a ton to get back on track and modify or change something in it.

 

So if you are on a team of coders and writing code for a big project with others then comments become even more valuable. It lets other people understand what you were doing as well as anyone who needs to mess with it in the future. There isn't a single right way to do things most of the time.

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, AngryBeaver said:

While this may be true... we are still probably talking about a college course here and they teach you to comment code for a reason. Now from the security side of things that can be a major PITA when we have to audit code/comments.

 

I don't do a ton of coding/scripting, but I can if needed. I just don't do it as a profession, but instead to just enhance and automate for my current role. That being said for someone like me if I write something and come back to it 4+ months later it will take me much longer than I want to admit to remember wtf I was doing and how I did it. So for me that commented code helps a ton to get back on track and modify or change something in it.

 

So if you are on a team of coders and writing code for a big project with others then comments become even more valuable. It lets other people understand what you were doing as well as anyone who needs to mess with it in the future. There isn't a single right way to do things most of the time.

At work comments on code are very rare, as we code in type script/ node writing type definitions is a far better way to "comment" code.

 

Knowing what the input should be and what you get as an output.

 

I would not approve code in a pull request that did comments unless there is a reason for example, not using arrow functions to node so that this isn't over written in things like mongoose schemas, where you want this to reference the model and not the context of the function.

 

Or some super complicated function however, even then documentation, I feel, is a far better why than comments.

 

It is always good to document your software even if it is only for you.

 

In python you can use doc strings for this.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

From my understanding, Global Variables in Python behave somewhat differently, so now I just use function specific variables and only use global variables where I absolutely need to. Still learning.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×