[go: up one dir, main page]

0% found this document useful (0 votes)
25 views87 pages

Lec - 1 - Introduction To Python

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

Lec - 1 - Introduction To Python

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

INTRODUCTION TO

PYTHON
Presented By : Ravleen Kaur
TRF, CSE Dept, NSUT
INTRODUCTION
Python is a high-level, general-purpose and a very popular programming
language. Python programming language (latest Python 3) is being used in web
development, Machine Learning applications, along with all cutting edge
technology in Software Industry. Python Programming Language is very well
suited for Beginners, also for experienced programmers with other programming
languages like C++ and Java.
Brief History of Python

•Invented in the Netherlands, early 90s by Guido van Rossum


•Named after Monty Python
•Open sourced from the beginning
•Considered a scripting language, but is much more
•Scalable, object oriented and functional from the beginning
•Used by Google from the beginning
•Increasingly popular
Why to Learn Python?

● Python is Open Source which means its available free of cost.


● Python is simple and so easy to learn
● Python is versatile and can be used to create many different things.
● Python has powerful development libraries include AI, ML etc.
● Python is Interpreted − Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it. This is similar to
PERL and PHP.
● Python is Interactive − You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.
● Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
● Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.
Characteristics of Python

● It supports functional and structured programming methods as well as OOP.


● It can be used as a scripting language or can be compiled to byte-code for
building large applications.
● It provides very high-level dynamic data types (no need to mention data type
based on the value assigned, it takes data type) and supports dynamic type
checking.
● It supports automatic garbage collection.
● It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Advantages of Python
● Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
● Easy-to-read − Python code is more clearly defined and visible to the eyes.
● Easy-to-maintain − Python's source code is fairly easy-to-maintain.
● A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
● Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
● Highly Efficient : Python’s clean object-oriented design provides enhanced
process control, and the language is equipped with excellent text processing and
integration capabilities, as well as its own unit testing framework, which makes
it more efficient.
● Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
● Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
● Databases − Python provides interfaces to all major commercial databases.
● GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
● Scalable − Python provides a better structure and support for large programs
than shell scripting.
Applications
• GUI-based desktop applications
• Graphic design, image processing applications, Games, and Scientific/ computational Applications
• Web frameworks and applications
• Enterprise and Business applications
• Operating Systems
• Education
• Database Access
• Language Development
• Prototyping
• Software Development
• Data Science and Machine Learning
• Scripting
Building Blocks of Python Programming Language
● Constants
● Variables
● Identifiers
● Data Types
● Reserved words
● Indentation
● Operators
● Expressions
PYTHON CHARACTER SET

What is Character Set?


Character set is a bunch of identifying elements in the programming language.
• Letters:- A-Z, a-z
• Digits:- 0 to 9
• Special Symbols:- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? &
• White Spaces:- Blank Space , Horizontal Tab, Vertical tab, Carriage Return.
• Other Characters:- Python can process all 256 ASCII and Unicode Characters.
TOKENS OR LEXICAL UNIT
Individual elements that are identified by programming language are called tokens or
lexical unit.

1. Key Words

5. Punctuators 2. Identifiers

TOKENS

4. Operators. 3. Literals
Keyword/Reserved Word
•Keywords are also called as reserved words these are having special meaning in
python language.
•The words are defined in the python interpreter hence these can't be used as
programming identifiers.
IDENTIFIERS
What is an identifier?
A Python Identifier is a name given to a function, class, variable, module, or other
objects that you’ll be using in your Python program.

For example: a, b, c
a b and c are the identifiers and
a b & c and , are the tokens
PYTHON NAMING CONVENTIONS
• An identifier can be a combination of uppercase letters, lowercase letters, underscores,
and digits (0-9). Hence, the following are valid identifiers: myClass, my_variable,
var_1, and print_hello_world.
• The first character must be letter.
• Special characters such as %, @, and $ are not allowed within identifiers.
• An identifier should not begin with a number. Hence, 2variable is not valid, but
variable2 is acceptable.
• Python is a case-sensitive language and this behaviour extends to identifiers. Thus,
Labour and labour are two distinct identifiers in Python.
• You cannot use Python keywords as identifiers.
• You can use underscores to separate multiple words in your identifier.
● Python Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
● Starting an identifier with a single leading underscore indicates that the
identifier is private identifier.
● Starting an identifier with two leading underscores indicates a strongly
private identifier.
● If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
PYTHON NAMING CONVENTIONS

