NASSCOM COPA M12 Creating and Running Simple Python Programs ILT PPT V2
NASSCOM COPA M12 Creating and Running Simple Python Programs ILT PPT V2
Python Programs
• Coding refers to the process of writing • Various applications, games and software
instructions for a computer to perform a programs are developed based on coding.
task.
• In simpler terms, it is telling the computer • Coding is used in almost every aspect of life.
what to do.
• Coding involves logic, reasoning, problem-
solving skills, organising, focus, persistence
and patience.
Creating and Running Simple
Python Programs
Introduction to Python - Python Programming
Business applications
Database access
Network programming
Creating and Running Simple
Python Programs
Introduction to Python - Features
Easy to read, learn and Enables simpler, less- Adopts test driven
write programs or codes cluttered syntax and development approach
grammar
Creating and Running Simple
Python Programs
Introduction to Python - Prerequisites
Python interpreter
Python interpreter
Python interpreter
Python interpreter
Used to print
Print()
information on
function the screen. Comments
Statements that are
used to explain
function Python code.
Text Type
Numeric Type
Sequence Type
Mapping Type
Set Type
Boolean Type
Binary Type
Creating and Running Simple
Python Programs
Introduction to Python - Data Types
Float • Floating points are the numbers with fractions or decimal points.
•Complex • Complex numbers are written with a "j" as the imaginary part.
Python Operators
Python Keywords
Errors in Python
Make sure you have Python and the expected version is available from
your command line.
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Make sure you can run Pip from the command line.
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
python3 -m venv
py -m venv tutorial_env
tutorial_env
tutorial_env\Scripts\acti
source
vate
tutorial_env/bin/activat
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
python3 -m virtualenv
virtualenv <DIR>
virtualenv <DIR>
<DIR>\Scripts\activate
source <DIR>/bin/activate
Pip is one of the most popular tool for installing Python packages.
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
8. Upgrading Packages
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
To install packages that are isolated to the current user, use the --
user flag.
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Installing from local src in Development Mode, i.e. in such a way that
the project appears to be installed, but yet is still editable from the src
tree.
You can check this by running command:
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
To install from other data sources, you can create a helper application
that presents the data in a PEP 503 compliant index format.
./s3helper --port=7777
python -m pip install --extra-index-url http://localhost:7777 SomeProject
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line
Some sites offer in-browser coding for those who want to learn Python:
Google CoLab and Azure Notebooks provide a flexible environment for developers to work.
They are very close to each other in terms of characteristics and can often be tricky to pick one.
Creating and Running Simple
Python Programs
Using Python from Command Line – Google Colab and Azure Note Book
Computer Importing
Speed Memory
Power Libraries
Similarity
Language Additional
File I/O with
Support Features
Jupyter
Creating and Running Simple
Python Programs
Using Python from Command Line – Google Colab and Azure Note Book
Allocates RAM of 12 GB and disk of memory 50 GB Allocates small RAM of only 4GB.
Questions, if any?
Creating and Running Simple
Python Programs
Performing Operations using Data types and Operators – Mobile Nugget
Data Types
Note: In Python, you need not declare the data type. The compiler automatically
recognises the data type during the variable declaration.
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Standard Data Types
Integer
Numeric Float
Complex Number
Strings
Boolean List
Set
Dictionary
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Numeric Data Type
Integers
Float
Note:
All real numbers with at least one digit after the decimal point is considered a float value.
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Numeric Data Type
Complex Numbers
Example:
a= X + iY Imaginary part
Real part
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Sequence Data Type
Sequence Data Type is the ordered collection of similar or different data types. It allows
to store multiple values.
Sequence Types
• A sequence of characters
String • Represented by a str class
[ ]
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Sequence Data Type
Tuple •
•
An ordered collection of Python objects
Can contain any number of elements
0 1
T1= 1, 2, “Tuple” 2
1 2 Tuple
Note:
Note:
Nested tuples are accessed using nested indexing.
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Sequence Data Type
List
Is an ordered
Is mutable
collection of data
Indices starts
at 0
Boolean data type is a basic data structure which holds one of the two possible
values: either False or True value.
To create a Boolean
Note:
True and False with capital ‘T’ and ‘F’ are valid Boolean values, otherwise you will find an error.
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Set Data Type
Example:
keys values
‘s’ ‘bank’
‘j’ ‘news’
‘n’ ‘compute’
Note:
Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Dictionary Data Type
Link…
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Questions Discussion
Are used to
unconditionally
Are primarily
Branching transfer program
used to interrupt control from one
loop instantly statements
point to elsewhere
in the program
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Types of Branching Statements
Break
To break the loop and transfer
control to the line which is
immediately outside of the loop.
Return
To explicitly end the execution and return
the result
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Break Statement
Output:
Current Letter : p
A break statement ends the loop it is in and the control flows to the next statement
immediately below the loop.
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Continue Statement
The loop does not terminate but moves to the next iteration.
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Return Statement
def func2():
a = 10
# 7 is returned
print(func1())
If return value not explicitly mentioned, then the value “None “ is returned automatically.
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Pass Statement
Pass statement:
• Is a branching statement
• Is a null statement
• Is used as a placeholder
• Can be implemented with a blank body for a function or empty class
# An empty loop
for letter in ‘happyforhappy ':
pass
print 'Last Letter :', letter
Output:
Last Letter : y
A function without the pass statement and empty code will throw an IndentationError exception.
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Conditional Statement
Conditional statement help to determine whether the statement must be executed or not.
Types of
conditional
statement
Code snippet shows how to use an if statement to declare the result of two students A and B:
studentA = 55
studentB = 25
Output:
StudentA Pass
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Looping Statement
Questions, if any?
Creating and Running Simple
Python Programs
Performing Input and Output Operations– Mobile Nugget
Link…
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Questions Discussion
What are the code segments that perform file input and output operations?
What are the code segments that perform console input and output operations?
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Importance of Input Operation
Document
as an input
Printed document
as an output
• Input plays an essential role because it allows you to interact and add new
information. What is web server?
• Python provides some built-in functions to read and modify the file, and to
perform input-output operations .
Creating and Running Simple
Python Programs
Performing Input and Output Operations – File Handling
How to read the data from a given file whenever you want to analyze the data
Creating and Running Simple
Python Programs
Performing Input and Output Operations – File Handling
Opening File
Appending to Files
Splitting Files
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Functions of File Handling
Opening File
Opening File
• There is more than one way to read a The interpreter will read the first five
file in Python. characters of stored data and return it as a
• If you need to extract a string that string.
contains all characters in the file then
we can use the file.read().
Python Python
Writing to Files
Python Python
Appending to Files
Splitting Files
Python
# Python code to illustrate split() function
with open("file.text", "r") as file: • Split lines using file handling in Python
data = file.readlines()
for line in data:
word = line.split() • Space- encountered
print (word)
• Split using any characters as we wish
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Input Operation
Features
Python programming language input () method:
provides an input() function to • Is simplest way to take input from the user, then
take input into a program from
evaluates the expression and finally converts the entered
the console.
value into the string format (irrespective of format or
type of entered value)
Syntax
num = input ("Enter number:")
print(num)
# Printing type of input value
print ("type of number", type(num))
Example
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Output Operation
Features
Syntax
print() function:
# printing two numbers at a time
Is the simplest way to present or display a program a=7
output to the console, where you can pass zero or
b=9
more expressions separated by commas
print(a, b)
Example
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Output Operation
Features
Space ‘ ’ as separator in print() Function
• Python print() function use space ‘ ’ as a separator between arguments passed in
print() function.
• We can modify or use any character, number, or string as a separator.
• ‘sep’ (Optional) parameter in print() function can be used to specify the character
or number or string as a separator to separate the arguments passed in print().
Syntax
print('Male', 'Female', sep='/') will print both Male and Female separated by ‘/’
Example
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Output Operation
Features
Dash ‘-’ as Separator in print() Function
Syntax
#for formatting a date
print('09','12','2018', sep='-')
Example
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Output Operation
Features
‘end’ Parameter in print() Function
‘end’ (Optional) parameter in print() function can be used to specify the character or
number or string to print at the end.
Syntax
# ends the output with a <space>
print("Welcome to" , end = ' ')
print("Python Progamming Course", end = ' '))
Example
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Output Operation
Features
‘file’ Parameter in print() Function
‘file’ (Optional) parameter in print() function can be used to specify where the function
should write a given object(s)
Syntax
String modulo operator ( % ) can be used to replace any integer, float, or string values.
Syntax
• Use “%d” for integer value and “%f” for
float value.
# print integer and float value • In this example, “%2d” is used for integer 1.
print("Integer : % 2d, Float : % 5.2f" %(1, 05.333)) • The prefix ‘2” signifies that the number will
be printed with 1 leading blank character
as integer value 1 consists only of one digit.
Example • The second one “%5.2f” is a format
description for a float number.
• The number following the “.” in the
placeholder signifies the decimal part of
the number or the precision, character “f”
of placeholder stands for “float”.
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Formatting Output Using Format Method
Use {} to mark where a variable will be substituted and can provide detailed formatting
directives.
We can either use the exact position of the variable to be substituted or empty {} will
substitute the variables in the order mentioned.
Syntax
• The brackets and characters
# using format() method and referring a position of the object within them (called format
print('{0} {1} {2}'.format('Python', 'Programming', 'Course')) fields) are replaced with the
objects passed into the format()
method.
Link…
Creating and Running Simple
Python Programs
Document and Structure Code – Questions Discussion
What are the code segments that use comments and documentation strings?
What are the code segments that include function definitions?
Creating and Running Simple
Python Programs
Document and Structure Code – Comments
Code:
#This is a comment
Hello, World!
print("Hello, World!")
Output:
Creating and Running Simple
Python Programs
Document and Structure Code – Docstrings
Objective:
To help the programmers working on the code to understand the details of its
implementation.
Creating and Running Simple
Python Programs
Document and Structure Code – Docstrings
OUTPUT
Python program to
explain multiple line
comment
Print(‘Hello’)
Python program to
explain multiple line
comment
Print(‘Hello’)
__doc__
Creating and Running Simple
Python Programs
Document and Structure Code – Docstrings
Indentation in Docstrings
Comments DocStrings
• Provides useful information to help the • Provides a convenient way of associating
reader understand the source code documentation with Python modules, functions,
• Explains logic or a part of it used in the code classes, and methods.
• Uses # symbol
Example: Output:
print(“HFH")
Creating and Running Simple
Python Programs
Document and Structure Code – Need for a Function
Function:
• Executes only when it called
• Uses parameters as data
• Returns data as a result
def my_function():
print("Hello from a function")
my_function()
Creating and Running Simple
Python Programs
Document and Structure Code – Parameters or Function
If the number of arguments is unknown, add a * before the parameter name in the
function definition.
Example:
Code Output
Questions, if any?
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Mobile Nugget
Link…
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Questions Discussion
Name Error
Syntax Error
Indentation Error
Python has
several different
classes of error
Type Error
Index Error
Attribute Error
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Types of Errors
Name Error
Syntax Error
Indentation Error
It needs to be used
Indentation is used to indicate
consistently throughout in the
program structure.
code.
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Types of Errors
Type Error
Index Error
Attribute Error
• Syntax errors occur when the parser detects an • This time, the code ran into an exception error.
incorrect statement.
• This type of error occurs whenever syntactically
• The arrow indicates where the parser ran into the syntax correct Python code results in an error.
error.
• The last line of the message is indicated what
• In this example, there was one bracket too many. type of exception error it is.
Remove it and run the code again.
• Python details what type of exception error was
encountered.
• It is a ZeroDivisionError
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Handling Exceptions
ZeroDivisionError: integer division This exception error will crash the program
or modulo by zero
if it is unhandled.
Python
Python
try:
linux_interaction()
except AssertionError as error:
print(error) If you were to run this code on a
else: Linux system, the output would be
print('Executing the else clause.')
on the screen.
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – The else Clause
Link…
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Questions Discussion
What are the basic operations that can be performed using built-in modules?
How are complex computing problems solved using built-in modules?
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules
Long and complex logic in a program is broken into smaller, independent, and reusable
blocks of instructions. These are called modules.
Modules are designed to perform a specific task that is a part of the entire process.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules
Each built-in module contains resources for certain specific functionalities such as:
OS Management Disk IO
Module
Networking Database Connectivity
Built-in modules are mostly written in C and integrated with a Python interpreter.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules
Random module
Math module
OS
module
Built-in
Modules
Statistics Time module
module
OS Module
To interact with the operating system you will need to import the os module.
Import it using the import os statement before using its functions.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules
Random Module
Python uses a pseudo-random generator based upon the Mersenne Twister algorithm that produces 53-
bit precision floats.
Functions in this module depend on pseudo-random number generator function random() which
generates a random float number between 0.0 and 1.0.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules
Math Module
Sys Module
Sys module provides functions and variables that are used to manipulate different parts
of the Python runtime environment.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules
Collection Module
Statistics Module
Time Module
The Time module has many time-related functions. It allows various operations
regarding time, conversions, and representations.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Solving Complex Computing Problems
Python converts the real numbers x and y into complex using the function complex(x,y).
The phase of a complex number is the angle between the positive real axis and the vector representing a
complex number.
The range of phase lies from -pi to +pi. i.e from -3.14 to +3.14.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Solving Complex Computing Problems
Conversion to polar is done using polar(), which returns a pair(r,ph) denoting the modulus r and
phase angle ph.
A complex number converts into rectangular coordinates by using rect(r, ph), where r is modulus and ph
is the phase angle.
Questions, if any?
Thank you!