Lec - 1 - Introduction To Python
Lec - 1 - Introduction To Python
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
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
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
❖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.
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
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
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
\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
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
○ 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
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
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
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
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
• 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