0% found this document useful (0 votes)
5 views27 pages

Core Python Notes for Students

Uploaded by

Gurnandan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views27 pages

Core Python Notes for Students

Uploaded by

Gurnandan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Core python notes for students

Python is a general-purpose programming language

1)Uses of python :
Web development: Python is used to build websites and web
applications
Software development: Python can be used for software testing,
prototyping, and build control
Data science and machine learning: Python is widely used in these
fields
https://docs.google.com/document/d/
1r1VuyMICHPwgSSYb4KDQckxrr72WZicE5zhb9LITb4w/edit?tab=t.0

Data analysis: Python can be used for data analysis and statistical
analysis
Blockchain development: Python is a strong language for blockchain
development due to its flexibility, functionality, and security
Python is a popular language because it is easy to learn, efficient, and
can run on many platforms. It is also known for its clear syntax and
emphasis on readability.
https://docs.google.com/document/d/
1mwjm7Vw7r5XUafsAXersF3UWkuGUc_NjnDq6iSteoFk/edit?tab=t.0

2)Features of Python:
Open source: Python is an open source community language, so
independent programmers are constantly building libraries and
functionality for it
Portable: Python runs on many Unix variants, including Linux and
macOS, and on Windows
Extensible: Python is extensible in C or C++
Supports multiple programming paradigms: Python supports
structured, object-oriented, and functional programming
3)Blockchain
It is a decentralized, digital ledger that securely stores and shares data
across a network of computers. It's also known as Distributed Ledger
Technology (DLT).

Benefits:
Data integrity: Blockchain provides a single source of truth,
eliminating data duplication and increasing security.
Fraud prevention: Data can't be altered without the permission of a
quorum of the parties.
Decentralized control: Each company has its copy of the ledger, and
the system automatically maintains consistency between the two
ledgers.

Blockchain can be used in a variety of applications, including:


Supply chain management
Healthcare
Identity management
Voting systems
Finance and banking
Media and entertainment

Some potential drawbacks of blockchain include:


Ownership,
Infrastructure issues,
Data challenges,
and Vulnerabilities.

3) Installing Python for use with VS Code involves two


main steps: installing the Python interpreter and then installing the
Python extension in VS Code.

1. Install the Python Interpreter:


Download Python:
Go to the official Python website (python.org) and download the
latest stable version of Python for your operating system (Windows,
macOS, or Linux).
Run the Installer:
Execute the downloaded installer. During the installation
process, ensure you check the box that says "Add Python to PATH" (or
a similar option, depending on your OS). This is crucial for VS Code and
other tools to easily locate your Python installation.
Complete Installation:
Follow the on-screen prompts to complete the installation.
Verify Installation:
Open a command prompt or terminal and type python --version (or python3
--version on some systems). This should display the installed Python version,
confirming the interpreter is set up correctly.

2. Install the Python Extension in VS Code:


Launch VS Code: Open Visual Studio Code.
Open Extensions View: Click on the Extensions icon in the Activity Bar on the
left side (it looks like four squares) or press Ctrl+Shift+X (or Cmd+Shift+X
on macOS).
Search for Python Extension: In the Extensions marketplace search bar, type
"Python".
Install Official Extension: Locate the official "Python" extension published
by Microsoft and click the "Install" button. This extension provides features
like IntelliSense, debugging, code formatting, and more.
Restart VS Code (if prompted): If prompted, restart VS Code to ensure the
extension is fully loaded and integrated.
After these steps, you can create a new Python file (.py) in VS Code, and the
Python extension will automatically provide language support, enabling you
to write, run, and debug your Python code within the editor.

4) Internal working of Python

Python is an object-oriented programming language like Java. Python is


called an interpreted language. Python uses code modules that are
interchangeable instead of a single long list of instructions that was standard
for functional programming languages. The standard implementation of
Python is called "cpython". It is the default and widely used implementation
of Python.

Internal working of Python


