0% found this document useful (0 votes)
13 views

Python Notes 1

The document provides an overview of programming and software categories. It discusses the layered view of a computer including application programs, system software, operating systems, and machine hardware. It describes operating systems and their functions. It also covers programs, programming languages, and the differences between machine language, assembly language, and high-level languages. The document discusses compilation versus interpretation and provides an introduction to Python.

Uploaded by

Rafae Dhopawakar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Notes 1

The document provides an overview of programming and software categories. It discusses the layered view of a computer including application programs, system software, operating systems, and machine hardware. It describes operating systems and their functions. It also covers programs, programming languages, and the differences between machine language, assembly language, and high-level languages. The document discusses compilation versus interpretation and provides an introduction to Python.

Uploaded by

Rafae Dhopawakar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Programming with Python

Maya Nair
What is a Software ?
• Computer is a bare machine,
• We need to give instructions that tell a computer what to do
• A software is a set of such instructions

Programming with Python I Maya Nair 27-10-2021 2


Software Categories
• System Software
• Programs written for computer systems
• Compilers, operating systems, …
• Application Software
• Programs written for computer users
• Word-processors, spreadsheets, & other application packages
Programming with Python I Maya Nair 27-10-2021 3
A Layered View of the Computer
Application Programs
Word-Processors, Spreadsheets,
Database Software, IDEs,
etc…
System Software
Compilers, Interpreters,Preprocessors, etc.
Operating System, Device Drivers
Machine with all its hardware
Programming with Python I Maya Nair 27-10-2021 4
Operating System (OS)
• Provides several essential services:
• Loading & running application programs
• Allocating memory & processor time
• Providing input & output facilities
• Managing files of information

Programming with Python I Maya Nair 27-10-2021 5


Programs
• Programs are written in programming languages
• PL = programming language
• Pieces of the same program can be written in different PLs
• Languages closer to the machine can be more efficient
• As long as they agree on how to communicate
• A PL is
• A special purpose and limited language
• A set of rules and symbols used to construct a computer program
• A language used to interact with the computer
Programming with Python I Maya Nair 27-10-2021 6
Computer Languages
– Machine Language
• Uses binary code
• Machine-dependent
• Not portable
• Assembly Language
• Uses mnemonics
• Machine-dependent
• Not usually portable
• High-Level Language (HLL)
• Uses English-like language
• Machine independent
• Portable (but must be compiled for different platforms)
• Examples: Python, C, C++, Java, . . .

Programming with Python I Maya Nair 27-10-2021 7


Machine Language
• The representation of a computer program which is actually read
and understood by the computer.
• A program in machine code consists of a sequence of machine
instructions.
• Instructions:
• Machine instructions are in binary code
• Instructions specify operations and memory cells involved in the
operation
Operation Address
Example: 0010 0000 0000 0100

0100 0000 0000 0101


0011 0000 0000 0110

Programming with Python I Maya Nair 27-10-2021 8


Assembly Language
• A symbolic representation of the machine language of a specific
processor.
• Is converted to machine code by an assembler.
• Usually, each line of assembly code produces one machine instruction
(One-to-one correspondence).
• Programming in assembly language is slow and error-prone but is more
efficient in terms of hardware performance.
• Mnemonic representation of the instructions and data
• Example:
Load Price
Add Tax
Store Cost
Programming with Python I Maya Nair 27-10-2021 9
High-level language
• A programming language which use statements consisting of English-like keywords
such as "FOR", "PRINT" or “IF“, ... etc.
• Each statement corresponds to several machine language instructions (one-to-many
correspondence).
• Much easier to program than in assembly language.
• Data are referenced using descriptive names
• Operations can be described using familiar symbols
• Example:
Cost = Price + Tax

Programming with Python I Maya Nair 27-10-2021 10


Running Programs
• Steps that the computer goes through to run a
program: Memory

Machine language
program
(executable file)
Input Data Data entered CPU
during execution

