XI-IP-I-Python Fundamentals-Module - I-June-7-2021

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

Chapter 2 -Python Fundamentals-Module-I

Module 1-Python character Sets; Barebones of Python program

A set of valid characters recognized by python. Python uses the traditional ASCII
character set. The latest version recognizes the Unicode character set. The ASCII
character set is a subset of the Unicode character set
Letters :– A-Z,a-z
Digits :– 0-9
Special symbols :– Special symbol available over keyboard + _ * / **
\ [ ] { } ( ) == =! >= <= > < ‘” “’ , ;, :% !
White spaces:– blank space,tab(, ) carriage return, ( ) new line, form
feed.
Other characters:- Python can process all ASCII and Unicode characters as
part of data or literals.

TOKENS:

Smallest individual unit in a program is known as token or lexical unit.


1. Keywords
2. Identifiers( Names)
3. Literals
4. Operators
5. Punctuators

1.Keywords:
Reserved word of the compiler/interpreter which can’t be used as identifier. It has a
special meaning reserved for programming language.

and exec not

as finally or

assert for pass

break from print

class global raise

continue if return

def import try

Page 1 of 12
del in while

elif is with

2.Identifiers:
A Python identifier is a name used to identify a variable, function, class, module or
other object.
 An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
 Python does not allow special characters except _ underscore.
 Identifier must not be a keyword of Python.
 Python is a case sensitive programming language.
 The digits 0 to 9 are allowed except for the first character.
 Identifiers are unlimited in length.

Thus, Rollnumber and rollnumber are two different identifiers in Python.


Some valid identifiers : Mybook, file123, z2td, date_2, _no

Some invalid identifier : 2rno,break,my.book,data-cs

3. Literals:
Literals in Python can be defined as number, text, or other data that represent values to
be stored in variables. Often refereed as Constant(fixed) values.
Types of Literals:
(a) String (b) Numeric (c ) Boolean
(d) Special Lieral (e ) Lieral Collections
Example of String Literals in Python
Name1 = ‘ABC’ , fname =“XYZ”
Python allows to have certain nongraphic-characters in string values.These characters
can not be typed directly from keyboard. Example backspace, .They can be
represented by escape sequences.
Escape sequence
Escape Sequence Description

Page 2 of 12
\\ Backslash (\)

\' Single quote (')

\" Double quote (")

\a ASCII Bell (BEL)

\b ASCII Backspace (BS)

\f ASCII Formfeed (FF)

\n ASCII Linefeed (LF)

\r ASCII Carriage Return (CR)

\t ASCII Horizontal Tab (TAB)

\v ASCII Vertical Tab (VT)

\ooo Character with octal value ooo

\xhh Character with hex value hh

A escape sequence represent a single character and hence consumes one byte in
ASCII representation.

String Types in Python:

(i) Single –line strings(Basic strings)

For Example:

T1=’hello

There’

Will show an error, the reason for the above error is –Python by default creates single
line strings with both single and double quotes. So, if at the end of a line ,there is no
closing quotation mark for an opened quotation mark , Python shows an error.

Page 3 of 12
(ii) Multiline strings:
When you need to store some text spread across multiple lines as one single
string. For that Python offers multiline Strings.
(a) By adding backslash at the end of normal single-quote/double-quote
strings:
In normal string just add a backslash in the end before pressing Enter to
continue typing text on the next line.
For Example:

T1=’hello\
Students’
Output:
'hellostudents'

(b) By typing the text in triple quotation marks:


In this no backslash is needed at the end of the line.
For Example:
T2=’’’DPS
Students
Demo of multiline.’’’
Output:
DPS
Students
demo of multiline

OR

For Example:
T2=” “ “Python
Fundamentals
learning.” “ “

Output:
Python
Fundamentals
Learning.

Size of Strings:

Page 4 of 12
Python determines the size of strings as the count of characters in the string. For
example “AB” is 2 and “DPS” is 3 but if string literal has escape sequence contained
within it will count that as one character.

‘\\’ size is 1(\\ is an escape sequence to represent backslash)

‘abc’ size is 3

“\ab” size is 2(\a is an escape sequence, thus one character)

“Ragav\’s pen” size is 11(For typing apostrophe(‘) sign,escape sequence\’ is


used)

“Amy’s” size is 5

For multiline strings created with triple quotes, while calculating size , the EOL(end
of line)character at the end of the line is also counted in the size.

For example:
S1=’ ‘ ‘ a
The enter keys are considered as EOL
character and counted in the length of
b line.

c’ ‘ ‘

Output:

Size of the string will be 5.

For Example :

S2=’a\

b\

c’

Page 5 of 12
Output:

Size of the s2 will be 3, backslash is not counted. This can be checked by typing Len
command.

Example:

len(s2)

len(s1)

Numeric Literals:

int(signed integers) They are positive or negative whole numbers with no decimal
point.

Integer Literals:

An integer constant must have at least one digit and must not contain any decimal
point. It may contain either (+) or (-) sign. A number with no sign is assumed to be
positive. Commas cannot appear in an integer constant.

It allows three types of integer literals:

(1) Decimal Integer Literal: 1234, 32, -17 are decimal integer literals.
(2) Octal Integer Literals: A sequence of digits starting with 0o(digit 0 followed by
letter o) is taken to be an octal int.
For example: Decimal no. 8 will be written as 0o10 as octal integer.(810=108)
An octal value can contain only digits 0-7;8 and 9 are invalid digits.0o28
(3) Hexadecimal Integer Literals: A sequence of digits preceded by 0x or 0X is taken to
be an hexadecimal int. It contain no.0-9 and letters A-F.
For example Decimal 12 will be written as 0XC as hexadecimal.

Floating Point Literals:Also called real literals. These may be written in two forms:
Fractional or Exponent form.

