Python 2
Python 2
Introduction
Python is an easy to learn, powerful programming language. It has efficient high-
level data structures and a simple but effective approach to object-oriented
programming. Python’s elegant syntax and dynamic typing, together with its
interpreted nature, make it an ideal language for scripting and rapid application
development in many areas on most platforms.
What is Python?
It is used for:
Why Python?
Good to know
Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.
Python Variables
Example
x=5
y = "Hello, World!"
Comments
Comments start with a #, and Python will render the rest of the line as 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
Multiline Comments
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
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
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
Exercise?
var x = 5
#x = 5
$x = 5
x=5
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
2myvar = "John"
my-var = "John"
my var = "John"
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one line
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Example
x = "Python is awesome"
print(x)
By: Sarah N. Almeer 8
Python Lab 2nd Stage
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)
The best way to output multiple variables in the print() function is to separate
them with commas, which even support different data types:
Example
x=5
y = "John"
print(x, y)
Exercise?
Hello, World
Hello World
HelloWorld
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:
You can get the data type of any object by using the type() function:
Example
x=5
print(type(x))
In Python, the data type is set when you assign a value to a variable
x = 20 Int
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
If you want to specify the data type, you can use the following constructor
functions:
x = int(20) Int
x = float(20.5) Float
x = complex(1j) Complex
x = range(6) Range
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Exercise?
If x = 5, what is a correct syntax for printing the data type of the variable x?
print(dtype(x))
print(type(x))
print(x.dtype())
Python Numbers
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))
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:
Example
By: Sarah N. Almeer 15
Python Lab 2nd Stage
Strings:
Example
print("Hello")
print('Hello')
Python Booleans
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Example
a = 200
b = 33
if b > a:
Append Items
To add an item to the end of the list, use the append() method:
Example
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Example
Example
Example
Example
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Example
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
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.
Example
a = 33
b = 200
if b > a:
print("b is greater than a")
Python Loops
Python has two primitive loop commands:
while loops
for loops
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.
Example
Example
+ Addition x+y
- Subtraction x–y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is not(x < 5 and x < 10)
true
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:
is not Returns True if both variables are not the same x is not y
object
<< Zero fill Shift left by pushing zeros in from the right and x << 2
left shift let the leftmost bits fall off
>> Signed Shift right by pushing copies of the leftmost bit in x >> 2
right shift from the left, and let the rightmost bits fall off
Example
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest
precedence at the top:
Operator Description
() Parentheses
** Exponentiation
^ Bitwise XOR
| Bitwise OR
and AND
or OR
If two operators have the same precedence, the expression is evaluated from left
to right.
Example
Addition + and subtraction - has the same precedence, and therefor we evaluate the
expression from left to right:
print(5 + 4 - 7 + 3)
Exercise?
3
5
8