Computed results
Program Output
Programming with Python I Maya Nair 27-10-2021 11
Compilation
Source Target
Program Compiler Program

Input Target Program Output

• Compiler translates source into target (a machine language program)


• Compiler goes away at execution time
• Compiler is itself a machine language program, presumably created by compiling
some other high-level program
• Machine language, when written in a format understood by the OS is object code
Programming with Python I Maya Nair 27-10-2021 12
Interpretation
Source
Program
Interpreter Output

Input

• The interpreter stays around during execution


• It reads and executes statements one at a time
Programming with Python I Maya Nair 27-10-2021 13
Compilation vs. Interpretation
• Compilation:
• Syntax errors caught before running the program
• Better performance
• Decisions made once, at compile time
• Interpretation:
• Better diagnostics (error messages)
• More flexibility
• Supports late binding (delaying decisions about program implementation
until runtime)
• Can better cope with PLs where type and size of variables depend on input
• Supports creation/modification of program code on the fly
Programming with Python I Maya Nair 27-10-2021 14
Python is
• an interpreted
• object-oriented
• high-level programming language with
dynamic semantics
• conceived by Guido Van Rossum in 1980
and implementation started in 1989.
Programming with Python I Maya Nair 15
• Python is powerful... and fast;
• plays well with others;
• runs everywhere;
• is friendly & easy to learn;
• is Open.

Programming with Python I Maya Nair 16


• IDLE is a cross-platform open-source IDE which
comes by default with Python. IDLE is
Installation completely written in Python.
of Python • IDLE name is used to honor Eric Idle who was
one of the founding members of Monty Python,
3 IDLE
the television show liked by the creator
of Python language Guido Van Rossum.

Programming with Python I Maya Nair 27-10-2021 17


To install python browse the URL :
https://www.python.org/downloads/

Programming with Python I Maya Nair 27-10-2021 18


Installation
of Python 3
IDLE

Programming with Python I Maya Nair 27-10-2021 19


Consists of a single statement
print(“Hello World”)

Programming with Python I Maya Nair 27-10-2021 20


• Comments- Represented by symbol ‘#’.Used for documentation.
• Variables-
• It can be only one word with no spaces or words separated by underscore
Building (_) character .
blocks of a • It can use only letters, numbers, and the underscore (_) character.
program • It can’t begin with a number.
• e.g. MaxMarks or Max_Marks.
• Variables are case-sensitive ie maxmarks is different from MaxMarks.
• Data types- boolean, int, float, string, list, dictionary, tuple
• Operators-Operator.pdf
• Literals-numeric, string
Programming with Python I Maya Nair 27-10-2021 21
• help()-Provides description of all python functions
• type()-gives data types of any variable
• input()- takes user’s input with a default data type of
String
Built in • print()- The print() function displays the string value
Functions inside its parentheses on the screen
• eval()-eval function evaluates the “String” like a python
expression and returns the result as an integer.
• int(),float()-Converts a String to integer and float
respectively
• str()-Converts an integer or float to a String
Programming with Python I Maya Nair 27-10-2021 22
f-Strings: A New and Improved Way to Format Strings in Python
Introduced in Python 3.6, fstrings are simple and readable way of
combining string literals and variable values.
Python
f-strings e.g.
name= “Andrews”
age=32
print( f ” Candidate’s name is {name} and age is { age} ” )

Output
Candidate's name is Andrews and age is 32

Programming with Python I Maya Nair 27-10-2021 23


Assignment Statement

Syntax: var_name = expression # L.H.S<=R.H.S


e.g max_marks=100 # variable named max_marks is created
# and is initialized as 100
Python
Statements Python supports multiple assignment, we create many variables and initialize
them at a time.
Syntax: var1,var2,var3=exp1,exp2,exp3
e.g a, b, c=1,2,3 # variables a, b and c are initialised with values 1, 2
#and 3 respectively
Programming with Python I Maya Nair 27-10-2021 24
Conditional Statement