Python doesn't convert its code into machine code, something that hardware
can understand. It converts it into something called byte code. So within
Python, compilation happens, but it's just not in a machine language. It is
into byte code (.pyc or .pyo) and this byte code can't be understood by
the CPU. So we need an interpreter called the Python virtual machine to
execute the byte codes.

Internal Working of Python


How is Python Source Code Converted into Executable Code
The Python source code goes through the following to generate an
executable code

Step 1: The Python compiler reads a Python source code or instruction in


the code editor. In this first stage, the execution of the code starts.
Step 2: After writing Python code it is then saved as a .py file in our system.
In this, there are instructions written by a Python script for the system.
Step 3: In this the compilation stage comes in which source code is
converted into a byte code. Python compiler also checks the syntax error in
this step and generates a .pyc file.
Step 4: Byte code that is .pyc file is then sent to the Python Virtual
Machine(PVM) which is the Python interpreter. PVM converts the Python byte
code into machine-executable code and in this interpreter reads and
executes the given file line by line. If an error occurs during this
interpretation then the conversion is halted with an error message.
Step 5: Within the PVM the bytecode is converted into machine code that is
the binary language consisting of 0's and 1's. This binary language is only
understandable by the CPU of the system as it is highly optimized for the
machine code.
Step 6: In the last step, the final execution occurs where the CPU executes
the machine code and the final desired output will come as according to your
program.

How Python Internally Works?

Code Editor: Code Editor is the first stage of programs where we write our
source code. This is human-readable code written according to Python's
syntax rules. It is where the execution of the program starts first.
Source code: The code written by a programmer in the code editor is then
saved as a .py file in a system. This file of Python is written in human-
readable language that contains the instructions for the computer.
Compilation Stage: The compilation stage of Python is different from any
other programming language. Rather than compiling a source code directly
into machine code. python compiles a source code into a byte code. In the
compilation stage python compiler also checks for syntax errors. after
checking all the syntax errors, if no such error is found then it generates
a .pyc file that contains bytecode.

Python Virtual Machine(PVM): The bytecode then goes into the main part of the
conversion is the Python Virtual Machine(PVM). The PVM is the main runtime engine
of Python. It is an interpreter that reads and executes the bytecode file, line by line.
Here In the Python Virtual Machine translate the byte code into machine code which
is the binary language consisting of 0s and 1s. The machine code is highly
optimized for the machine it is running on. This binary language is only
understandable by the CPU of a system.
Running Program: At last, the CPU executes the given machine code and the
main outcome of the program comes as performing task and computation
you scripted at the beginning of the stage in your code editor.
Python Libraries/Modules
When you import libraries or modules in your Python program. Firstly python
checks if the given module is built-in, and executes the corresponding C
code. If the module is not built-in then the list of directories is defined in sys.
path. the directory of the input script, and directories listed in the
PYTHONPATH. if a .py file corresponds to the modules imported, Python
creates a new module object, On executing the code in the .py file within the
object's namespace. Then Python compiles source code into byte
code( the .pyc file), allowing for quicker execution

Compiler Vs Interpreter
In the system both the compiler and interpreter are the same they convert
high-level code to machine code. The interpreter converts source code into
the machine when the program runs in a system while a compiler converts
the source code into machine code before the program runs in our system.

Compiler
Interpreter
The compiler is faster, as conversion occurs before the program executes.
The interpreter runs slower as the execution occurs simultaneously.
Errors are detected during the compilation phase and displayed before the
execution of a program.
Errors are identified and reported during the given actual runtime.
Compile code needs to be recompiled to run on different machines.
Interpreted code is more portable as it can run on any machine with the
appropriate interpreter.
It requires more memory to translate the whole source code at once.
It requires less memory than compiled ones.
Debugging is more complex due to batch processing of the code.
Debugging is easier due to the line-by-line execution of a code.

5)Variables
Python Variable is containers that store values. Python is not “statically
typed”. We do not need to declare variables before using them or declare their
type. A variable is created the moment we first assign a value to it. A Python
variable is a name given to a memory location. It is the basic unit of storage in a
program.

