Download as pdf or txt
Download as pdf or txt
You are on page 1of 142

Creating and Running Simple

Python Programs

Creating and Running Simple


Python Programs
Creating and Running Simple
Python Programs
Introduction to Python – Mobile Nugget

Let’s see the video on


Introduction to Python
Creating and Running Simple
Python Programs
Introduction to Python – Questions Discussion

 What are the uses of Python programming?


 What are the basic concepts of Python programming?
Creating and Running Simple
Python Programs
Introduction to Python - What is Coding?

What is Coding? Advantages of Coding

• 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

Python is an easily interpretable, high-level and general-purpose programming language.

• Freely usable - Developed under an


approved open-source license

• Supports the development of many


applications

• Focuses on the solution rather than


language and functionality of the
application

• Helps to work more quickly and integrate


systems more effectively
Creating and Running Simple
Python Programs
Introduction to Python - Applications

Web and internet development

Scientific and numeric computing

Education: For teaching programming

Desktop Graphical User Interfaces or GUIs

Software development: To build, control, manage and test

Business applications

Database access

Games and 3D graphics

Network programming
Creating and Running Simple
Python Programs
Introduction to Python - Features

Hosts and compatible


with various platforms Uses English
and systems keywords

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

• Install Python program in the system

• Install standard Python


development environment
– Python Interpreter
Creating and Running Simple
Python Programs
Introduction to Python - Prerequisites

What does the program interpreter do?

Python interpreter

Allows to write, run, edit,


Executes the code browse and debug the
programme
Creating and Running Simple
Python Programs
Introduction to Python - Prerequisites

What are the ways to use the Python


Interpreter?

Python interpreter

Interactive mode Script mode


Creating and Running Simple
Python Programs
Introduction to Python - Prerequisites

How can the Python Interpreter be written?

Python interpreter

Command line Server using ‘.py’


Creating and Running Simple
Python Programs
Introduction to Python - Prerequisites

What does the Python Interpreter rely on?

Python interpreter

Python Syntax Python Indentation


Creating and Running Simple
Python Programs
Introduction to Python - Functions

The most common function used in Python is print.

Used to print
Print()
information on
function the screen. Comments
Statements that are
used to explain
function Python code.

Input() Used to accept


function data from the user
of the program.
Creating and Running Simple
Python Programs
Introduction to Python - Variables

These are created the Python does not have


Variables are names
moment a value is any command to
that store data.
assigned to the name. declare variables.

A variable can change the


data type even after it is set.
Creating and Running Simple
Python Programs
Introduction to Python - Variables

1.It must start with a letter or the underscore


character.

It can only contain alpha-numeric characters and


underscores (A-Z, 0-9, and _ ).

It is case-sensitive (Example: age, Age and AGE).

It cannot start with a number.

It assigns values to multiple variables in one line.

Allows same value to be assigned to multiple variables


Creating and Running Simple
Python Programs
Introduction to Python - Data Types

In python programming, different types of data can be stored in variables.

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

• A sequence of characters, enclosed in single quote or double


Str quotes.

• Integers are whole numbers consisting of ‘+’ or ‘-’ sign with


Int decimal digits like 10, -20.

Float • Floating points are the numbers with fractions or decimal points.

•Complex • Complex numbers are written with a "j" as the imaginary part.

List • A collection, which is ordered and changeable.

• Tuple is a collection, which is ordered and unchangeable. In


Tuple Python, tuples are written with round brackets.

• Used to repeat a set of statements for a specified number of


Range times.

Dict • A collection, which is unordered, changeable and indexed.

Set • A collection, which is unordered and unindexed.

Bool • Booleans represent either True or False.


Creating and Running Simple
Python Programs
Introduction to Python - Operators

Python Operators

Arithmetic Assignment Comparison Logical Identity Membership Bitwise


operators operators operators operators operators operators operators
• Used with • Used to • Used to • Used to • Used to • Used to test • Used to
numeric assign compare two combine compare if a sequence compare
values to values to values. conditional the objects. is presented (binary)
perform variables. statements. in an object. numbers.
common
mathemati
cal
operations
Creating and Running Simple
Python Programs
Introduction to Python - Keywords

