Programming - Python Reference

Section 1: Basics

Section 1 Part 1: Built-in Functions

The print() Function

The print() function prints things on the screen. To use it, type print().Then put two double quotes or single quotes between the parentheses. In the quotes, type a word. The print() function can have multiple parameters.

Example

>>> print("Hello world ")

Hello world

>>> print(242)

242

The input() function

The input function gets input from a user. It can have only one parameter. The string inside the parenthesis is what is printed out.

Example

>>> x = input("Type something:")

Type something:5

>>> print(x)

5

The quit() function

The quit() function quits python

>>> quit()

Section 1 Part 2: Numbers, Strings, Booleans, and None

Numbers

A number without decimals is an integer. In python it is called an int.

Example

>>> x = 5

>>> print(x)

5

A number with decimals is a called a float.

Example

>>> x = 5.5

>>> print(x)

5.5

Strings

A string is a string of characters. Strings can include any character.

Example

>>> x = "Hello world 123^!(*@:+_-"

>>> print(x)

Hello world 123^!(*@:+_-

Strings can be added to create bigger strings

>>> x = "63"

>>> y = "37"

>>> z = x + y

>>> print(z)

6337

escape characters

Some characters need to have a backslash to work

print("Hello world\t")

That will print a tab

\n prints a newline

\\ prints a backslash

Conversions

To convert an int to a float, the keyword is float

>>> x = 17

>>> print(float(x))

17.0

To convert a float to an int, the keyword is int. Since it is an int, it is rounded down.

>>> x = 17.23

17

The keyword for strings is str

>>> print(str(23))

23

Formats

Formats are used to embedd variables into strings.

x = 5

print("x is equal to %s" % x)

Booleans

A boolean is a variable that is either true or false.

>>> x = True

>>> y = False

>>> print(x)

True

>>> print(y)

False

The bool() function

The bool function decides whether a value is true or false. It is useful for input validation.

>>> print(bool(0))

False

>>> print(bool(1))

True

None

None is type without any value.

>>> a = None

>>> print(a)

None

Section 1 Part 2.5: Assignment and Math Operators

Addition

Unlike strings, floats and ints can be added to get a sum.

>>> x = 63

>>> y = 37

>>> z = x + y

>>> print(z)

100

Simple operators

You can also subtract, multiply, or divide numbers.

>>> a = 687 + 274

>>> b = 1000 - 39

>>> c = 31 * 31

>>> d = 3844 / 4

>>> print(str(a) + str(b) + str(c) + str(d))

961961961961

Advanced operators

You can also use exponent.

>>> 31**2

961

The modulo operator finds the remainder.

>>> 962 % 31

1

The order of assignment operations is (), **, %, /, *, +, -

Section 1 Part 3: Lists, Tuples, and Dictionaries

Lists

A list is a collection of different datatypes that are stored in one variable

>>> a = [12, "12str", True, "true"]

>>> print(a)

[12, '12', True, 'True']

The name has index values starting from 0. To access an individual item from a list put the name of the list and in between square brackets put the index value

>>> print(a[3])

true

Tuples

A tuple is a similar to a list. It uses parenthesis instead of square brackets.

>>> b = (412, 1256, 67, 5, bool(None))

>>> print(b(4))

>>> True

You cannot change items in a tuple.

Dictionaries

Dictionaries are lists with multiple named variables inside it instead of index numbers.

Dictionaries consists of key:value pairs.

>>> c = {"ca": 1, "cb": 2, "cc": 3, "cd": 4, "ce": 5}

>>> print(c["cc"])

3

>>> d = {"ca": "row", "cb": "bow", "cc": "tow", "cd": "low", "ce": "joe"}

>>> print(c["ca"])

row

Another way of using a dictionary is the dict() function.

>>> d = dict(da=1, db=2, dc=3, dd=4, de=5)

Section 1 Part 4: Comparison Operators

== and !=

Comparison operators compare numbers. They return a boolean.

>>> 5 != 6

True

>>> 4 + 4 == 8

True

== and != check whether 2 values are equal or not.

This is a condition.

>, >=, <=, and <

> and < check whether a number is greater or less than another number.

>>> 5 > 6

False

>>> 6 < 7

True

<= and >= check whether the number is greater than or equal to or less than or equal to

Section 1 Part 5: Logical Operators

and/or

logical operators test more than one condition.

The or operator tests whether one of the conditions is true. The and operator tests whether both conditions are true

>>> 5 == 6 or 4 == 4

True

>>> 5 == 6 and 4 == 4

False

The order of logical operations is: brackets, and, or.

>>> 5 == 6 and (4 == 4 or 5 == 3) and 2 == 4

False

Section 1 Part 6: If Statements

An if statement runs code only if a condition is true.

if 10 == 9 or 4 == 4:

print("4 equals 4")

4 equals 4

The else runs if the condition is not true.

if 10 == 9 and 4 == 4:

print("Condition is true")

else:

print("10 does not equal 9")

10 does not equal 9.

elif runs a piece of code depending on a different condition if the first condition isn't true.

if 3 > 5:

print("first is true.")

elif 3 > 2:

print("second is true")

else:

print("none are true")

second is true

Section 1 Part 7: Loops

for loop

The for loop runs a piece of code depending on an integer.

for variable in range(5):

print("hello")

hello

hello

hello

hello

hello

The while loop

The while loop runs a piece of code while a condition is met.

x = 5

while x >= 0:

print("hello")

x = x - 1

hello

hello

hello

hello

hello

Section 1 Part 8: break and continue

break/continue

break will quit the control structure.

continue will continue the control structure.

while True:

print("hello")

if 5 != 5:

continue;

else:

break;

hello

Section 2: Modules, Functions, and Classes

Section 2 Part 1: Modules

A module is a group of related functions and classes. It is also known as a library

The import statement accesses a module.

The math module has math functions

>>> import math

Now the program has access to math functions such as square root and pow.

>>> import math

>>> print(math.sqrt(64))

8

>>> math.pow(2, 3)

8

The time module has time functions

>>> import time

>>> time.sleep(5)

>>>

The computer paused for 5 seconds.

>>> print(time.asctime())

Tue May 1 07:41:23 2018

>>> print(time.time())

1525309467.8433716

prints the time from 1970.

Section 2 Part 2: Functions

Basics

Functions are groups of code.

def calculate():

print(13 + 13)

...

calculate()

26

Parameters

Functions with parameters need extra information to run.

def calculate(x, y):

print(x, y)

calculate(13, 13)

26

The print function has 1 or more parameters

Named parameters

Parameters can have variable declarations

calculate(x=5, y=6)

11

The return statement

Return returns a value

def calculate(x, y):

z = (x + y) * 3

return z

x = calculate(x=7, y=9)

print(x)

16

Section 2 Part 3: Objects

Built-in objects

An object is a collection of related variables and functions

The math object has it's own variable called pi.

import math

>>> math.pi

3.141592936

It also has a function such called sqrt()

>>> math.sqrt(25)

5

The subprocess object has functions for the console.

import subprocess

subprocess.call('clear', shell=True)

The shell will clear now

Section 2 Part 4: constant variables

Constants are variables that cannot change. Constants in python are in capital letters. Constants are declared in the beginning of the program

CONSTANTEXAMPLE = "Hello"

Section 2 Part 5: Classes -Properties

A class is a blueprint for an object. The name of a class usually starts with a capital letter. All classes in python have an __init__() function to declare the variables. Every function has a self parameter.

class Dog:

def __init(self, breed, color, size):

self.breed = breed

self.color = color

self.size = size

breed, color, and size are properties(information) of the Dog class. This is how to create an object of the Dog class.

a = Dog(breed="beagle", color="black", size=65)

print(a.breed)

beagle

print(a.color)

black

print(a.size)

65

Section 2 Part 6: Classes -Methods

Methods are the functions of the class. The functions must have a self parameter.

class Dog:

def __init(self, breed, color, size):

self.breed = breed

self.color = color

self.size = size

def eat(self):

print("Munch munch")

a = Dog(breed="grayhound", color="gray", size=125)

a.eat()

Munch munch

Section 3: Graphics

Section 3 Part 1: Turtles

Section 3 Part 2: Tkinter

Section 3 Part 2.1: Animation

Section 3 Part 2.2: Events

Section 3 Part 3: Sprites

Section 3 Part 4: Animation

Section 3 Part 5: Built-in functions for sprites

Other languages

Programming Main Page