Python Cheat Sheet (Read THIS one FIRST)

Python is one of the best first languages to learn when it comes to coding. The syntax is simple, so you can really focus on the logic going on

In this post, I will go through the basics of Python in this order:

These elements of coding show up in every language, only with slightly different syntax. Again, the syntax to Python is fairly easy, which is why I recommend this cheat sheet first.


Variables

There are five main types of values we can assign to variables, and these are the same main five in almost every mainstream language: Booleans, Strings, Integers and Floats. (The fifth are lists, and we’ll discuss that later).

Booleans are always either the value true or false. They become important later on when we’ll look at conditionals and loops. Here is an example:

x = true
y = (5 < 3)

(notice how I don’t need to write the variables’ types before declaring their names and values. That is often required in other languages, not Python)

If you were to print the values of x and y, you would get true and false in that order. When the computer sees (5 < 3), it computes whether that is actually a true computation, and then returns the result

Strings are like text. They come in quotations, but if you print a string, the quotations won’t show up on your console.

hello_world = "Hello World!"
print(hello_world)
(this displays Hello World!)

Integers are effectively just any whole number, positive or negative. You can change an integer by doing arithmetic on it:

my_int = 5
my_int = my_int + 1
print(my_int)
(this displays 6)

Floats are effectively the same as integers, except they have decimals (like 5.0 instead of 5). Mathematically they work the same as integers.


Conditionals

A conditional is a set of code that only runs if a certain requirement(s) is/are met, often by a variable. There are three ways a conditional can be structured. Here is the first way:

if (condition):
	do stuff

(You must always have a colon after the codition, and you must always indent the body)

This is a simple if statement. If the condition (which would have a boolean value of either true or false) is true, then the code within the indentations (“do stuff”) is run. Otherwise, nothing happens.

Here is the second way:

if (condition):
	do stuff

else:
	do other stuff

This is known as an if-else statement. If a condition is met, then run “do stuff”. Otherwise, run “do other stuff”.

Here is the third and final way:

if (condition A):
	do stuff

elif (condition B):
	do other stuff

else:
	do this thing

This is an if-elif-else statement. Elif stands for “else-if”. The computer checks the conditionals in the order they’re written in and stops at the first true one, running the code inside. For example, if condition A were false and condition B were true, then “do other stuff” would be run and the “else” would be skipped.

The body in the else statement is only run when nothing above is true.

To simplify it, this kind of statement only runs one of the conditionals, the first one to be true. (If you wanted every conditional with a true condition to be run, you would have replace all of your elifs with ifs.)


Lists

my_list = ["apple","banana","pear","grape"]

This is a list. Lists are variables that can store multiple values (strings, integers, floats, booleans, even a mix of these types). The computer recognizes a list when you put in a set of brackets (even empty lists can be represented by [])

An element is an item in a list, and the elements are separated by commas.

To reference an element, we use the name of the list and the position of the element in that list. For example:

my_list = ["apple","banana","pear","grape"]
second_item = my_list[1]
print(second_item)

This will display the element at index 1 of the list my_list.

The indices of a list start with 0, not 1. So instead of “apple”, my_list[1] will print

banana

Which is the SECOND element in the list.

Python has a couple of built-in functions you can use to tweak a list:


Loops

Loops allow you to repeat a body of code a certain number of times. There are two kinds: a while loop, and a for loop.

Here is the general structure of the while loop:

while (condition):
	do stuff

This reads as “while the condition is true, continously run the do stuff code”. Like an if statement, you must have a colon after the condition and indent your body of code.

The problem with this though is that the code in the while loop isn’t changing the condition, so the loop will run infinitely as it will always be true. To fix that, we use an incrementer:

x = 0
while (x < 10):
	do stuff
	x = x + 1

This will make the loop run only ten times, as each time the code runs, x increases by one, making the conditions x < 10 closer to being false.

The other kind of loop is a for loop:

my_list = ["apple","banana","pear","grape"]
for i in my_list:
	print i

This reads as “For every “i” (we could call this any variable name) in the list my_list (so for each element), print it.”

The for __ in __ structure is recognized by the computer, and it knows to go through the list element by element. There are a few kinds of for loops, one going through every number in a given range of numbers (for num in range(0,10):).


Functions

Functions are perhaps one of the most important tools of any programming language. They allow you to assign a specific body of code to a function name (ex. do_laundry()). That way, if you have to run that code several times in different places in the program, you don’t have to write it over and over again.

Here’s an example:

def do_laundry():
	do stuff

do_laundry()

The def keyword is recognized by the computer, and after it you can make the name of your function. With an indent, “do stuff” is now associated with the function call “do_laundry()”. So when the function is called below, THAT’S when “do stuff” is run, NOT when it’s written in the function definition.

There are two other things you can add to a function, the first being parameters. A parameter is a value you input into a function, and the function uses that parameter in the body of code:

def print_sum(num1, num2):
	print(num1 + num2)

print_sum(2, 3)

We have put num1 and num2 within the parentheses of the print_sum definition, because that is where parameters go. The function takes in these two values, and prints their sum. Since 2 corresponds to num1 in the parentheses and 3 to num2, the call to print_sum() below will print 5 (2+3).

The second thing you can add to a function is a return value. This effectively gives a function a VALUE, rather than only running a body of code:

def average(num1,num2):
	return (num1+num2)/2

print(average(2,4))

By using the return keyword, we have set the average() function equal to the average of its parameters. So when we try and print average(2,4), the computer will display 3.


Classes

To be completely honest, I don’t quite understand classes in python yet, but you can see some of that in my Java cheat sheet.