PYTHON
PYTHON
What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
Why Python?
Good to know
Example
print("Hello, World!")
PYTHON SYNTAX
Or by creating a python file on the server, using the .py file extension, and
running it in the Command Line:
Python Indentation
Example
if 5 > 2:
print("Five is greater than two!")
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables
In Python, variables are created when you assign a value to it:
Example
Variables in Python:
x = 5
y = "Hello, World!"
You will learn more about variables in the Python Variables chapter.
Comments
Comments start with a #, and Python will render the rest of the line as a
comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
PYTHON COMMENTS
Creating a Comment
Example
#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:
Example
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:
Example
#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:
Example
#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:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
PYTHON VARIABLES
Creating Variables
Example
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.
Example
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.
Example
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
You can get the data type of a variable with the type() function.
Example
x = 5
y = "John"
print(type(x))
print(type(y))
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Example
a = 4
A = "Sally"
#A will not overwrite a
VARIABLES NAMES
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:
Example
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Try it Yourself »
Example
2myvar = "John"
my-var = "John"
my var = "John"
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
myVariableName = "John"
Pascal Case
MyVariableName = "John"
Snake Case
my_variable_name = "John"
ASSINGING MULTIPLE VARIABLES
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: Make sure the number of variables matches the number of values,
or else you will get an error.
Unpack a list:
Example
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a
comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Notice the space character after "Python " and "is ", without them the
result would be "Pythonisawesome".
Example
x = 5
y = 10
print(x + y)
In the print() function, when you try to combine a string and a number
with the + operator, Python will give you an error:
Example
x = 5
y = "John"
print(x + y)
Example
x = 5
y = "John"
print(x, y)
GLOBAL VARIABLES
Variables that are created outside of a function (as in all of the examples
above) are known as global variables.
Example
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable
will be local, and can only be used inside the function. The global variable
with the same name will remain as it was, global and with the original
value.
Example
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)
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Also, use the global keyword if you want to change a global variable
inside a function.
Example
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
PYTHON DATA TYPES
You can get the data type of any object by using the type() function:
Example
x = 5
print(type(x))
Setting the Data Type
In Python, the data type is set when you assign a value to a variable:
x = 20 int Try it »
x = 20.5 float
x = 1j complex Try it »
x = range(6) range
x = True bool
x = bytearray(5) bytearray
x = None NoneType T
If you want to specify the data type, you can use the following constructor
functions:
x = float(20.5) float
x = complex(1j) complex Try it »
x = range(6) range
x = bool(5) bool
x = bytearray(5) bytearray
PYTHON 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:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
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.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of
10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
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:
Example
Import the random module, and display a random number between 1 and
9:
import random
print(random.randrange(1, 10))
PYTHON CASTING
The conversion of one data type into the other data type is known as type casting in
python or type conversion in python. Python supports a wide variety of functions or
methods like: int(), float(), str(), ord(), hex(), oct(), tuple(), set(), list(), dict(), etc. for the
type casting in python.
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.
Example
Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Example
Floats:
Strings:
PYTHON STRINGS
Strings in python are surrounded by either single quotation marks, or
double quotation marks.
Example
print("Hello")
print('Hello')
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:
Example
a = "Hello"
print(a)
Multiline Strings
Example
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in
the code.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string,
with a for loop.
Example
for x in "banana":
print(x)
String Length
To get the length of a string, use the len() function.
Example
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use
the keyword in.
Example
Use it in an if statement:
Example
Print only if "free" is present:
Use it in an if statement:
Example
Slicing
Specify the start index and the end index, separated by a colon, to return
a part of the string.
Example
b = "Hello, World!"
print(b[2:5])
By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Slice To the End
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
b = "Hello, World!"
print(b[-5:-2])
MODIFY STRINGS
Python has a set of built-in methods that you can use on strings.
Upper Case
Example
a = "Hello, World!"
print(a.upper())
Lower Case
Example
a = "Hello, World!"
print(a.lower())
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the
end:
a = "Hello, World!"
print(a.replace("H", "J"))
Split String
The split() method returns a list where the text between the specified
separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of
the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Methods
CONCATE STRINGS
String Concatenation
Example
a = "Hello"
b = "World"
c = a + b
print(c)
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
FORMAT STRINGS
String Format
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are:
Example
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
ESCAPE CHARACTERS
Escape Character
Example
You will get an error if you use double quotes inside a string that is
surrounded by double quotes:
The escape character allows you to use double quotes when you normally
would not be allowed:
\\ Backslash Try it »
\n New Line
\t Tab
\b Backspace Try it »
\f Form Feed
STRING METHODS
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods return new values. They do not change the
original string.
Method Description
endswith() Returns true if the string ends with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice
versa
Python 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.
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
print(bool("Hello"))
print(bool(15))
Example
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Example
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
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.
Example
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
One more value, or object in this case, evaluates to False, and that
is if you have an object that is made from a class with
a __len__ function that returns 0 or False:
Example
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
def myFunction() :
return True
print(myFunction())
Example
def myFunction() :
return True
if myFunction():
print("YES!")
else:
print("NO!")
Python also has many built-in functions that return a boolean value,
like the isinstance() function, which can be used to determine if an
object is of a certain data type:
Example
x = 200
print(isinstance(x, int))
Python Operators
Operators are used to perform operations on variables and values.
Example
print(10 + 5)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
<< Zero fill Shift left by pushing zeros in from the right
left shift and let the leftmost bits fall off
Python 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.
Example
Create a List:
List Items
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.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
List Length
To determine how many items a list has, use the len() function:
Example
Example
Example
type()
From Python's perspective, lists are defined as objects with the data type
'list':
<class 'list'>
Example
It is also possible to use the list() constructor when creating a new list.
Example
There are four collection data types in the Python programming language:
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
List items are indexed and you can access them by referring to the
index number:
Example
Negative Indexing
-1 refers to the last item, -2 refers to the second last item etc.
Example
Range of Indexes
You can specify a range of indexes by specifying where to start and
where to end the range.
When specifying a range, the return value will be a new list with the
specified items.
Example
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"
]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5
(not included).
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT
including, "kiwi":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"
]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the
list:
Example
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"
]
print(thislist[2:])
Specify negative indexes if you want to start the search from the
end of the list:
Example
This example returns the items from "orange" (-4) to, but NOT
including "mango" (-1):
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"
]
print(thislist[-4:-1])
Example
Example
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "mango"
]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
If you insert more items than you replace, the new items
will be inserted where you specified, and the remaining
items will move accordingly:
Example
Note: The length of the list will change when the number
of items inserted does not match the number of items
replaced.
If you insert less items than you replace, the new items
will be inserted where you specified, and the remaining
items will move accordingly:
Example
Example
Example
Insert Items
To insert a list item at a specified index, use
the insert() method.
Example
Insert an item as the second position:
Extend List
To append elements from another list to the current list,
use the extend() method.
Example
Example
Example
Remove "banana":
Example
Example
Example
Remove the first item:
Example
Example
Example
Example
Example
Example
A short hand for loop that will print all items in a list:
Example:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one
line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
The Syntax
newlist =
[expression for item in iterable if condition == True]
Condition
The condition is like a filter that only accepts the items
that valuate to True.
Example
Example
With no if statement:
Iterable
The iterable can be any iterable object, like a list, tuple,
set etc.
Example
Example
Expression
The expression is the current item in the iteration, but it is
also the outcome, which you can manipulate before it
ends up like a list item in the new list:
Example
Example
Example
newlist = [x if x !
= "banana" else "orange" for x in fruits]
Try it Yourself »
Example
thislist =
["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
Example
Sort Descending
To sort descending, use the keyword argument reverse =
True:
Example
thislist =
["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Example
Example
Example
Example
Reverse Order
What if you want to reverse the order of a list, regardless
of the alphabet?
The reverse() method reverses the current sorting order
of the elements.
Example
Example
Example
Example
Example
for x in list2:
list1.append(x)
print(list1)
Example
Use the extend() method to add list2 at the end of list1:
list1.extend(list2)
print(list1)
Method Description
Python Tuples
mytuple = ("apple", "banana", "cherry")
Tuple
Tuples are used to store multiple items in a single
variable.
Example
Create a Tuple:
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:
Example
thistuple =
("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Example
Print the second item in the tuple:
Negative Indexing
Negative indexing means start from the end.
Example
Range of Indexes
You can specify a range of indexes by specifying where to
start and where to end the range.
Example
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon"
, "mango")
print(thistuple[2:5])
By leaving out the start value, the range will start at the
first item:
Example
This example returns the items from the beginning to, but
NOT included, "kiwi":
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon"
, "mango")
print(thistuple[:4])
Example
Add Items
Since tuples are immutable, they do not have a build-
in append() method, but there are other ways to add items
to a tuple.
Example
Example
Create a new tuple with the value "orange", and add that
tuple:
print(thistuple)
Note: When creating a tuple with only one item, remember
to include a comma after the item, otherwise it will not be
identified as a tuple.
Remove Items
Example
Example