PYTHON FUNDAMENTALS
Python Character Set
Is a set of valid characters that python can recognize. A
character represent letters, digits or any symbol. Python
support UNICODE encoding standard. Following are the
Python character set
➢ Letters : A-Z, a-z
➢ Digits : 0-9
➢ Special symbols :space +-*/()~`!@#$%^ & [{
]};:‟”,<.>/?
➢ White spaces : Blank space, Enter, Tab
➢ Other character : python can process all ASCII and
UNICODE as a part of data or literal
TOKENS
In a passage of text, individual words and punctuation
marks are called tokens or lexical units or lexical
elements. The smallest individual unit in a program is
known as Tokens. Python has following tokens:
✓ Keywords
✓ Identifiers(Name)
✓ Literals
✓ Operators
✓ Punctuators
KEYWORDS
Keywords are the reserved words and have special
meaning for python interpreter. Every keyword is
assigned specific work and it can be used only for that
purpose.
A partial list of keywords in Python is
IDENTIFIERS
Are the names given to different parts of program like variables,
objects, classes, functions etc.
Identifier forming rules of Python are :
➢ Is an arbitrarily long sequence of letters and digits
➢ The first character must be letter or underscore
➢ Upper and lower case are different
➢ The digits 0-9 are allowed except for first character
➢ It must not be a keyword
➢ No special characters are allowed other than underscore is allowed.
➢ Space not allowed
The following are some valid identifiers
GradePay File_12_2018 JAMES007
GRADEPAY _ismarried _to_update
The following are some invalid identifiers
BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
Literals / Values
Literals are data items that have a fixed value.
Python supports several kinds of literals:
🞑 String Literal
🞑 Numeric Literals
🞑 Boolean Literals
🞑 Special Literals – None
🞑 Literal Collections
String Literals
It is a collection of character(s) enclosed in a double or
single quotes
Examples of String literals
🞑 “Python”
🞑 “Mogambo”
🞑 „123456‟
🞑 „Hello How are your‟
🞑 „$‟, „4‟,”@@”
In Python both single character or multiple characters
enclosed in quotes such as “kv”, „kv‟,‟*‟,”+” are treated
as same
Non-Graphic (Escape) characters
They are the special characters which cannot be
type directly from keyboard like backspace, tabs,
enter etc. When the characters are typed they
perform some action. These are represented by
escape characters. Escape characters are always
begins from backslash(\) character.
List of Escape characters
Escape Sequence What it does Escape Sequence What it does
\\ Backslash \r Carriage return
\‟ Single quotes \t Horizontal tab
\” Double quotes \uxxxx Hexadecimal
value(16 bit)
\a ASCII bell \Uxxxx Hexadecimal
value(32 bit)
\b Back Space \v vertical tab
\n New line \ooo Octal value
String type in Python
Python allows you to have two string types:
🞑 Single Line Strings
◼ The string we create using single or double quotes are
normally single-line string i.e. they must terminate in one line.
◼ For e.g if you type as
◼ Name="KV and press enter
◼ Python we show you an error “EOL while scanning string literal”
◼ The reason is quite clear, Python by default creates single-line
string with both single quotes and it must terminate in the same
line by quotes
String type in Python
Multiline String
🞑 Some times we need to store some text across
multiple lines. For that Python offers multiline string.
🞑 To store multiline string Python provides two ways:
(a) By adding a backslash at the end of normal Single / Double
quoted string. For e.g.
>>> Name="1/6 Mall Road \
Kanpur"
>>> Name
'1/6 Mall RoadKanpur'
>>>
String type in Python
Multiline String
(b) By typing text in triple quotation marks
for e.g.
>>> Address="""1/7 Preet Vihar
New Delhi
India"""
>>> print(Address)
1/7 Preet Vihar
New Delhi
India
>>> Address
'1/7 Preet Vihar\nNew Delhi\nIndia'
Size of String
Python determines the size of string as the count of characters in the string.
For example size of string “xyz” is 3 and of “welcome” is 7. But if your
string literal has an escape sequence contained in it then make sure to count
the escape sequence as one character. For e.g.
String Size
„\\‟ 1
„abc‟ 3
„\ab‟ 2
“Meera\‟s Toy” 11
“Vicky‟s” 7
You can check these size using len() function of Python. For example
>>>len(„abc‟) and press enter, it will show the size as 3
Size of String
For multiline strings created with triple quotes : while calculating size
the EOL character as the end of line is also counted in the size. For
example, if you have created String Address as:
>>> Address="""Civil lines
Kanpur"""
>>> len(Address)
18
For multiline string created with single/double quotes the EOL is not
counted.
>>> data="ab\
bc\
cd"
>>> len(data)
6
Numeric Literals
The numeric literals in Python can belong to any of
the following numerical types:
1) Integer Literals: it contain at least one digit and must
not contain decimal point. It may contain (+) or (-) sign.
🞑 Types of Integer Literals:
a) Decimal : 1234, -50, +100
Numeric Literals
2) Floating point Literals: also known as real
literals. Real literals are numbers having fractional
parts. It is represented in two forms Fractional Form
or Exponent Form
Fractional Form: it is signed or unsigned with decimal point
🞑 For e.g. 12.0, -15.86, 0.5, 10. (will represent 10.0)
Boolean Literals
A Boolean literals in Python is used to represent one of the two
Boolean values i.e. True or False
These are the only two values supported for Boolean Literals
For e.g.
>>> isMarried=True
>>> type(isMarried)
<class 'bool'>
Special Literals None
Python has one special literal, which is None. It indicate absence
of value. In other languages it is knows as NULL. It is also used
to indicate the end of lists in Python.
>>> salary=None
>>> type(salary)
<class 'NoneType'>
Complex Numbers
Complex: Complex number in python is made up of two floating point values,
one each for real and imaginary part. For accessing different parts of
variable (object) x; we will use x.real and x.image. Imaginary part of the
number is represented by “j” instead of “I”, so 1+0j denotes zero imaginary.
part.
Example
>>> x = 1+0j
>>> print x.real,x.imag
1.0 0.0
Example
>>> y = 9-5j
>>> print y.real, y.imag
9.0 -5.0
Conversion from one type to another
Explicit type conversion
To perform explicit type conversion Python provide functions like
int(), float(), str(), bool()
>>> a=50.25
>>> b=int(a)
>>> print b
50
Here 50.25 is converted to int value 50
>>>a=25
>>>y=float(a)
>>>print y
25.0
Operators
are symbol that perform specific operation when
applied on variables. Take a look at the expression:
(Operator)
10 + 25 (Operands)
Above statement is an expression (combination
of operator and operands)
i.e. operator operates on operand. some operator requires two
operand and some requires only one operand to operate
Types of Operators
Unary operators: are those operators that require
one operand to operate upon. Following are some
unary operators:
Operator Purpose
+ Unary plus
- Unary minus
~ Bitwise complement
Not Logical negation
Types of Operators
Binary Operators: are those operators that require two
operand to operate upon. Following are some Binary
operators:
1. Arithmetic Operators
Operator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
// Floor division
Example
>>> num1=20
>>> num2=7
>>> val = num1 % num2
>>> print(val)
6
>>> val = 2**4
>>> print(val)
16
>>> val = num1 / num2
>>> print(val)
2.857142857142857
>>> val = num1 / / num2
>>> print(val)
2
Identity Operators
Operators Purpose
is Is the Identity same?
is not Is the identity not same?
Relational Operators
Operators Purpose
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not equal to
Logical Operators
Operators Purpose
and Logical AND
or Logical OR
not Logical NOT
Assignment Operators
Operators Purpose
= Assignment
/= Assign quotient
+= Assign sum
-= Assign difference
*= Assign product
**= Assign Exponent
//= Assign Floor division
Membership Operators
Operators Purpose
in Whether variable in
sequence
not in Whether variable not in
sequence
Punctuators
Punctuators are symbols that are used in programming
languages to organize sentence structure, and indicate
the rhythm and emphasis of expressions, statements,
and program structure.
Common punctuators are: „“ # $ @ []{}=:;(),.
Expression
An expression is any legal combination of symbols that
represents a value. An expression is generally a
combination of operators and operands
Example:
expression of values only
20, 3.14
Expression that produce a value when evaluated
A+10
Salary * 10 / 100
Statement
It is a programming instruction that does something i.e.
some action takes place.
Example
print(“Welcome to python”)
The above statement call print function
When an expression is evaluated a statement is executed
i.e. some action takes place.
a=100
b = b + 20
Comments
Comments are additional information written in a
program which is not executed by interpreter i.e.
ignored by Interpreter. Comment contains information
regarding statements used, program flow, etc.
Comments in Python begins from #
Python supports 3 ways to enter comments:
1. Full line comment
2. Inline comment
3. Multiline comment
Comments
Full line comment
Example:
#This is program of volume of cylinder
Inline comment
Example
area = length*breadth # calculating area of rectangle
Variables
Variables are named temporary location used to store
values which can be further used in calculations, printing
result etc. Every variable must have its own Identity, type
and value. Variable in python is created by simply
assigning value of desired type to them.
For e.g
Num = 100
Name=“JamesF
Lvalues and Rvalues
Lvalue : expressionthat comes on the Left hand Side of
Assignment.
Rvalue : expressionthat comes on the Right hand Side of
Assignment
Lvalue refers to object to which you can assign value. It refers to
memory location. It can appear LHS or RHS of assignment
Rvalue refers to the value we assignto any variable. It can
appear on RHS of assignment
Lvalues and Rvalues
For example (valid use of Lvalue and Rvalue)
x = 100
y = 200
Invalid use of Lvalue and Rvalue
100 = x
200 = y
a+b = c
Note: values cannot comes to the left of assignment. LHS must be a
memory location
Multiple Assignments
Python is very versatile with assignments. Let‟s see in how different ways
we can use assignment in Python:
1. Assigning same value to multiple variable
a = b = c = 50
2. Assigning multiple values to multiple variable
a,b,c = 11,22,33
Note: While assigning values through multipleassignment, remember that
Python first evaluates the RHS and then assigns them to LHS
Examples:
Multiple Assignments
x,y,z = 10,20,30 #Statement 1
z,y,x = x+1,z+10,y-10 #Statement 2
print(x,y,z)
Output will be
10 40 11
Now guess the output of following code fragment
x,y = 7,9
y,z = x-2, x+10
print(x,y,z)
Multiple Assignments
Let us take another example
y, y = 10, 20
In above code first it will assign 10 to y and again it assign 20
to y, so if you print the value of y it will print 20
Now guess the output of following code
x, x = 100,200
y,y = x + 100, x +200
print(x,y)
Variable definition
Variable in python is create when you assign value to it
i.e. a variable is not create in memory until some value is
assigned to it.
Let us take as example(if we execute the following code)
print(x)
Python will show an error „x‟ not defined
So to correct the above code:
x=0
print(x) #now it will show no error
Dynamic Typing
In Python, a variable declared as numeric type can be
further used to store string type or another.
Dynamic typing means a variable pointing to a value of
certain type can be made to point to value/object of
different type.
Lets us understand with example
x = 100 # numeric type
print(x)
x=“KVians” # now x point to string type
print(x)