Example of Variable in Python


An Example of a Variable in Python is a representational name that serves as a
pointer to an object. Once an object is assigned to a variable, it can be referred to
by that name. In layman’s terms, we can say that Variable in Python is containers
that store values.

Here we have stored “Webphplearn.com” in a variable var, and when we call its
name the stored information will get printed.

Rules for Python variables


A Python variable name must start with a letter or the underscore character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
Variable in Python names are case-sensitive (name, Name, and NAME
are three different variables).
The reserved words(keywords) in Python cannot be used to name the
variable in Python.
—----------------
Change Values Stored in Variables
The value of a variable can change as the program runs, which is why it is
called a variable. For example,
age = 25
print(age)

age = 100
print(age)

Assign Value of One Variable to Another


You can also assign the value of one variable to another.
color1 = "blue"
print(color1) # Output: blue

color2 = "pink"

# Assign the value stored in color2 to color1


color1 = color2

print(color1) # Output: pink


print(color2) # Output: pink
Assign Value of One Variable to Another
# Create a variable
city1 = "Paris"

# Assign city2 to city1


city1 = city2

print(city1)
Assign One Variable to Other
Write a program to assign one variable to another.

Create a variable named favorite_food with the value "steak".


Print the value of favorite_food.
Create another variable named food with the value "pizza".
Assign the food variable to the favorite_food variable.
Print the favorite_food variable again.
Legal Variables Name
There are certain rules for naming variables. Let's learn about them.
A variable name can only consist of three elements:

alphabets
numbers
underscores
Do not use spaces or any other symbols when naming a variable. If a
variable name consists of two words, separate them with an underscore, _ or
use camelCase.

For example, first name and first-name are not valid variable names, but
first_name and firstName are valid.

Introduction to Output
We have previously used print() to display a single value or variable. Here's a
quick recap:
# Print an integer
print(34) # Output: 34

# Print a string
print("Squid Game") # Output: Squid Game

# Create a variable
city = "London"

# Print the city variable


print(city) # Output: London
Print Multiple Values
We can print multiple pieces of data at once by separating them with
commas. For example:
# Display three numbers
print(67, -5, 19)

# Display two strings


print("Hey.", "Are you enjoying the course?")

# Display numbers and strings


print("Rating:", 8.5)
Print Strings and Variables
You can also display values and variables using a single print() function. For
example:
name = "Jack"
print("Name:", name)
Print a String and a Number
Write a program to print a string and a number using a single print()
function.

Define a variable age with value 19.


Create another variable message to store the string "My age is:".
Use a single print() function to display the message and age variables
together.
Print Newline (Enter Key)
It's possible to use a single print() function to display output in multiple lines.

To do this, we use the newline character \n in the position where we want to


break the line:
print("Welcome to Programiz\nThe Amazing Spider-Man")

—----------------

A) Assigning single value to multiple variables:

name = "Rajesh" ; age=35 ; marks=78.67

print(name)
print(age)
print(marks)

print(name,age,marks);

B) Assigning single value to multiple variables

x=y=z=151;
print(y)

c) Assigning multiple values to multiple variables


p,q,r = 10,20,30;
print(p);

d) Local Variables
def displayvaribles():
d=20;
e=30;
f= d+e;
print("The sum of D and E is ",f)

displayvaribles()

#print(d)
e)Global Variables
p=121;
def displayvaribles2():
global p;
print(p)
p="Hello World"
print(p)

displayvaribles2();

f)Delete a variable

q1= 20;
print(q1)
del q1;
print(q1)

6)Function
—-----------------------------------------------------------------------------

A)Functions Introduction
As you write more complex programs, you'll quickly encounter repetitive
code. Consider this program to find the total after a discount for a customer:

total = float(input("Total? "))


discount_percent = 10

if total > 100:


excess = total - 100
discount = (discount_percent / 100) * excess
total = total - discount

print(f"The final amount to pay is: ${total}")

