Introduction

What is Python?

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.
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.

Creating a Comment

Comments starts with a #, and Python will ignore them:

#This is a comment
print(Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code:

#print("Hello, World!")
print("Cheers, Mate!")

Multi Line Comments

Python does not really have a syntax for multi line 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!")

Or, not quite as intended, you can use a multiline string. Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:

"""
This is a comment
written in
more than just one line
"""
print(Hello, World!")

As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a multiline comment.

Variables

Variables

Variables are containers for storing data values.

Creating Variables

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)

Variables do not need to be declared with any particular type, and can even change type after they have been set.

x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

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

Get the Type

x = 5
y = "John"
print(type(x))
print(type(y))

Single or Double Quotes?

String variables can be declared either by using single or double quotes:

x = "John"
# is the same as
x = 'John'

Case-Sensitive

Variable names are case-sensitive.

a = 4
A = "Sally"
#A will not overwrite a
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

Getting the Data Type

You can get the data type of any object by using the type() function:

x = 5
print(type(x))

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

ExampleData Type
x = "Hello World"str
x = 20int
x = 20.5float
x = 1jcomplex
x = ["apple", "banana", "cherry"]list
x = ("apple", "banana", "cherry")tuple
x = range(6)range
x = {"name" : "John", "age" : 36}dict
x = {"apple", "banana", "cherry"}set
x = frozenset({"apple", "banana", "cherry"})frozenset
x = Truebool
x = b"Hello"bytes
x = bytearray(5)bytearray
x = memoryview(bytes(5))memoryview
x = NoneNoneType

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Numbers

Python Numbers

There are three numeric types in Python:

  • int
  • float
  • complex

Variables of numeric types are created when you assign a value to them:
x = 1 # inty = 2.8 # floatz = 1j # complexTo verify the type of any object in Python, use the type() function: print(type(x))print(type(y))print(type(z))

Int

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Float

Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.

Complex

Complex numbers are written with a "j" as the imaginary part.

Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods.Note: You cannot convert complex numbers into another number type.

Random Number

Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers.

Casting

Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:


  • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
  • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
  • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals
x = int(1) # x will be 1y = int(2.8) # y will be 2z = int("3") # z will be 3x = float(1) # x will be 1.0y = float(2.8) # y will be 2.8z = float("3") # z will be 3.0w = float("4.2") # w will be 4.2x = str("s1") # x will be 's1'y = str(2) # y will be '2'z = str(3.0) # z will be '3.0'
Strings

Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:

Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

Multiline Strings

You can assign a multiline string to a variable by using three quotes.Note: in the result, the line breaks are inserted at the same position as in the code.

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.

Looping Through a String

Since strings are arrays, we can loop through the characters in a string, with a for loop.

String Length

To get the length of a string, use the len() function.

Check String

To check if a certain phrase or character is present in a string, we can use the keyword in.

Check if NOT

To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

Slicing Strings

Slicing

You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.

Slice From the Start

By leaving out the start index, the range will start at the first character:

Slice To the End

By leaving out the end index, the range will go to the end:

Negative Indexing

Use negative indexes to start the slice from the end of the string:

Booleans

Booleans represent one of two values: True or False.

Boolean Values

In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean answer:

When you run a condition in an if statement, Python returns True or False:

Evaluate Values and Variables

The bool() function allows you to evaluate any value, and give you True or False in return,

Most Values are True

Almost any value is evaluated to True if it has some sort of content.
Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.

Some Values are False

In fact, there are not many values that evaluate to False, except empty values, such as (), [], ,"", the number 0, and the value None. And of course the value False evaluates to False.

Functions can Return a Boolean

You can create functions that returns a Boolean Value:

Operators

Python Operators

Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

Python Assignment Operators

Assignment operators are used to assign values to variables:

Python Comparison Operators

Comparison operators are used to compare two values:

Python Logical Operators

Logical operators are used to combine conditional statements:

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Lists

mylist = ["apple", "banana", "cherry"]

List

Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:

List Items

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.

Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items will not change.

Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

Tuples

mytuple = ("apple", "banana", "cherry")

Tuple

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.

Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Sets

myset = "apple", "banana", "cherry"

Set

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.

* Note: Set items are unchangeable, but you can remove items and add new items.

Sets are written with curly brackets.

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created.

Once a set is created, you cannot change its items, but you can remove items and add new items.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Dictionaries

Dictionary

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.

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Ordered or Unordered?

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.

Changeable

Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

Duplicates Not Allowed

Dictionaries cannot have two items with the same key:

Dictionary Length

To determine how many items a dictionary has, use the len() function:

Reference

  • All the documentation in this page is taken from W3Schools