Python KNC402-2023 (Notes)
Python KNC402-2023 (Notes)
IV SEM-IT-2023
Introduction to Python
Python is derived from many languages like ABC, C/C++, Modula-3, Algol-63 etc
The first version of python was developed in 1991.
2
Features of Python
1. Simple – Python is a simple language. Reading python programs feel like reading english.
2. Easy to learn- It is easy to learn because the structure of python is very simple.
3. Versatile- It is used to develop simple to advance applications
4. Free and open source- Python is a open source language. So anyone can use it freely.
5. High-level language- It is an high-level language , so the programmers no need to worry
about low level details.
6. Portable- program written on one platform can be executed on another without change.
7. Object oriented- support object oriented features
8. Interpreted- python uses interpreter to convert source code into machine code(byte code)
9. Multithreaded – It can execute more processes of programs simultaneously.
3
10. Garbage collection- It support automatic garbage collection environment.
Limitations of Python
Parallel processing can be done in Python but not as elegantly as done in some other languages
(like JavaScript and Go Lang).
• Being an interpreted language, Python is slow as compared to C/C++. Python is not a very
good choice for those developing a high-graphic 3d game that takes up a lot of CPU.
• As of now, there are few users of Python as compared to those using C, C++ or Java.
• It lacks true multiprocessor support.
•• Python is slower than C or C++ when it comes to computation heavy tasks and desktop
applications.
• It is difficult to pack up a big Python application into a single executable file. This makes it
difficult to distribute Python to non-technical.
4
Applications of Python
5
Applications of Python
• GUI-based desktop applications: Simple syntax, modular architecture, rich text processing
tools and the ability to work on multiple operating systems makes Python a preferred choice
for developing desktop-based applications.
• Image processing and graphic design applications: Python is used to make 2D imaging
software such as Inkscape, GIMP, Paint Shop Pro and Scribus. It is also used to make 3D
animation packages, like Blender, 3ds Max, Cinema 4D, Houdini, Lightwave and Maya.
• Scientific and computational applications: Features like high speed, productivity and
availability of tools, such as Scientific Python and Numeric Python, have made Python a
preferred language to perform computation and processing of scientific data. 3D modeling
software, such as FreeCAD, and finite element method software, like Abaqus, are coded in
6
Python.
Applications of Python
Games: Python has various modules, libraries, and platforms that support development of
games. Games like Civilization-IV, Disney's Toontown Online, Vega Strike, etc. are coded
using Python.
• Enterprise and business applications: Simple and reliable syntax, modules and libraries,
extensibility, scalability together make Python a suitable coding language for customizing
larger applications. For example, Reddit which was originally written in Common Lips, was
rewritten in Python in 2005. A large part of Youtube code is also written in Python.
• Operating Systems: Python forms an integral part of Linux distributions.
7
Python editions
• Python 1.0 - 1991
• Python 2.0 - 2000
• Python 3.0 – 2008
2. When you install Python, IDLE ((Integrated Development Learning Environment) is also
installed by default. This makes it easy to get started in Python. Its major features include the
Python shell window(interactive interpreter), auto-completion, syntax highlighting, smart
indentation, and a basic integrated debugger.
IDLE is a decent IDE for learning as it's lightweight and simple to use. However, it's not for
optimum for larger projects.
Stop the
Stop the application application
Edit the program Edit the program
code code
Recompile code
Relink the
executable
10
Writing and Executing First Python Program
Step 1: Open an editor.
Step 2: Write the instructions
Step 3: Save it as a file with the filename having the extension .py.
Step 4: Run the interpreter with the command python program_name.py or use IDLE to
run the programs.
To execute the program at the command prompt, simply change your working directory
to C:\Python34 (or move to the directory where you have saved Python) then type
python program_name.py.
If you want to execute the program in Python shell, then just press F5 key or click on Run
Menu and then select Run Module.
11
Input and Output statement
To take input from the users, Python makes use of the input() function. However, we
must always remember that the input function takes user’s input as a string.
To display the result or output , python support print() function
Example:
WAP
Example Output
After you have written your code, you should run your program and it should
print the following:
Example Input
Angela
Example Output
6
Elements of Python
16
Keywords
• Keywords are the reserved words in Python.
• We cannot use a keyword as a variable name, function name or
any other identifier.
• In Python, keywords are case sensitive.
• All the keywords except True, False and None are in lowercase, and
they must be written as they are.
• Example
– and, as, assert, await, break, class, continue, def, del, elif, else,
except, finally, for, global, if, import, in, is, lambda, not, or, pass,
raise, return, try, while, with, yield
17
Identifiers
Identifiers are names given to identify something. This something can be a variable,
function, class, module or other object. For naming any identifier, there are some
basic rules like:
• The first character of an identifier must be an underscore ('_') or a letter (upper or
lowercase).
• The rest of the identifier name can be underscores ('_'), letters (upper or lowercase), or
digits (0-9).
• Identifier names are case-sensitive. For example, myvar and myVar are not the same.
• Punctuation characters such as @, $, and % are not allowed within identifiers.
• Examples of valid identifier names are sum, __my_var, num1, r, var_20, First, etc.
• Examples of invalid identifier names are 1num, my-var, %check, Basic Sal, H#R&A, etc.
18
Variables
• Variable means its value can vary. You can store any piece of
information in a variable. Variables are nothing but just parts of your
computer’s memory where information is stored. To be identified
easily, each variable is given an appropriate name.
• No need to declare a variable before using it.
19
Variables
• For example
20
Comments
Comments are the non-executable statements in a program. They are just added to
describe the statements in the program code. Comments make the program easily
readable and understandable by the programmer as well as other users who are seeing
the code. The interpreter simply ignores the comments.
In Python, a hash sign (#) that is not inside a string literal begins a comment. All
characters following the # and up to the end of the line are part of the comment
Example:
21
Indentation
Whitespace at the beginning of the line is called indentation. These whitespaces or the
indentation are very important in Python. In a Python program, the leading whitespace
including spaces and tabs at the beginning of the logical line determines the indentation
level of that logical line.
Example:
22
Multiple Assignment in Variables
• A single value may be assigned to several variables simultaneously.
For example
>>> a = b = c = 1
• It also allows to assign multiple objects to multiple variables.
For example −
>>> a, b, c = 23, 29.45, “Ram”
• Swapping variable values
For example −
x, y= y, x
23
Data types
• Everything is an object in Python programming, data
types are classes and variables are instance (object) of
these classes Data Types Keyword
String Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set
Boolean Types bool
Binary Types bytes
24
Types of Number Types
25
Strings
• Strings in Python are identified as a contiguous set of characters
represented in the single or double quotation marks.
• Python allows for either pairs of single or double quotes.
String slicing- Subsets of strings can be taken using the slice operator ([ ]
and [:] ) with indexes starting at 0 in the beginning of the string and working
their way from -1 at the end. It has following syntax
string[start : end : stepover]
example- String[::] string [::1] string[::-1] string[:3]
0 1 2 3 4
H C S T #
-5 -4 -3 -2 -1 26
Strings
• The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator.
• For example
>>> str = ‘Hello World!’
>>> print(str)
>>> print(str[0])
>>> print(str[2:5])
>>> print(str[2:])
>>> print(str * 2)
>>> print(str + ‘TEST’)
27
Strings
• For example
>>> str = ‘Hello World’
>>> print(str[::])
>>> print(str[::-1])
>>> print(str[::-2])
>>> print(str[-1:])
>>> print(str [:-1])
>>> print(str [-1:5])
28
Operators in Python
Python language supports the following types of operators.
• Arithmetic Operators
• Relational Operators
• Unary operator
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
29
Arithmetic Operators
30
Relational Operators (Comparison operators)
31
Unary Operators
Unary operators act on single operands. Python supports unary minus operator. Unary minus
operator is strikingly different from the arithmetic operator that operates on two operands
and subtracts the second operand from the first operand. When an operand is preceded by a
minus sign, the unary operator negates its value.
For example, if a number is positive, it becomes negative when preceded with a unary minus
operator. Similarly, if the number is negative, it becomes positive after applying the unary
minus operator. Consider the given example.
b = 10 a = -(b)
The result of this expression, is a = -10, because variable b has a positive value. After applying
unary minus operator (-) on the operand b, the value becomes -10, which indicates it as a
32
negative value.
Assignment Operators
Operator Description
a=b
=
Assigns values from right side operands(b) to left side operand (a)
a+=b is same as a = a + b
+=
It adds right operand to the left operand and assign the result to left operand
a-=b is same as a = a - b
-= It subtracts right operand from the left operand and assign the result to left
operand
a*=b is same as a = a * b
*= It multiplies right operand with the left operand and assign the result to left
operand
a/=b is same as a = a / b
/=
It divides left operand with the right operand and assign the result to left operand
33
Assignment Operators
Operator Description
a%=b is same as a = a % b
%=
It takes modulus using two operands and assign the result to left operand
a**=b is same as a = a ** b
**= Performs exponential (power) calculation on operators and assign value to
the left operand
a//=b is same as a = a //b
//=
It performs floor division on operators and assign value to the left operand
34
Logical Operators
Logical operators are ---- and, or, not.
Operator Description
35
Logical Operators
Logical AND (&&) operator is used to simultaneously evaluate two conditions or expressions
with relational operators. If expressions on both the sides (left and right side) of the logical
operator are true, then the whole expression is true. For example, If we have an expression
(a>b) && (b>c), then the whole expression is true only if both expressions are true. That is, if
b is greater than a and c.
Logical OR (||) operator is used to simultaneously evaluate two conditions or expressions
with relational operators. If one or both the expressions of the logical operator is true, then
the whole expression is true. For example, If we have an expression (a>b) || (b>c), then the
whole expression is true if either b is greater than a or b is greater than c.
36
Logical Operators
Logical not (!) operator takes a single expression and negates the value of the expression.
Logical NOT produces a zero if the expression evaluates to a non-zero value and produces a 1
if the expression produces a zero. In other words, it just reverses the value of the expression.
For example, a = 10, b b = !a; Now, the value of b = 0. The value of a is not zero, therefore, !a
= 0. The value of !a is assigned to b, hence, the result.
37
Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level. These
operators include bitwise AND, bitwise OR, bitwise XOR, and shift operators. Bitwise
operators expect their operands to be of integers and treat them as a sequence of bits.
39
Shift Operators
Python supports two bitwise shift operators. They are shift left (<<) and shift right (>>).
These operations are used to shift bits to the left or to the right. The syntax for a shift
operation can be given as follows:
Examples:
40
Membership Operators
Example
Operator Description Result
x = {2,3,5}
in True if value/variable is found in the sequence 5 in x True
True if value/variable is not found in the
not in 5 not in x False
sequence
41
Identity Operators
• Identity operators compare the memory locations of two objects.
• 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.
Example
Operator Description a = ‘Hello’ Result
b = ‘Hello’
True if the operands are identical (refer to the
is a is b True
same object)
True if the operands are not identical (do not
is not a is not b False
refer to the same object)
42
Type conversion
• The process of converting the 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
43
Implicit Type conversion
• Python automatically converts one data type to another data
type without any user involvement.
• It always converts smaller data types to larger data types to
avoid the loss of data.
• Example
>>> a = 4
>>> b = 2.3
>>> c = a + b
• In above example, data type of a and b are int and float,
respectively. Data type of c will be float and its value is 6.3
44
Explicit Type conversion
• In Explicit Type Conversion, users convert the data type of an object
to required data type.
• The predefined functions like int(), float(), str() are used 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
<datatype>(expression)
• Example
>>> a = 2.6
>>> c = int(a)
45
Function of type conversion
Function Description
int(x) Convert x to an integer
float(x) Convert x to a float number
str(x) Convert x to a string
tuple(x) Convert x to a tuple
list(x) Convert x to a list
set(x) Convert x to a set
ord(x) Convert x to ASCII code
bin(x) Convert x to a binary
oct(x) Convert x to an octal
hex(x) Convert x to a hexadecimal
chr(x) Convert x to a character
46
WAP to compute Life in Weeks
Create a program using maths and f-Strings that tells us how many days, weeks,
months we have left if we live until 90 years old.
It will take your current age as the input and output a message with our time left in this
format:
Example Input
56
Example Output
You have 12410 days, 1768 weeks, and 408 months left.
WAP to reverse the given string
Example Input
Malyalam
Example Output
The reverse string is malyalam
Example Input
123456789
Example Output
The reverse string is 987654321
Which statement below is incorrect?
•932 is an Integer
•"False" is a Boolean
•857.25 is a Float
•"523" is a String
If I give you the following code, what will you print out?
1.street_name = "Abbey Road"
2.print(street_name[4] + street_name[7])
•eR
•en
•yo
•ya
#Guess the output of each print statement
print(python[1:4])
print(python[1:])
print(python[:])
print(python[1:100])
print(python[-1])
print(python[-4])
print(python[:-3])
print(python[-3:])
print(python[::-1])