If you have multiple customers, you'd need to repeat the same code for each
one, which would make your program long and difficult to manage.

In such cases, you can wrap the repetitive code inside a function and use it
when needed.

Let's learn how to create functions next.

B)Creating a Function
Suppose you have these two statements:

print("Hello")
print("How do you do?")

Let's wrap this code inside a function.


def webphplearn():
print("Hello")
print("How do you do?")

If you run this program, you'll not see any output.

Few Notes:

You can give any name to a function, just like variables. In this program, our
function name is webphplearn.
A function name must be followed by parentheses () at the end.
Similar to if statements and loops, indentation is used to define the body of a
function.
Next, we'll use this function.

Call a Function

# Function definition
def webphplearn():
print("Hello")
print("How do you do?")

Creating a function doesn't automatically run it. It simply makes the code
available for your use whenever you need to.

To use this function, you need to call it. Here's how:


# Function definition
def webphplearn():
print("Hello")
print("How do you do?")

# Function call
webphplearn()

print("Next statement")

In this program, we've defined a function named greet().

To run the code inside the function, call it using its name followed by
parentheses: webphplearn().

When you call the function:

The control of the program jumps to the function definition.


The statements inside the function are executed.
Once all the statements are executed, the control of the program returns to
where the function was called. Then, the program continues executing the
next statement outside the function.
Run the visualizer below to understand the program's flow in detail:

Using a Function Multiple Times


Once you create a function, you can use it as many times as you want. For
example:
# Function definition
def webphplearn():
print("Hello")
print("How do you do?")

# Call the webphplearn() function


webphplearn()

print("------")

# Call the webphplearn() function again


webphplearn()

Output

Hello
How do you do?
------
Hello
How do you do?

In the program, we've called the webphplearn() function twice.


If you're unsure how this program works, click the Visualize Code button
above to see it in action step by step.

Function Call Inside a Loop


You can even place the function call inside a loop to run it multiple times. Try
it out—run the code and see the output for yourself!
# Function definition
def webphplearn():
print("Hello")
print("How do you do?")

# Run the loop five times


for i in range(1, 6):
webphplearn()

In the program, we've used a for loop to iterate five times. Each time the
loop runs, the greet() function is called, so the function is executed a total of
five times.

Don't Make this Mistake


Many beginners mistakenly define functions inside a loop to run them
multiple times, but this is incorrect. A function should be defined only once.

After defining a function, you can place the function call inside a loop to
execute it multiple times.
Call a Function
Write a program to call a function.

Define a function named print_numbers().


Inside the function, put two print statements:print(5)print(100)
Call the print_numbers() function twice.

Making Functions Dynamic


The webphplearn() function we previously created was very inflexible; the
output of the function was always the same. Now, we will learn to make our
functions more dynamic.

It is possible to create functions that can take input and return output. In
programming terms:
Argument: Refers to the input passed to the function.
Return value: Refers to the output produced by the function.
Let's take a look at arguments first. Then, we will learn about return value.
Function Arguments
Here's a slight modification to the webphplearn() function we previously
created:
# Function definition
def webphplearn(name):
print("Hello", name)
print("How do you do?")

# Function call
webphplearn("Kamal")
When you define the function using def webphplearn(name):, two key things
happen:

A function named webphplearnis created.


A placeholder variable name is set up inside the function to accept a value
(called an argument).
You provide a value to this name variable when you call the function:
# Function call
webphplearn("Kamal")
Here,

The string "Kamal" is passed as an argument during the function call.


This value is assigned to the name variable inside the function.
Sounds confusing?

Don't worry! Next, we'll explore how this function works in detail.
Working of the Function
Here's how the program on the previous page works:
When the webphplearn() function is called, the control of the program jumps
to that function (as before).

However, this time, we are passing "Kamal" as an argument to the function.


This value is assigned to the name variable inside the function.

As a result, the statement:

print("Hello", name)
prints:

