Neural Sports

ABOUTARTICLES

Python CheatSheet

May 13, 202010 min read

To be able to get started with the many tutorials/fun articles coming your way I thought I should associate you peeps with the main programming language we’ll be using - Python. This isn’t a full-length tutorial but more of a cheat sheet that will help you get going as the best way to learn is to honestly programme. Play around with the language, fail with the language, and then learn how it failed. It can be a frustrating journey but don’t sweat it, everyone has them ‘I want to throw this laptop out the window’ moments, even those working at Google. (Disclaimer I don’t know if those at Google actually do this, plz don’t sue me)

I will start by listing the basic properties of Python but important when comparing to other languages such as Java, C++, etc and how it works under the hood. When I go into a certain aspect of the language if I feel there is certainly a more advanced way of doing something I will link you to a brilliant tutorial where you can explore further because I know you’ll be flicking around tutorials and cheating on this page.

Properties


You will read a lot of malarky when googling about regarding Python. You will hear words being tossed around that they just assume you will understand and move onto to the next topic with you more baffled than ever. So what the f do we mean when we talk about properties of a programming language? The properties are basically the traits of a language, what characteristics does a language have. Before we get started let me define a variable that you will see popping up a lot below - variable is a value that can change and have something assigned to it eg) basketball = 'ball'.

  • Python is strongly typed - This means if you assign a string (‘123’) to a variable then it stays a string (‘123’) and will not change. It does not convert to a number (123) for example, (notice the quotation marks to make it a string). In order to convert a string to a number, you need to explicitly convert it yourself.
  • Python is dynamically typed - Basically meaning we do not have to assign a type to a variable. For example, if we were writing a programme to add the number of shots made during a weekend in the premier league season we would have to add every shot each team made together. So we’d say in Python, arsenal = 3, chelsea = 5 etc etc. BUT in Java, for example, we’d need to state what type of variable arsenal or chelsea is like so int arsenal = 3, int chelsea = 5. The int short for integer means arsenal can only hold an integer. Whilst in Python we do not have to do that. Python automatically recognises that type at runtime.
  • Python is case sensitive - Meaning if I wanted to assign how many shots taken by a team, manchesterunited = 9 and MANCHESTERUNITED = 9 are two DIFFERENT variables and can be used in two different ways.
  • Python is object orientated - You may see this term ‘object orientated’ tossed around and have no idea what it means. Basically it means everything is an object but most importantly there are four principles to object-orientated programming and if you’re interviewing for a junior level job you should probs know these.

    • Encapsulation - When creating classes in Python you can restrict access to methods and variables that you do not want to be manipulated or changed. So the variable or method can only be called within the class and not outside. Hence it is encapsulated within the class.
    • Abstraction - Abstraction is all about easing how a Class for example is used. Say we make a class for scoring a goal in football (soccer ball). By implementing abstraction we only want to expose the public methods that make it simple to understand. This mechanism should hide the internal implementation details. It should only reveal operations relevant to the other objects. For example, you can score through heading the ball, left foot, or right foot. But the mechanics of how you do that via pulling your neck back to generate power in the header, lifting your arm up in a David Beckham-esque way should be hidden because other objects may only want to know how they scored.
    • Inheritence - Probably the simplest and means that you create a (child) class by deriving from another (parent) class. In such a way that we form a hierarchy. For example, my parent class may be HockeyTeam and may contain a badge variable, a team name variable and a location variable. These variables are common among all teams. Then my child class BostonBruins would inherit all these variables from my parent class HockeyTeam.
    • Polymorphism - What a complicated word, sounds like a Pokemon. Polymorphism means the ability to take various forms. In Python, Polymorphism allows us to define methods in the child class with the same name as defined in their parent class. If we had a parent class called Scoring and a method called score and a child class called Football that inherits Scoring but also has a method called score as there score method is different to the one defined in Scoring when Football is called Python recognise that score has been overridden and use that method instead of the pre-defined one in the Parent class.

That was a lot for properties. But knowing these concepts will bode you well in interviews down the line and understanding the ins and outs of Python.

Hello World


What could be more classic than the classic programming introduction?

print("hello world")

Variables & Data Types


Numbers

arsenal = 3 # Integer total number of shots
chelsea = 2.345 # Float/Decimal used for averag shots
liverpool = 1e3 # Scientific notation equivalent to 10^3 = 1000.0

Mathematical Operations

arsenal = 10 # Hashtags allow you to leave comments
man_city = 5 # You can not have spaces in variables
addition = arsenal + man_City # 15
division = arsenal / man_city # 5
multiplication = arsenal * man_city # 50

Read more here

Strings

team_a = "Boston Celtics"
team_b = "Los Angeles Lakers"

Read more here

Booleans

is_mj_the_goat = True
is_lebron_the_goat = False

Read more here

Data Structures


List, Tuple & Set

