0% found this document useful (0 votes)
22 views107 pages

Chapter 1. Basic Concepts and Techniques

Uploaded by

schlaggen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views107 pages

Chapter 1. Basic Concepts and Techniques

Uploaded by

schlaggen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

PYTHON INTRODUCTION

DR. PHẠM MINH HOÀN – [email protected]


OBJECTIVES OF CHAPTER 1
• Understand the building blocks of programming: variables, data types, operators,
expressions, and control flow.
• Learn how to write simple programs: input, output, calculations, conditional
statements, and loops.
• Recognize Python's grammar and structure: keywords, indentation, code blocks,
functions, and classes.
• Write well-formatted and readable code: adhere to Python's style guidelines.
CONTENTS
1.1 Introduction to Python
1.2 Install and Configure the Programming Environment
1.3 Introduction to IDE (Integrated Development Environment)
1.4 Syntax
1.5 Modules and Functions
1.6 Object Oriented Programming
1.7 Debugging and fixing errors
INTRODUCTION TO 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.
INTRODUCTION TO PYTHON
In the context of Python, a "program" refers to a set of instructions
written in the Python programming language that a computer can
execute to perform a specific task or achieve a certain goal.
Key concepts involved in Python programs:
• The actual text written in Python, consisting of statements, expressions, and
functions.
• It's structured using proper syntax and indentation to ensure readability and
functionality.
INTRODUCTION TO PYTHON
Types of Python Programs:
• Simple scripts: Automate tasks, perform calculations, generate text or data.
• Web applications: Create interactive websites using frameworks like Django
or Flask.
• Data analysis and visualization: Explore and visualize data using libraries like
NumPy, Pandas, and Matplotlib.
• Scientific computing: Perform numerical computations and simulations.
• Machine learning: Build models for prediction, classification, and decision-
making.
• Game development: Create games using libraries like PyGame.
INTRODUCTION TO PYTHON
Python programs are written in plain text and saved with a .py
extension.
They can be executed using a Python interpreter or integrated
development environment (IDE).
Python's readability, beginner-friendliness, and extensive libraries make
it a popular choice for various programming tasks.
INTRODUCTION TO PYTHON
• Simple "Hello, World!" program:
print("Hello, World!")
• Basic calculations:
a = 10
b=5
print(a + b) # Output: 15
print(a - b) # Output: 5
print(a * b) # Output: 50
print(a / b) # Output: 2.0
INTRODUCTION TO PYTHON
• Gathering user input:
name = input("What is your name? ")
print("Hello,", name + "!")
• Conditional statements (making decisions):
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
INTRODUCTION TO PYTHON
• Loops (repeating tasks):
for i in range(5):
print("Looping!")
INSTALL AND CONFIGURE THE PYTHON
PROGRAMMING ENVIRONMENT
1. Download and Install Python:
• Visit the official Python website: https://www.python.org/downloads/
• During installation, ensure you check the option to "Add Python to
PATH" (if
available): This allows you to run Python from the command line without
specifying its full path.
2. Verify Installation: Open a command prompt or terminal, Type python --version
or python3 --version and press Enter: This should display the installed Python
version, confirming successful installation.
INSTALL AND CONFIGURE THE PYTHON
PROGRAMMING ENVIRONMENT
3. Install Additional Packages:
• Use the pip package manager to install required libraries
• Open a command prompt or terminal and type pip install <package_name>
• Example: pip install numpy pandas matplotlib to install NumPy, Pandas, and
Matplotlib (common data science libraries)
INSTALL AND CONFIGURE THE PYTHON
PROGRAMMING ENVIRONMENT
4. Run program with Python:
• Open a command prompt or terminal,
• Write Python file, called helloworld.py, which can be done in any text editor.
Example: notepad helloworld.py
print("Hello, World!")
• Run helloworld.py with Python
python helloworld.py
INSTALL AND CONFIGURE THE PYTHON
PROGRAMMING ENVIRONMENT
5. The Python Command Line (Python can be run as a command line itself)
• Open a command prompt or terminal,
• Run python,
C:\Users\Your Name>python

• From there you can write any python,


