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

Python Fundamentals

The document discusses the basic elements of a Python program including Python character set, tokens, literals, operators, and escape sequences. It provides examples and descriptions of keywords, identifiers, numeric, boolean and string literals, and different types of operators used in Python.

Uploaded by

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

Python Fundamentals

The document discusses the basic elements of a Python program including Python character set, tokens, literals, operators, and escape sequences. It provides examples and descriptions of keywords, identifiers, numeric, boolean and string literals, and different types of operators used in Python.

Uploaded by

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

Class 11

Python Fundamentals
For Computer Science and Informatics Practices students’

Hopefully, all of you go through the previous uploaded materials. In this material we shall be talking about all basic
elements that a Python program can contain.

PYTHON CHARCTER SET


Character set is a set of valid characters that a language can recognize. A character represent any letter, digit or any
other symbol. Python supports Unicode encoding standard. That means Python has the following character set:

Letters :- A – Z, a – z
Digits :- 0–9
Special symbols:- All special symbols available over keyboard
Whitespaces :- Blank space, tabs, carriage return, new line, form feed
Other Characters:- All ASCII and Unicode characters

TOKENS
The smallest individual unit in a program is known as Token or a lexical unit.
Python has following tokens:
(i) Keywords (ii) Identifiers (iii) Literals (iv) Operators (v) Punctuators/Delimiters

Keywords:-
A keyword is a word having special meaning reserved by programming language.
These words are reserved for special purposes and must not be used as normal identifier names.
Python programming language contains the following keywords:

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

Identifiers:-
Identifiers are the names given to different parts of the program like variables, objects, classes, functions, lists,
dictionaries etc.
Identifier forming rules of Python are specified below:
 An identifier is an arbitrarily long sequence of letters and digits.
 The first character must be a letter or underscore ( _ ).
 Upper and lower case letters are different as Python is a case sensitive language.
 An identifier must not be a keyword
 An identifier cannot contain any special character except underscore ( _ )
Examples of some valid identifiers:

Myfile myfile Date_9_5_19 m2var1 _Ds File123

Examples of some invalid identifiers:

My-data contains special charcter


29var Starting with a digit
break reserved keyword
my file contains special charcter

Literals:-
Literals (often referred to as constant values) are data items that have a fixed value.
Python allows different kind of literals:
(i) String literals (ii) Numeric literals (iii) Boolean literals (iv) Special literal- None
(v) Literal collections

String Literals:-
The text enclosed in single or double quotes (sometimes triple quotes also) forms a string literal in Python.
Example:
‘Ram’ “Rahim” “12345” ‘123-456’ ‘11FB22D’

Python allows:
(i) Single line strings – created by enclosing text in single quotes or double quotes and must terminate in one line.
Example:- ‘ram’ “ram”
(ii) Multiline strings – text spread across multiple lines.
Multiline strings can be created in two ways:
(a) by adding a backslash ( \ ) at the end of the first line:-
Example:- ‘ram\
kumar’
OR
“ram\
kumar”
(Note:- backslash ( \ ) is must at the end of first line. it considered the text as continuous.)
(b) by typing a text in triple quotation marks:-
Example: ‘‘‘ how
are
you’’’
OR

“ “ “ how
are
you” ” ”

Escape Sequences in Python:-

Python allows you to have certain nongraphic characters in string values. Nongraphic characters are those characters
that cannot be typed directly from keyboard like backspace, tabs, carriage return etc. (No characters is typed when
these keys are pressed, only some action takes place). These nongraphic characters can be represented by using
escape sequences.
Escape sequences represents a single character with a special meaning and have special purpose. An escape
sequence is represented by a backslash ( \ ) followed by one or more characters. It consumes one byte in
ASCII representation.
Escape sequences in Python:-

Escape Sequence Description


\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n New line characater
\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

Example:-

If we write the following in Python:

The output will be:

(Explanation: on the above statement we used ‘\n’, ‘\n’ is an escape sequence used for creating a new line)

Similarly, if we write following in Python:

Then the output will be:

(Explanation: on the above statement we used ‘\n’ for creating a line and ‘\t’ for tab; Both are escape
sequences in Python)
Numeric Literals:-
Examples of different numerical types are:-
Examples of integer type literals- (whole numbers without any fractional part):-
25 1234 -31 +97 etc.
Examples of floating point literals –
(i) Fractional form:-
Examples:- 17.5 -23.25 .25 23.0
(ii) Exponent form:-
Examples:- 152E+8 -0.172E-3
(Note :- ‘E’ indicate the exponent part and it cannot be fractional form)

