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

IP Notes Python Introduction

Python notes handwritten

Uploaded by

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

IP Notes Python Introduction

Python notes handwritten

Uploaded by

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

Program:

An ordered set of instructions to be executed by a computer to carry out a


specific task is called a program, and the language used to specify this set of
instructions to the computer is called a programming language.
Introduction to Python
Python language was developed by Guido Von Rossum in 1991. It is a high-level
object-oriented programming language.
Python Programming Language uses an interpreter to convert its
instructions into machine language, so that it can be understood by the
computer.
Note: Interpreter converts high level language to low level language line by line.
Features of Python
1. It is a high-level language.
2. Free and open source
3. Portable and platform independent.
4. It has a rich library of predefined functions.
5. It uses indentation for blocks and nested blocks.
Execution mode
There are two ways to use the Python Interpreter:
1. Interactive Mode
2. Script Mode
1. Interactive mode: In the interactive mode, we can simply type a Python
statement on the >>> prompt directly. As soon as we press enter, the interpreter
executes the statement and displays the result(s). This mode is convenient for
testing a single line code for instant execution. But in the interactive mode, we
cannot save the statements for future use and we have to retype the statements
to run them again.
for example:
>>>7+3
10
>>>a=8
>>>b=9
>>>a+b
17
2. Script mode: In the script mode, we can write a Python program in a file,
save it and then use the interpreter to execute it. Python files has an extension
".py". To execute the Python Program in script mode click Run-> Run Module
from menu or press F5 from the keyboard.
Steps to write a program in Script mode
1. Open Python IDLE
2. Click File->New or Ctrl + N
3. A new window open.
4. Type the commands/program and save your file.
5. Execute/Run the program by pressing F5.