Hello Kamal
The output of this program varies based on the argument passed during the
function call. Run the visualizer below to understand the program's flow and
how arguments work step by step.
# Function definition
def webphplearn(name):
print("Hello", name)
print("How do you do?")

# Function call with "Kamal" as argument


webphplearn("Kamal")

# Function call with "Adam" as argument


webphplearn("Raman")
Output

Hello Kamal
How do you do?
Hello Raman
How do you do?

—------------------------------------------------------------------------------

Passing multiple arguments to a function

def printmyname(myname):
print("my name is "+myname)

printmyname('Kirti')
printmyname('Rajesh')

def printmyfullname(firstname,lastname):
print("my name is "+firstname + " " + lastname)

printmyfullname('rajesh','kumar')

Passing * as an argument to retrieve multiple parameters

def printmyfullnameargs(*random):
print("my name is "+random[0] + " " + random[1])

printmyfullnameargs('rajesh','kumar')

Default parameter
def printmyname1(myname ='kirti'):
print("my name is "+myname)

printmyname1('David')

books = ['hindi','english','math']
def readmybooks(books):
for book in books:
print(book)

readmybooks(books)
Return a value

def addsomthing(xyz):
return 10 * xyz ;

print(addsomthing(13))

#pass keyword

def passmyfunction():
pass

Recursive function:- function within function

A recursive function in Python is a function that calls itself during its


execution. This technique is used to solve problems that can be broken down
into smaller, similar subproblems.
Key components of a recursive function:
Base Case:
This is the condition that terminates the recursion. Without a base case, the
function would call itself indefinitely, leading to an infinite recursion and
eventually a RecursionError. The base case provides a direct solution for the
simplest instance of the problem.
Recursive Case:
This part of the function involves breaking down the problem into smaller,
similar subproblems and calling the function itself with these smaller inputs.
The function continues to call itself until the base case is reached.

def recursivefunction(y):
print(y)
if(y>5):
x = y + recursivefunction(y-1)
print(x)
else:
x=0;
return x

recursivefunction(10)
#lambda function

A lambda function in Python is a small, anonymous function defined using


the lambda keyword. Unlike standard functions defined with def, lambda
functions are typically used for single-expression operations and do not
require a return statement, as the expression's result is automatically
returned.
Key characteristics of lambda functions:
Anonymous: They are not bound to a name unless explicitly assigned to a
variable.
Single Expression: They can take any number of arguments but can only
contain one expression.
Concise: Their single-line nature makes them suitable for simple, on-the-fly
operations.
Commonly used with Higher-Order Functions: They are frequently
passed as arguments to functions like map(), filter(), and sorted(), which
accept other functions as input.
Examples :-
# A lambda function to add two numbers
add_numbers = lambda a, b: a + b
print(add_numbers(5, 3)) # Output: 8

# Using a lambda function with filter()


numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]

Data Types of Python

Text Type: str

Numeric int, float, complex


Types:
Sequence list, tuple, range
Types:

Mapping dict
Type:

Set Types: set, frozenset

Boolean bool
Type:

Binary bytes, bytearray, memoryview


Types:

None Type: NoneType

x= "hello world" #String


y = 20 #integer
z = 20.06 #float
a = 1j #complex
b = ["hello","world"] #list
c = ("hello","world") #touple
d= range(10) #range
e= {"name":'rajesh',"address":'faridabad'} # dic
f= {"hello","world"} #set;
g = frozenset({"hello","world"}) #frozenset
h = True #boolion

How to set a Data type


y = int(20)

Python Numbers

y = 20 #integer
z = 20.06 #float
a = 1j #complex
integer
x= 10
x= 7678687687687687676;
x= -2222

float
y= 10.06
y= 7678687687687687676.99;
y= -2222.77

complex no
z = 2+1j
z= 1j
z= -5j

type conversion
q= int(10.06);
#strings

tt = "hello world"
print(tt)

String predefined methods

a= "hello world";
print(a)

b= '''
hello david how
are you
hello Rajesh
how are you
hello kirti how are
you
hello kirti how are
you

''';
print(b);

