Python Notes Ch 1
Python Notes Ch 1
History of Python
• Python laid its foundation in 1980s.
• The implementation of Python was started in December 1989 by Guido Van Rossum at CWI
(Centrum Wiskunde & Informatica) in Netherland.
• In February 1991, Guido Van Rossum published the labeled version 0.9.0 to alt.sources.
• In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
• In 2000, Python 2.0 was released with new features such as list comprehensions, garbage
collection, cycle detecting and Unicode support.
• On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
• ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling.
2
Python Programming Unit-1 Notes
Python can build a wide range of different data visualizations, like line and bar graphs, pie
charts, histograms, and 3D plots. Python also has a number of libraries that enable coders to write
programs for data analysis and machine learning more quickly and efficiently, like TensorFlow and
Keras.
2) Web development
Python is often used to develop the back end of a website or application—the parts that a user
doesn’t see. Python’s role in web development can include sending data to and from servers,
processing data and communicating with databases, URL routing, and ensuring security. Python offers
several frameworks for web development. Commonly used ones include Django and Flask.
3) Automation or scripting
If you find yourself performing a task over and over again, you could work more efficiently
by automating it with Python. Writing code used to build these automated processes is called
scripting. In the coding world, automation can be used to check for errors across multiple files,
convert files, execute simple math, and remove duplicates in data.
5) Everyday tasks
Python isn't only for programmers and data scientists. Learning Python can open new
possibilities for those in less data-heavy professions, like journalists, small business owners, or social
media marketers. Python can also enable non-programmer to simplify certain tasks in their lives.
Here are just a few of the tasks you could automate with Python:
• Keep track of stock market or crypto prices
• Send yourself a text reminder to carry an umbrella anytime it’s raining
• Update your grocery shopping list
• Renaming large batches of files
• Converting text files to spreadsheets
• Randomly assign chores to family members
• Fill out online forms automatically
3
Python Programming Unit-1 Notes
• Compiles the code into a byte code format which is a lower-level language understood by the
computers.
• The Python Virtual Machine (PVM) perform over the instructions of low-level byte code to
run them one by one.
The Python script is saved with a .py extension which informs the computer that it is a Python
program script.
Python Installation
Unlike Windows, the Unix based operating systems such as Linux and Mac come with pre-
installed Python. Also, the way Python scripts are run in Windows and Unix operating systems
differ.
4
Python Programming Unit-1 Notes
a=1
b=3
if a > b:
print("a is Greater")
else:
print("b is Greater")
5
Python Programming Unit-1 Notes
On a Mac system, it is very straight-forward. All you need to do is open Launchpad and
search for Terminal, and in the terminal, type Python and boom, it will give you an output
with the Python version.
Like the Mac system, accessing terminal on a Linux system is also very easy. Right click on
the desktop and click Terminal and in terminal type Python and that's all!
2. Command Line –
We have to make python file first and save by .py extension. This file you can run in
command prompt by write python first and then your filename.
• Create a file having extension .py
• Write Python script in created file
• To run a Python script store in a ‘.py’ file in command line, write ‘python’ keyword
before the file name in the command prompt.
python hello.py
Note: You can write your own file name in place of ‘hello.py’.
# File Name:- hello.py
# File Path:- C:\Users\Anonymous\Desktop\GfG\hello.py
print ("Hello World!")
6
Python Programming Unit-1 Notes
Example:-
>>> print('Hello, World!')
Hello, World!
>>> print(1)
1
>>> print(2.2)
2.2
>>> print('Abc@123')
Abc@123
type( ):- To find the type of given value type() function is used.
In python we don’t have to write int, float, char it will automatically understand the type of
given value. So, if we want to find particular type of given value, we can use the type function.
Variables
Variables are containers for storing data values.
Creating Variables
1. Python has no command for declaring a variable. We just have to write variable name
and assign the value in it.
2. A variable is created the moment you first assign a value to it.
Example:- Output:-
x=5
y = “LJ Polytechnic” 5
print(x) LJ Polytechnic
print(y)
7
Python Programming Unit-1 Notes
3. Variables do not need to be declared with any particular type, and can even change
type after they have been set. If we use the same name, the variable starts referring to
a new value and type.
Example:- Output:-
x=5
LJ Polytechnic
x = “LJ Polytechnic”
print(x)
4. Python allows assigning a single value to several variables simultaneously with “=”
operators.
Example:-
x = y = z = 100 Output:- 100
print(y)
8
Python Programming Unit-1 Notes
Keywords:-
and del from none true continue lambda
String:
• Strings are arrays of bytes representing Unicode characters.
• String data type is most important data type in python.
• Python does not have a character data type, a single character is simply a string with a length
of 1.
• String is not a small. It can also big as million characters.
• Python has also built in functions and algorithms for string.
• String is the combination of multiple characters.
• String index is starting from 0.
Example:- Output:-
s = 'P' P
print(s) <class ‘str’>
type(s) Python
<class ‘str’>
language = 'Python'
print(language)
type(language)
9
Python Programming Unit-1 Notes
String:- P y t h o n
[-6] [-5] [-4] [-3] [-2] [-1]
Length of a string:
• To find the length of the string len( ) function is used.
• len() is a built-in function that returns the number of characters in a string:
Example:- Output:-
language = 'Python' 6
print( len(language))
• To get the last letter of a string, you might be tempted to try something like this:
Because if you write simply length, then length will start from 0 so it can’t display last digit.
x = "Python"
length = len(x) n
y=x[length-1]
print(y)
String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
We can specify start, stop and step (optional) within the square brackets as:
string[start:stop:step]
• start: It is the index from where the slice starts. The default value is 0.
• stop: It is the index at which the slice stops. The character at this index is not included in the
slice. The default value is the length of the string.
• step: It specifies the number of jumps to take while going from start to stop. It takes the
default value of 1.
10
Python Programming Unit-1 Notes
Example:-
s = 'Welcome to LJKU'
print(s[0:8])
print(s[11:16])
#if we can write same digit at both place then it will not give us any output
print(s[3:3])
print(s[ : :-2]) #it will first reverse the string and skip 1 character after reverse.
Output:-
Welcome
LJKU
Welcome to LJKU
Welcome to LJKU
Jelcome to LJKU
UKJL ot emocleW
Wloet JU
UJ teolW
String methods
Everything in Python is an object. A string is an object too. Python provides us with various methods
to call on the string object.
Note: Note that none of these methods alters the actual string. They instead return a copy of the
string. This copy is the manipulated version of the string.
11
Python Programming Unit-1 Notes
capitalize( )
This method is used to capitalize a string.
lower( )
This method converts all alphabetic characters to lowercase.
upper( )
This method converts all alphabetic characters to uppercase.
title( )
This method converts the first letter of each word to uppercase and remaining letters to
lowercase
swapcase([<chars>])
This method swaps case of all alphabetic characters.
rstrip( )
This method removes trailing characters from a string. Removes trailing whitespaces if you don’t
provide a <chars> argument.
strip( )
This method removes leading and trailing characters from a string. Removes leading and
trailing whitespaces if you don’t provide a <chars> argument
join(<iterable>)
This method returns the string concatenated with the elements of iterable.
>>>s=('We','are','coders')
>>>s1= '_'.join(s)
print(s1)
We_are_coders
split(sep=None, maxsplit=-1)
This method splits a string into a list of substrings based on sep. If you don’t pass a value to sep, it
splits based on whitespaces.
Strings can be concatenated (glued together) with the + operator, and repeated with *:
>>>3*'un'
'ununun'
>>>'Py''thon'
'Python'
>>>'Py'+'thon'
'Python'
Escape Characters
To insert characters that are illegal in a string, use an escape character. An escape character is a
backslash (\) followed by the character you want to insert.
14
Python Programming Unit-1 Notes
\\ Backslash \b Backspace
Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:
>>>x = 1 #int
>>> y = 2.8 #float
>>> z = 1j #complex
>>>print(type(x))
<class 'int'>
>>>print(type(y))
<class 'float'>
>>>print(type(z))
<class 'complex'>
Int
Integer is a whole number, positive or negative, without decimals, of unlimited length.
>>>x = 1
>>>y = 35656222554887711
>>>z = -3255522
>>>print(type(x))
<class 'int'>
>>>print(type(y))
<class 'int'>
>>>print(type(z)) 15
<class 'int'>
Python Programming Unit-1 Notes
Float
Float or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
Complex
Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j <class 'complex'>
<class 'complex'>
print(type(x))
<class 'complex'>
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods
Example:-
x = 1 # int Output:-
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x) 1.0
#convert from float to int: <class 'float'>
b = int(y) 2
#convert from int to complex: <class 'int'>
c = complex(x) (1+0j)
print(a) <class 'complex'>
print(type(a))
print(b)
print(type(b))
print(c) 16
print(type(c))
Python Programming Unit-1 Notes
Operators
Operators in general are used to perform operations on values and variables. These are
standard symbols used for the purpose of logical and arithmetic operations.
Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like addition,
subtraction, multiplication, and division.
Example:- Output:-
a = 21
b = 10
c=0
c=a+b
print("Addition is:-",c)
c=a-b Addition is:- 31
print('Subtraction is:-',c) Subtraction is:- 11
c=a*b Multiplication is:- 210
print('Multiplication is:-',c) Division is:- 2.1
c=a/b Reminder of a/c is:- 1
print('Division is:-',c) result of p^q is:- 8
c=a%b result of a devide b is:- 2
print("Reminder of a/c is:-",c)
p=2
q=3
r =p**q
print("result of p^q is:-",r)
x = 11
y=5
17
z = a//b
print("result of a devide b is:-",z)
Python Programming Unit-1 Notes
Comparison Operators
Comparison of Relational operators compares the values. It either returns True or False
according to the condition.
> Greater than: True if the left operand is greater than x > y
the right
< Less than: True if the left operand is less than the x < y
right
<= Less than or equal to True if the left operand is less x <= y
than or equal to the right
Example:
>>># a == b is False
>>>print(a == b)
False
>>># a != b is True
>>>print(a != b)
True
18
Python Programming Unit-1 Notes
Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used
to combine conditional statements.
and Logical AND: True if both the operands are true x and y
Example: Output:
x=5
False
print(x>3 and x>10) #and
True
print (x>3 or x>10) #or
True
print(not(x > 3 and x > 10))
# returns False because not is used to reverse the result
Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on
binary numbers.
Operator Description Syntax
>> The left operands value is moved left by the number x>>
Bitwise right of bits specified by the right operand.
shift
19
Python Programming Unit-1 Notes
Example: Output:
Assignment Operators
Assignment operators are used to assigning values to the variables.
20
Python Programming Unit-1 Notes
Identity Operators
is and is not are the identity operators both are used to check if two values are located on
the same part of the memory. Two variables that are equal do not imply that they are identical.
Operator Description
>>> a = 10
>>> b = 20
>>> c = a
Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a
sequence.
Operator Description
Example:-
#membership_ex.py
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output:-
22
Python Programming Unit-1 Notes
Operator Associativity
If an expression contains two or more operators with the same precedence then Operator
Associativity is used to determine. It can either be Left to Right or from Right to Left.
23