Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
print("Hello, World!")
python --version
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
#This is a comment
print("Hello, World!")
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a #
for each line:
#This is a comment
#written in
#more than just one line
print("Hello, World!")
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Variables
Variables are containers for storing data values.
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
x = 5
y = "John"
print(x)
print(y)
Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Global Variables
Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Create a variable inside a function, with the same name as the global variable.
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
If you use the global
keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
To change the value of a global variable inside a function, refer to the variable by using the global
keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python Data Types
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: | str |
Numeric Types: | int , float , complex |
Sequence Types: | list , tuple , range |
Mapping Type: | dict |
Set Types: | set , frozenset |
Boolean Type: | bool |
Binary Types: | bytes , bytearray , memoryview |
None Type: | NoneType |
You can get the data type of any object by using the type()
function:
x = 5
print(type(x))
Python Numbers
There are three numeric types in Python:
int
float
complex
x = 1 # int
y = 2.8 # float
z = 1j # complex
Python Casting
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Strings
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Booleans
Booleans represent one of two values: True
or False
.
Print a message based on whether the condition is True
or False
:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Python Operators
Operators are used to perform operations on variables and values.
print(10 + 5)
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Lists
mylist = ["apple", "banana", "cherry"]
Lists are used to store multiple items in a single variable.
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0]
, the second item has index [1]
etc.
thislist = ["apple", "banana", "cherry"]
print(thislist)
Python Tuples
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable**, and unindexed*.
thisset = {"apple", "banana", "cherry"}
print(thisset)
Python Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and do not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if keyword.
a = 33
b = 200
if b > a:
print("b is greater than a")
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the preceding conditions.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Python Loops
Python has two primitive loop commands:
while loops
for loops
With the while loop we can execute a set of statements as long as a condition is true.
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use the range() function.
for x in range(6):
print(x)
Using the start parameter:
for x in range(2, 6):
print(x)
Python Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
def my_function():
print("Hello from a function")
my_function()
Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Add 10 to argument a
, and return the result:
x = lambda a : a + 10
print(x(5))
Multiply argument a
with argument b
and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Python Arrays
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
cars = ["Ford", "Volvo", "BMW"]
What is an Array?
An array is a special variable, which can hold more than one value at a time.
Python Classes/Objects
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class
:
class MyClass:
x = 5
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Python Iterators
An iterator is an object that contains a countable number of values.
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__()
and __next__()
.
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
Python Polymorphism
The word "polymorphism" means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
Class Polymorphism
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Fly!")
car1 = Car("Ford", "Mustang") #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class
for x in (car1, boat1, plane1):
x.move()
What is a Module?
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
ave this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
import platform
x = platform.system()
print(x)
Python Dates
A date in Python is not a data type of its own, but we can import a module named datetime
to work with dates as date objects.
import datetime
x = datetime.datetime.now()
print(x)
Python Math
Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.
Built-in Math Functions
The min()
and max()
functions can be used to find the lowest or highest value in an iterable:
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
Python JSON
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.
JSON in Python
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
What is PIP?
PIP is a package manager for Python packages, or modules if you like.
What is a Package?
A package contains all the files you need for a module.
Modules are Python code libraries you can include in your project.
Python Try Except
The try
block lets you test a block of code for errors.
The except
block lets you handle the error.
The else
block lets you execute code when there is no error.
The finally
block lets you execute code, regardless of the result of the try- and except blocks.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
try:
print(x)
except:
print("An exception occurred")
Python User Input
User Input
Python allows for user input.
That means we are able to ask the user for input.
The method is a bit different in Python 3.6 than Python 2.7.
Python 3.6 uses the input()
method.
username = input("Enter username:")
print("Username is: " + username)
Python String Formatting
F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.
Before Python 3.6 we had to use the format()
method.
F-Strings
F-string allows you to format selected parts of a string.
To specify a string as an f-string, simply put an f
in front of the string literal, like this:
txt = f"The price is 49 dollars"
print(txt)