Python Keywords

• Python keywords are used for a predefined purpose.


• These words have a specific meaning for the Interpreter.
• Hence, they should not be used for other purposes.

IF An "if” statement is written by


using the ‘if’ keyword.

If the previous conditions were


not true, then, you can give Elif
another condition using elif.

The else keyword is used to give


Else condition, which is not provided in
previous conditions.

If an ‘if’ statement is used Nested


inside an ‘if’, then, it is If
known as Nested If.

And / These are logical operators used to


Or combine conditional statements.
Creating and Running Simple
Python Programs
Introduction to Python - Errors

Errors in Python

Syntax errors Logical errors Runtime errors

• Python programme has • These are semantic • It causes abnormal


its own rules of errors where the termination of
programing. If there is program semantics are programme while it is
any error in the coding incorrect. being executed. It will
or syntax, it will display appear after the
syntax error. program starts running.
Creating and Running Simple
Python Programs
Using Python from Command Line – Mobile Nugget

Let’s see the video on


Use Python from
command line
Creating and Running Simple
Python Programs
Using Python from Command Line – Questions Discussion

 How to install and use of Command line?


 What is Google Colab and Azure note book?
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

1. Run Python from the Command Line

Make sure you have Python and the expected version is available from
your command line.

You can check this by running command:

python3 --version py --version

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

2. Run Pip from the Command Line

Make sure you can run Pip from the command line.

You can check this by running command:

python3 -m pip --version py -m pip --version

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

3. Update Pip, Setuptools, and Wheel

Make sure Pip, Setuptools, and Wheel are up to date.

You can check this by running command:

python3 -m pip install -- py -m pip install --


upgrade pip setuptools upgrade pip setuptools
wheel wheel

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

4. Create a Virtual Environment

Basic venv command can be used on a typical Linux system.


You can check this by running command:

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

5. Tools to create a Virtual Environment

python3 -m venv <DIR> py -m venv <DIR>


venv source <DIR>/bin/activate <DIR>\Scripts\activate

python3 -m virtualenv
virtualenv <DIR>
virtualenv <DIR>
<DIR>\Scripts\activate
source <DIR>/bin/activate

Tools Unix/macOS Windows


Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

6. Use Pip for installing

Pip is one of the most popular tool for installing Python packages.

It is also included in modern versions of Python.

Pip provides the essential core features for finding, downloading,


and installing packages from PyPI and other Python package
indexes

It can be incorporated into a wide range of development


workflows via its command-line interface (CLI).
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

7. Installing from PyPI

To install the latest version of “SomeProject” by the following


command.

You can check this by running command:

python3 -m pip install py -m pip install


"SomeProject" "SomeProject"

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

8. Upgrading Packages

Upgrade an already installed SomeProject to the latest from PyPI by


specifying directly on the command line.

You can check this by running command:

python3 -m pip install -- py -m pip install --


upgrade SomeProject upgrade SomeProject

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

9. Installing to the User Site

To install packages that are isolated to the current user, use the --
user flag.

You can check this by running command:

python3 -m pip install -- py -m pip install --user


user SomeProject SomeProject

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

10. Installing Requirements Files

Install a list of requirements specified in a Requirements File.

You can check this by running command:

python3 -m pip install -r py -m pip install -r


requirements.txt requirements.txt

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

11. Installing from VCS

Install a project from VCS in “editable” mode.

You can check this by running command:

python3 -m pip install -e git+https://git.repo/some_pkg.git#egg=SomeProject #


from git py -m pip install -e git+https://git.repo/some_pkg.git#egg=SomeProject # from git
python3 -m pip install -e hg+https://hg.repo/some_pkg#egg=SomeProject # py -m pip install -e hg+https://hg.repo/some_pkg#egg=SomeProject # from
from mercurial mercurial
python3 -m pip install -e svn+svn://svn.repo/some_pkg/trunk/#egg=SomeProject # py -m pip install -e svn+svn://svn.repo/some_pkg/trunk/#egg=SomeProject # from svn
from svn py -m pip install -e git+https://git.repo/some_pkg.git@feature#egg=SomeProject # from a
python3 -m pip install -e branch
git+https://git.repo/some_pkg.git@feature#egg=SomeProject # from a branch

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