Examples of complex number literals:- (consists of real part and imaginary part(j or J))
Examples:- 3+4j 3+6J

Boolean Literals:-
A Boolean literal can have any of the two values: True or False.

Special Literal – None:-


Python contains one special literal i.e., None.

None is used to specify to that field that is not contains any value.

Eg:

Literal collections:-
Collections such as Tuples, Lists and Dictionary are used in Python. These are used to store collection of values in
Python. (There are separate chapters on Lists, Tuples and Dictionaries in your syllabus….so those collections will
discuss later)

Operators:-
Operators can be defined as symbols that are used to perform operations on operands.
Example:
Types of Operators in Python:-

1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Arithmetic operators:-
We discuss the following operators based on two variables; variable a = 10 and variable b = 20

Operator Description Example


Addition - Adds values on either side of
+ a + b = 30
the operator.
Subtraction - Subtracts right hand operand
- a – b = -10
from left hand operand.
Multiplication - Multiplies values on
* a * b = 200
either side of the operator
Division - Divides left hand operand by
/ b/a=2
right hand operand
Modulus - Divides left hand operand by
% b%a=0
right hand operand and returns remainder
Exponent - Performs exponential (power)
** a**b =10 to the power 20
calculation on operators
Floor Division - The division of operands
where the result is the quotient in which
the digits after the decimal point are
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4,
// removed. But if one of the operands is
-11.0//3 = -4.0
negative, the result is floored, i.e.,
rounded away from zero (towards
negative infinity) −

Relational / Comparison Operators:-


We discuss the following operators based on two variables; variable a = 10 and variable b = 20

Operator Description Example


Equal to - If the values of two operands are
== (a == b) is not true.
equal, then the condition becomes true.
Not equal - If values of two operands are not
!= (a != b) is true.
equal, then condition becomes true.
Not equal - If values of two operands are not
<> (a <> b) is true. This is similar to != operator.
equal, then condition becomes true.
> Greater than - If the value of left operand is (a > b) is not true.
greater than the value of right operand, then
condition becomes true.
Less Than - If the value of left operand is less
< than the value of right operand, then condition (a < b) is true.
becomes true.
Greater or equal - If the value of left operand is
>= greater than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
Less or equal - If the value of left operand is
<= less than or equal to the value of right operand, (a <= b) is true.
then condition becomes true.

Assignment operators:-

Operator Description Example


Assignment - Assigns values from right side
= c = a + b assigns value of a + b into c
operands to left side operand
Add and assign - It adds right operand to the
+= left operand and assign the result to left c += a is equivalent to c = c + a
operand
Subtract and assign - It subtracts right operand
-= from the left operand and assign the result to c -= a is equivalent to c = c - a
left operand
Multiply and assign - It multiplies right
*= operand with the left operand and assign the c *= a is equivalent to c = c * a
result to left operand
Divide and assign - It divides left operand with
/= the right operand and assign the result to left c /= a is equivalent to c = c / a
operand
Modulus and assign - It takes modulus using
%= two operands and assign the result to left c %= a is equivalent to c = c % a
operand
Exponent and assign - Performs exponential
**= (power) calculation on operators and assign c **= a is equivalent to c = c ** a
value to the left operand
Floor division and assign - It performs floor
//= division on operators and assign value to the c //= a is equivalent to c = c // a
left operand
Logical operators:-

and - logical AND


or - logical OR
not - logical NOT

Bitwise operators:-

& - bitwise AND


| (pipe symbol) - bitwise OR
^ - bitwise XOR
~ - bitwise complement
Membership operators:-

in - whether variable present in sequence


not in - whether variable not present in sequence

Identity operators:-
is - returns True if two variables points the same object, otherwise False
is not - returns True if two variables points different objects, otherwise False

(The detail discussions on different operators with examples is in ‘Data Handling’ topic as per your
syllabus……so, I will discuss these details with examples in the material of ‘Data Handling’ in Python(next
material).)

Punctuators / Delimiters:-

Punctuators are symbols that are used in programming languages to organize programming-sentence structures, and
indicate the rhythm and emphasis of expressions, statements and program structure.