Fundamentals of Python
Character Set: A character set is a collection of valid characters which is
recognized by the programming language. Python has the following character
set.
Letters : A-Z, a-z
Digits: 0-9
Special Symbols: >, <, <>, _, (), [], (), /, % etc.
Whitespaces: Blank space, Enter, Tab etc.
Tokens: The smallest individual unit of program is known as Token. Various
types of tokens are given below:
1. Keywords
2. Identifiers
3. Literals
a. Numeric Literals
b. String Literals
c. Boolean Literals
4. Punctuators
5. Operators
Keywords: Keywords are reserved words. Each keyword has a specific meaning
to the Python interpreter, and we can use a keyword in our program only for the
purpose for which it has been defined.
Identifiers: Identifiers are names used to identify a variable, function, or other
entities in a program. The naming conventions of identifiers in Python are as
follows
1. An identifier cannot start with a digit.
2. Keywords cannot be used as identifiers.
3. We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
(underscore can be used)
4. Identifiers cannot have spaces.
Examples of valid identifiers
a. num1
b. percentage
c. mark1
d. Stu_marks
Examples of invalid identifiers
a.1_ num (reason: Starting from digit)
b. marks@123 (reason: Using special character)
c. pass (reason: Keyword)
d. student age (reason: space)
Literals: Literals are the fixed value or constant value which we used in Python.
There are several kinds of literals in Python.
1. Numeric Literal: Numeric literals are the numbers that can be with or without
decimal. Numeric literals are of following types
a. Integer literal: These literals are the numbers/values which are without
decimal. It includes both positive and negative numbers along with 0. In other
words we can say that these literals are the whole numbers. for example 12, -3,
0
b. Floating Point Literals: These literals are the numbers/values with
decimal, for example 2.3, 3.9, -5.6, 6.0
2. String Literals: String literals are the values which are enclosed in quotes
(either single, double or tripple), for example: 'a', "anuj", '34", "S"
NOTE: Triple quotes are used to write multi line string.
3. Boolean Literals: Boolean literals have only two values ie True or False
Punctuators: These are the symbols used in Python to frame structure,
statement or expression.
Commonly used punctuators in Python are: [], {), (), +,-, //= ,== etc.
Operators: Operators are special symbols which are used to perform some
mathematical or logical operations on values.
Examples:
a = 12 #12 is integer literal and 'a' is identifier
b = 7.0 #7.0 is float literal and 'b' is identifier
c = "Numbers" #"Number" is string literal and 'c' is identifier
s = a+b #=and+are operators
print("Sum of two", c, "is", s) #print is keyword and double quotes("),
comma(,) are punctuators.
Variables: Variable in Python refers to an object an item or element that is
stored in the memory. Value of a variable can be a string (e.g., 'b', 'Global
Citizen'), numeric (e.g., 345) or any combination of alphanumeric characters.
for example
marks = 56
name = "Ananya"
Remark: Variable declaration is implicit in Python, means variables are
automatically declared and defined when they are assigned a value the first
time. Variables must always be assigned values before they are used in
expressions as otherwise it will lead to an error in the program.
Variables in Python are created when we assign values. for example,
>>> x #lt return error as we didn't assign any value
Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> X
NameError: name 'x' is not defined
>>> x=8
>>> x #It is not showing any error
8
 In python we can assign same value to different variables in one
statement, for example
p=q=r= 28
The above statement will assign value 28 to all the three variables.
>>>p
28
>>>q
28
>>>r
28
 We can also assign different values to different variables in a single
statement. For Example,
x, y, z = 1, 2, 3
>>>x
1
>>>y
2
>>>z
3
Remark: The values will be assigned in order
 Swapping of values
>>>a=9
>>>b=25
>>>a, b
(9, 25)
>>>a, b=b, a
>>>a, b
(25, 9)

Comments:
Comments are used to add a remark or a note in the source code.
Comments are not executed by the interpreter. They are added with the purpose
of making the source code easier for humans to understand. In Python, a
comment starts with # (hash sign). Multiline comment can be given in python by
enclosing it in triple quote ("') for example
#following program is to add two numbers
a=8
b=3
print("Sum = ", a+b)
'''Multi line comment in python can be given by enclosing it in triple quotes'''
id():
This function returns the identity (memory address) of an object which
remains the same for the lifetime of that object. for example:
num1 = 20
num2 = 20
print(id(num1))
print(id(num2))
OUTPUT:
8791510210176 #Your output can be different 8791510210176 #Both are
showing same address as both variables are storing same number ie 20
Dynamic Typing:
A variable referring to a value of any datatype say integer. In next line
same variable can be used to refer a value of another data type say String. This
process of shifting from one data type to another without giving any error is
called Dynamic Typing. for example
>>>a = 24
>>>a
24
>>>type(a)
<class 'int'>
>>>a = "Ilovemycountry" a

Ilovemycountry
>>>type(a)
<class 'str'>
NOTE: In Python, the values stored in variables decide its data type.
Data Types :
Data type identifies the type of data values a variable can hold and the
operations that can be performed on that data. Various data types in Python are
as follows:
1. Numbers
• Integer
• Boolean
• Floating Point
• Complex
2. Sequences
• Strings
• Lists
• Tuples
3. Mappings
• Dictionary
Number:-
This data type stores numerical values only. It is further classified into
three different types: int, float and complex.
DATA DESCRIPTION EXAMPLES
TYPE
int This data type stores integers. 4, -5, 23, -90
float This data type stores floating point -23.45, 40.26
numbers.
complex This data type stores complex numbers. 1+2j, 21+5j
Boolean data type (bool) is a sub type of integer. This data type stores two
values, True and False. Boolean True value is non-zero. Boolean False is the value
zero.
marks1 = 34
marks2 = 23.12
m1 = True
print(type(marks1))
print(type(marks2))
print(type(m1))
OUTPUT:
<class 'int'>
<class 'float'>
<class 'bool'>
NOTE: type() function determines the data type of the variable.
Variables of simple data types like integers, float, boolean, etc., hold single
values. But such variables are not useful to hold a long list of information, for
example, marks of all students in a class test, names of the months in a year,
names of students in a class. For this, Python provides data types like tuples,
lists, dictionaries and sets.
Sequence :
It is an ordered collection of items, where each item is indexed by an
integer. The three types of sequence data types available in Python are Strings,
Lists and Tuples.
1. String: String is a group of characters (like alphabets, digits or special
characters including spaces). Strings are enclosed in Single quotes (' ') or in
double (" "). for example:
st1 = "Anuj"
st2 = '2342'
NOTE: Numerical functions cannot be performed on String.
2. List: List is a sequence of items enclosed in square brackets [] and items are
separated by commas. for example:
L1 = [23, 'a', 4, 2.3, 'b'] #It is a list containing items of different data types.
L2 = ['a', 'b', 'c', 'd'] #It is a list containing items of same data types.
3. Tuple: Tuple is a sequence of items separated by commas and items are
enclosed in parenthesis ().
T1 = (1, 3, 56, 's', 5)
Difference between List and Tuple:
List Tuple
a. It is mutable a. It is immutable
b. Items are enclosed in [] b. Items are enclosed in ()

Mapping:
Mapping is an unordered data type in Python. Mapping data type in
Python is Dictionary.
Dictionary: Dictionary in Python holds data items in key-value pairs. Items in a
dictionary are enclosed in curly brackets {}. Every key is separated from its value
using a colon (:) sign.
The key: value pairs of a dictionary can be accessed using the key.
for example:

D1 = {"a": "Apple", "b": "Ball", "c": "Cat"} #"a","b", "c" are keys and "Apple",
"Ball", "Cat" are respective values
Mutable and Immutable Data Types
Variables whose values can be changed after they are created and
assigned are called mutable. Variables whose values cannot be changed after
they are created and assigned are called immutable. Python data types can be
classified into mutable and immutable as shown below:
Immutable data types are: Mutable data types are:
1. Integer 1. List
2. Float 2. Sets
3. Boolean 3. Dictionary
4. String
5. Tuple

Operators
Operators are special symbols which are used to perform some
mathematical or logical operations on values. The values on which the operators
work are called operands.
for example, in 34 + 31, here '+' is a mathematical addition operator and the
values 34 and 31 are operands.

Python supports various kinds of operators like


1. Arithmetic Operator:
Operato Operator Explanation Example
r Symbol Name
‘+’ Addition This operator help to add the >>> 5 + 9
two numeric values. 14
>>>12 + 8
This operator can also be used to
>>>’a’ + ‘b’
concatenate two strings on ab
either side of the operator >>>’C’ + ‘S’
CS
‘-‘ Subtraction This operator helps to find the >>>9 – 8
difference between two numbers 1
>>>130-31
99
‘*’ Multiplication This operator helps us to find the >>>7*4
product of two numeric values 28

‘/’ Division This operator helps us to divide >>>7/2


the two numeric values and 3.5
return the quotient with decimal. >>>8/2
4.0
‘%’ Mod This operator helps us to divide >>>8%2
the two numbers and return the 0
>>>40%6
remainder.
4
‘//’ Floor Division This operator divides the two >>>6//4
numbers and return quotient 1
>>>9//2
without decimal. It is also called
4
integer division.
‘**’ Exponent It performs exponential (power) >>>2**2
calculation on operands 4
>>>4**3
64
2. Relational Operators:
Relational Operators compares the values and return the Boolean value.
Operator Operator Explanation Examples
Symbol Name
> Greater than This operator returns True if >>>9 > 4
the number on the left side of True
operator is larger than number >>>20 > 100
False
on the right side
< Less than This operator returns True if >>>56 < 43
the number on the left side of False
>>> 34 < 50
operator is smaller than
True
number on the right side
>= Greater than If the value of the left-side >>> 20 >=7
equals to operand is greater than or True
equal to the value of the right- >>> 8>=10
False
side operand, then condition is >>> 4>=4
True, otherwise it is False True
<= Less than If the value of the left-side >>> 20 <=25
equals to operand is smaller than or True
>>> 8<=4
equal to the value of the right-
False
side operand, then condition is >>> 4<=4
True, otherwise it is False True
== Equal to This operator returns True, if >>> 4 == 4
both the operand are equal. True
>>> 5==6
False
!= Not equal to This operator returns True, if >>> 7!=9
both the operands are not True
>>>2!2
equal.
False

3. Assignment Operators:
Operator Explanation Examples
= Assigns value of right-side operand to left-side >>> x=7
operand. >>> x
7
+= X+=y is same as x = x+y >>> x = 20
>>> y = 10
>>> x+=y
30
-= X+=y is same as x = x-y >>> x = 20
>>> y = 10
>>> x-=y
10
*= X*=y is same as x = x*y >>> x = 20
>>> y = 10
>>> x*=y
200
/= X/=y is same as x = x/y >>> x = 20
>>> y = 10
>>> x/=y
2.0
//= X//=y is same as x = x//y >>> x = 20
>>> y = 10
>>> x//=y
2
**= X**=y is same as x = x**y >>> x=2
>>> y=3
>>> x**=y
8
*= X%=y is same as x = x%y >>> x = 22
>>> y = 10
>>> x%=y
2

4. Logical Operators:
There are three logical operators in Python. The logical operator evaluates
to either True or False
Operator Explanation Examples
and It returns True if all the conditions are >>> x = 7
True >>> y = 9
>>> x > 5 and y >
7
True
>>> x < 10 and y >
10
False
or It returns True if any one of the >>> x = 7
conditions are True >>> y = 4
>>> x > 5 and y >
7
True
>>> x > 10 and y >
7
False
not It negates the truth. It makes True to >>> x = 7
False and False to True >>> y = 4
>>> not(x>5 or
y>7)
False
5. Identity Operators:
Identity operators is used to determine whether two variables are
referring to the same object or not. There are two identity operators.
Operator Explanation Examples
is Evaluates True if the variables on either >>> n1 = 5
side of the operator point towards the >>> n2 = n1
>>> id(n1)
same memory location and False
1423451526
otherwise. >>> id(n2)
1423451526
>>> n1 is n2
True
Is not Evaluates False if the variables on either >>> n1 = 5
side of the operator point towards the >>> n2 = n1
>>> id(n1)
same memory location and False 1423451526
otherwise. >>> id(n2)
1423451526
>>> n1 is not n2
False
6. Membership operators:
Membership operators are used to check if a value is a member of the
given sequence (List, String, Tuple etc.) or not. There are two membership
operators in Python.
Operators Explanation Examples
In Returns True if the >>>'a' in 'amit'
variable/value is found in True
the specified sequence and >>>1 in [11, 22, 33, 44]
False
otherwise False
not in Returns False if the >>>'a' not in 'amit'
variable/value is found in False
the specified sequence and >>>1 not in [11,
22, 33, 441
True otherwise
True

Expressions:
An expression is defined as a combination of constants, variables, and
operators, An expression always evaluates to a value.
1. 3+4 (34-23)
2. 34 %3+3
Evaluation of expressions:
Evaluation of the expression is based on precedence of operators. (It
determines which operator will be evaluated first). Higher precedence operator
is evaluated before the lower precedence operator.
The following table lists precedence of all operators from highest to lowest.
Order of Precedence Operators Description
1 ** Exponentiation
2 *, /, %, // Multiply, Divide, Modulo,
and Floor division
3 +, - Addition and Subtraction
4 <=, <, >, >=, ==, != Relational and Comparison
operators
5 =, %=, /=, //=, -=, +=, Assignment operators
*=, **=
6 is, is not Identity operators
7 in, not in Membership operators
8 not Logical operator
9 and Logical operator
10 or Logical operator

Remark: The expression within bracket () is evaluated first. The expression is


evaluated from left to right for operators with equal precedence.
Ques. Evaluate the following expressions
a. 12+32-20
b. 25*2-8
c. 50 % 2 + 3
d. (25 – 20 )*2
Ans. 24, 42, 3, 10
input() function:
This function helps to take or accept data from the user.
The syntax for input() is: input ("Any message which you want to display")
for example:
>>>n1 = input("Enter any number: ")
Enter any number: 8 #value 8 will be stored in variable n1
>>>age = input("Enter your age:") #input() function takes everything as
string
Enter your age: 23
>>>type(age)
<class 'str'>
>>age = input("Enter your age: ") #input() function takes everything as
string
Enter your age: 23
>>>type(age)
<class 'str'>
>>>nm = input("Enter your name:") #input() function takes everything as
string
Enter your name: Anil
>>>type(nm)
<class 'str'>
>>>age = int(input("Enter your age: ")) #int() function convert string to
integer
Enter your age: 23
>>>type(age)
<class 'int'>
>>>p = float(input("Enter Price: ")) #float() function convert string to float
Enter Price: 420.50
>>>type(p)
<class 'float'>
print() function :
This function help to display message or text on screen. The syntax for
print() is:
print(value [, ..., sep = ' '])
sep: The optional parameter sep is a separator between the output values. We
can use a character, integer or a string as a separator. The default separator is
space. for example,
>>>print("Read my blog")
Read my blog
>>>print("Sum of two numbers is: ", 2+9)
Sum of two numbers is: 11
>>>a = 9
>>>b = 6
>>>print("First number is: ",a, "Second number is: ",b)
>>>print("Hello","World","India") #by default value of sep is space' 1
Hello World India
>>>print("Hello","World","India", sep = "@") Hello@World@India
Type Conversion :
In Python we can change the data type of a variable in Python from one
type to another. Such data type conversion can happen in two ways: either
explicitly (forced) or implicitly.
Explicit Conversion :
When the programmer specifies for the interpreter to convert a data type
to another type. Explicit conversion, also called type casting. It happens when
data type conversion takes place because the programmer forced it in the
program. The general form of an explicit data type conversion is:
(new_data_type) (expression)
With explicit type conversion, there is a risk of loss of information since we are
forcing an expression to be of a specific type. for example,
>>>x = 9.56
>>>y = int(x)
>>>y
9
NOTE: In above example decimal part will be discarded
Explicit type conversion functions in Python
Function Description
int(x) Converts x to an integer
float(x) Converts x to a floating-point number
str(x) Converts x to a string representation
chr(x) Converts ASCII value of x to character
ord(x) returns the character associated with the ASCII code x

Implicit Conversion :
Implicit conversion, also known as coercion, happens when data type
conversion is done automatically by Python and is not instructed by the
programmer.
n1 = 7 #n1 is an integer
n2 = 2.0 #n2 is a float
res = n1 - n2 #res is difference of a float and an integer
print(res)
print(type(res))
OUTPUT:
5.0
<class 'float'>
NOTE: In above example variable 'res' was automatically converted to a float
value.

Debugging:
We can make some mistakes while writing a program, due to which, the
program may not execute or may give wrong output. The process of identifying
and removing such mistakes (called bugs), from a program is called debugging.
Errors in the programs can be classified into three categories.
1. Syntax Error:
When we are not writing the programs according to the rules that
determine its syntax then Syntax error occurs. If any syntax error is present, the
interpreter shows error message(s) and stops the execution there only. for
example (1 + 2) is syntactically correct, whereas (9-2 is not due to absence of
right parenthesis.
2. Logical Error:
An error that causes the program to behave incorrectly. Logical error
produces an undesired output but without abrupt termination of the program.
Logical errors are also called semantic errors as they occur when the meaning of
the program (its semantics) is not correct. for example, code to find the average
of two numbers
>>> 12 + 6/2 #This code will not give the correct output so statement is
logically incorrect
>>>15 # This is not the average of 12 and 6

3. Runtime Error:
A runtime error causes abnormal termination of program. Runtime error is
when the statement is syntactically correct, but the interpreter cannot execute
it. for example Division by Zero is most common runtime error.

You might also like