12. Installing from other indexes

Install from an alternate index by specifying directly on the


command line.
You can check this by running command:

python3 -m pip install -- py -m pip install --index-


index-url url
http://my.package.repo/ http://my.package.repo/
simple/ SomeProject simple/ SomeProject

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

13. Installing from A Local Src Tree

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:

python3 -m pip install -e py -m pip install -e


<path> <path>

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

14. Installing from a Local Archives

Install a particular source archive file.

You can check this by running command:

python3 -m pip install py -m pip install


./downloads/SomeProje ./downloads/SomeProje
ct-1.0.4.tar.gz ct-1.0.4.tar.gz

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

15. Installing from Other sources

To install from other data sources, you can create a helper application
that presents the data in a PEP 503 compliant index format.

Use the --extra-index-url flag to direct pip to use that index.

./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

16. Installing Prereleases

Find pre-release and development versions, in addition to stable


versions. By default, pip only finds stable versions.

You can check this by running command:

python3 -m pip install -- py -m pip install --pre


pre SomeProject SomeProject

Unix/macOS Windows
Creating and Running Simple
Python Programs
Using Python from Command Line – Install and Use of Command Line

17. Installing Setuptools “Extras”

Install setuptools extras.


Setuptools allows you to declare dependencies that only get installed
under specific circumstances.
You can check this by running command:
python3 -m pip install
SomePackage[PDF] py -m pip install SomePackage[PDF]
python3 -m pip install py -m pip install SomePackage[PDF]==3.0
SomePackage[PDF]==3.0 py -m pip install -e .[PDF] # editable
python3 -m pip install -e .[PDF] # project in current directory
editable project in current directory

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:

Codecademy Coding Bootcamps DataCamp

Dataquest HackInScience High School


Technology Services
Creating and Running Simple
Python Programs
Using Python from Command Line – Google Colab and Azure Note Book

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

Comparison between the two can be done on the basis of:

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

Google Colab Azure Note book

Supports multiple kernels: python, R, F#


Supports python (currently 3.6.7 and 2.7.15).

Allocates RAM of 12 GB and disk of memory 50 GB Allocates small RAM of only 4GB.

GPU is available by default. You can use it for


GPU is not available to use. You should deploy
anything except for crypto mining and long-term
your own VM to have GPU.
usage!

Codes will be saved in google drive and can edited


collaboratively (by sharing). It is integrated with Retrieving s3 data takes so much time
cloud storage such as Amazon s3.

It is not sure how to use local hardware


It has capability to use local hardware

Integrated with code development in a team such


Integrated with github
as github
Creating and Running Simple
Python Programs

Questions, if any?
Creating and Running Simple
Python Programs
Performing Operations using Data types and Operators – Mobile Nugget

Let’s see the video on


Perform Operations
using Data types and
Operators.
Creating and Running Simple
Python Programs
Performing Operations using Data types and Operators – Questions Discussion

 Why do we need to classify different data items?


 What are different data types in Python?
 What are different classes inside these different data types?
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Overview of Data Types

Data types represent the type of


value that specifies the operations
Data types are classification
that can be performed on a given
of data elements
set of data

Data Types

Data types are classes and variables


are instance of these classes

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

Standard or Built-in data types

Integer

Numeric Float

Complex Number

Strings

Python – Data Types Sequence Tuple

Boolean List

Set

Dictionary
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Numeric Data Type

A numeric data type represents the data having numeric value.

Numeric Data Type


Classification
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Numeric Data Type

Integers

• Are represented by the int class.


• Contains positive or negative whole numbers (without fraction or
decimal).
• Does not restrict the length of the value of an integer.
• Is represented in Decimal (base 10) by default.
• Can be stored as Binary, Octal or Hexadecimal.
• Need a prefix before the number as given below:
• Hexadecimal - 0x,0X
• Binary - 0b, 0B
• Octal- 0o, 0O
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Numeric Data Type