c= " Kirti is nice ";


#print(c[4]);
#print(c[3]);
for x in c:
print(x);

print(len(c));
print('nice' in c);
if 'nice' in c:
print('yes the content is present');
else:
print('NO the content is Not present');

if 'hello' not in c:
print('yes the content is not present');

f= 'hello world';

#slice [index:position]
print(f[3:7])
print(f[:9])
print(f[3:])
print(f[-7:-2])
#[-position,-postion]
print(f[-9:-4])
print(f.upper())
print(f.lower())
print(len(f))
print(f)
print(f.strip()) To remove space from both side

print(f.replace('hello','ok'))
print(f.split(' '));

Concatenate String

a= "hello";
b= "world";
d="news"
c= a+" "+b+" "+d;
print(c)

book = "Science"
mytext = "I love to read "+book +" Book";
print(mytext);
#Format method
socialbook= "social studies";
mytext = "I love to read {} Book";
print(mytext.format(socialbook));

seience = 'seience'
social = 'social'
english = 'english'
mytext = "I love to read {2} {1} {0} Book";
print(mytext.format(seience ,social,english))
# Escape strings
mytext ="my name is \"rajesh\""
mytext ="my name is \n rajesh"
print(mytext)

# Strings methods
#join()
#split()

#Data type Boolean


print(10>9)
print(10<9)
#if condition

a= 100;
b= 20;
if(a>b):
print("a is greater than b");
else:
print("b is greater than a")
#Nested If
a = 100
b = 60
if(a>50):
print("a is greater then 50")
elif(a>100):
print("a is greater then 100")
elif(a>200):
print(" a is greater then 200")
else:
print("a is less then 50")

#Python Operators

#Arithmetic operators
#Assignment operators
#Comparison operators
#Logical operators
#Identity operators
#Membership operators
#Bitwise operators

#Arithmetic operators
x= 103; y= 20;
z= x+y;
print(z)
z= x-y;
print(z)
z= x*y;
print(z)
z= x/y;
print(z)
z= x%y;
print(z)
z= x**y;
print(z)

#Assignment Operators
a = 101;
print(a)
a= a+5;
a+=5
print(a)
a= a-5;
print(a)
a*=5
print(a)

#Comparison Operators
a = 20;
b= 20;
if(a==b):
print("a is equal to b");
else:
print("a is not equal to b");

if(a!=b):
print("a is not equal to b");
else:
print("a is equal to b");

#logical operator

#Logical operators are used to combine conditional statements:


# and
# Returns True if both statements are true
x=10;
y=30;
#print(x>5 and y>200)

#Or
#Returns True if one of the statements is true
#print(x>5 or y>200)
#not
#Reverse the result, returns False if the result is true
print (not(x>5 and y>20))

#Identity Operator

#Identity operators are used to compare the objects,


# not if they are equal, but if they are actually the same object,
# with the same memory location:
#is
x=['english','hindi']
y=['english','hindi']
z = x;
print(x is z)
print(x==y)
print(z)
print(x)
f="10";
g="10";
q=f;
print(f is g)
print(f==g)
#is not
#Returns True if both variables are not the same object

print(x is not z)
print (x != z)
#Membership Operators
#in
#Returns True if a sequence with the specified value is present in the object
x=['english','hindi'];
print('hindi' in x)

# not in
#Returns True if a sequence with the specified value is not present in the
object

print('hindi' not in x)
print('hindi1' not in x)

#Bit wise operator


#bitwise operator
#AND
print(6&3)
#110 6
#010
#011 3

#110
#011
#-----
# 010 2

# 1000
# 1001
# 1010
# 1100
#OR
print(6|3)

#110
#011
#-----
# 111 7
#XOR
print(6|3)
#110
#011
#-----
# 101 5

#NOT
~3
# 011
# 100
#Zero fill left shift
#3<<2
#011
#01100 12
# right shift
#0100 4
#0001 1

You might also like