champions_league_winners = ['celtic', 'liverpool', 'real madrid']  # List
never_won_a_champions_league = ('manchester city', 'psg', 'atletico madrid')  # Tuple, similar to List but immutable
never_won_an_mvp = {"jerry west", "dwayne wade", "scottie pippen"}  # Set of unique items/objects

A list, tuple, and set are all iterable which means we can loop over each one. Notice how each structure uses a different type of bracket too. When we say a tuple is immutable we mean it cannot be modified after it is created. Within a set, you cannot change what is currently in it but you can add to it.

Dictionary

barcelona_information = {"name": "Barcelona FC", "goals_scored": 100} # Key: Value pair

Iterables


List

Lists can hold multiple data types.

random_data_types = [1, "LA Chargers", 9.34, True]

If I want to access a certain element in that list I would use indexing. Each element in the list had an index starting from 0.

random_data_types[0] # 1
random_data_types[1] # LA Chargers
random_data_types[2] # 9.34
random_data_types[3] # True

If you want to add to a list we use append()

random_data_types.append("New England Patriots" )# [1, "LA Chargers", 9.34, True, "New England Patrios"]

Read more here.

Tuple

golfers = ('Tiger Woods', 'Phil Mickleson')

Why tuples over lists? Program execution is normally faster when manipulating a tuple than it is for a list and sometimes you just don’t want data to be modified.

Read more here.

Set

A set contains unordered unique items.

atlanta_hawks_set = set('atlanta') # atlanta_hawks_set = {'a', 't', 'l', 'a', 'n', 't', 'a'}

You can create a set from a list.

set_from_list = set([1, "LA Chargers", 9.34, True]) # set_from_list = {True, 9.34, "LA Chargers", 1}

Read more here.

Dictionary

A dictionary is a collection

barcelona_information = {"name": "Barcelona FC", "goals_scored": 100}
barcelona_information['name'] # Barcelona FC
barcelona_information['goals_scored'] # 100

To check if a key exists in a dictionary.

'name' in barcelona_information # True

Logical Operators


epl_teams = ['chelsea', 'arsenal', 'man_united', 'spurs']
'spurs' in epl_teams # True
'fulham' in epl_teams # False
'fulham' not in epl_teams # True

Read more here.

Conditional Statements


If, Elif & Else

celtic_wins = 50
rangers_wins = 20
if celtic_wins > rangers_wins: # 50 > 30
    print('celtic wins are more than rangers')
elif celtic_wins == 49:
    print('celtic wins are equal to 49')
else:
    print('celtic wins are less than 49')

# in this case 'celtic wins are more than rangers' will be printed

Read more here.

Loops


for shots in range(1,10):
    print(shots) # will print numbers from 1 to 9 not including 10

epl_teams = ['chelsea', 'arsenal', 'man_united', 'spurs']
for team in epl_teams:
    print(team) # will print each epl_teams from the list above

mj_is_the_goat = True
while mj_is_the_goat:
    print('lebron never will be') # this will continually print 'lebron never will' until the condition is_mj_the_goat becomes false

points = 1
while points < 5:
    print('game continues') # will print 'game continues' until points are no longer less than 5
    points = points + 1

Read more here.

Functions


To be able to define a function you need to use the def keyword and then whatever you want to call the function.

def hello_world():
    print("Hello World")

def your_sport_team(team_name):
    print(team_name)

your_sport_team('real madrid') # prints 'real madrid'

Read more here.

Classes and Objects


class Team(object):
    def print_team(self):
        print('This is a method in a class')

miami_heat = Team()
print(miami_heat.print_team)
# this accesses the print_team method.
# prints out 'this is a method in a class'.

class Team(object):    def __init__(self, name):        self.name = name        def team_name(self):            print(f'this is the team name - {self.name}')
denver_nuggets = Team('Denver Nuggets')
print(denver_nuggets.name) # Denver Nuggets

Classes can be confusing, so let me explain what you see in the second Team class. The __init__ method can be thought of as an initialisation of the class, the create term being a constructor. This method is called straight away when a class is created or ‘initialised’.

We use the term self as it represents the instance of the class. By using self we can access attributes and methods of the class in Python.

MicroPyramid has a great article explaining Classes in Python in more depth here. Read more here too.

Summary


We hope this short summary gave you some insight into how Python works and the very basics of the syntax that should be enough for anyone to start following along with any tutorials or blog posts Neural Sports posts from here on out. I must stress that this is the bare minimum to get you up and running with understanding the language and please do check out the links posted with each section for further insight.

But this is dope, right? You’ve just started your journey into software development and the open, never-ending world that comes with it. Don’t be overwhelmed Neural Sports is here to help that journey be a little easier with interesting, ‘what the hell I didn’t know that was possible’ like articles and tutorials!

P.S We have heavily linked a lot of Programiz articles but only because we feel they’re some of the best out there for Python.


Developed by Sean O'Connor, a sports and AI enthusiast.