Float

• Are represented by the float class.


• Is a real number with floating point representation.
• Is denoted by a decimal point.
• Does not restricts the number of digits before and after the decimal
point.
• To specify scientific notation, append the character e or E followed by a
positive or negative integer

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

• Are represented by the complex class.


• Are is specified in two parts, real part and imaginary part.

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

String List Tuple


Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Sequence Data Type

• A sequence of characters
String • Represented by a str class

String data type


Are represented
a = “A” by the str class
b = “Python”
type(a) = <type 'str'>
type(b) = <type 'str'>
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Sequence Data Type

String To access the individual characters of a string,


use indexing.

[ ]
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

Tuples are created by placing a sequence of values separated by ‘comma’ with or


without the use of parentheses for grouping of the data sequence.

0 1
T1= 1, 2, “Tuple” 2

1 2 Tuple

Note:

• Tuples can also be created with a single element.


• Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’
to make it a tuple
• Creating a tuple without using the parentheses is known as Tuple Packing.
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Sequence Data Type

Tuple To access the tuple items, refer to the index number


inside the square bracket.

tuple1 = tuple([1, 2, 3, 4, 5])

# Accessing element using indexing


print("First element of tuple")
print(tuple1[0])

# Accessing element from last


# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])

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

Is heterogeneous in Can be accessed


nature sequentially
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Sequence Data Type

List Use the index operator [ ] to access the list items.

Indices starts
at 0

Indexes represent positions from the


end of the array.
Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Boolean Data Type

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

Assign either True or False to an identifier

Don’t use quotes like in a string data type

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

Set data type

A collection of Do not contain Similar to the


unordered and Mutable Iterable duplicate concept of the
unindexed values mathematical set
Python objects.

Example:

Myset={ “red”, “blue”, “green”}


Creating and Running Simple
Python Programs
Perform Operations using Data types and Operators – Dictionary Data Type

Dictionary Data Type

Unordered, indexed Key value pair declared in Created by the built-in


and mutable curly brackets function dict()

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

To access the items of a dictionary:


• Refer to its key name. Key can be used inside square brackets.
• Use the get() method.
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Mobile Nugget

Let’s see the video on


Control Flow with
Decisions and Loops

Link…
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Questions Discussion

 What are branching statements?


 What are conditional statements?
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Branching Statements

Branching statements or jump statements change the normal flow of execution


based on some condition.

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

Python provides the following branching statements:

Break
To break the loop and transfer
control to the line which is
immediately outside of the loop.

Have two forms:


Continue
• Labeled
To escape the current execution and • Unlabeled
transfer the control back to the start
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

Break statement is used


• To terminate a loop
• Within the for and while loops to alter the normal behavior of the code.

Code snippet shows the usage of the break statement:


# break the loop as soon it sees ‘p'
# or 'y’
for letter in ‘happyforhappy'
if letter == ‘p' or letter == ‘y':
break

print 'Current Letter :', letter

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

Continue statement is used to:


• End the current iteration in a for loop or a while loop and move to the next iteration.
• Skip the rest of the code inside a loop.

Code snippet shows the usage of the continue statement:

for i in range(1, 11):


if i == 7:
Continue
print(i)

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

Return statement is used:


• Inside a function to return a value.
• To exit the function.

Code snippet shows the usage of the return statement:


def func1():
x = 7
return x

def func2():
a = 10

# 7 is returned
print(func1())

# None is returned automatically


print(func2())

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

Code snippet shows the usage of the pass statement:

# 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

“if elif else


“If” statement “if else statement” statement (nested
if statement)”

Has a Boolean Executes when the Uses one if elif else


expression Boolean expression statements as
followed by one or for “if statement” is nested “if”
more statements. false. statements.
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – 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

if studentA >= 40:


