SlideShare a Scribd company logo
1 of 57
Click to edit Master title style
1
2 Python Fundamentals
Course: PROG12583
Click to edit Master title style
2 2
Objectives
At the end of this module, students will be able to:
• Define the fundamentals of computer programming with Python
language.
• Analyze code syntax.
• Apply the programming fundamentals by writing python programs using
the IDE (Visual Studio Code).
• Identify different types of errors in a program and fix them.
• Define and analyze numbers and arithmetic expressions through code.
Python Fundamentals
Click to edit Master title style
3 3
Python Fundamentals
Part - 1
Click to edit Master title style
4 4
Block of statements:
• A statement in Python is the instructions you type in the editor (visual
studio code) that interpreter executes, e.g., print(“Hello World!”). Python
interpreter executes the print statement and displays the result to the
console.
• A block is a group of statements in a program or script. Usually, it
consists of at least one statement and of declarations for the block,
depending on the programming or scripting language. Your code could
also contain nested blocks.
Python Fundamentals
Click to edit Master title style
5 5
Block of statements: an example of a block of statement (lines 3 and 4)
Python Fundamentals
Click to edit Master title style
6 6
Rules for coding Python
• Python relies on proper indentation.
• Unlike many programming languages, the indentation of each line
matters in a Python program. With Python, the indentation is typically
four spaces (or one tab).
• Python doesn't use braces { } to indicate blocks of code for class and
function definitions or flow control.
• Blocks of code are denoted by line indentation, which is rigidly
enforced. All statements within the block must be indented the same
amount.
Python Fundamentals
Click to edit Master title style
7 7
Indentation Examples:
• A good indentation in Python:
Python Fundamentals
Click to edit Master title style
8 8
Indentation Examples:
• An indentation that causes an error:
Python Fundamentals
Click to edit Master title style
9 9
Statement continuation:
• You can use implicit continuation.
• To do that, you divide a statement before or after an operator like a plus
or minus sign.
• You can also divide a statement after an opening parenthesis.
Python Fundamentals
Click to edit Master title style
10
10
Statement continuation:
• You can also use explicit continuation.
• To do that, you code a backslash to show that a line is continued.
• However, this way is discouraged.
Python Fundamentals
Click to edit Master title style
11
11
Comments:
• Adding comments to programs is a very important practice in
programming.
• Comments are added for people (not the computer) to understand what
a part of the program does – they are notes added by programmers to
explain part for the code.
• Python interpreter ignores the comments – it does not execute them.
They have no effect on the operation of the program.
Python Fundamentals
Click to edit Master title style
12
12
Comments:
• To add a comment to describe a portion of the code, type # then type
the python statement.
• You can also add a comment after the statement (inline comments).
• Another way to add a comment is by commenting out a python
statement, if you don’t want the interpreter to execute that statement
(this is mainly for testing purpose).
Python Fundamentals
Click to edit Master title style
13
13
Comment examples:
Python Fundamentals
Click to edit Master title style
14
14
Quotation in Python:
• In programming terms, a sequence of characters that is used as data is
called a string.
• When a string appears in the actual code of a program, it is called a
string literal.
• In Python code, string literals must be enclosed in quote marks.
Python Fundamentals
Click to edit Master title style
15
15
Quotation in Python:
• Python accepts single ('), double (") and triple (''' or """) quotes to
denote string literals, as long as the same type of quote starts and ends
the string.
• The triple quotes are used to span the string across multiple lines. In
this case, the string can be a comment.
Python Fundamentals
Click to edit Master title style
16
16
Quotation in Python:
• The quote marks are not displayed when the statement executes.
• The quote marks simply specify the beginning and the end of the text
that you wish to display.
Python Fundamentals
output
Click to edit Master title style
17
17
Quotation in Python:
• If you want a string literal to contain either a single-quote or an
apostrophe as part of the string, you can enclose the string literal in
double-quote marks.
• Likewise, you can use single-quote marks to enclose a string literal that
contains double-quotes as part of the string.
Python Fundamentals
output
Click to edit Master title style
18
18
Working with datatypes and variables in Python:
• We saw three different types of data in the previous examples – string
(str), integer (int) and floating-point (float).
• The str data type holds string literals.
• The int and float data types hold numerical literals.
Python Fundamentals
Click to edit Master title style
19
19
Working with datatypes and variables in Python:
• When you develop a python program, you work with variables that store
data (values). Variables vary as code executes.
• To work with variables, you assign data to them using the assignment
operator (=). This is called (assignment statement).
• Initialization is when assign an initial value to a variable. Then different
values are assigned later in the program.
• You can assign literal values or literal strings to a variables.
Python Fundamentals
Click to edit Master title style
20
20
Working with datatypes and
variables in Python:
• To code a literal value for a string,
enclose the characters of the string
in single or double quotation
marks. This is called a string literal.
• To code a literal value for a
number, code the number without
quotation marks. This is called a
numeric literal.
Python Fundamentals
Click to edit Master title style
21
21
Working with datatypes and
variables in Python:
• You can also assign multiple
values to multiple variables in one
statement.
• Because variable names are
case-sensitive, you must be sure
to use the correct case when
coding the names of variables.
Python Fundamentals
Click to edit Master title style
22
22
Working with datatypes and variables in Python:
Variables naming conventions that must be respected by programmers
• A variable name must begin with a letter or underscore.
• A variable name can’t contain spaces, punctuation, or special
characters other than the underscore.
• A variable name can’t begin with a number, but can use numbers later
in the name.
• Use underscore notation or camel case.
• Use meaningful names that are easy to remember.
• Don’t use the names of built-in functions, such as print().
Python Fundamentals
Click to edit Master title style
23
23
Working with datatypes and variables in Python:
Variables naming conventions
A variable name can’t be the same as a keyword that’s reserved by Python.
Two naming styles for variables
Python Fundamentals
Click to edit Master title style
24
24
The print() function:
• The print function is one of the most important built-in functions in
python that you will be using to print out and display the results
(outputs) of the code to the screen.
• A function is a reusable unit of code that performs a specific task.
• Python provides many built-in functions that do common tasks like
getting input data from the user and printing output data to the console.
Python Fundamentals
Click to edit Master title style
25
Python Fundamentals
25
The print() function:
• When you call a function, you code the name of the
function followed by a pair of parentheses.
• Within the parentheses, you code any arguments
(could values of variables) that the function requires,
and you separate multiple arguments with commas.
• In a syntax summary like the one at the top of this
page, brackets [ ] mark the portions of code that are
optional.
• The italicized portions of the summary are the ones that
you have to supply.
• But note that the arguments are optional. If no
arguments are passed to this function, it prints a blank
line.
Click to edit Master title style
26
Python Fundamentals
26
The print() function:
Click to edit Master title style
27
Python Fundamentals
27
The print() function:
• Print can take other arguments like (sep)
and (end).
• sep: string inserted between values,
default a space.
• end: string appended after the last value,
default a newline.
Click to edit Master title style
28
Python Fundamentals
28
The type() function:
• type() is another built-in function that can
be used by programmers to debug their
code( debugging is the process of
identifying and fixing bugs in the software).
• It returns the class type of object (data)
passed to it, in between the parenthesis.
• The example, on the right, shows the data
type of list (line 1), tuple (line 2), string (line
3), float (line 4) and integer (line 5).
• We will discuss more of the data types
later.
Click to edit Master title style
29
Python Fundamentals
29
Type casting (conversions):
• There are two types of type conversion in
python; implicit and explicit type
conversions.
• In the implicit, python automatically
converts one data type to another.
• Python can perform the conversion of
lower datatypes to the higher without data
loss like converting integer to float.
Click to edit Master title style
30
Python Fundamentals
30
Type casting (conversions):
• In the explicit, programmers perform the conversion using some pre-defined functions
(e.g., int(), float(), str()).
• The int() converts numbers with decimals (e.g., 89.5) or literal values in between quotes (
‘123’) into integer.
• The float() converts integers to float format (adding a zero after the decimal point) or literal
values in between quotes into float.
• You cannot convert string literal into numbers (e.g., “abc” into a number).
• The str() converts values into strings (e.g., 87 into “87”).
Click to edit Master title style
31
Python Fundamentals
31
Type casting (conversions):
Click to edit Master title style
32
Python Fundamentals
32
Types of errors:
• As you test your program, three types of errors can occur.
• Syntax errors prevent your program from compiling and running. Since syntax
errors occur when Python attempts to compile a program, they’re known as
compile-time errors. This type of error is the easiest to find and fix.
• When you use Visual Studio Code, it highlights the location of the syntax errors
that it finds each time you attempt to run the program. Then, you can correct that
error and try again.
Click to edit Master title style
33
Python Fundamentals
33
Types of errors:
Common syntax errors
• Misspelling keywords.
• Forgetting the colon at the end of the opening line of a function definition, if clause,
else clause, while statement, for statement, try clause, or except clause.
• Forgetting an opening or closing quotation mark or parenthesis.
• Using parentheses when you should be using brackets, or vice versa.
• Improper indentation.
Click to edit Master title style
34
Python Fundamentals
34
Types of errors:
• Syntax error example (can you figure what causes theses errors?!)
Click to edit Master title style
35
Python Fundamentals
35
Types of errors:
• Runtime errors don’t violate the syntax rules, but
they throw exceptions (errors that python
interpreter generates and displayed in the
console or the terminal) that stop the execution of
the program. Many of these exceptions are due to
programming errors that need to be fixed.
• This example shows the runtime error occurs
when trying to divide a value by zero. You notice
that there was no syntax error meaning the
program was compiled and run and then python
threw an exception: ZeroDivisionError: division by zero
Click to edit Master title style
36
Python Fundamentals
36
Types of errors:
• Logic errors are statements that don’t cause syntax or runtime errors, but produce
the wrong results. In the example shown above the program produced a wrong
result. The value of average should be 90, not 260.
• It is the programmer’s responsibility to ensure that the code is written right so the
result is right.
• (can you try and fix the error ?!!)
Click to edit Master title style
37
Python Fundamentals
37
Class exercises: Do it yourself !
Write a python program to produce the following output (define variables
and assign values to them, then use print function).
Click to edit Master title style
38
Python Fundamentals
38
Class exercises: Do it yourself !
Write a python program that contains 4 variables for 4 grades of a
student. Assign values to the variables. Find the sum of the 4 grades.
Make sure to use explicit continuation for the sum statement. Print the
sum and use the end keyword in the print statement. Your program should
start with a comment that spans two lines to describe your code.
Click to edit Master title style
39
Python Fundamentals
39
Class exercises: Do it yourself !
Write a python program that assign 3 tax amounts to 3 variables all in one
statement. Then print all the values using one print statement with the sep
keyword.
Click to edit Master title style
40
40
Working with numeric data
and arithmetic operations
Part - 2
Click to edit Master title style
41
Python Fundamentals
41
• Arithmetic operators consist of two or more
operands that are operated upon by arithmetic
operators.
• The operands in an expression can be either
numeric variables or numeric literals.
• The +, -, * and / are the same as those used in
basic arithmetic.
• Python also has an operator for integer division (//)
that truncates the decimal portion of the division. It
has a modulo operator (%), or remainder operator,
that returns the remainder of a division. And it has
an exponentiation operator (**) that raises a number
to the specified power.
Click to edit Master title style
42
42
Python Fundamentals
Click to edit Master title style
43
Python Fundamentals
43
• The order of precedence: when an expression
includes two or more operators, the order of
precedence determines which operators are applied
first. This order is summarized in the table in this
figure. For instance, Python performs all
multiplication and division operations from left to
right before it performs any addition and subtraction
operations.
• If you need to override the default order of
precedence, you can use parentheses. Then,
Python performs the expressions in the innermost
sets of parentheses first, followed by the
expressions in the next sets of parentheses, and so
on.
Click to edit Master title style
44
Python Fundamentals
44
• On the right side:
Code that calculates sales tax
Code that calculates the perimeter
of a rectangle
Click to edit Master title style
45
Python Fundamentals
45
• The compound assignment(=) operators provide a shorthand way to code common
assignment statements.
• For instance, the += operator modifies the value of the variable on the left of the
operator by adding the value of the expression on the right to the value of the variable
on the left. When you use this operator, the variable on the left must already have
been initialized.
• The other operators, -= and *= work similarly.
Click to edit Master title style
46
Python Fundamentals
46
Click to edit Master title style
47
Python Fundamentals
47
Floating-point numbers:
• A floating-point number consists of a positive or negative sign, a decimal value for the
significant digits, and an optional exponent.
• Floating-point numbers provide for very large and very small numbers, but with a
limited number of significant digits. The float type can only use 16 significant digits to
store the number.
• To express the value of a floating-point number, you can use scientific notation.
• This notation consists of an optional plus sign or a required minus sign, a decimal
value for the significant digits, the letter e or E, and a positive or negative exponent.
For example:
2.302e+5
Click to edit Master title style
48
Python Fundamentals
48
Floating-point numbers:
• In this example, the number contains four significant digits (2.302), and the exponent
specifies how many places the decimal point should be moved to the right or to the
left. Here, the exponent is positive so the point is moved to the right and the value is:
230,200
• But if the exponent was negative (e-5), the point would be moved to the left and the
value would be:
.00002302
• An integer is an exact value that yields expected results.
• A floating-point number is an approximate value that can yield unexpected results
known as floating-point errors.
Click to edit Master title style
49
Python Fundamentals
49
Floating-point numbers:
• The floating-point numbers are approximate values,
not exact values. Look at this example:
• In this example, Balance should be 300.30
• As a result, they sometimes cause floating-point errors.
• To fix this error, we use round() function. The round()
function can take additional argument which is an integer
that represents the number of digits to display after the
decimal point.
Click to edit Master title style
50
Python Fundamentals
50
The standard math module:
• The math module for Python provides many functions
for mathematical, trigonometric, and logarithmic operations.
• The floating-point numbers are approximate values,
not exact values. Look at this example:
Balance should be 300.30
• As a result, they sometimes cause floating-point errors.
• To fix this error, we use round() function. The round()
function can take additional argument which is an integer
that represents the number of digits to display after the
decimal point.
Click to edit Master title style
51
Python Fundamentals
51
The standard math module:
• We list four common functions and the pi constant that required importing the math
module.
• You can use the ceil() function if you always want to round up (towards the ceiling).
And you can use the floor() function if you always want to round down (towards the
floor). See examples in next slide
* you can also use the exponential operator (**) to raise a number to the power.
Click to edit Master title style
52
Python Fundamentals
52
The standard math module:
• The m in the import statement is called alias that is defined so we use through
the program instead of using the module name – math.
Click to edit Master title style
53
Python Fundamentals
53
The standard math module:
• The m in the import statement is called alias that is
defined so we use through the program instead of
using the module name – math.
Click to edit Master title style
54
Python Fundamentals
54
Class exercises: Do it yourself !
• Create a program that calculates a user’s weekly gross and take-home pay.
• Follow the Console (on the right) and assign values to the hours Worked and hourly pay rate.
Specifications
The formula for calculating gross pay is:
 gross pay = hours worked * hourly rate
The formula for calculating tax amount is:
 tax amount = gross pay * (tax rate / 100)
The formula for calculating take home pay is:
 take home pay = gross pay – tax amount
• The tax rate should be 18%, but the program should store the tax rate in a variable so
you can easily change the tax rate later just by changing the value that’s stored in the variable.
Console
Pay Check Calculator
Hours Worked: 35
Hourly Pay Rate: 14.50
Gross Pay: 507.5
Tax Rate: 18%
Tax Amount: 91.35
Take Home Pay: 416.15
Click to edit Master title style
55
Python Fundamentals
55
Class exercises: Do it yourself !
• Create a program that calculates total sales and dsplays the following information to the
console.
• Follow the Console (on the right) and assign values to the cost of the meal and the tip percent.
Specifications
The formula for calculating the tip amount is:
 tip = cost of meal * (tip percent / 100)
Console
Tip Calculator
Cost of meal: 52.31
Tip percent: 20
Tip amount: 10.46
Total amount: 62.77
Click to edit Master title style
56
Python Fundamentals
56
Class exercises: Do it yourself !
• Create a program that converts the temperature in Celsius into Fahrenheit and vice versa.
• Follow the Console (on the right) and assign values to the cost of the meal and the tip percent.
Specifications
The formula for calculating the tip amount is:
 Fahrenheit = (Celsius * 9/5) + 32
 Celsius = (Fahrenheit – 32) * 5/9
Console
Temperature conversion Calculator
In Celsius: 20.0
In Fahrenheit: 68.0
In Fahrenheit: 68.0
In Celsius: 20.0
Click to edit Master title style
57
57
Material has been taken from (can be accessed through Sheridan's Library Services) :
• Starting Out with Python (ISBN-13: 9780136912330 ):
• https://www.pearson.com/en-ca/subject-catalog/p/starting-out-with-
python/P200000003356/9780136912330
• Murach’s Python 2nd Edition programming, 2nd Edition :
• https://bookshelf.vitalsource.com/reader/books/9781943872756/pages/recent
• Introducing Python, Lubanovic, B., O'Reily Media, 2nd Edition, 2019
• https://www.oreilly.com/library/view/introducing-python-
2nd/9781492051374/
References

More Related Content

Similar to Python Fundamentals for the begginers in programming

Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this ppt
ANISHYAPIT
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar
 

Similar to Python Fundamentals for the begginers in programming (20)

Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python for katana
Python for katanaPython for katana
Python for katana
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
 
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfCSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this ppt
 
1.3 Basic coding skills_tupels_sets_controlloops.ppt
1.3 Basic coding skills_tupels_sets_controlloops.ppt1.3 Basic coding skills_tupels_sets_controlloops.ppt
1.3 Basic coding skills_tupels_sets_controlloops.ppt
 
17575602.ppt
17575602.ppt17575602.ppt
17575602.ppt
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
490450755-Chapter-2.ppt
490450755-Chapter-2.ppt490450755-Chapter-2.ppt
490450755-Chapter-2.ppt
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
GE3151_PSPP_UNIT_2_Notes
GE3151_PSPP_UNIT_2_NotesGE3151_PSPP_UNIT_2_Notes
GE3151_PSPP_UNIT_2_Notes
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning Introduction to Python for Data Science and Machine Learning
Introduction to Python for Data Science and Machine Learning
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 

Python Fundamentals for the begginers in programming

  • 1. Click to edit Master title style 1 2 Python Fundamentals Course: PROG12583
  • 2. Click to edit Master title style 2 2 Objectives At the end of this module, students will be able to: • Define the fundamentals of computer programming with Python language. • Analyze code syntax. • Apply the programming fundamentals by writing python programs using the IDE (Visual Studio Code). • Identify different types of errors in a program and fix them. • Define and analyze numbers and arithmetic expressions through code. Python Fundamentals
  • 3. Click to edit Master title style 3 3 Python Fundamentals Part - 1
  • 4. Click to edit Master title style 4 4 Block of statements: • A statement in Python is the instructions you type in the editor (visual studio code) that interpreter executes, e.g., print(“Hello World!”). Python interpreter executes the print statement and displays the result to the console. • A block is a group of statements in a program or script. Usually, it consists of at least one statement and of declarations for the block, depending on the programming or scripting language. Your code could also contain nested blocks. Python Fundamentals
  • 5. Click to edit Master title style 5 5 Block of statements: an example of a block of statement (lines 3 and 4) Python Fundamentals
  • 6. Click to edit Master title style 6 6 Rules for coding Python • Python relies on proper indentation. • Unlike many programming languages, the indentation of each line matters in a Python program. With Python, the indentation is typically four spaces (or one tab). • Python doesn't use braces { } to indicate blocks of code for class and function definitions or flow control. • Blocks of code are denoted by line indentation, which is rigidly enforced. All statements within the block must be indented the same amount. Python Fundamentals
  • 7. Click to edit Master title style 7 7 Indentation Examples: • A good indentation in Python: Python Fundamentals
  • 8. Click to edit Master title style 8 8 Indentation Examples: • An indentation that causes an error: Python Fundamentals
  • 9. Click to edit Master title style 9 9 Statement continuation: • You can use implicit continuation. • To do that, you divide a statement before or after an operator like a plus or minus sign. • You can also divide a statement after an opening parenthesis. Python Fundamentals
  • 10. Click to edit Master title style 10 10 Statement continuation: • You can also use explicit continuation. • To do that, you code a backslash to show that a line is continued. • However, this way is discouraged. Python Fundamentals
  • 11. Click to edit Master title style 11 11 Comments: • Adding comments to programs is a very important practice in programming. • Comments are added for people (not the computer) to understand what a part of the program does – they are notes added by programmers to explain part for the code. • Python interpreter ignores the comments – it does not execute them. They have no effect on the operation of the program. Python Fundamentals
  • 12. Click to edit Master title style 12 12 Comments: • To add a comment to describe a portion of the code, type # then type the python statement. • You can also add a comment after the statement (inline comments). • Another way to add a comment is by commenting out a python statement, if you don’t want the interpreter to execute that statement (this is mainly for testing purpose). Python Fundamentals
  • 13. Click to edit Master title style 13 13 Comment examples: Python Fundamentals
  • 14. Click to edit Master title style 14 14 Quotation in Python: • In programming terms, a sequence of characters that is used as data is called a string. • When a string appears in the actual code of a program, it is called a string literal. • In Python code, string literals must be enclosed in quote marks. Python Fundamentals
  • 15. Click to edit Master title style 15 15 Quotation in Python: • Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. • The triple quotes are used to span the string across multiple lines. In this case, the string can be a comment. Python Fundamentals
  • 16. Click to edit Master title style 16 16 Quotation in Python: • The quote marks are not displayed when the statement executes. • The quote marks simply specify the beginning and the end of the text that you wish to display. Python Fundamentals output
  • 17. Click to edit Master title style 17 17 Quotation in Python: • If you want a string literal to contain either a single-quote or an apostrophe as part of the string, you can enclose the string literal in double-quote marks. • Likewise, you can use single-quote marks to enclose a string literal that contains double-quotes as part of the string. Python Fundamentals output
  • 18. Click to edit Master title style 18 18 Working with datatypes and variables in Python: • We saw three different types of data in the previous examples – string (str), integer (int) and floating-point (float). • The str data type holds string literals. • The int and float data types hold numerical literals. Python Fundamentals
  • 19. Click to edit Master title style 19 19 Working with datatypes and variables in Python: • When you develop a python program, you work with variables that store data (values). Variables vary as code executes. • To work with variables, you assign data to them using the assignment operator (=). This is called (assignment statement). • Initialization is when assign an initial value to a variable. Then different values are assigned later in the program. • You can assign literal values or literal strings to a variables. Python Fundamentals
  • 20. Click to edit Master title style 20 20 Working with datatypes and variables in Python: • To code a literal value for a string, enclose the characters of the string in single or double quotation marks. This is called a string literal. • To code a literal value for a number, code the number without quotation marks. This is called a numeric literal. Python Fundamentals
  • 21. Click to edit Master title style 21 21 Working with datatypes and variables in Python: • You can also assign multiple values to multiple variables in one statement. • Because variable names are case-sensitive, you must be sure to use the correct case when coding the names of variables. Python Fundamentals
  • 22. Click to edit Master title style 22 22 Working with datatypes and variables in Python: Variables naming conventions that must be respected by programmers • A variable name must begin with a letter or underscore. • A variable name can’t contain spaces, punctuation, or special characters other than the underscore. • A variable name can’t begin with a number, but can use numbers later in the name. • Use underscore notation or camel case. • Use meaningful names that are easy to remember. • Don’t use the names of built-in functions, such as print(). Python Fundamentals
  • 23. Click to edit Master title style 23 23 Working with datatypes and variables in Python: Variables naming conventions A variable name can’t be the same as a keyword that’s reserved by Python. Two naming styles for variables Python Fundamentals
  • 24. Click to edit Master title style 24 24 The print() function: • The print function is one of the most important built-in functions in python that you will be using to print out and display the results (outputs) of the code to the screen. • A function is a reusable unit of code that performs a specific task. • Python provides many built-in functions that do common tasks like getting input data from the user and printing output data to the console. Python Fundamentals
  • 25. Click to edit Master title style 25 Python Fundamentals 25 The print() function: • When you call a function, you code the name of the function followed by a pair of parentheses. • Within the parentheses, you code any arguments (could values of variables) that the function requires, and you separate multiple arguments with commas. • In a syntax summary like the one at the top of this page, brackets [ ] mark the portions of code that are optional. • The italicized portions of the summary are the ones that you have to supply. • But note that the arguments are optional. If no arguments are passed to this function, it prints a blank line.
  • 26. Click to edit Master title style 26 Python Fundamentals 26 The print() function:
  • 27. Click to edit Master title style 27 Python Fundamentals 27 The print() function: • Print can take other arguments like (sep) and (end). • sep: string inserted between values, default a space. • end: string appended after the last value, default a newline.
  • 28. Click to edit Master title style 28 Python Fundamentals 28 The type() function: • type() is another built-in function that can be used by programmers to debug their code( debugging is the process of identifying and fixing bugs in the software). • It returns the class type of object (data) passed to it, in between the parenthesis. • The example, on the right, shows the data type of list (line 1), tuple (line 2), string (line 3), float (line 4) and integer (line 5). • We will discuss more of the data types later.
  • 29. Click to edit Master title style 29 Python Fundamentals 29 Type casting (conversions): • There are two types of type conversion in python; implicit and explicit type conversions. • In the implicit, python automatically converts one data type to another. • Python can perform the conversion of lower datatypes to the higher without data loss like converting integer to float.
  • 30. Click to edit Master title style 30 Python Fundamentals 30 Type casting (conversions): • In the explicit, programmers perform the conversion using some pre-defined functions (e.g., int(), float(), str()). • The int() converts numbers with decimals (e.g., 89.5) or literal values in between quotes ( ‘123’) into integer. • The float() converts integers to float format (adding a zero after the decimal point) or literal values in between quotes into float. • You cannot convert string literal into numbers (e.g., “abc” into a number). • The str() converts values into strings (e.g., 87 into “87”).
  • 31. Click to edit Master title style 31 Python Fundamentals 31 Type casting (conversions):
  • 32. Click to edit Master title style 32 Python Fundamentals 32 Types of errors: • As you test your program, three types of errors can occur. • Syntax errors prevent your program from compiling and running. Since syntax errors occur when Python attempts to compile a program, they’re known as compile-time errors. This type of error is the easiest to find and fix. • When you use Visual Studio Code, it highlights the location of the syntax errors that it finds each time you attempt to run the program. Then, you can correct that error and try again.
  • 33. Click to edit Master title style 33 Python Fundamentals 33 Types of errors: Common syntax errors • Misspelling keywords. • Forgetting the colon at the end of the opening line of a function definition, if clause, else clause, while statement, for statement, try clause, or except clause. • Forgetting an opening or closing quotation mark or parenthesis. • Using parentheses when you should be using brackets, or vice versa. • Improper indentation.
  • 34. Click to edit Master title style 34 Python Fundamentals 34 Types of errors: • Syntax error example (can you figure what causes theses errors?!)
  • 35. Click to edit Master title style 35 Python Fundamentals 35 Types of errors: • Runtime errors don’t violate the syntax rules, but they throw exceptions (errors that python interpreter generates and displayed in the console or the terminal) that stop the execution of the program. Many of these exceptions are due to programming errors that need to be fixed. • This example shows the runtime error occurs when trying to divide a value by zero. You notice that there was no syntax error meaning the program was compiled and run and then python threw an exception: ZeroDivisionError: division by zero
  • 36. Click to edit Master title style 36 Python Fundamentals 36 Types of errors: • Logic errors are statements that don’t cause syntax or runtime errors, but produce the wrong results. In the example shown above the program produced a wrong result. The value of average should be 90, not 260. • It is the programmer’s responsibility to ensure that the code is written right so the result is right. • (can you try and fix the error ?!!)
  • 37. Click to edit Master title style 37 Python Fundamentals 37 Class exercises: Do it yourself ! Write a python program to produce the following output (define variables and assign values to them, then use print function).
  • 38. Click to edit Master title style 38 Python Fundamentals 38 Class exercises: Do it yourself ! Write a python program that contains 4 variables for 4 grades of a student. Assign values to the variables. Find the sum of the 4 grades. Make sure to use explicit continuation for the sum statement. Print the sum and use the end keyword in the print statement. Your program should start with a comment that spans two lines to describe your code.
  • 39. Click to edit Master title style 39 Python Fundamentals 39 Class exercises: Do it yourself ! Write a python program that assign 3 tax amounts to 3 variables all in one statement. Then print all the values using one print statement with the sep keyword.
  • 40. Click to edit Master title style 40 40 Working with numeric data and arithmetic operations Part - 2
  • 41. Click to edit Master title style 41 Python Fundamentals 41 • Arithmetic operators consist of two or more operands that are operated upon by arithmetic operators. • The operands in an expression can be either numeric variables or numeric literals. • The +, -, * and / are the same as those used in basic arithmetic. • Python also has an operator for integer division (//) that truncates the decimal portion of the division. It has a modulo operator (%), or remainder operator, that returns the remainder of a division. And it has an exponentiation operator (**) that raises a number to the specified power.
  • 42. Click to edit Master title style 42 42 Python Fundamentals
  • 43. Click to edit Master title style 43 Python Fundamentals 43 • The order of precedence: when an expression includes two or more operators, the order of precedence determines which operators are applied first. This order is summarized in the table in this figure. For instance, Python performs all multiplication and division operations from left to right before it performs any addition and subtraction operations. • If you need to override the default order of precedence, you can use parentheses. Then, Python performs the expressions in the innermost sets of parentheses first, followed by the expressions in the next sets of parentheses, and so on.
  • 44. Click to edit Master title style 44 Python Fundamentals 44 • On the right side: Code that calculates sales tax Code that calculates the perimeter of a rectangle
  • 45. Click to edit Master title style 45 Python Fundamentals 45 • The compound assignment(=) operators provide a shorthand way to code common assignment statements. • For instance, the += operator modifies the value of the variable on the left of the operator by adding the value of the expression on the right to the value of the variable on the left. When you use this operator, the variable on the left must already have been initialized. • The other operators, -= and *= work similarly.
  • 46. Click to edit Master title style 46 Python Fundamentals 46
  • 47. Click to edit Master title style 47 Python Fundamentals 47 Floating-point numbers: • A floating-point number consists of a positive or negative sign, a decimal value for the significant digits, and an optional exponent. • Floating-point numbers provide for very large and very small numbers, but with a limited number of significant digits. The float type can only use 16 significant digits to store the number. • To express the value of a floating-point number, you can use scientific notation. • This notation consists of an optional plus sign or a required minus sign, a decimal value for the significant digits, the letter e or E, and a positive or negative exponent. For example: 2.302e+5
  • 48. Click to edit Master title style 48 Python Fundamentals 48 Floating-point numbers: • In this example, the number contains four significant digits (2.302), and the exponent specifies how many places the decimal point should be moved to the right or to the left. Here, the exponent is positive so the point is moved to the right and the value is: 230,200 • But if the exponent was negative (e-5), the point would be moved to the left and the value would be: .00002302 • An integer is an exact value that yields expected results. • A floating-point number is an approximate value that can yield unexpected results known as floating-point errors.
  • 49. Click to edit Master title style 49 Python Fundamentals 49 Floating-point numbers: • The floating-point numbers are approximate values, not exact values. Look at this example: • In this example, Balance should be 300.30 • As a result, they sometimes cause floating-point errors. • To fix this error, we use round() function. The round() function can take additional argument which is an integer that represents the number of digits to display after the decimal point.
  • 50. Click to edit Master title style 50 Python Fundamentals 50 The standard math module: • The math module for Python provides many functions for mathematical, trigonometric, and logarithmic operations. • The floating-point numbers are approximate values, not exact values. Look at this example: Balance should be 300.30 • As a result, they sometimes cause floating-point errors. • To fix this error, we use round() function. The round() function can take additional argument which is an integer that represents the number of digits to display after the decimal point.
  • 51. Click to edit Master title style 51 Python Fundamentals 51 The standard math module: • We list four common functions and the pi constant that required importing the math module. • You can use the ceil() function if you always want to round up (towards the ceiling). And you can use the floor() function if you always want to round down (towards the floor). See examples in next slide * you can also use the exponential operator (**) to raise a number to the power.
  • 52. Click to edit Master title style 52 Python Fundamentals 52 The standard math module: • The m in the import statement is called alias that is defined so we use through the program instead of using the module name – math.
  • 53. Click to edit Master title style 53 Python Fundamentals 53 The standard math module: • The m in the import statement is called alias that is defined so we use through the program instead of using the module name – math.
  • 54. Click to edit Master title style 54 Python Fundamentals 54 Class exercises: Do it yourself ! • Create a program that calculates a user’s weekly gross and take-home pay. • Follow the Console (on the right) and assign values to the hours Worked and hourly pay rate. Specifications The formula for calculating gross pay is:  gross pay = hours worked * hourly rate The formula for calculating tax amount is:  tax amount = gross pay * (tax rate / 100) The formula for calculating take home pay is:  take home pay = gross pay – tax amount • The tax rate should be 18%, but the program should store the tax rate in a variable so you can easily change the tax rate later just by changing the value that’s stored in the variable. Console Pay Check Calculator Hours Worked: 35 Hourly Pay Rate: 14.50 Gross Pay: 507.5 Tax Rate: 18% Tax Amount: 91.35 Take Home Pay: 416.15
  • 55. Click to edit Master title style 55 Python Fundamentals 55 Class exercises: Do it yourself ! • Create a program that calculates total sales and dsplays the following information to the console. • Follow the Console (on the right) and assign values to the cost of the meal and the tip percent. Specifications The formula for calculating the tip amount is:  tip = cost of meal * (tip percent / 100) Console Tip Calculator Cost of meal: 52.31 Tip percent: 20 Tip amount: 10.46 Total amount: 62.77
  • 56. Click to edit Master title style 56 Python Fundamentals 56 Class exercises: Do it yourself ! • Create a program that converts the temperature in Celsius into Fahrenheit and vice versa. • Follow the Console (on the right) and assign values to the cost of the meal and the tip percent. Specifications The formula for calculating the tip amount is:  Fahrenheit = (Celsius * 9/5) + 32  Celsius = (Fahrenheit – 32) * 5/9 Console Temperature conversion Calculator In Celsius: 20.0 In Fahrenheit: 68.0 In Fahrenheit: 68.0 In Celsius: 20.0
  • 57. Click to edit Master title style 57 57 Material has been taken from (can be accessed through Sheridan's Library Services) : • Starting Out with Python (ISBN-13: 9780136912330 ): • https://www.pearson.com/en-ca/subject-catalog/p/starting-out-with- python/P200000003356/9780136912330 • Murach’s Python 2nd Edition programming, 2nd Edition : • https://bookshelf.vitalsource.com/reader/books/9781943872756/pages/recent • Introducing Python, Lubanovic, B., O'Reily Media, 2nd Edition, 2019 • https://www.oreilly.com/library/view/introducing-python- 2nd/9781492051374/ References