C:\Users\Administrator.HOANPM.000.001.002.003.004.005.006>python
Python 3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello world!")
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT)
An Integrated Development Environment (IDE) is a software application that
provides a comprehensive set of tools for software development. It combines
several tools traditionally used by programmers into a single, user-friendly
interface, streamlining the development process and increasing productivity.
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT)
Here are some key features of IDEs:
• Source code editor: This is the main tool for writing and editing code. IDEs offer
features like syntax highlighting, code completion, and indentation styles to make
coding easier and more efficient.
• Buildautomation tools: IDEs can automate tasks like compiling, linking, and
running your code, saving you time and effort.
• Debugger: This tool helps you identify and fix errors in your code. IDEs often
provide visual representations of your code execution and allow you to set
breakpoints to step through your code line by line.
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT)
Here are some key features of IDEs:
• Version control system (VCS) integration: IDEs can integrate with VCS like Git
to help you track changes to your code and collaborate with other developers.
• Project management tools: IDEs can help you organize your code into projects,
set up dependencies, and manage tasks.
• Testing tools: Some IDEs include built-in testing tools or integrate with external
testing frameworks to help you test your code.
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT)
Popular IDEs:
• PyCharm: A popular IDE for Python development
• Visual Studio Code: A versatile IDE that supports many programming languages
and frameworks
• WebStorm: An IDE for web development with support for JavaScript, HTML,
CSS, and other web technologies
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT) - PYCHARM
• PyCharm is an integrated development environment (IDE) specifically
designed for working with the Python programming language. It's developed
by JetBrains, a renowned company known for creating high-quality
developer tools.
• PyCharm provides a comprehensive set of features to help you write, run,
debug, and test your Python code efficiently and effectively.
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT) - PYCHARM
Install PyCharm:
• Goto https://www.jetbrains.com/pycharm/ and choose the appropriate edition
(Community or Professional).
• Click on Download and select the installer for your operating system (Windows,
macOS, or Linux).
• Run the installer and follow the on-screen instructions.
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT) - PYCHARM
Utilities:
• Project Management:
• Create and open new projects.
• Organize your code into modules and packages.
• Integrate with popular version control systems like Git.
• Code Editor:
• Benefit from intelligent code completion, syntax highlighting, and error checking.
• Refactor your code for better readability and maintainability.
• Leverage built-in tools for popular frameworks like Django and Flask.
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT) - PYCHARM
Utilities:
• Debugger:
• Step through your code line by line to identify and fix errors.
• Set breakpoints to pause execution at specific points.
• Inspect variables and expressions to understand their values.
• Testing:
• Run and debug unit tests directly within the IDE.
• Utilize PyCharm's built-in test runner and coverage tools.
INTRODUCTION TO IDE (INTEGRATED
DEVELOPMENT ENVIRONMENT) - PYCHARM
Utilities:
• Additional Features:
• Explore the console for interactive Python environment.
• Access powerful tools for scientific computing and data analysis (in
Professional edition).
• Customize the IDE appearance and keyboard shortcuts to suit your
preferences.
SYNTAX
Execute Python Syntax:
• Execute by writing directly in the Command Line:
>>> print("Hello, World!")
Hello, World!
• Create a python file on the server, using the .py file extension, and running it in
the Command Line:
C:\Users\Your Name>python myfile.py
SYNTAX
Python Indentation:
• Indentation refers to the spaces at the beginning of a code line (one or more, at
least one).
• Python uses indentation to indicate a block of code.
• Example:
for i in range(5):
print("Looping!")
SYNTAX
Python 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.
• Comments starts with a #, and Python will ignore them:
#This is a comment
print("Hello, World!")

Or:
print("Hello, World!") #This is a comment
SYNTAX
Python Comments:
• Multiline Comments:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
SYNTAX
Variables: Variables are containers for storing data values.
• Creating Variables:
x=5
y = "John"
print(x)
print(y)

• Casting (specify the data type of a variable):


x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
SYNTAX
Variables: Variables are containers for storing data values.
• Get the Type: use type() function to get data type of a variable.
x=5
y = "John"
print(type(x))
print(type(y))

• Single or Double Quotes: string value.