print(“StudentA Pass")
eliif student >= 40;
print(“Student B Pass”)

Output:

StudentA Pass
Creating and Running Simple
Python Programs
Control Flow with Decisions and Loops – Looping Statement

Looping statements repeatedly execute a block of statements until a given condition


within the loop is satisfied.
Types of looping statements

While While with else For

Used to execute a block of


Used to execute the else Used for iterating over a
statements repeatedly until
part of a while loop, if the sequence either:
a given condition in a while
condition in the while loop • A list,
loop is satisfied i.e., true.
yields the value, False. • A tuple,
• A dictionary,
• A set, or

The while loop can
be terminated with a • A string.
break statement.
Creating and Running Simple
Python Programs

Questions, if any?
Creating and Running Simple
Python Programs
Performing Input and Output Operations– Mobile Nugget

Let’s see the video on


Perform Input and
Output Operations

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

File handling in Python

File handling in Python is extremely important

Easy to implement Python file handling

Python input/output operations involves reading and writing process and


many other file handling options

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

Built-in Python methods can manage two file:


• Text
• Binary
Encode these two files differently

Each line of code includes:


• A sequence of characters
PYTHON • Form a text file

Each line of a file is terminated with:


• Special character, called the EOL or End of
Line characters like comma {,} or newline
character

• Ends the current line


• Tells the interpreter a new one has begun
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Functions of File Handling

Opening File

Reading from Files

File Handling Writing to Files

Appending to Files

Splitting Files
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Functions of File Handling

Opening File

Before performing any operation on the file like reading


or writing:
Python
Open that file

Use Python’s inbuilt function open() f = open(filename, mode)

Specify the mode, which represents the


purpose of the opening file
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Functions of File Handling

Opening File

Python supports a few more modes, such as:

• r: Open an existing file for a read operation Python


• w: Open an existing file for a write operation, but if the
# a file named "geek", will be opened with the
file already contains some data then it will be overridden
reading mode.
• a: Open an existing file for append operation, but it won’t file = open('geek.txt', 'r')
override existing data # This will print every line one by one in the file
• r+: To read and write data into the file, but the previous for each in file:
data in the file will not be deleted. print (each)
• w+: To write and read data, but it will override existing
data
• a+: To append and read data from the file, but it won’t
override existing data

The open command will open the file


in the read mode, and the for loop
will print each line present in the file.
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Functions of File Handling

Reading from Files

• 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

# Python code to illustrate read() mode


file = open("file.txt", "r") # Python code to illustrate read() mode
print (file.read()) character wise
file = open("file.txt", "r")
print (file.read(5))
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Functions of File Handling

Writing to Files

• Python provides a write() method to write a string


or bytes sequence.
• We can also use the write function along • This function returns a number that is the size of
with the with() function. data stored in a single Write call.
• The close() command terminates all used resources
and frees the system from the specific program.

Python Python

# Python code to create a file


file = open('geek.txt','w') # Python code to illustrate with() alongwith
file.write("This is the write command") write()
file.write("It allows us to write in a particular with open("file.txt", "w") as f:
file") f.write("Hello World!!!")
file.close()
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Functions of File Handling

Appending to Files

• Various other commands in file handling that


• Provide much cleaner syntax and exception is used to handle various tasks like:
handling when working with code • rstrip(): This function strips each line of
• Will be automatically closed after one is a file off spaces from the right-hand
done automatically by this method side.
• lstrip(): This function strips each line of
a file off spaces from the left-hand side.
Python Python

# Python code to illustrate append() mode


file = open('geek.txt','a') # Python code to illustrate with()
file.write("This will add this line") with open("file.txt") as file:
file.close() data = file.read()
# do something with data
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Functions of File Handling

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)

• Accepts a string message which is optional and meant to


be displayed on the output console to ask a user to enter
Input Operation the input value

Syntax
num = input ("Enter number:")
print(num)
# Printing type of input value
print ("type of number", type(num))

Typecast the input to the desired type because


the entered value is always returned as a string
Output
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Use of split() Method
Features Syntax
split() method:
• Take multiple values in one line # taking two inputs at a time
x, y = input("Enter a two value: ").split()
• Breaks the given input by the specified print("Number of boys: ", x)
separator print("Number of girls: ", y)
• If the separator is not provided, then print()
any white space is a separator.

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

For formatting a date we can specify a dash ‘-’ as separator

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.

Default is newline character ‘\n’.

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)

