Python Programming Tur
Python Programming Tur
Table of Contents
1. Introduction to Python
2. Setting Up the Environment
3. Variables and Data Types
4. Operators and Expressions
5. Conditional Statements
6. Loops
7. Functions
8. Lists and Tuples
9. Dictionaries and Sets
10. Strings and String Methods
11. File Handling
12. Error Handling (Exceptions)
13. Object-Oriented Programming (OOP)
14. Modules and Packages
15. Virtual Environments
16. Working with External Libraries
17. Introduction to Projects
1. Introduction to Python
What is Python?
Python is a high-level, interpreted programming language known for its readability. It was created
by Guido van Rossum and released in 1991
Widely used in web development(server side), data science, automation, and AI.
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.
Steps:
Check Installation:
python --version
Python is an interpreted programming language, this means that as a developer you write Python (.py)
files in a text editor and then put those files into the python interpreter to be executed.
The way to run a python file is like this on the command line:
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the directory where you saved
your file, and run:
To test a short amount of code in python sometimes it is quickest and easiest not to write the code in a
file. This is made possible because Python can be run as a command line itself.
From there you can write any python, including our hello world example from
earlier in the tutorial:
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>> print("Hello, World!")
Hello, World!
You can type exit() to quit the python command line interface.
Python Indentation
Valid synthax
if 5 > 2:
print("Five is greater than two!")
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:
#This is a comment.
print("Hello, World!")
#print("Hello, World!")
print("Cheers, Mate!")
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
name = "Alice"
age = 25
height = 5.6
is_student = True
print(name)
print(age)
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.
You can get the data type of a variable with the type() function.
x = 5
y = "John"
print(type(x))
print(type(y))
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
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"
And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output Variables
The Python print() function is often used to output variables.
x = "Python is awesome"
print(x)
Notice the space character after "Python " and "is ", without them the
result would be "Pythonisawesome".
In the print() function, when you try to combine a string and a number with
the + operator, Python will give you an error:
x = 5
y = "John"
print(x + y) #will throw an error
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()
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.
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Normally, when you create a variable inside a function, that variable is local, and can only
be used inside that function.
To create a global variable inside a function, you can use the global keyword.
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.
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Data Types:
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:
x = 5
print(type(x))
If you want to specify the data type, you can use the following constructor functions:
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 # int
y = 2.8 # float
z = 1j # complex
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited
length.
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.
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.
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:
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:
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:
print(random.randrange(1, 10))
Python Casting
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.
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 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
print("Hello")
print('Hello')
You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
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.
However, Python does not have a character data type, a single character is simply a string
with a length of 1.
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Since strings are arrays, we can loop through the characters in a string, with a for loop.
for x in "banana":
print(x)
To check if a certain phrase or character is present in a string, we can use the keyword in.
txt = "The best things in life are free!"
print("free" in txt)
Use it in an if statement:
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement:
print only if "expensive" is NOT present:
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.
b = "Hello, World!"
print(b[2:5])
By leaving out the start index, the range will start at the first character:
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
By leaving out the end index, the range will go to the end:
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Use negative indexes to start the slice from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
Upper Case
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case
The lower() method returns the string in lower case:
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.
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Replace String
The replace() method replaces a string with another string:
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.
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 Concatenation
To concatenate, or combine, two strings you can use the + operator.
String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers
like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using f-strings or the format() method!
F-Strings
F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.
To specify a string as an f-string, simply put an f in front of the string literal, and add curly
brackets {} as placeholders for variables and other operations.
age = 36
txt = f"My name is John, I am {age}"
print(txt)
A placeholder can contain variables, operations, functions, and modifiers to format the
value.
price = 59
txt = f"The price is {price} dollars"
print(txt)
A placeholder can include a modifier to format the value.
Escape Character
You will get an error if you use double quotes inside a string that is surrounded by double
quotes:
txt = "We are the so-called "Vikings" from the north."
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.
print(10 > 9)
print(10 == 9)
print(10 < 9)
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
The bool() function allows you to evaluate any value, and give you True or False in
return,
print(bool("Hello"))
print(bool(15))
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
Any list, tuple, set, and dictionary are True, except empty ones.
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.
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:
class myclass():
def __len__(self):
return 0
myobj = myclass()
print(bool(myobj))
print(myFunction())
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:
x = 200
print(isinstance(x, int))
In the example below, we use the + operator to add together two values:
print(10 + 5)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise 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
Operator Precedence
Parentheses has the highest precedence, meaning that expressions inside parentheses
must be evaluated first:
print((6 + 3) - (6 + 3))
Multiplication * has higher precedence than addition +, and therefore multiplications are
evaluated before additions:
print(100 + 5 * 3)
The precedence order is described in the table below, starting with the highest precedence
at the top:
Addition + and subtraction - has the same precedence, and therefore we evaluate the
expression from left to right:
print(5 + 4 - 7 + 3)
5. Conditional Statements
if
An "if statement" is written by using the if keyword.
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than
33, and so we print to screen that "b is greater than a".
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.
elif
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")
In this example a is equal to b, so the first condition is not true, but the elif condition is
true, so we print to screen that "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")
In this example a is greater than b, so the first condition is not true, also the elif condition
is not true, so we go to the else condition and print to screen that "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")
Short Hand If
If you have only one statement to execute, you can put it on the same line
as the if statement.
If you have only one statement to execute, one for if, and one for else, you
can put it all on the same line:
a = 2
b = 330
print("A") if a > b else print("B")
For example
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Not
The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements,x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
a = 33
b = 200
if b > a:
pass
6. Loops
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.
The for loop does not require an indexing variable to set beforehand.
With the break statement we can stop the loop before it has looped through all the items:
Exit the loop when x is "banana":
With the continue statement we can stop the current iteration of the loop, and continue
with the next:
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
for x in range(6):
print(x)
The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but
not including 6):
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!"
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
for x in adj:
for y in fruits:
print(x, y)
for loops cannot be empty, but if you for some reason have a for loop with no content,
put in the pass statement to avoid getting an error.
for i in range(5):
print(i)
count = 0
while count < 5:
print(count)
count += 1
7. Functions
Example:
def greet(name):
return f"Hello, {name}"
print(greet("Bob"))
List Example:
Tuple Example:
Dictionary Example:
student = {"name": "Alice", "age": 22}
print(student["name"])
Set Example:
unique_numbers = {1, 2, 3, 3}
print(unique_numbers)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values
into variables. This is called unpacking.
Example:
Example:
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
Example:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says woof!")
d = Dog("Fido")
d.bark()
Example:
import math
print(math.sqrt(16))
Use requests:
import requests
response = requests.get("https://api.github.com")
print(response.status_code)