x = “John”
#is the same as
x = ‘John’
SYNTAX
Variables: Variables are containers for storing data values.
• Many Values to Multiple Variables:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• One Value to Multiple Variables
x = y = z = "Orange"
print(x)
print(y)
print(z)
SYNTAX
Variables: Variables are containers for storing data values.
• Unpack a Collection: If you have a collection of values in a list, tuple etc. Python
allows you to extract the values into variables.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
SYNTAX
Variables: Variables are containers for storing data values.
• Global Variables: Variables that are created outside of a function (as in all of the
examples above) are known as global variables.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
SYNTAX
Variables: Variables are containers for storing data values.
• The global Keyword: 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)
SYNTAX
Python print() Function.
• The print() function prints the specified message to the screen, or other standard
output device.
• The message can be a string, or any other object, the object will be converted into
a string before written to the screen.
SYNTAX
Python print() Function.
• Syntax
print(object(s), sep=separator, end=end, file=file, flush=flush)
Parameter Description

object(s) Any object, and as many as you like. Will be converted to string before printed

sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default is ' '

end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)

file Optional. An object with a write method. Default is sys.stdout

flush Optional. A Boolean, specifying if the output is flushed (True) or buffered (False).
Default is False
PYTHON DATA TYPES
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
PYTHON NUMBERS
• There are three numeric types in Python:
int
float
complex
• Type Conversion: convert from one type to another with the int(), float(), and
complex() methods.
• Random Number: Python has a built-in module called random that can be used to
make random numbers
#Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
PYTHON STRINGS
• Strings in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "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.
a = "Hello"
print(a)
PYTHON STRINGS
• Multiline Strings: Can assign a multiline string to a variable by using three quotes.
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

• Strings are Arrays: Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])
PYTHON STRINGS
• String Length: To get the length of a string, use the len() function.
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.
txt = "The best things in life are free!"
print("free" in txt)
PYTHON STRINGS
• String Methods
Learn more about String Methods with our String Methods Reference:
https://www.w3schools.com/python/python_ref_string.asp
PYTHON BOOLEANS
• Booleans represent one of two values: True or False.
print(10 > 9)
print(10 == 9)
print(10 < 9)
• Evaluate Values and Variables
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
PYTHON OPERATORS
• Python Arithmetic Operators
Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y
PYTHON OPERATORS
• Python Assignment Operators
Operator Example Same As
= 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
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
PYTHON OPERATORS
• Python Comparison Operators
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
PYTHON OPERATORS
• Python Logical Operators

Operator Description Example


and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
PYTHON LISTS
• 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.
• Ex:
thislist = ["apple", "banana", "cherry"]
print(thislist)
PYTHON LISTS
• 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.Lists are created using square brackets.
• Ex:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
PYTHON LISTS
• List Length
• To determine how many items a list has, use the len() function.
• List Items - Data Types: List items can be of any data type
print(thislist)
• type(): lists are defined as objects with the data type 'list’.
• The list() Constructor: It is also possible to use the list() constructor when
creating a new list.
PYTHON COLLECTIONS (ARRAYS)
• There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered, unchangeable*, and unindexed. No
duplicate members.
• Dictionary is a collection which is ordered** and changeable. No
duplicate members.
PYTHON TUPLES
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Ex:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
PYTHON TUPLES
• 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.
• 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.
PYTHON SETS
• Sets are used to store multiple items in a single variable.
• A set is a collection which is unordered, unchangeable*, and unindexed.
• Sets are written with curly brackets.
• Ex:
thisset = {"apple", "banana", "cherry"}
print(thisset)
PYTHON SETS
• 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.

• Duplicates Not Allowed


• Sets cannot have two items with the same value.
PYTHON DICTIONARIES
• 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.
• Dictionaries are written with curly brackets, and have keys and values.
• Ex:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
PYTHON DICTIONARIES
• 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. Dictionaries are written with curly brackets, and have keys and values.