If not specified explicitly, it is sys.stdout by default.

Syntax

# Code for printing to a file


welcomeFile = open("c:\\welcome.txt", 'w')
print('python course', file = welcomeFile)
welcomeFile.close()
Creating and Running Simple
Python Programs
Performing Input and Output Operations – Formatting Output Using String Modulo Operator (%)
Features
The String modulo operator (%) can be used for string formatting by adding a placeholder in
the string which is later replaced with the values in the tuple.

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.

Example • A number in the brackets is


used to refer to the position of
the object passed into the
format() method.
Creating and Running Simple
Python Programs
Document and Structure Code – Mobile Nugget

Let’s see the video on


Document and
Structure Code

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

Comments can be used to:

• Explain Python code


• Make the code more readable
• Prevent execution when testing code
Creating and Running Simple
Python Programs
Document and Structure Code – Comments

Comments starts with a #, and Python will ignore them

Code:

#This is a comment
Hello, World!
print("Hello, World!")
Output:
Creating and Running Simple
Python Programs
Document and Structure Code – Docstrings

Python documentation strings or


docstrings is a string used to explain
the declared Python modules,
functions, classes, and methods.

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

Declaring and Accessing Docstrings

Two ways of declaring Docstrings: Accessing Docstrings


• ”’triple single quotes”’ Use the __doc__ method
• “””triple double quotes””” of the object or using the help function.

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

• The entire docstring is indented the same


as the quotes at its first line.
• Docstring processing tools will strip a
uniform amount of indentation from the
second and further lines of the docstring,
equal to the minimum indentation of all
non-blank lines after the first line.
• Any indentation in the first line of the
docstring (i.e., up to the first newline) is
insignificant and removed.
• Relative indentation of later lines in the
docstring is retained.
Creating and Running Simple
Python Programs
Document and Structure Code – Comments vs 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:

# Python program to demonstrate HFH


comments

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

In Python a function is defined using the def keyword.


Creating and Running Simple
Python Programs
Document and Structure Code – Calling a Function

To call a function, use the function name followed by parenthesis

Example: Hello from a function

def my_function():
print("Hello from a function")

my_function()
Creating and Running Simple
Python Programs
Document and Structure Code – Parameters or Function

A parameter is the variable listed inside def my_function(fname):


the parentheses in the function definition. print(fname + " Refsnes")

An argument is the value that is sent


to the function when it is called.
my_function("Emil")
Creating and Running Simple
Python Programs
Document and Structure Code – Arbitrary Arguments

If the number of arguments is unknown, add a * before the parameter name in the
function definition.

Example:

Code Output

def my_function(*kids): The youngest child is Linus


print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Creating and Running Simple
Python Programs
Document and Structure Code – Recursion

Recursion is a common The developer should be When written


mathematical and very careful with recursion correctly recursion can
programming concept. as it can be quite easy to slip be a very efficient and
It means that a into writing a function which mathematically-
function calls itself. never terminates, or one elegant approach to
that uses excess amounts of programming.
memory or processor
power.
Creating and Running Simple
Python Programs

Questions, if any?
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Mobile Nugget

Let’s see the video


Perform
Troubleshooting and
Error Handling

Link…
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Questions Discussion

 What are the different errors in code segments?


 What are the code segments that handle exceptions?
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Types of Errors

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

Encountered when Python Can happen when we try and


does not recognise the name refer to a variable that has not
of something in a statement been defined
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Types of Errors

Syntax Error

Encountered with Python Construction- Does not


when it is unable to parse a conform to a format that
section of the code Python can interpret
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Types of Errors

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

Encountered when something


Try to combine data types
is wrong with the data type
using an operator that it
used for a particular operation
doesn’t know what to do with
or function
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Types of Errors

Index Error

Encountered when we try and access an


element of a collection beyond the number
of elements that the collection contains.
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Types of Errors

Attribute Error

Encountered when trying to use a function or


