INTRODUCTION
TO
PYTHON
WHAT IS PYTHON
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991
INTERACTIVE: allows the creator to make changes to the program while it is already running
INTERPRETED: Code is written and directly executed by an interpreter. Allow you to type one command at a time and
see results
OBJECT ORIENTED SCRIPTING LANGUAGE: that organizes software design around data, or objects, rather than
functions and logic. An object can be defined as a data field that has unique attributes and behavior.
HIGH LEVEL PROGRAMMING LANGUAGE:
WHAT IS PYTHON CONT’…
It is used for:
web development (server-side),
Desktop development,
DataScience,
Network programming,
Games and 3D graphics
Mobile App development,
Machine Learning,
mathematics,
system scripting.
WHY CHOOSE PYTHON
ADVANTAGES OF PYTHON
LANGUAGE
DISADVANTAGES OF PYTHON
LANGUAGE
Python frameworks
Python frameworks automate the implementation of several tasks and give developers a structure for application
development. Each framework comes with its own collection of modules or packages that significantly reduce
development time
WEB FRAMEWORKS OF PYTHON
DATASCIENCE FRAMEWORKS OF
PYTHON
1) NumPy: Foundations for statistical
computing
2) Pandas: Simplified data processing
3) Matplotlib and Seaborn: great plotting
capabilities
4) Scikit-learn: Machine learning made it
easier
5) TensorFlow and PyTorch: Deep Learning
Leaders
6) Dask: Parallel Processing for Large
Datasets
7) Natural Language Tools (NLTK): Text Analysis
Controller
DESKTOP FRAMEWORKS OF PYTHON
1.Tkinter
2. PyQt
3. Kivy
4. PySide
5. wxPython
6. PyGTK
GAME DEVELOPMENT FRAMEWORKS
OF PYTHON
1. Pygame
2. Pyglet
3. PyOpenGL
4. Panda3D
5. Kivy
6. Arcade
7. Pymunk
Popular website build with
Python
Installing Python on Windows
Step: 1
To download and install Python, go to Python's official website http://www.python.org/downloads/
Step 4
when installation completes you will see the message “setup was successful” on screen
IDLE Development Environment
Integrated DeveLopment Environment
Text editor with smart indenting for creating python files.
Menu commands for changing system settings and running files
Python Interpreter
Interactive Interface to python
HOW PYTHON CODE RUNS
RUNNING PYTHON CODE
When you open the interpreter and type command
PRINT() FUNCTION
The Python print() function is often used to output variables.
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)
PRINT() FUNCTION CONT’ …
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
For numbers, the + character works as a mathematical operator:
Example
x=5
y = 10
print(x + y)
PRINT() FUNCTION CONT’ …
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)
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.
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
VARIABLES CONT’…
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.
VARIABLES CONT’…
x=5
y = "John"
print(type(x))
print(type(y))
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))
VARIABLES CONT’…
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Example
x = "John" # is the same as
x = 'John'
VARIABLES CONT’…
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)
VARIABLES CONT’…
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
VARIABLES CONT’…
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
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.
VARIABLES CONT’…
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange“
print(x)
DATATYPES
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
DATATYPES CONT’ …
Getting the Data Type
You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x:
x=5
print(type(x))
Setting the Data Type
In Python, the data type is set when you assign a value to a variable:
DATATYPES CONT’ …
Example Datatype
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
DATATYPES CONT’ …
Example Datatype
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) Frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) Bytearray
x = memoryview(bytes(5)) memoryvie w
x = None NoneType
DATATYPES CONT’ …
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
DATATYPES CONT’ …
Setting the Specific Data Type
If you want to specify the data type, you can use the following constructor functions:
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:
Example
#This is a comment
print("Hello, World!")
COMMENTS CONT’…
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!")
COMMENTS CONT’…
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!“)
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
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
NUMBERS CONT’…
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))
NUMBERS CONT’…
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))
NUMBERS CONT’…
Complex
Complex numbers are written with a "j" as the imaginary part:
Example
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
NUMBERS CONT’…
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x)
#convert from float to int:
b = int(y)
#convert from int to complex:
c = complex(x)
Note: You cannot convert complex numbers into another number type.
NUMBERS CONT’…
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))
USER INPUT
Python allows for user input.
That means we are able to ask the user for input.
Python 3 uses the input() method.
# top accept string value
username = input("Enter username:")
print("Username is: " + username)
Enter username
# to accept numerical value
age =int(input(“Enter your age”))
Python 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:
Example
print("Hello")
print('Hello')
Python Strings cont’…
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Python Strings cont’…
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.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Python Strings cont’…
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Python Strings cont’…
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Python Strings cont’…
Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
Use it in an if statement
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Python Strings cont’…
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement:
Example
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present."
Python Slicing
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.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Note: The first character has index 0.
Python Slicing cont’ …
Slice From the Start
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:])
Python Slicing cont’ …
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
Python - Modify Strings
Python has a set of built-in methods that you can use on strings
Upper Case
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Lower Case
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Python - Modify Strings cont’…
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.strip()) # returns "Hello, World!"
Replace String
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Python - Modify Strings cont’…
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!']
Python – String concatenation
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
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)
Python – Format Strings
String Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:
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
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Python – Format Strings cont’…
The format() method takes unlimited number of arguments, and are placed into the respective placeholders:
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:
Python – Format Strings cont’…
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))
Python – Escape characters
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is
surrounded by double quotes:
Example
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."
To fix this problem, use the escape character \":
Example
The escape character allows you to use double quotes when you normally would
not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
Python – Escape characters cont’…
Other escape characters used in Python:
Code Result
\’ Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
Python – String Functions
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
Python – String Functions cont’…
Method Description
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string