Chapter 1 :- Python Revision Tour - 1
Python Introduction......
- Python is a general purpose interpreted, interactive, object oriented and high level programming language.
- It was initially designed by Guido Van Rossum.
- The first version of Python 0.9.0 was released in 1991.
- Python has a simple syntax similar to the English language.
- Python can be easily installed on Windows, macOS, and various Linux distributions, allowing developers to create software that runs across different operating systems.
- Python comes with several standard libraries that provide ready-to-use modules and functions for various tasks, ranging from web development and data manipulation to machine learning and networking.
- Python is an open-source, cost-free programming language. It is utilized in several sectors and disciplines as a result.
PYTHON CHARACTER SET
Character set is a set of valid characters that represents any digit, alphabet and special symbol. The character used in a Python source program belongs to unicode standard.
Python supports the following character sets
- Alphabets – A to Z (uppercase), a to z (lowercase)
- Digits – 0 to 9
- Special Characters :: etc. Space()+-*/\^&%#${}[]!_(underscore) ><?@.
- White Space Blank space, Horizontal tab (→), Carriage return (1), Newline, formfeed
- Other Characters Python can process any of the ASCII and unicode characters as data or as literals
PYTHON TOKENS
A smallest individual unit in a program is known as token or lexical unit or lexical element.
The Python has following tokens:
(i) identifiers
(ii) keywords
(iii) literals
(iv) operators
(v) punctuators
The programmer can write a Python program by using these tokens.
1. Identifiers
Identifiers are names used to identify a variable, function, or other entities in a program.
The rules for naming an identifier in Python are as follows
- The name should begin with an uppercase or a lowercase alphabet or an underscore sign(). This may be followed by any combination of characters a-z, A-Z, 0-9 or underscore). Thus, an identifier cannot start with a digit.
- It can be of any length.
- It should not be a keyword or reserved word.
- We cannot use special symbols like!. @, #, $, %, etc. in identifiers.
2. Keywords
Keywords are predefined reserved words that have some special or predefined meanings. These are reserved for special purpose and must not be used as identifier names. Some commonly used keywords in Python, which are listed below.
3. Constants or Literals
Literals refer to fixed values that the program may not alter (change) during the program execution.
Python allows several types of literals as follows
- Numeric literals
- String literals
- Boolean literals
- Special literal None
- Literal collections
Numeric Literals
A numeric literal is a character string whose characters are selected from the digits 0-9, a sign character (+ or -) and the immutable decimal point.
Numeric literals (unchangeable). Numeric literals can belong to three different numerical types as Integer, Float and Complex.
e.g.
integer literals -100, 55, 18588
Floating Point Literals -19.0, 0.99, 5.E2
Complex Number Literals 2 + 5j
String Literals
The literal which is stored in a variable within single quotation mark :- ‘ ‘ or double quotation marks :- ” ” is called string literal.
These represent a sequence of zero or more characters enclosed by double quotes. It can also include blank spaces.
Some valid string constants are “Codemaniacstudio.com”
String literal can either be single line strings or multi-line strings.
Boolean Literals
A boolean literals is used to represent one of the two boolean values True and False.
True represents a true value and False represents a false value.
Literals True or False should not be represented by the quotation marks around it. Python interpreter will take it as a string of characters, if it is represented in quotation marks.
PYTHON OPERATOR
An operator is used to perform specific mathematical or logical operation on values. The values that the operators work on are called operands.
Python support two types of Operator
- Unary Operator
- Binary operator
Unary Operator :-
The operators that work on single operand to form an expression are known as unary operators.
These operators are
- + unary plus
- – unary minus
- ~ Bitwise complement
- not logical negation
Binary Operators
The operators that work upon two operands are known as binary operators.
There are various types of binary operators in Python as follows
(a) Arithmetic operators :-
These operators are used to do arithmetic operations. These operators are :-
(b) Logical operator : –
These operators are used to make a decision on two conditions. Logical operators are typically used with Boolean values and what they return is also a Boolean value.
(c) Relational operator : –
These operators are compare two operand to one another. These operators are
(d) Assignment operator :-
These operators are used to assign the value of an expression to a variable. These operator are
(e) Bitwise operator : –
These operators works on bits and perform bit by bit operation. These operators are
(f) Shift operator : –
These operators works on bits and perform bit by bit operation. These operators are
(g) Identify operator : –
These operators are
(h) Membership operator : –
These operators are
PYTHON Punctuators
Python Punctuators
A punctuator is a token that has syntactic and semantic – meaning to the compiler, but the exact significance depends on the context. Punctuators (separators) is used to separate line of codes, variables etc.
The following characters are used as punctuators in Python ‘”#\() []{}@, : . ‘ =
Some of them are discussed below
- Brackets [] indicate list.
- Parentheses () indicate tuples, function calls, function parameters for grouping expressions etc.
- Comma (,) can be used as a separator in a function argument list or variable declaration.
- Colon (:) indicates a labelled statement or conditional operator symbol.
- Equal sign (=) is used to initialize the value of variable i.e. used as assignment operator in an expression.
BASIC STRUCTURE OF PYTHON PROGRAM
1. Expressions
An expression is a combination of operators, constants and variables. Any part in a program which can have a value, is an expression. It will have operands and operators together to produce a value. From the above program, we have 4 expressions 50, 35, x – y + 10 z < 30
2. Statements
A statement in Python is a logical instruction which Python interpreter can read and execute. It could be an expression or assignment statement.
e.g. if x ==y print (“x is equal to y”) when expression will be evaluated, statement or group of statements executed.
From the above program, we have 5 statements as
x = 50
y = 35
z = x – y + 10
print (z – 5)
if z < 30
3. Comment :-
Comment are used to add a remark or a note in the source code that are ignored by the interpreter or complier and are not executed by the computer .
There are two type of comment
- Single line comment
- multi line comment
Single line comment are denoted by “#”
Multi line comment are denoted by “”” ABC”””.
4. Function :-
A function is a self contained block of statements which are kept together to perform a specific task in related manner.
We have one function add(). All the statement which are intended below by add().
5. Block and Indentation
Block and indentation indicate the relationship between various statement and thus allows us to get a better picture of the overall organisation and structure of the solution given in the program.
PYTHON dATATYPES
DATA TYPES
Data type is a term that is used to show the kind of data values or the type of data that is expected to be handled.
i.e. Data types are used to identify the type of data and associated operations to handle it.
There are different data types available in Python
1. Numeric
This data type stores only numeric value in Python. It is further classified into three different types:
- Integers :- Integers are the whole numbers having different storage range supported by particular machine. Integers have no fractional parts. They can be positive or negative.
e.g. 8, 17, -195 etc. - Floating Point Numbers :- The float data type in Python designates a floating point number. Float values are specified with a decimal point. The decimal point signals that it is a floating point number not an integer. e.g. 159.12, 734.30 etc.
- Complex Numbers :- A complex number is a number expressed in the form a+ib, where, a (real part) and b (imaginary part) are real numbers and i is the imaginary part. So, we can say that complex number is made up of both real numbers and imaginary numbers.
e.g. 2+3i, 1+ 4i, 2-5i etc.
2. Boolean
Boolean data type is a unique data type, consisting of two values – True and False.
3. Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
Three types of sequence data types are available in Python
- Strings :- Strings are group of characters. These characters may be alphabets, digit or special character including spaces. String values may be delimited using either single quotes or double quotes, such as “Rahul”, “ABC”, “??\+”, ‘$ABC’ etc.
A string in Python can contain as many characters as you want. The string limit is depend on your machine’s memory resources. A string can also be empty. In Python, the string type is called str. - Lists :- List is a sequence of items separated by commas and the items are enclosed in the square brackets []. Lists are mutable that means they can be change after creation. e.g.x-[1,2,3,’A’,’B’,’C’,55.55].
All lists in Python are zero based indexed. When referencing a member or the length of a list the number of list elements is always the number shown plus one. - Tuples :-
Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable and lists are mutable. Tuples once created cannot be modified. Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically. Tuples are defined by parentheses ().
eg sub(“Maths”, “English”, “Hindi”. “Computer”)
4. Sets
Set is an unordered collections of items separated by commas and the items are enclosed in curly brackets |). A set is similar to list, expected that it cannot have duplicated entries. One created, elements of a set cannot be changed.
e.g. >>> set (10, 20, 3.14. “Delhi”)
>>> print (type (setl))
<class ‘set’>
>>> print (setl)
110, 20, 3.14. “Delhi”)
>>> set2 11. 2. 1. 3)
>>>> print (set2)
11. 2. 31
5. Mapping
Mapping is an unordered data type in Python. In Python. there is only one standard mapping data type called dictionary.
- Dictionary :- Dictionaries in Python are lists of key: value pairs. Dictionaries are created by using braces | with pairs separated by a comma (,) and the key values associated with a colon (:).In dictionaries, the key must be unique. Dictionaries can also be used to sort, iterate and compare data.
e.g. dict{“Name: “Neha’, ‘Salary : 25000. “Post”: “Coordinator’}
6. None
- None is a special data type with a single value. It is used to signify the absence of value in a situation. None supports no special operations and it is neither False nor 0 (zero).
c.g. >>> myFav None
>>> print (type (myfav))
<class ‘NoneType”>
>>> print (myfav)
None
Python EXPRESSIONS
PYTHON EXPRESSIONS
An expression is a combination of operators, constants and variables. An expression may consist of one or more operands and zero or more operators to produce a value. A value or a standalone variable is also considered as an expression but a standalone operator is not an expression. There are various types of expressions as follows
- Arithmetic Expression :- These expressions are composed with operators, constants, variables etc. It can be either a pure integer expression, a floating point expression or complex numbers. e.g. ab – 5 (integer expression) x + y / 10 (floating expression) 1 + 2i (complex number expression)
- Logical Expression :- The expressions have logical operators are called logical expression. e.g. x and y.
- Relational Expression :- This type of expression includes relational operators. e.g. a = b a <= b . a 1 = b.
- String Expression :- This type of expression includes string operators with string operands and integers. e.g. >>>”Code”+ “Maniacstudio” Output :- ”CodeManiacstudio”.
Python Statement
- Statements
The process of converting a data type into another data type is known as type conversion.
Python has two types of type conversion as follows
1. Implicit Type Conversion
In implicit type conversion, Python automatically converts one data type to another data type. This process does not need user involvement. This conversion takes place during compilation or run time.
eg.
a=16
b-5.5
sum = a+b
print(sum)
print(type (sum))
Output
21.5
<class ‘float’>
2. Explicit Type Conversion
In explicit type conversion, user converts the data type of an object to required data type. This type conversion is also called typecasting because the user casts (change) the data type of the object.
PROGRAMMING TOOLS
There are many tools for programmers to solve the programming problems
- Pseudocode :- Pseudocode is a simple way of writing programming code in English. It is not actual programming language. It uses short phrases to write programs code before they are actually created in a specific language.
General rules used in writing pseudocodes are as follows
- Imperative sentence These sentences are used to show actions.
- Operators Mostly arithmetic operators (+,-,*,% etc) and relational operators (=, <, >=, <,> etc) are used.
- Decision IF, THEN, ELSE, ENDIF, CASE, END CASE are used for decision making.
- Looping The looping or repetition of statements is shown by FOR, FOR DO, END FOR, DO, DO WHILE, DO UNTIL, END DO etc.
e.g. Compute the perimeter of a rectangle. Enter length, 1 Enter width, w Compute perimeter 21+2*w Display perimeter of a rectangle
- Algorithm :-
It is a step by step process of solving a well-defined computational problem. “An algorithm is a set of instructions, sometimes called a procedure or a function that is used to perform a certain task”. e.g. Algorithm to input two numbers and print their sum and also check whether they are equal or not.
Step 1 Enter first number is A
Step 2 Enter second number is B
Step 3 C=A+B
Step 4 print C
Step 5 if (A==B) print “Numbers are equal” else print “Numbers are not equal”
Step 6 Stop
- Flowchart
A flowchart is a graphical representation of the steps taken to reach a certain result. It shows how information move from one part of a computer system to another and shov how one instruction in a program leads to another.
Python Control Structure
A control structure is a programming language construct which affects the flow of the execution of program.
Selection Statements
A selection statement is a control statement that allows statement choosing two or more execution paths in a program. These statements allow a program to execute a statement or a set of statements depending upon a given condition. These statements are also called conditional statements or decision statements.
Python provides three types of selectors are described below
1. if Statement
if statement is used to decide whether a certain statement or block of statements will be executed or not, i.e. if a certain condition is True, then a block of statement is executed otherwise not.
Syntax if(conditional expression): statement(s)
Flowchart
if statement
2. if-else Statement
This statement also tests a conditional expression. If the condition is True, the entire block of statements following the if will be executed.
Otherwise, the entire block of statements following the else will be executed.
Syntax if(conditional statement): statement(s)
else: statement(s)
Flowchart if-else statement
3. if-elif-else Statement
Sometimes, we need to execute different statement to perform in different conditions. It requires the evaluation of several conditions. First of all, the first condition is evaluated, if it is true then respective statements are processed. Otherwise, the next condition is evaluated to process another statements. This process is continued for several times.
Syntax
if (condition 1):
statement 1
elif(condition 2):
statement 2
else: statement 3
ог if(condition 1): statement 1
elif(condition 2): statement 2
Flowchart if-elif-else statement
4. nested if Statement
Nested means if statements or if-else statements are placed in the statement block of if statement or else statement.
Syntax
if(condition 1):
if(condition 2):
statement 1
else:
statement 2
else:
statement 3
e.g. if(a > b):
if(a > c):
result = a
else:
result = c
else:
if(b>c):
result = b
else:
result = c
Point to remembered
- A logical statement always evaluates True/False.
Any value in Python other than zero is considered to be True whereas a zero(0) is considered to be False.
(==) must be used for comparision in the expression of if condition, if you use (=) the expression will always return True, because it performs assignment not comparison.
Python range() Function
The range() function is used to generate a sequence of numbers overtime.
The range() function has two sets of parameters, as follows1. range (stop)
stop number of integers to generate, starting from zero. e.g. range (5) = [0,1, 2, 3, 4]2. range ([start,] stop [,step])
start starting number of the sequence.
stop generate numbers upto, but not including this number.
step difference between each number in the sequence.
Python Iterative Statements
Iteration is the repetition of a process in order to generate an outcome. Iterative statements or loops enable a program with a cyclic flow of logic. Each statement which is written under the scope of a looping statement gets executed the number of times the iteration/looping continues for. There are two basic types of looping statements available in Python, they are as follows.
- while() Loop
A while() loop tests for its ending condition before executing the statements enclosed in the loop body even the first time. Syntax while(loop-condition): statement(s)
A while continues iteration cycle till its loop condition is evaluated as true. If the loop-condition is false, then loop will not execute even once.
In while() loop, the looping condition is evaluated at the beginning of the loop’s scope, i.e. prior to entering into the scope of loop. This type of checking is called “Entry control checking”, if the condition fails this checking, then the entry into the scope of loop will not be allowed. So, while () loops are often called as Entry Control Loop.
The while() loop can accept expression and not just conditions, the following are all illegal expressions:
(i) while(x = x + 1)
(ii) while (n–)
(iii) while(count + =î)
When the result of x = x + 1, nor count += i, evaluates to 0, then the while condition fails and the loop will exit.
- for () Loop
The for statement encloses one or more statements that form the body of the loop, the statements in the loop repeat continuously a certain number of times.
This loop is also known as entry control loop, as condition is checked before entering into the scope of the loop.
Syntax
for(variable) in <sequence>: statement(s)
or range (start, stop, step): for(variable) in range. statement(s)
- nested Loop
When a loop may contain another loop in its body is called nested loop. Any conditional statement can be nested within any other conditional statement. In nested loop, two loops; inner loop and outer loop are executed. But the inner loop must terminate before the outer loop.
Syntax for<variable> in <sequence>: for<variable> in <sequence>: statements
e.g. for i in range (1,6,+2): for j in range (1.1,+1): print(i, “”, j)
- JUMP STATEMENTS
Jump statements allow altering the flow of a program by performing jumps to specific locations.
The jump statements defined in Python are break and continue.
- break Statement
The break statement alters the normal flow of execution as it terminates the current loop and resumes execution of the statement following that loop.
It can also be used to stop executing further statements inside the body of conditional statements. break statement used in a nested loop affects only the inner loop in which it is used and not any of the outer loops.
Syntax
break
- continue Statement
When a continue statement is encountered, the control skips the execution of remaining statements inside the body of the loop for the current iteration and jumps to the beginning of the loop for the next iteration. If the loop’s condition is still True, the loop is entered again, else the control is immediately following the loop. transferred to the staternent
Syntax
continue
In a while loop, the next iteration starts by re-evaluating the controlling expression of the while statement. In a for loop, the loop execution clause is executed.
e.g. for i in range (0.3):
print(“Before the continue”)
continue
print(“After the continue, should never print”)
print(“After the for loop”)