A decision has to be taken when the script or program comes


to a point where it has a choice of actions, i.e. different
Python
computations, to choose from.
Statements

Programming with Python I Maya Nair 27-10-2021 25


if.. else… Statement
Syntax
if expression:
Statement 1 block for condition being True
Python Statement 2
Statements else :
Conditional Statement 1 block for condition being false
Statement Statement 2

e.g:
if marks > 80 :
grade=‘A’
else :
grade=‘B’
Programming with Python I Maya Nair 27-10-2021 26
if.. elif… Statement
Syntax
if expression:
Python Statement
Statements elif expression:
Conditional
Statement
Statement
:
.
else :
Statement

Programming with Python I Maya Nair 27-10-2021 27


Looping Statement
A loop statement allows us to execute a statement or group of
Python statements multiple times. The following diagram illustrates
Statements
a loop statement.

Programming with Python I Maya Nair 27-10-2021 28


While loop
Syntax
while expression:
statement 1
Python statement 2
Statements
Looping Statement :
statement n
count = 0 Output:
while (count <5): The count is: 0
The count is: 1
print ('The count is:',count) The count is: 2
The count is: 3
count = count +1 The count is: 4

Programming with Python I Maya Nair 27-10-2021 29


For loop
Syntax
for index_var in range(rangeval):
Python statement 1
Block of code to be
Statements statement 2 looped
Looping Statement
:
statement n
e.g: Output:
2
for x in range(2,7): 3
4
print(x) 5
6
Programming with Python I Maya Nair 27-10-2021 30
Range function

• range(start,stop,step) Syntax for range


range(start, stop, step)
• Step is by default +1
start-Optional,Default 0
• It can be positive or negative stop-Required
step- Optional,Default 1

Programming with Python I Maya Nair 27-10-2021 31


Break Statement
Break statements allows us to break or terminate out of a
loop
Python e.g. for x in range (10,20):
Statements
if (x == 15):
break
print(x)
Output:
10
11
12
13
14
Programming with Python I Maya Nair 27-10-2021 32
Continue Statement
Continue statements allows us skip an iteration and go ahead
with next iteration
Python e.g. for x in range (10,20):
Statements if (x == 15): Output:
10
continue 11
12
print(x) 13
14
16
17
18
19

Programming with Python I Maya Nair 27-10-2021 33


Else clause of loops
When the loop condition of "for" or "while" statement fails then
code part in "else“ is executed. If break statement is executed
inside for loop then the "else" part is skipped.
e.g.:
Python count=0
Statements while (count<5):
Output:
0
print(count) 1
2
count+=1 3
else: 4
count value reached 5
print("count value reached ",count)

Programming with Python I Maya Nair 27-10-2021 34


Compound DataTypes
• Strings
Python
• Lists
Compound • Tuple
Datatypes
• Dictionary

Programming with Python I Maya Nair 27-10-2021 35


Strings
Immutable datatype
Python
String in Python are identified as a contiguous set of
Compound
characters represented in the quotation marks. Python
allows either pair of single or double quotes. Subsets of
Datatypes
strings can be taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string and
working their way from -1 to the end.
For a string Subject=“PYTHON” , these are the indices for
various characters, i.e Subject[2]=Subject[ -4]=‘T’ .
0 1 2 3 4 5
P Y T H O N
-6 -5 -4 -3 -2 -1
Programming with Python I Maya Nair 27-10-2021 36
Strings
A for loop can be used for iterating through a string , as shown in the e.g.
code snippet for counting the occurrences of a character
count=0
Python
for letter in “Hello World”:
Compound
Datatypes if letter==‘l’:
count+=1
print(count,’letters found’)

