Class XI -Python Basics
Class XI -Python Basics
1
• Python is free – is open source distributable software.
• Python is easy to read and learn – has a simple English language syntax and is uncluttered by punctuation.
• Python has extensive libraries – provides a large standard libraries for easy integration into your own
programs. The presence of libraries also makes sure that you don’t need to write all the code yourself and
can import the same from those that already exist in the libraries.
• Python is interactive – has a terminal for debugging and testing snippets of code (You can actually sit at a
Python prompt and interact with the interpreter directly to write your programs).
• Python is portable – runs on a wide variety of hardware platforms (Mac/Linux/Windows)and has the
same interface on all platforms.
• Python is interpreted – If you’re familiar with any languages like C++ or Java, you must first compile it, and
then run it. But in Python, there is no need to compile it. Internally, its source code is converted into an
immediate form called bytecode. So, all you need to do is to run your Python code without worrying about
linking to libraries, and a few other things.
3
If Python is installed in your system, then you can start at command line or
IDLE (It is a graphical integrated development environment for Python).
Click Start.
Click All Programs >> Python 3.7 >> Python 3.7 (64-bit)
You will see that the Python (command line) window appears with the Python >>> primary prompt
as shown below:
4
To start Python at shell prompt:
• Click Start >> All Programs >> Python 3.7 >> IDLE (Python 3.7 32-bit)
• Double click on the desktop
When you start the Python GUI program, you will see the Python Shell window containing
the Python >>> primary prompt.
5
There are two modes to use the python interpreter:
i. Interactive Mode
ii. Script Mode
i. Interactive Mode: Without passing python script file to the interpreter, directly
execute code to Python (Command line).
Example:
>>>6+3
output: 9
Note: >>> is a prompt , which python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.
6
Script Mode: In this mode source code is stored in a file with the .py extension and use the
interpreter to execute the contents of the file. To execute the script by the interpreter, you
have to tell the interpreter the name of the file.
Example:
To run the script you have to follow the steps given below:
Step-1: In Python Shell window, click File >> New File or click Ctrl+N.
Note. If you already have a program file with .py extension, click File >> Open Or click
Ctrl+O to open .py file.
Notice that an Untitled window appears as shown below:
Click here to create a program in new window
7
Step-2: Click File >> Save or Press Ctrl + S. Like other windows applications, in Save As
window, select a folder, type the name of the file (Hello) and click Save button. You
will notice that the named file is saves as .py extension.
To run Python program:
Step-3: Click Run >> Run Module command or Click F5 key.
If the code is written correctly, you will see the output in the Python Shell window with
following output:
8
Python Character Sets & Tokens
Letters: Both lowercase (a, b, c, d, ...., etc.) and uppercase (A, B, C, D, ...., etc..) letters
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
9
Python Tokens
Python Tokens
Delimiters
Keywords: Reserved words in the library of a language. All the keywords are in lowercase
except 03 keywords (True, False, None).
Ex: and, as, break, class, continue, def, elif etc
Identifiers: The name given by the user to the entities like variable name, class-name,
function-name etc.
Ex: roll_no, salary, name, sep98_score
10
Literals: Literals are the constant value. Literals can be defined as a data that is given in
a variable or constant.
11
Operators: An operator performs the operation on operands. Basically there are two
types of operators in python according to number of operands.
• Unary Operator: Performs the operation on one operand.
Example:
x=+2
y=-x
12
Variables
Variable is a container in which a data value can be stored within the computer’s memory.
The stored value can then be referenced using the variable’s name. The programmer can
choose any name for a variable, except the python keywords.
Variable = Value/Expression
L-Value Assignment R-Value
Operator
• Variable is an identifier.
• Value/Expression is an expression with a value or some calculation, function, etc.
• Variable refers to an L-value because it resides in memory and it is addressable
and Value/Expression is an R-value i.e., a value that is not L-value.
In concept, R-value correspond to temporary objects returned from functions, while L-values
correspond to objects you can refer to, either by name or by following a L-value reference.
Python first evaluates the RHS expression and then assigns to LHS.
13
Examples:
>>> Num1 = 10 # Assigns an integer value
>>> Num2 = 20 # Assigns an integer value
>>> sumN = Num1 + Num2 # An expression
>>> PiValue = 3.14 # A floating-point value
>>> MyName = "XYZ" # A string
Python is Dynamic – Python variables adjust the memory allocation to suit the various
data values assigned to their variables (dynamic).
Initialize variables with integer values. Assign a string value to the variable.
A, B = 10, 20 Message = 'Python in middle schools.'
C=A+B
Assign a float value to the variable. Assign a Boolean value to the variable.
PiValue = 4.13 Flag = True
14
Variable Declaration Rules
Some basic rules to declare variables in Python:
• Variable names can be as short as a single letter either in uppercase or
lowercase.
• Variable names must begin with a letter or an underscore ('_').
• After the first letter or underscore, they can contain letters, numbers, and additional
underscores. For example totalCost, y2014, _sysVal, _my_name, _my_name, etc.
• Variable names are case-sensitive. For example, myname and myName are not the same
names, they are two different variables.
• Variable names should not be reserved words or keywords. That is, variables cannot have the
same name as a Python command or a library function. For example, while, if, etc. cannot be
declared as variable name.
• No blank spaces are allowed between variable name. Also, it cannot use any special
characters (such as @, $, %, etc. ) other than underscore ('_').
• Variables or identifiers can be of unlimited length. 15
Valid Variable Names
roll_no, Salary ,sep98_score, index_age, percentageamount, dob, Cust_no, D_o_j, _my_name
>>> while
SyntaxError: invalid syntax because variable is a reserve word
>>> myname@
SyntaxError: invalid syntax because variable contains a special character
>>> 98Sep_score
SyntaxError: invalid syntax because variable start with a digit
16
Way to Assign Value to Variable
There are different ways to assign value to a variable.
x –351.0
17
A variable can be assigned many times. It always retains the value of the most
recent assignment.
7 0 10
Example:
>>> Var1 = 7
>>> Var1 # Returns: 7
>>> Var1 = 0 # Returns: 0
>>> Var1
>>> Var1 = Var1 + 10
>>> Var1 # Returns: 10
18
Assigning a value to multiple variables: In Python, we can assign a value to multiple variables.
Example:
>>> a = b = c = d = 5
>>> print (a, b, c, d) # Returns: 5, 5, 5, 5
Here, all the variables a, b, c and d are assigned a single value called 5.
Multiple assignments in a single line. You can even assign values to multiple variables in a single line.
While assigning, the left and the right side must have the same number of elements. The general
format is:
<var1>, <var2>, <var3>, …. <varN> = <expr1>, <expr2>, <expr3>, ….<exprN>
This is called simultaneous assignment. Semantically, this tells Python to evaluate all the
expressions on the right-hand side and then assign these values to the corresponding
variables named on the left-hand side. If the variables in left-
hand side differs with
Example: the values with right-
hand side and vice-
versa, then an exception
will raised and the
program will stop.
19
Example:
p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-1
print (p,q,r)
Note: Expressions separated with commas are evaluated from left to right and assigned in
same order.
>>> a,b,a=1,2,3
>>> print(a,b)
?
>>> a,b,c=b+1,a+1,b+1
>>> print(a,b,c)
?
20
Basic terms of a Python Programs
Blocks and Indentation: Python provides no braces to indicate blocks of code for class and
function definition or flow control.
Maximum line length should be maximum 79 characters. Blocks of code are denoted by
line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount.
for example – if True:
print(“True”)
else:
print(“False”)
Statements : A line which has the instructions or expressions.
Expressions: A legal combination of symbols and values that produce a result. Generally it
produces a value.
Comments: Comments are not executed. Comments explain a program and make a
program understandable and readable. All characters after the # and up to the end of the
line are part of the comment and the Python interpreter ignores them.
# This is a new line comment.
21
Comments in Python
Comments in Python
Writing a comment as a new line:
Example:
>>> # This is a new line comment.
Here, Python ignores everything after the hash mark and up to the end of
the line.
22
There are two types of comments in python:
• Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values
The first way is simply by pressing the return key after each line, adding a new hash
mark and continuing your comment from there:
# This is a pretty good example
# of how you can spread comments
# over multiple lines in Python
Each line that starts with a hash mark will be ignored by the program.
Second way is use multiline strings by wrapping your comment inside a set of triple
quotes:
23
Second way is use multiline strings by wrapping your comment inside a set of triple
quotes:
"""
If I really hate pressing `enter` and
typing all those hash marks, I could
just do this instead
"""
While this gives you the multiline functionality, this isn’t technically a comment. It’s a
string that’s not assigned to any variable, so it’s not called or referenced by your
program. Still, since it’ll be ignored at runtime and won’t appear in the bytecode, it can
effectively act as a comment.
Comments
Expression Statements
Indentation
24
Multiple Statements on a Single Line: The semicolon ( ; ) allows multiple statements
on the single line given that neither statement starts a new code block.
Example:
x=5; print(“Value =” x)
25
Data Types in Python
Every value in Python has a data type and everything in Python is an object.
Python provides various standard data types that define the storage method on each of
them.
26
Number Data Type: Number data type stores Numerical Values. This data type is immutable
i.e. value of its object cannot be changed.
1. int: A Python object of type int an integer, that is, a signed whole number (i.e., signed
integer, 32 bits long). The range is at least –2,147,483,648 to 2,147,483,647 (approximately
±2 billion).
Example:
>>> Num1, Num2 = 1, 10
>>> type(Num1)
<class 'int'>
Notice that the object name of Num1 is defined as <class ‘int’>, i.e., the class type is int.
The type() function tells the data type of the object Num1.
• Boolean: Boolean Type which is a unique data type, consisting of two constants, True
& False. A Boolean True value is Non-Zero, Non-Null and Non-empty.
Example:
>>> flag = True
>>> type(flag)
<class 'bool'>
27
2. Float: A float is a format for representing numbers with fractional parts is called
floating point or real numbers . In a floating point number, the decimal point must
preceded or followed by one or more digits.
Example:
>>> pi = 3.14
>>> type(pi)
<class 'float'>
Notice that the object name of pi is defined as <class ‘float’>, i.e., the class type is float.
If the exponent present consists of either "e" or "E" indicating the power of 10.
Example:
>>> aFloatValue = 3.5e2 It is just equal to 3.5 x 10 x 10
>>> print(aFloatValue) 350.0
3. 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 x; we will use
x.real and x.imag. Imaginary part of the number is represented by “j” instead of “i”,
so 1+0j denotes zero imaginary part.
Example:
>>> x = 1+0j >>> y = 9-5j
>>> print(x.real,x.imag) >>> print(y.real, y.imag)
1.0 0.0 9.0 -5.0 28
None :
This is special data type with single value. It is used to signify the absence of value/false in a
situation. It is represented by None.
Example:
>>> a=None
>>> print(a)
Sequence Data Type: A sequence is an ordered collection of items, indexed by positive
integers. It is combination of mutable and non mutable data types. Three types of
sequence data type available in Python are Strings, Lists & Tuples.
29
2. Lists: List is also a sequence of values of any type. Values in the list are called
elements / items. These are mutable and indexed/ordered. List is enclosed in square
brackets.
Example
l = [“sam”, 20.5,5]
3. Tuples: Tuples are a sequence of values of any type, and are indexed by integers.
They are immutable. Tuples are enclosed in ().
Example
t= (4, 2)
Sets: Set is an unordered collection of values, of any type, with no duplicate entry. Sets
are immutable.
Example
s = set ([1,2,34])
30
Dictionaries: Can store any number of python objects. What they store is a key – value
pairs, which are accessed using key. Dictionary is enclosed in curly brackets.
Example :
d = {1:'a',2:'b',3:'c'}
31
>>> x=x+y
In the statement, expression on RHS will result into value 10 and when this is assigned
to LHS (x), x will rebuild to 10. So now
x 10 and y 5
Identity of the object: It is the object's address in memory and does not change once it
has been created. Id() function is used to display the memory address.
(We would be referring to objects as variable for now)
32
Printing Data:
print() function is the standard function used to print the output to the console. The general
form of print is
print()
print (value/expr)
print(value, ...., sep=' ', end='\n’)
1. print(): Output displayed by the print() function will, by default, add an invisible \n newline
character at the end of the line to automatically move the print head to the next line.
Example:
>>> print () # Print a blank line
The sep parameter is a separator used in between the values. It defaults into a space
character.
Example:
>>> print(10,20,30,40, sep=' * ‘) # Prints a space and separator *
o/p:
10 * 20 * 30 * 40
The end parameter is used to print the last printed character(s). It defaults into a new line.
Example:
>>> # A new end is assigned @
>>> print(10,20,30,40, sep=' * ', end='@’)
o/p:
10 * 20 * 30 * 40@
34
Escape Characters (Non-printing characters):
In Python the backslash "\" is a special character, also called the "escape" character. It is
used in representing certain whitespace characters:
"\t" is a tab
"\n" is a newline
An escape character gets interpreted in a single quoted as well as double quoted strings.
Example:
35
User Input: Just as we assign value to a variable in Python, a user can assign value
to a variable using input() function.
The main purpose of this function is:
• Read input from the standard input (the keyboard, by default).
• By default you can input only the string values not numbers.
The general format is:
input([prompt])
• The prompt is an optional parameter which is a string you wish to display on the
screen.
• The prompt is an expression that serves to prompt the user for input. This is
almost always a string literal which is enclosed within quotes (single or double)
with parentheses.
Example:
# input() function
rollno = input("Enter your roll no. ")
perc = input("Enter your percentage: ")
print ("My roll no. is:", rollno)
print ("My percentage is:", perc)
36
Python Type Conversion and Type Casting
Type Conversion
The process of converting a value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another data
type. This process does not need any user involvement.
Example1:
37
Note:
• We add two variables Num1 and Num2, storing the value in Result.
• In the output, we can see the data type of Num1 is an integer while the data type of
Num2 is a float.
• Also, we can see the Result has a float data type because Python always converts smaller
data types to larger data types to avoid the loss of data.
Example2:
38
Note:
• We add two variables Num1 and Num2, storing the value in Result.
• In the output, we can see the data type of Num1 is an integer while the data type of
Num2 is a string.
• As we can see from the output, we got TypeError. Python is not able to use Implicit
Conversion in such conditions.
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the predefined functions like int(), float(), str(), etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts (changes) the data
type of the objects.
Syntax :
<required_datatype>(expression)
Typecasting can be done by assigning the required data type function to the expression.
39
Note:
• We add two variables Num1 and Num2.
• We converted Num2 from string(higher) to integer(lower) type using int() function to
perform the addition.
• After converting Num2 to an integer value, Python is able to add these two variables
Points to Remember:
• Type Conversion is the conversion of object from one data type to another data type.
• Implicit Type Conversion is automatically performed by the Python interpreter.
• Python avoids the loss of data in Implicit Type Conversion.
• Explicit Type Conversion is also called Type Casting, the data types of objects are converted
using predefined functions by the user.
• In Type Casting, loss of data may occur as we enforce the object to a specific data type. 40
• int() - constructs an integer number from an integer literal, a float literal (by rounding
down to the previous whole number), or a string literal (providing the string represents a
whole number)
Example: x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
• float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
Example: x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
• str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
Example: x = str("s1") # x will be 's1’
y = str(2) # y will be '2’
z = str(3.0) # z will be '3.0'
41
Python Operators
In Python, operators are the special symbols which carry out arithmetic and logical operations.
The value that the operator operates on is called operand.
42
Arithmetic operators - Used to perform mathematical operations like addition, subtraction,
multiplication, etc.
43
Relational Operators – They are also known as Comparison operators which are used to
compare values. It returns either True or False according to the condition.
44
Assignment operators - Used in Python to assign values to variables.
45
Logical operators
46
Special operators -
Identity operators :
is and is not are the identity operators in Python. They are used to check if two values (or
variables) are located on the same part of the memory. Two variables that are equal does
not imply that they are identical.
47
Operator Description Example
in Evaluates to true if it finds a variable
x in y, here in results in a 1 if x is a
in the specified sequence and false
member of sequence y.
otherwise.
not in Evaluates to true if it does not finds x not in y, here not in results in a 1 if x is
a variable in the specified sequence not a member of sequence y.
and false otherwise.
48
Operator precedence rule in Python
Operators Meaning
() Parenthesis
** Exponent
+, - Addition, Subtraction
==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators
49
Associativity of Python Operators
From the above table we notice that more than one operator exists in the same group.
These operators have the same precedence.
Associativity is the order in which an expression is evaluated that has multiple operator of
the same precedence. Almost all the operators have left-to-right associativity.
For example, multiplication and floor division have the same precedence. Hence, if both of
them are present in an expression, left one is evaluates first.
Example 1: Example 2:
50
Non associative operators
Some operators like assignment operators and comparison operators do not have
associativity in Python. There are separate rules for sequences of this kind of operator
and cannot be expressed as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to x
< y and y < z, and is evaluates from left-to-right.
51