10012
(i) Fractional form:
Page 6 of 12
A real constant in fractional form must have at least one digit with the
decimal point, either before or after. It may also have +ve or –ve sign
preceding it. A real no. without sign is assumed as positive.
For example: 2.0, 17.4, -0.0987, .3(will represent 0.3), 7. (will represent 7.0)

Invalid real literals:


7 no decimal point
+17/2 / illegal symbol
17,250.26.2 two decimal points
17,250.262 comma not allowed

(ii) Exponent form: It consists of two parts-mantissa and exponent.


For example 5.8 can be written as 0.58*101=0.58E01, where mantissa part is
0.58) the part appearing before E and exponent part is 1.

The mantissa must be either an integer or a proper real constant. The


mantissa is followed by a letter E or e and the exponent. The Exponent must
be an integer.

Valid Real literals:


152E+8, 1520E04, -0.172E-3, 172.E3, .25E-4, 3.E3(equivalent to 3.0E3)
Invalid Real Literals:
1.7E No digit specified for exponent
0.17E2.3 Exponent can’t have fractional part
17,225E02 No comma allowed

Numeric values with commas are not considered int or float rather treats
them as tuple. A tuple in python stores sequence of values.

Boolean Literals:

True and false are only two literals in python. In programming you often need to know
if an expression is True or False.You can evaluate any expression in Python, and get one
of two answers, True or False.

When you compare two values, the expression is evaluated and Python returns the
Boolean answer:

Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

Page 7 of 12
Example Program:Print a message based on whether the condition is True or False:

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Special literal None:


Python contains one special literal i.e., None. It indicates the absence of value.
For example :
A=10
B=None
A
B
Print(“now use print”)
print(B)

Output
10
Now use print
None

4.Operators
Operators can be defined as symbols that are used to perform operations on operands.
a. Unary operator:
These operators required one operand to operate upon.
Following are some Unary operators:
+ Unary plus
- Unary minus
~ Bitwise Compliment
not Logical negation
b. Binary Operator
This requires two operands to operate upon.
Following are some Binary operators:
+ Addition
- Substratction
* Multiplication
/ Division
% Remainder/Modulus
** Exponent
// Floor Division

Page 8 of 12
c. Bitwise Operators:
& Bitwise AND
^ Bitwise exclusive OR(XOR)
| Bitwise OR
d. Shift Opearotor:
<< shift left
>> shift right
e. Identity Operator:
is is the identity same ?
is not is the identity not same ?
f. Relational Operators
Relational Operators are used to compare the values.

Operators Description Example

== Equal to, return true if a equals to b a == b

!= Not equal, return true if a is not equals to b a != b

> Greater than, return true if a is greater than b a>b

Greater than or equal to , return true if a is greater


>= a >= b
than b or a is equals to b

< Less than, return true if a is less than b a<b

Less than or equal to , return true if a is less than b


<= a <= b
or a is equals to b

g. Assignment Operator:

Used to assign values to the variables.


Operators Description Example

= Assigns values from right side operands to left side operand a=b

+= Add 2 numbers and assigns the result to left operand. a+=b

Page 9 of 12
/= Divides 2 numbers and assigns the result to left operand. a/=b

*= Multiply 2 numbers and assigns the result to left operand. A*=b

-= Subtracts 2 numbers and assigns the result to left operand. A-=b

%= modulus 2 numbers and assigns the result to left operand. a%=b

Perform floor division on 2 numbers and assigns the result to


//= a//=b
left operand.

calculate power on operators and assigns the result to left


**= a**=b
operand.

h. Logical Operators
Logical Operators are used to perform logical operations on the given two
variables or values.

Operators Description Example

and return true if both condition are true x and y

or return true if either or both condition are true x or y

not reverse the condition not(a>b)

a=30
b=20
if(a==30 and b==20):
print('hello')
Output:
hello

i. Membership Operator

Page 10 of 12
The membership operators in Python are used to validate whether a value is
found within a sequence such as such as strings, lists, or tuples.
Operators Description Example

in return true if value exists in the sequence, else false. a in list

not in return true if value does not exists in the sequence, else false. a not in list

5. Punctuators:
Used to implement the grammatical and structure of a Syntax.Following are the
python punctuators.

Assignment Questions:
1. What are literals in Python explain with example?
2. How many types of integer literals are allowed in Python?
3. What is an identifier? What are the identifier forming rules of Python?
4. What are keywords? Can keywords be used as identifiers?
5. What is meant by token? Name the tokens available in Python?
6. What will varl and var2 store with statements:
varl = 2,121E2 and var2 = 0.2,121E2 ?
What are the types of values stored in varl and var2?
7. What kind of program elements are the following?
‘a’, 4.38925, “a”, “main”
8. Out of the following literals, determine their type whether decimal / octal /
hexadecimal integer literal or a floating point literal in fractional or exponent
form or string literal or other ?
123, 0ol24, OxABC, ‘abc’, “ABC”, 12.34, 0.3E-01, ‘”ftghjkjl”‘, None, True, False
9. Name some built-in literals of Python.
10. What are the two Boolean literals in Python?
11. Write the following real constants into fractional form :
0.13E04, 0.417E-04, 0.4E-5, .12E02, 12.E02
12. Write the following real constants into exponent form :
23.197, 7.214, 0.00005, 0.319
Page 11 of 12
13. What is meant by a floating-point literal in Python? How many ways can a
floating literal be represented into?
14. What are string-literals in Python? How many ways, can you create String
literals in Python? Are there any differences in them?
15. Which escape sequences represent the newline character and backspace
character? An escape sequence represents how many characters?
16. Why are characters \ , ” and tab typed using escape sequences ?

Page 12 of 12

You might also like