Most common punctuators of python programming language are:-

‘ “ # \ ( ) [ ] { } @ , . : ` =
BAREBONES OF A PYTHON PROGRAM:-
The following program code is used to illustrate the basic structure of a Python program.

(Don’t worry if the following things are not clear to you at that moment………….They’ll become clear when
we discuss further about these elements later on…..)

As you can see that the above sample program contains various components like:
expressions, statements, comments, function blocks and indentation

(i) Expressions:-
An expression is any legal combination of symbols that represents a value.
Examples:
15
2.8
a+5
3+4/2
a>5 etc.
(ii) Statements:-
Instruction that does something.
Examples:
a = 20
print(“hello”) etc.

(iii) Comments:-
which is readable for programmer but ignored by python interpreter means that statement will not execute.
i. Single line comment: Which begins with # sign.
ii. Multi line comment : either write multiple line beginning with # sign or use triple quoted multiple line.
E.g.
# this is single line comment

‘‘‘ this
is
multiline comment’’’
(iv) Functions:-
a set of instructions that has some name and it can be reused.e.g. mymessage( ) in above program.
(The details of Functions will be discuss later on……)

(v) Blocks and Indentation:-


Group of statements is formed a block is also called a suite in Python.
Python creates indentation to create blocks of code. Statements at same indentation level are part of same
block / suite.

Variables and Assignments:-


Variable is a name given to a memory location. A variable can consider as a container which holds value. Python is a
type infer language that means you don't need to specify the datatype of variable.Python automatically get variable
datatype depending upon the value assigned to the variable.

Creating a variable:-

x = 50

here 50 is assigned to a numeric variable x.

Assigning Values To Variable:-

name = ‘python' # String Data Type


m = 50 # integer type variable
p = 12.5 # floating type variable
s = None # a variable without any value

s=a+b # s is assigned with summation value of a and b


Lvalues and Rvalues:-
Lvalues are the objects to which you can assign a value. Lvalues come on LHS of an assignment statement.
Rvalues are the objects that are assigned to Lvalues. Rvalues can come on RHS of an assignment statement.

Example:-

a = 50
b = 10

but if you write:


50 = a Generates ERROR
10 = b

Multiple assignments:-

Python allows different way of assigning values to a variable.


(i) Assign same value to multiple variables:-

a = b = c = 10
It will assign value 10 to all three variables a, b, c

(ii) Assigning multiple values to multiple variables:-

x, y, z = 20, 50, 5
It will assign the values order wise i.e. first variable is given the first value, second variable is given second values
and so on……….So, x becomes 10, y becomes 50 and z becomes 5

Try to solve:-

1. What is the difference between a keyword and an identifier?


2. How many types of strings are supported in Python?
3. How can you write multi-line strings in Python?
4. What is None literal indicates in Python?
5. Is the following program executed successfully? If not, why?
print(“My name is “, name)
6. What will be the output of the following code?
x, y = 2, 6
x, y = x, x+2
print(x)
print(y)
Look at the following and try to understand:
7. What will be the sizes of following constants?

‘\a’ - size is 1 as there is 1 character (escape sequence)

“Reema\’s” - size is 7 (as \’ is an escape sequence character)

“it’s” - size is 4

“““Ram
Roy””” - size is 7. it is triple quoted multi-line string. So End Of Line(EOL) character (  ) is present
just after the first line.( as you pressed Enter key after 1st line)

“Ram\
Roy” - size is 6. It is a multi-line string created with \ symbol.

Program Tasks:-
1. Write a program to calculate the addition, subtraction, multiplication and division of two user given numbers.
2. Write a program that accepts the marks of 5 different subjects from the user then calculate and display Total marks
and percentage.
3. Write a program to ask for your height in centimeters and then converts your height to feet and inches.
(hints: 1 foot = 12 inches and 1 inch = 2.54 cm)
4. Write a program to ask the price of an item and the discount rate from the user then calculate the net amount.
5. Write a program that accept the Number of sixes, number of Fours and number of Singles of a player then
calculate his total runs.
6. Write a program which accepts two numbers from the user and store it in two variables then interchange (swap)
the values of two variables.
(Hints: let, x = 15 and y = 37 then after interchanging your program display x = 37 and y = 15

Try to solve all the tasks above.


If any problem then message me in my personal whatsapp no. 8145472773

You might also like