• Ex:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
PYTHON DICTIONARIES
• Ordered or Unordered?
• 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:
• Ex:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
SYNTAX
Example 1: solve the equation ax + b = 0
"""
Solves the linear equation ax + b = 0 for x.
Args:
a: The coefficient of the x term.
b: The constant term.
Returns:
The solution for x, or None if a is 0 and b is not 0,
or float('inf') if both a and b are 0.
"""
SYNTAX
Example 1: solve the equation ax + b = 0
def solve_linear_equation(a, b):
if a == 0:
if b != 0:
return None # No solution if a is 0 and b is not 0
else:
return float('inf') # Infinite solutions if a and b are both 0
else:
return -b / a
SYNTAX
Example 1: solve the equation ax + b = 0
# Example usage:
a=2
b=3
solution = solve_linear_equation(a, b)
print(f"The solution for the equation {a}x + {b} = 0 is x = {solution}")
SYNTAX
Example 2: solve the equation ax2 + bx + c = 0
"""
This function solves the quadratic equation ax^2 + bx + c = 0 using the quadratic formula.
Args:
a: The coefficient of the x^2 term.
b: The coefficient of the x term.
c: The constant term.
Returns:
A tuple containing the two solutions of the equation, or None if there are no real solutions.
"""
SYNTAX
Example 2: solve the equation ax2 + bx + c = 0
def quadratic_equation(a, b, c):
if a == 0:
return None # Not a quadratic equation
discriminant = b**2 - 4 * a * c
if discriminant < 0:
return None # No real solutions
elif discriminant == 0:
return -b / (2 * a) # One real solution
else:
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
return root1, root2
SYNTAX
Example 2: solve the equation ax2 + bx + c = 0
# Example usage
a=1
b=2
c=1
roots = quadratic_equation(a, b, c)
if roots is None:
print("No real solutions")
elif isinstance(roots, float):
print("One real solution:", roots)
else:
print("Two real solutions:", roots[0], roots[1])
PYTHON IF ... ELSE
Python Conditions and If statements:
Python supports the usual logical conditions from mathematics:
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.
PYTHON IF ... ELSE
Python Conditions and If statements:
• An "if statement" is written by using the if keyword.
Ex:
a = 33
b = 200
if b > a:
print("b is greater than a")
PYTHON IF ... ELSE
Python Conditions and If statements:
• Elif: The elif keyword is Python's way of saying "if the previous conditions were not true, then try
this condition".
Ex:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
PYTHON IF ... ELSE
Python Conditions and If statements:
• Short Hand If ... Else
Ex: If you have only one statement to execute:
if a > b: print("a is greater than b")
Ex: If you have two statement to execute, one for if, and one for else:
a=2
b = 330
print("A") if a > b else print("B")
Ex: You can also have multiple else statements on the same line:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
PYTHON IF ... ELSE
Python Conditions and If statements:
• The and, or, and not keyword is a logical operator, they are used to combine conditional
statements:
Ex:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
if a > b or a > c:
print("At least one of the conditions is True")
if not a > b:
print("a is NOT greater than b")
PYTHON IF ... ELSE
Python Conditions and If statements:
• Nested If: You can have if statements inside if statements, this is called nested if statements.
Ex:
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
PYTHON LOOPS
• Python has two primitive loop commands:
• while loops
• for loops
THE WHILE LOOPS
• The while loops: With the while loop we can execute a set of
statements as long as a condition is true.
• Ex:
i=1
while i < 6:
print(i)
i += 1
THE WHILE LOOPS
• The else Statement: With the else statement we can run a
block of code once when the condition no longer is true.
• Ex:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
THE FOR LOOPS
• The for loops: A for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set, or a string).
• Ex:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
THE FOR LOOPS
• Looping Through a String: Even strings are iterable objects,
they contain a sequence of characters.
• Ex:
for x in "banana":
print(x)
THE FOR LOOPS
• The range() Function: To loop through a set of code a
specified number of times, we can use the range() function.
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.
• Ex:
for x in range(6):
print(x)
THE FOR LOOPS
• The range() Function: The range() function defaults to 0 as a
starting value, however it is possible to specify the starting
value by adding a parameter: range(start, end), which means
values from start to end (but not including end).
• Ex:
for x in range(2, 6):
print(x)
THE FOR LOOPS
• The break Statement: With the break statement we can stop
the loop before it has looped through all the items.
• Ex:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
THE FOR LOOPS
• The continue Statement: With the continue statement we can stop the
current iteration of the loop, and continue with the next.
• Ex:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
THE FOR LOOPS
• Else in For Loop: The else keyword in a for loop specifies a block of
code to be executed when the loop is finished.
• Ex:
for x in range(6):
print(x)
else:
print("Finally finished!")
THE FOR LOOPS
• Nested Loops: A nested loop is a loop inside a loop. The "inner loop"
will be executed one time for each iteration of the "outer loop".
• Ex:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
PYTHON FUNCTIONS
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
PYTHON FUNCTIONS
• Creating a Function.
• In Python a function is defined using the def keyword.
• Example:
def my_function():
print("Hello from a function")
PYTHON FUNCTIONS
• Arguments.
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
• Example:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
PYTHON FUNCTIONS
• Number of Arguments.
• By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
• Example: This function expects 2 arguments, and gets 2 arguments.
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
PYTHON FUNCTIONS
• Arbitrary Arguments, *args.
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the
items accordingly
• Example:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
PYTHON FUNCTIONS
• Return Values.
• To let a function return a value, use the return statement.
• Example:
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
PYTHON MODULES
• Consider a module to be the same as a code library.
• A file containing a set of functions you want to include in your application.
PYTHON MODULES
• Create a Module.
• To create a module just save the code you want in a file with the file extension
.py.
• Example: Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
PYTHON MODULES
• Use a Module.
• Now can use the module just created, by using the import statement.
• Example:
import mymodule