SOME VALID IDENTIFIERS:


Myfile1 DATE9_7_8 y3m9d3 _xs
MYFILE _FXd
SOME INVALID IDENTIFIERS:
MY-REC 28dre break
elif false del
LITERALS / CONSTANT VALUES
What is literals?
Literals are also called as constants or constant values which never change during
the execution of program.
NUMERICAL LITERALS

Numerical Literal is a literal containing only the digits 0-9, an optional sign character +
or - and a possible decimal sign.
Numeric literals have the following types:
● int or integers - Whole numbers
● float - real values
● complex : complex numbers
Commas are never used in numeric literals.
INTEGER LITERALS OR CONSTANTS

❖ Decimal Integer Literals: Any whole number (+ve) or (-ve).


INTEGER LITERALS OR CONSTANTS

❖ Octal Integer Literals(base 8): A Sequence of digits starting with 0O (digit


zero followed by letter o) is taken to be an Octal Integer Literals.
INTEGER LITERALS OR CONSTANTS

❖ Hexadecimal Integer Literals (base 16): Sequence of digits preceded by ox or


OX is hexadecimal integer literals
INTEGER LITERALS OR CONSTANTS

❖Binary literals (base 2): To signify binary literals, you’ll use the prefix ‘0B’
or ‘0b’ (zero and uppercase or lowercase ‘b’).
Complex Number
• Python represents complex numbers in the form a+bj.
• Example- Sum of two Complex Numbers
>> a=7+8j
>>b=3.1+6j
>>c=a+b
>>print("Sum of two Complex Numbers")
>>print(a,"+",b,"=",c)
Output:
(7+8j) + (3.1+6j) = (10.1+14j)
FLOATING POINT LITERALS OR CONSTANTS

Floating point literals are also called as real literals having fractional part.

These may be written in one of the two forms:

1. Fractional Form: for example 15.75

2. Exponent Form: It consists of two parts Mantissa and Exponent. for example 5.8
can be represented as 0.58 x 10-1 = 0.58E01. where mantissa part is 0.58 and E01
is the exponent.
FLOATING POINT LITERALS OR CONSTANTS

Float type
STRING LITERALS OR CONSTANTS
What is string?
Sequence of letters enclosed in quotes is called string or string literal or constant.
Python supports both form of quotes i.e.
‘Hello’
“Hello”
REPRESENTATION OF STRING
>>> s = “Hello Python”
This is how Python would index the string:

Backward Indexing

Forward Indexing
REPRESENTATION OF STRING

To access the first character on the string you just created, type and enter the
variable name s and the index 0 within square brackets like this:
>>>s[0]
You’ll get this output:
‘H’
REPRESENTATION OF STRING

To access the last character, you can use this expression:


>>>s[len(s)-1]
Len() function
You’ll get the output: is used to find
‘n’ the length of
the string.
REPRESENTATION OF STRING

The expression introduces you to the len function. There is actually an easier way to
access the last item on the string:
>>>s[-1]
‘n’
To access the penultimate character:
>>>s[-2]
‘o’
TYPES OF STRINGS
Python supports two ways of representation of strings:
1) Single Line Strings.
2) Multi Line Strings.
SINGLE LINE STRINGS

Strings created using single quote or double quote must end in one line are called
single line strings
For Example:
Item=“Computer”
Or
Item= ‘Computer’
MULTI LINE STRINGS
Strings created using single quote or double quote and spread across multiple lines
are called Multi Line Strings.
• by adding backslash \ one can continue to type on next line.
For instance: Item = ‘Key\
board’
SIZE OF STRINGS

‘\\’ Size is 1 (\ is an escape sequence)


‘abc’ size is 3
“\ab” size is 2
“Raama\’s Laptop” size is 13
STRINGS WITH TRIPLE QUOTES

For multi line strings created by triple quotes, while calculating size, the EOL(End of
Line) character at the end of line is also counted.
For instance:
Str2=“’x Enter keys are
y considered as
Z”’ EOL so size of
str2 is 5
ESCAPE SEQUENCES

\\ Back Slash

\’ Single Quote (‘)

\” Double Quote (“)


ESCAPE SEQUENCES

\a ASCII Bell

\b ASCII Backspace

\f ASCII Formfeed
ESCAPE SEQUENCES

\n New Line

\r Carriage return

\t Horizontal Tab
ESCAPE SEQUENCES

\t Vertical Tab

\x 16 bit hex value

\ooo Octal Value