Output
3 letters found
Programming with Python I Maya Nair 27-10-2021 37
String Slicing
• There are many inbuilt operators and functions for manipulating strings
• String indexing operator [ ] and string slicing [:] are two main operators
• String slicing gives a substring of one or more charcters from the string as per, start index,stop index
and step value provided by user

Here is a basic example of string slicing.

S = 'ABCDEFGHI’
print(S[2:7]) # CDEFG

Programming with Python I Maya Nair 27-10-2021 38


Slice with Negative Indices
S = 'ABCDEFGHI’
print(S[-7:-2]) # CDEFG

Programming with Python I Maya Nair 27-10-2021 39


Specify Step of the Slicing
• # Return every 2nd item between position 2 to 7
S = 'ABCDEFGHI'
print(S[2:7:2]) # CEG

Programming with Python I Maya Nair 27-10-2021 40


Other slicing considerations
• Negative Step Size
• # Returns every 2nd item between position 6 to 1 in reverse order
S = 'ABCDEFGHI'
print(S[6:1:-2]) # GEC
• Omitting the start index starts the slice from the index 0. Meaning, S[:stop] is equivalent to S[0:stop]
• # Slice first three characters from the string
S = 'ABCDEFGHI'
print(S[:3]) # ABC
• Omitting the stop index extends the slice to the end of the string. Meaning, S[start:] is equivalent to S[start:len(S)]
• # Slice last three characters from the string
S = 'ABCDEFGHI'
print(S[6:]) # GHI
• Reverse a String
• Reverse a string by omitting both start and stop indices and specifying a step as -1.
S = 'ABCDEFGHI'
print(S[::-1]) # IHGFEDCBA
Programming with Python I Maya Nair 27-10-2021 41
Other operators and functions
• Compound data type operators and functions

Programming with Python I Maya Nair 27-10-2021 42


List
Mutable datatype
The list is the most versatile datatype available in Python,
which can be written as a list of comma-separated values
Python (items) between square brackets. Important thing about a list
Compound is that the items in a list need not be of the same type.
Datatypes list1 = [‘Computer Science', ‘Biotechnology', 1999, 2002]
list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
Similar to string indices, list indices start at 0, and lists can be
sliced, concatenated and so on

Programming with Python I Maya Nair 27-10-2021 43


List
A for loop can be used for iterating through a list, as shown
in the code snippet below
Python
Compound List1=[1,”ABC”,2.30]
Datatypes for element in List1:
print(element)

Output
1
ABC
2.3

Programming with Python I Maya Nair 27-10-2021 44


Tuple
Immutable datatype
A tuple is a sequence of immutable Python objects. Tuples are sequences, just
like lists. The main difference between the tuples and the lists is that the
tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists
Python use square brackets.
Compound tup1 = (‘Computer Science', ‘Information Technology', 1999, 2002)
Datatypes tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d“
The empty tuple is written as two parentheses containing nothing tup1 = ();
To write a tuple containing a single value you have to include a comma, even
though there is only one value tup1 = (50,)
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.

Programming with Python I Maya Nair 27-10-2021 45


Dictionary
Mutable data type
A list is an ordered sequence of objects, whereas dictionaries are
unordered sets. The main difference is that items in dictionaries are
accessed via keys and not via their position
Python Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly
Compound braces. An empty dictionary without any items is written with just
Datatypes two curly braces, like this:
my_dict={ }.
Keys are unique within a dictionary while values may not be.
The values of a dictionary can be of any type, but the keys
must be of an immutable data type such as strings,
numbers, or tuples.

Programming with Python I Maya Nair 27-10-2021 46


Dictionary
e.g.:
Stud_dict={“Name”: “Andrews”,”Marks”:[85,55,40,60,90]}
Python
Compound >>> print(Stud_dict)
Datatypes
{'Name': 'Andrews', 'Marks': [85, 55, 40, 60, 90]}

>>> print(Stud_dict.get("Marks"))
[85, 55, 40, 60, 90]

Programming with Python I Maya Nair 27-10-2021 47

You might also like