variable attached a data that is not present.
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Syntax Errors verses Exceptions

Syntax Error Exception


Python Traceback Python Traceback

>>> print( 0 / 0 )) >>> print( 0 / 0)


File "<stdin>", line 1 Traceback (most recent call last):
print( 0 / 0 )) File "<stdin>", line 1, in <module>
^ ZeroDivisionError: integer division or
SyntaxError: invalid syntax
VS modulo by zero

• 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

The try and except blocks in Python are used


to catch and handle exceptions.

Python executes code following the try


statement as a “normal” part of the
program.

The code that follows the except statement


is the program’s response to any exceptions
in the preceding try clause.
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – Handling Exceptions

>>> print( 0 / 0) When syntactically correct code runs into an


Traceback (most recent call last): error, Python will throw an exception error.
File "<stdin>", line 1, in <module>

ZeroDivisionError: integer division This exception error will crash the program
or modulo by zero
if it is unhandled.

We can also start by asserting Python.

If this condition turns out to be true, then


that is excellent!

If the condition turns out to be False, you


can have the program throw an
AssertionError exception.
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – The else Clause

Python

You can instruct a program to


execute a particular block of code
only in the absence of exceptions.
Creating and Running Simple
Python Programs
Performing Troubleshooting and Error Handling – The else Clause

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

You can also try to run code inside the else


clause and catch possible exceptions there
as well.

If you were to execute this code on a


Linux machine, you would get the result
given on the screen.

You can see that the linux_interaction()


function ran. Because no exceptions were
encountered, an attempt to open file.log
was made.

That file did not exist, and instead of


opening the file, you caught the
FileNotFoundError exception.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Mobile Nugget

Let’s see the video on


Perform Operations
Using Modules and
Tools

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

Built-in modules where the functions are frequently used:

Random module
Math module
OS
module

Built-in
Modules
Statistics Time module
module

Collections module Sys module


Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules

OS Module

OS module has functions to perform many tasks of the operating system.


The OS module in Python provides functions for
• Creating and removing a directory (folder)
• Fetching its contents
• Changing and identifying the current directory, etc.

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

Random module defines various functions for handling randomization.

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

Math module presents commonly required mathematical functions such as:


• Trigonometric functions
• Representation functions
• Logarithmic functions
• Angle conversion functions
Two Mathematical constants are also defined in this module such as:
• Pie
• Euler’s number
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules

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

This module provides alternatives to built-in container data types such as


• List
• Tuple
• Dict
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules

Statistics Module

The statistics module provides functions to mathematical statistics of numeric data.


Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Built-in Modules

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

This module provides access to mathematical functions for complex numbers.


The functions in this module accept
• Integers, floating-point numbers, or complex numbers as arguments.
• Any Python object that has either a complex() or a float() method.
These methods are used to convert the object to complex or floating-point numbers.
The function is then applied to the result of the conversion.
Python can handle complex numbers and their associated functions using the file “cmath”.
Complex numbers are useful in many mathematical applications, and Python provides useful tools for
handling and manipulating them.
Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Solving Complex Computing Problems

Converting real numbers to complex numbers

A complex number is represented by “ x + yi “.

Python converts the real numbers x and y into complex using the function complex(x,y).

The real part can be accessed using the function real()

The imaginary part is represented by the function imag().


Creating and Running Simple
Python Programs
Performing Operations using Modules and Tools – Solving Complex Computing Problems

Phase of complex number

The phase of a complex number is the angle between the positive real axis and the vector representing a
complex number.

Phase is returned using phase(), which takes complex numbers as an argument.

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

Converting from polar to rectangular form and vice versa

Conversion to polar is done using polar(), which returns a pair(r,ph) denoting the modulus r and
phase angle ph.

Modulus can be displayed using abs() and phase using phase().

A complex number converts into rectangular coordinates by using rect(r, ph), where r is modulus and ph
is the phase angle.

It returns a value numerically equal to r * (math.cos(ph) + math.sin(ph)*1j)


Creating and Running Simple
Python Programs

Questions, if any?

Thank you!

You might also like