\\ Back Slash
\’ Single Quote
\” Double Quote
\x 16 bit Hex Val
\ooo Octal Value

Note: ooo represents 3 octal digits.


BOOLEAN LITERALS OR CONSTANTS.

A Boolean literal in python is used to represent the Boolean values (true or false).
SPECIAL LITERAL NONE
The None literal is used to indicate absence of value.
For example: val = None
OPERATORS
What is an operator?
Operators are tokens that trigger some computation when applied to a variable.
Arithmetic operations
Assignment operators
Comparison operators
Comparison examples

False
Logical operators
Identity operators
Membership operators
Bitwise operators
Operator Precedence and Associativity
1 + 2 ** 3 / 4 *
>>> x = 1 + 2 ** 3 / 4 *
5
5
>>> print x 1+8/4*
11 5
>>>
1+2*
Note 8/4 goes before 4*5 because 5
of the left-right rule.

1+
Parenthesis
Power
10
Multiplication
Addition
1
Left to Right 1
PUNCTUATORS
Punctuators are also called as separators
The Followings are used as punctuators:

● Brackets [ ]
● Parentheses ( )
● Braces { }
● Comma ,
● Semicolon ;
● Colon :
● Asterisk *
● Ellipsis …
● Equal Sign =
● Pound Sign #
Indentation
● Whitespace at the beginning of the line called indentation
Example
Age =7
price=10
count=6
● These whitespaces are very important in python
● In most programming languages , indentation has no effect on program logic.
● In python indentation has a major effect on program logic.
● In python , indentation is used to associate and group statements.
Whitespace
• Whitespace is meaningful in Python: especially indentation and placement of
newlines
• Use a newline to end a line of code
• Use \ when must go to next line prematurely
• No braces {} to mark blocks of code, use consistent indentation instead
• First line with less indentation is outside of the block
• First line with more indentation starts a nested block
• Colons start of a new block in many constructs, e.g. function definitions, then
clauses
COMMENTS

• Comments are non executable statements in a program.


• Single line comment always starts with #
• Multiline comment will be in triple quotes. For example “’ write a program to
find the simple interest “’.
Note: Triple apostrophe is called docstrings.
STATEMENTS
Instructions written in the source code for execution are called statements. There are
different types of statements in the Python programming language like Assignment
statements, Conditional statements, Looping statements, etc. These all help the user to
get the required output. For example, n = 50 is an assignment statement.

Multi-Line Statements: Statements in Python can be extended to one or more lines


using parentheses (), braces {}, square brackets [], semi-colon (;), and continuation
character slash (\). When the programmer needs to do long calculations and cannot fit his
statements into one line, one can make use of these characters.
FUNCTIONS
Function is a self contained program segment which carries out some specific well
defined task.
For Example:
def sqr( num ):
result= num *num
print ("Square = " , result)
sqr()
PYTHON PROGRAMMING CONVENTIONS

○ Statement Termination: python does not use any symbol to terminate the
statement.
○ Maximum Line Length: Line Length be maximum 79 characters.
○ Whitespaces: You should always have whitespace around operators but not
with parenthesis.
○ Block or Code Block: A group of statements which are part of another
statement or function is called Block or Code Block.
○ Case Sensitive: Python is case sensitive.
VARIABLES AND ASSIGNMENTS

Named labels are called variables.


For example: marks =86

78 79 80 81 82 83 84 85 86 87
2000 2016 2018 2026 2032 2044 2048 2050 2054 2068

marks refers to
location 2054
VARIABLES AND ASSIGNMENTS

Now marks = 81

78 79 80 81 82 83 84 85 86 87
2000 2016 2018 2026 2032 2044 2048 2050 2054 2068

marks refers to
location 2026

Note: Variables in python do not have fixed


locations unlike other programming languages
VARIABLES AND ASSIGNMENTS

Multiple Assignments
Python is very versatile with assignment statements.
● Assigning same value to multiple variables:
a=b=c=d=e=10
● Assigning Multiple values to multiple variables:
p,q,r =5,10,15
print(q, r) will print 10 15
p,q=q,p
print (p,q) will print 10 5
VARIABLES AND ASSIGNMENTS

● Assigning Multiple values to multiple variables:


a,b,c = 5,10,7
b,c,a = a+1, b+2, c-1
print(a,b,c) will print 6 6 12
● Expressions separated by commas are evaluated from left to right.
x = 10
y,y = x+2,x+5
y,y = 12,15
First It will assign y = 12 then y = 15
So print(y) will print 15
VARIABLES AND ASSIGNMENTS