mymodule.greeting("Jonathan")
PYTHON MODULES
• Variables in Module.
• The module can contain functions, as already described, but also variables of
all types (arrays, dictionaries, objects etc).
• Example: Save this code in the file mymodule.py.
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
PYTHON MODULES
• Variables in Module.
• Example: Import the module named mymodule, and access the person1
dictionary.
import mymodule

a = mymodule.person1["age"]
print(a)
PYTHON MODULES
• Naming a Module.
• You can name the module file whatever you like, but it must have the file
extension .py.

• Re-naming a Module.
• You can create an alias when you import a module, by using the as keyword.
• Example: Create an alias for mymodule called mx.
import mymodule as mx

a = mx.person1["age"]
print(a)
PYTHON MODULES
• Built-in Modules.
• There are several built-in modules in Python, which you can import whenever
you like.
• Example: Import and use the platform module.
import platform

x = platform.system()
print(x)
PYTHON MODULES
• Using the dir() Function.
• There is a built-in function to list all the function names (or variable names) in
a module. The dir() function.
• Example: List all the defined names belonging to the platform module.
import platform

x = dir(platform)
print(x)
OBJECT ORIENTED PROGRAMMING
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and
methods.
•A Class is like an object constructor, or a "blueprint" for creating
objects.
OBJECT ORIENTED PROGRAMMING
• Create a Class.
• To create a class, use the keyword class.
• Example:
class MyClass:
x=5
OBJECT ORIENTED PROGRAMMING
• Create Object.
• Create an object named p1, and print the value of x.
• Example:
p1 = MyClass()
print(p1.x)
OBJECT ORIENTED PROGRAMMING
• The __init__() Function.
• All classes have a function called __init__(), which is always executed when
the class is being initiated.
• Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created.
OBJECT ORIENTED PROGRAMMING
• The __init__() Function.
• Example: Create a class named Person, use the __init__() function to assign values for name
and age
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
• Note: The __init__() function is called automatically every time the class is being used to
create a new object.
OBJECT ORIENTED PROGRAMMING
• The __str__() Function.
• The __str__() function controls what should be returned when the class object
is represented as a string.
• If the __str__() function is not set, the string representation of the object is
returned.
OBJECT ORIENTED PROGRAMMING
• The __str__() Function.
• Example: The string representation of an object WITH the __str__() function.
class Person:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}({self.age})"
p1 = Person("John", 36)
print(p1)
OBJECT ORIENTED PROGRAMMING
• Object Methods.
• Objects can also contain methods. Methods in objects are functions that belong to the object.
• Example: Insert a function that prints a greeting, and execute it on the p1 object.
class Person:
def __init__(self, name, age):
self.name = name
Note: The self parameter is a reference to the
self.age = age current instance of the class, and is used to
def myfunc(self): access variables that belong to the class.

print("Hello my name is " + self.name)


p1 = Person("John", 36)
p1.myfunc()
OBJECT ORIENTED PROGRAMMING
• The self Parameter.
• The self parameter is a reference to the current instance of the class, and is
used to access variables that belongs to the class.
• It does not have to be named self , you can call it whatever you like, but it has
to be the first parameter of any function in the class.
OBJECT ORIENTED PROGRAMMING
• The self Parameter.
• Example: Use the words mysillyobject and abc instead of self.
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
OBJECT ORIENTED PROGRAMMING
• Modify Object Properties.
• You can modify properties on objects.
• Example: Set the age of p1 to 40.
p1.age = 40

• Delete Object Properties.


• You can delete properties on objects by using the del keyword.
• Example:
del p1.age

• Delete Objects
• You can delete objects by using the del keyword
• Example: Delete the p1 object.
del p1
DEBUGGING AND FIXING ERRORS
SUMMARY

You might also like