rh22
PYTHON
PROGRAMMING
This notebook includes:
PYTHON PROGRAMMING FOR BEGINNERS
CORE PYTHON
Instagram_id :- rising_harmony22
Python Full Stack
rh22
Web Developer Profile
HTML
Basic Web
CSS Technologies
JavaScript React
UI Libraries &
Vue
Frameworks Angular
Python jQuery
Django
Python
Flask Technologies
Node.JS SQL
Oracle
Database MySQL
MongoDB
Git/Github
VScode Tools and Cloud
Hosting
AWS
Azure/GC
rh22
Introduction :-
Python is a high-level interpreted programming language.
It is used in many areas.
Like-
• Software development
• Web development
• Software testing
• Machine learning
• Data Science
• Game development
• App development
History of Python :-
Python was developed by Guido Van Rossum in the Year 1990. At Centrum in the
Netherlands as a successor of a language called ABC.
Name “Python” picked from TV show Monty python’s flying circus.
Version :-
• Python 0.9.0 February 1991
• Python 1.0 January 1994
• Python 2.0 October 2000
• Python 3.0 December 2008
• Python 3.12 October 2023(Latest)
•
Features :-
• Easy to learn
• High-level language
rh22
• Interpreted language
• Plateform independent
• Procedure & Object oriented
• Scalable & Huge library
How Python work :-
• Write code (Source code)/Program.
• Compile the program using python program into byte code.
• Machine can not understand byte code so we convert it into machine code
using PVM.
• PVM uses an interpreter which understands the byte code and convert it
into machine code.
• Machine code instructions are then executed by the processor and results
are displayed.
Binary Output
Program code
Byte code
Python virtual machine :-
• Python virtual machine(PVM) is a program which provide programming
environment. The role of PVM is to convert the byte code instructions into
machine code so the computer can execute those machine code
instructions and display the output.
• Interpreter converts the byte code into machine code and sends that
machine code to the computer processor for execution.
rh22
Identifier :-
• An identifier is a name having a few letters, numbers and special
characters.
• It should always start with a non-numeric character.
• It is used to identify a variable, function, symbolic constant, class etc.
Reserved word :-
Python language uses the following keywords which are not available to
users to use them as identifiers.
Like- False, else, import, pass, yield…etc.
Constant :-
• There are no constants in python, the way they exist in c and java.
• In python, constants are usually defined on a module level and
written in all capital letters with underscores seprating words but
remember its value can be changed.
Variable :-
In Python, a variable is considered as tag that is tied to some value,
Python considered value as objects.
Data Type :-
Datatype represents the type of data stored into a variable or memory.
Types of Datatype :-
I. Built-in Data type-
• Integer:- In Python, integers are classified into zero, positive, or
negative whole numbers with no fractional part.
rh22
Examples-1,3,12,10….etc.
a=10,
b=23,
• String:- Sequence of character is known as string.
Examples- “Hello”,”world”….etc.
X=”Hello world”
• Float:- The float data types are used to store positive and
negative numbers with a decimal point.
Examples- 2.3, 2.22, 5.8…etc.
• Complex number:- A complex number is a number that is written
in the form of a+bj. Where, a=real part of the number b=imaginary
part of the number
j=square root value of -1
• Bool type:- It represents the Boolean value True or False. Python
internally represents True as 1 and False as 0.
Examples-True, False
• List:- It represents a group of elements.
It is mutable and dynamic which means size is not fixed.
List items are ordered, changeable, and allow duplicate
values. Examples- a=[10,20,”hello”] a[0]=23
• Set:- A set is an unordered collection of elements.
It is immutable and not accept duplicate elements.
Examples- a={1,2,3,4,2,2,2,2}
output- {1,2,3,4}
rh22
• Tuple:- A tuple contains a group of elements which can be different
types.
It allows duplicate but we can not modify its element. Examples-
a=(10,20,-33,’hello’)
• Dictionary:- It is used to store data values in key:value pairs.
They are ordered, mutable and do not allow duplicates keys.
Examples-
a={11:”raj”,12:”simran”,13:”rahul”}
II. User Defined Data type-
Array
Class
Module
Operator :-
An operator is a symbol that performs an operations.
Types of operators-
• Arithmatic operator
Like- +, -, *, /, %, **, //
• Relational or Comparison operator
Like- >, <, ==, >=, <=, !=
• Logical operator
Like- and, or, not
• Assignment operator
Like- =, +=, -=, *=, %=, **=, //= ….etc.
rh22
• Bitwise operator
Like- &, |, <<, >> …etc.
• Membership operator
Like- in, not in
• Identity operator
Like- is, is not
Type conversion:-
Converting one data type into another data type is called type conversion.
Types of type conversion-
• Implicit type conversion- in the implicit type conversion, python
automatically converts one data type into another data type.
Eg- a=5
b=2
value=a/b
print(value) # show output in float type
• Explicit type conversion- in the cast type conversion, programmer
converts one data type into another data type.
Eg-
o Int(n)
o Float(n)
o Str(n)
o list(n)
o tuple(n)
o complex(n)
o complex(x,y)
o bin(n)
o oct(n)
rh22
• Possible type conversion-
o float to integer
o integer to float
o string to tuple
o string to list
o tuple to list
Escape sequence:-
Escape sequences are control character used to move the cursor and print
characters such as ‘,’’ and so on
Escape sequence Meaning
• /a Bell
• /b Backspace
• /f Formfeed
• /n Newline
• /r Carriage return
• /t Horizontal tab
• /v Vertical tab
• // Backslash
• /’ Single quote
• /” Double quote
Input and Outpur-
Print()- print() function is used to print the specified message to the output
screen/device.
Syntax-
Print(“Hello world”)
Input()- input() function is used to accept input from keyboard.
rh22
This function will stop the program flow until the user gives an input and end the
input with the return key.
Syntax-
Input(“Enter your message….”)
Condition Statements:-
• If statement- It is used to execute an instruction or block of instructions
only if a condition is fulfilled.
Syntax-
If condition:
Statements….
• If-else statement-If-else is used when a different sequence of instructions is
to be executed depending on the logical value(true/false) of the condition
evaluated.
Syntax-
If condition:
Statements….
else:
Statements….
• If elif statement-To show a multi-way decision based on several conditions,
we use if elif statement.
Syntax-
If condition:
Statements….
elif condition:
rh22
Statements….
elif condition:
Statements….
• Nested if-else statement-In nested if else statement, an entire if-else
construct is written within either the body of the if statement or the body
of an else statement.
Syntax-
If condition:
If condition:
Statements…
else:
Statements…
else:
Statements….
• If elif else statement-
Syntax-
If condition:
Statements….
elif condition:
Statements….
elif condition:
Statements….
else:
Statements….
rh22
Control statements:-
Loops- Repeation of task is called loop.
Types of loop-
• While loop- The while loop keeps repeating an action until an associated
condition returns false.
Syntax-
While condition:
Statements….
• For loop- The for loop is useful to iterate over the elements of sequence
such as string, list, tuple etc… Syntax- for I in sequence:
Statements….
• For loop with range- Syntax- for i in range(start,stop,stepsize):
Statements….
• Range()- range() function is used to generate a sequence of integers
starting from 0 by default, and increments by 1 by default, till condition.
Syntax-
range(start,stop,stepsize)
Break statements:-
Break statement is used to jump out of loop to process the next statement in the
program. Syntax-
Break
Continue statements:-
Continue statement is used in a loop to go back to the beginning of the loop.
Syntax-
Continue
rh22
Pass statements:-
Pass statement is used to do nothing. It can be used inside a loop or if statement
to represent no operation.
Pass is useful when we need statement syntactically correct but we do not want
to do any operation.
Syntax-
Pass
Array:-
Collection of similar datatype is known as array.
In python, arrays can increase or decrease their size dynamically.
Array uses less memory than list.
We have to import array module for use array in python.
Note- Python does not support multi-dimensional array but we can create
Multidimensional array using third party packages like numpy.
Syntax-
Import array
array_name=array.array(‘type_code’,[element])
Eg-
Import array
roll=array.array(‘ I ’,[11,12,13])
Getting array input from user-
From array import *
roll=array(‘ I ’,[ ])
n=int(input(“how many elements”))
for i in range(n):
roll.append(int(input(“enter a el.. ”)))
for i in range(len(roll)):
print(roll[i])
rh22
Some important methods :-
• Append()- This method is used to add an element at the end of the existing
array. Syntax-
Array_name.append(new_element)
• Insert()- This method is used to insert an element in a particular position of
the existing array.
Syntax-
Name.insert(position,new_element)
• Pop()- It is used to remove last element from the existing array.
Syntax-
Name.pop()
• Remove()- This method is used to remove first occurrence of given element
from the existing array. If it does not found the element, shows value error.
Syntax-
Name.remove(element)
• Index()- It returns position number of first occurrence of given element in
the array. If it does not found the element, shows value error.
Syntax-
Name.index(element)
• Reverse()- This method is used to reverse the order of elements in the
array. Syntax-
Name.reverse()
Pip:-
Pip is the package manager for python.
Using pip we can install python packages.
Check if pip is already installed
rh22
Pip –version # shows pip version
Pip help- It shows list of pip commands and their functions.
Pip list- display list of installed packages
Some String Functions: -
• upper()- This method is used to convert all character of a string into
uppercase.
Syntax-
Stringname.upper()
• lower()- It is used to convert all character of a string into lower case.
Syntax-
Stringname.lower()
• swapcase()- It is used to convert lowercase character into uppercase and
vice versa.
Syntax-
Stringname.swapcase()
• title()- It is used to convert the string in such that each word in string will
start with a capital letter and remaining will be small letter.
Syntax-
Stringname.title()
• isupper()- It is used to test whether given string is in uppercase or not, it
returns True if string contains at least one letter and all character are in
uppercase else return False.
Syntax-
Stringname.isupper()
rh22
• islower()- It is used to test whether given string is in lowercase or not, it
returns True if string contains at least one letter and all character are in
uppercase else return False.
Syntax-
Stringname.islower()
• istitle()- It is used to test whether given string is in title formate or not.
Syntax-
Stringname.istitle()
• isdigit()- It returns True if the string contains only numeric digits(0 to 9) else
returns False.
Syntax-
Stringname.isdigit()
• isalpha()- It returns True if the string has at least one character and all are
alphabates (A to Z and a to z) else returns False.
Syntax-
Stringname.isalpha()
• isalnum()- It returns True if the string has at least one character and all
characters in the string are alphanumeric (A to Z, a to z and 0 to 9) else
returns False.
Syntax-
Stringname.isalnum()
• isspace()- It returns True if the string contains only space else returns False.
Syntax-
Stringname.isspace()
• lstrip()- It is used to remove the space which are at left side of the string.
Syntax-
Stringname.lstrip()
rh22
• rstrip()- It is used to remove the space which are at right side of the string.
Syntax-
Stringname.rstrip()
• strip()- It is used to remove the space from the both side of the string.
Syntax-
Stringname.strip()
• replace()- It is used to replace a sub string in a string with another sub
string.
Syntax-
Stringname.replace(old,new)
• split()- It is used to split/break a string into pieces. These pieces returns as a
list.
Syntax-
Stringname.split(‘seprator’)
• join()- It is used to join strings into one string.
Syntax-
“separator”.join(string_list)
• startswith()- It is used to check whether a string is starting with a substring
or not. Syntax-
Stringname.startswith(‘specified_string’)
• endswith()- It is used to check whether a string is ending with a substring or
not.
Syntax-
Stringname.endswith()
rh22
Function:- function is a code of block that perform a task.
We use def keyword to create functions.
Syntax-
def fun_name():
statements…. Function definition
deffun_name(para1,para2,….):
statements….
fun_name() calling
fun_name(para1,para2,…)
Types-
• Built-in functions- Predefined functions
Like- print(), upper(), lower()… etc.
• User defined functions- defined by users.
Like- sum(), add()… etc.
Advantages-
• Code reusability
• Ease of code maintainance
• Easy to debugging
rh22
Return statement- Return statements can be used to return something from
the function. In python, it is possible to return one or more values/variables.
Syntax-
return(variable or expression);
Example-
def add(y):
x=10
c=x+y
return c
sum=add(20)
print(sum)
Formal argument- function definition parameters are called as formal
arguments.
Actual argument- function call arguments are actual arguments.
Examples-
def add(x,y): formal arguments
c=x+y
print(c)
add(10,20) actual arguments
Types of actual arguments-
I. Positional arguments- This arguments are passed to the function in
correct positional order.
Position of actual and formal arguments should be same.
rh22
Example- def pw(x,y):
z=x**y
print(z)
pw(3,6)
II. Keyword arguments- These arguments are passed to the function with
name_value pair so keyword arguments can identify the formal arguments
by their names.
The keyword argument’s name and formal argument’s name must match.
Example-
def show(name,age):
print(name,age)
show(name=”henni”,age=22) or
show(age=22,name=”henni”)
III. Default arguments-
Example-
def show(name,age=22):
print(name,age)
show(name=”henni”)
or,
def show(name,age=23):
print(name,age)
show(name=”henni”,age=62)
rh22
IV. Variable length arguments- Variable length argument is an argument that
can accept any number of values.
The variable length argument is written with * symbol.
It stores all the value in a tuple.
Example-
def add(*num):
z=num[0]+num[1]+num[2]
print(z)
add(6,2,9)
Anonymous function or Lambdas-
A function without name is called as anonymous function. It is also known as
Lambda function.
• They are defined using lambda keyword.
• Lambda function returns a function.
Eg- show=lambda x: print(x)
• It can only contain expression and can’t include statements in its body.
• You can use all the type of actual arguments.
• In lambda function there is no need to write return statement.
Syntax-
lambda argument_list: expression
Example-
lambda x: print(x)
Nested lambda function-
Eg-
add= lambda x=10 : (lambda y: x+y)
rh22
a=add()
print(a)
print(a(20))
Local variable- The variable which are declared inside a function called as local
variable.
Local variable scope is limited only to that function where it is created.
Eg-
def add():
x=20 local variable
print(x)
Global variable- When a variable is declared above a function, it becomes global
variable.
This variables are available to all the function which are written after it.
The scope of global variable is the entire program body written below it.
Eg-
a=60 global variable
def show():
x=20 local variable
Global keyword- If local variable and global variable has same name then the
function by default refers to the local variable and ignores the global variable.
In this situation, if we need to access global variable inside the function we can
access it using global keyword followed by variable name.
Eg-
i=60
def
show():
global i=60 creation global variable
i=i+1
print(i)
print(i)
rh22
Global function- This function returns a table of current global variables in the
form of dictionary.
Recursion- A function calling itself again and again to compute a value is
referred to recursive function or recursion. Eg-
def fun():
print(“henni”)
fun() calling itself
fun()
• How to know recursion’s limit-
Import sys
print(sys.getrecursionlimit())
default limit-1000
• How to set recursion’s limit-
Import sys
sys.setrecursionlimit(2000)
print(sys.getrecursionlimit())
rh22
Function decorator- It is a function that accepts a function as parameter and
returns a function.
We use @function_name to specify a decorator to be applied on another
function.
Eg-
def décor(num):
def inner():
a=num()
add=a+5
return add
return inner
def num()
return 20
num=décor(num)
print(num())
Math module- It is a module that contains several functions to perform
mathematical operation.
Some functions-
• floor(n)-
• ceil(n)-
• fabs(n)-
• factorial(n)-
• sqrt(n)-
• pow(n,m)-
• sin(n)-
• cos(n)-
• tan(n)-
rh22
Generator- generators are functions that returns a sequence of values.
We use yield statement to returns the value from function.
Eg- def disp(a,b):
yield a
yield b
result=disp(10,20)
print(result)
print(type(result))
print(next(result))
print(next(result))
Yield statement- Yield statement returns the elements from a
generator function into generator object.
Eg- yield a
Next() function- This function is used to retrieve element by element
from a generator object.
Syntax- next(gen_obj)
Higher order function- A function is called higher order function if it
contains other functions as a parameter or returns a function as an
output.
Eg-
def shout(text):
returns text.upper()
print(shout(“henni”))
yell=shout
print(yell(“hello”))
rh22
Some methods used for list-
• append()-
• insert()-
• pop()-
• remove()-
• index()-
• reverse()-
• extend()-
• count()-
• sort()-
• clear()-
• list()-
Some important note about tuple-
• we can not delete an element of a tuple. We can delete tuple using del
keyword.
Syntax-
del tuple_name
• we can not take a direct tuple input from user. We take a list input from
user and after that convert into tuple.
rh22
THE END
Instagram_id :- rising_harmony22
By-heni