Dynamic Typing:
A variable pointing to a value of certain type can be made to point to a
value/object of different type this is called Dynamic Typing.
x=10
print(x)
x=“ Hello World”
print(x)

Output :
10
Hello World
Important lesson to remember!
We can't do arithmetic operations on variables of different types. Therefore make sure
that you are always aware of your variables types!

You can find the type of a variable using type(). For example type type(x).
VARIABLES AND ASSIGNMENTS

type() function:
To know the data type of a value which is pointing use type ( )
>>>a=10
>>>type(a)
Type returned as integer
<class ‘int’>
>>>a=20.4
>>>type(a)
Type returned as float
<class ‘float’>
>>>a=“Hello”
>>>type(a)
<class ‘str’> Type returned as string
Types

Variables actually have a type, which defines the way it is stored.


The basic types are:
Casting types

Luckily Python offers us a way of converting variables to different types!


Casting – the operation of converting a variable to a different type

Similar methods exist for other data


types: int(), float(), str()
Data types in Python
•A data type represents the type of data stored into variable or memory
•Can be
•Built in Datatypes
•User Defined datatypes
Built-in Datatype
• None type
• Represents an object that does not contain any value
• maximum of only one 'None' object is allowed
• can be used inside a function as a default value of arguments
• Numeric types
• int
• float
• complex
• Sequences
• Sets
• Mappings
SEQUENCES

A sequence represents group of items or elements. There are six types of sequences
in python
• str or string datatype
• bytes
• bytearray
• list
• tuple
• range
bytes data type
• Represents a group of byte numbers just like an array does
• A byte number is any positive number between 0 to 255(inclusive)
• Bytes array can store numbers in the range from 0 to 255 and cannot store even
negative numbers
• We can also modify numbers in a bytes array
• Example
>> elements = [10,20,50,100,0] # list of byte numbers
>> x = bytes(elements) # convert the list into byte type array
>> print(x[0]) # display 0th element
bytearray datatype
• Similar to bytes data type
• The difference is bytes type array cannot be modified but the bytearray type array
can be modified
• Example
x = [10,20,0,48,50]
y = bytearray(x)
print(y[0])

y[0] = 34
y[1] = 60

for i in y: print(i)
list datatype
• Similar to arrays in C or Java
• A list represents a group of elements
• The difference is that a list can store different types of elements but array can store
only one type of element
• Lists can grow dynamically in memory
• Lists are mutable
• Size of arrays is fixed and they cannot grow at runtime

• list = [10,4.5,'hello', “India”]


tuple datatype
• Similar to list
• A list represents a group of elements
• The difference is that elements are enclosed in parenthesis
• It is not possible to modify the elements of a tuple
• Tuple is treated as a read only list

• tp = (10,4.5,'hello', “India”)
• tp[0] = 78 will give error
range datatype
• Represents a sequence of numbers
• Numbers in the sequence are not modifiable
• Generally used for repeating a loop for a specific number of types
r = range(10)
a range object is created with numbers starting from 0 to 9
for i in r: print(i) #will print numbers from 0 to 9
r = range(30,40,2)
This will create a range object with a starting number 30, an ending number 39
and step size 2
• l = list(range(10))
• print(l) # will display [0,1,2,3,4,5,6,7,8,9]
Sets
•A set is an unordered collection of elements much like a set in maths.
•The order of elements is not maintained in sets
•It means elements may not appear in the same order as they are entered into set
•A set does not accept duplicate element
•There are two subtypes in sets
• set datatype
• frozenset datatype
set Datatype
• To create a set enter the elements separated by commas inside curly brackets
s = {10,20,30,10,50}
print(s) # may display { 50,10,20,30}
ch = set(“Hello”)
print(ch) #may display {'H','e','l' 'o'}
• Since sets are unordered we can not retrieve the elements using indexing or slicing
operations
• Update or remove method is used to add/remove elements to a set
e.g. s.update([45,34]}
s.remove(50)
frozenset Datatype

•Is same as the set datatype but the elements in frozenset cannot be modified
s = {10,20,30,50}
print(s) # may display { 50,10,20,30}
fs = frozenset(s)
•However, update or remove method will not work on a frozen set
Mapping Types
• A map represents a group of elements in the form of key value pairs so that when
the key is given we can retrieve the value associated with that key
• Example is dict datatype

You might also like