Core Python Notes
Core Python Notes
Basics of languages
What is language ?
Why it is required ?
Type of languages ?
What is Low level languages (Machine & assembly language)?
What is high level languages ()?
Type of Programming languages
Assembly C, C++
Machine Python
Java
PHP, etc
Python Introduction
Python is a :
1. Free and Open Source
2. General-purpose
3. High Level Programming language
Features/Advantages of Python:
1. Simple and easy to learn
2. Procedure and object oriented
3. Platform Independent
4. Portable
5. Dynamically Typed
6. Both Procedure Oriented and Object Oriented
7. Interpreted
8. Vast Library Support
Syntex:----
Example 1:-
C:
#include<stdio.h>
void main()
{
print("Hello world");
}
Python:
print("Hello World")
Python:
A,b=10,20
print("The Sum:",(a+b))
Limitations of Python:
1. Performance and Speed: Python is an interpreted language, which
means that it is slower than compiled languages like C or Java. This
can be a problem for certain types of applications that require high
performance, such as real-time systems or heavy computation.
2. Support for Concurrency and Parallelism: Python does not have
built-in support for concurrency and parallelism. This can make it
difficult to write programs that take advantage of multiple cores or
processors.
3. Static Typing: Python is a dynamically typed language, which means
that the type of a variable is not checked at compile time. This can
lead to errors at runtime.
4. Web Support: Python does not have built-in support for web
development. This means that programmers need to use third-party
frameworks and libraries to develop web applications in Python
5. Runtime Errors
Python can take almost all programming features from different languages:--
1. Functional Programming Features from C
2. Object Oriented Programming Features from C++
3. Scripting Language Features from Perl and Shell Script
4. Modular Programming Features from Modula-3(Programming Language)
2. Jython or JPython:
It is for Java Applications. It can run on JVM
3. IronPython:
It is for C#.Net platform
4. PyPy:
The main advantage of PyPy is performance will be improved because JIT
(just in time)compiler is available inside PVM.
5. RubyPython
For Ruby Platforms
6. AnacondaPython
It is specially designed for handling large volume of data processing.
Python Internal working
1. Source Code:
You write your Python code using plain text. This code can be written in .py files
or interactively using environments like Jupyter Notebooks.
2. Interpreter:
The interpreter reads the source code and breaks it into tokens, which are
small meaningful components like keywords, operators, identifiers, etc.
For example, in the line x = 10, the tokens would be:
o x (identifier)
o = (assignment operator)
o 10 (integer literal)
5. Compilation:
7. Memory Management:
Python's vast standard library provides modules and packages that extend its
functionality. External libraries can be added using package managers like
pip.
9. Exception Handling:
After execution, Python either returns results to the user or modifies the system
(e.g., by creating files, interacting with databases, etc.).
Example Flow:
x=5
y = 10
z=x+y
print(z)
Each of these steps occurs behind the scenes, making Python a powerful and
flexible language.
Source Binary_Code /
Byte_Code PVM O/P
Code/Program Machine_Code
Python interpretor
Examples:---
first.py:---
a = 10
b = 10
print("Sum ", (a+b))
Compilation
The program is converted into byte code. Byte code is a fixed set of instructions that
represent arithmetic, comparison, memory operations, etc. It can run on any operating
system and hardware. The byte code instructions are created in the .pyc file. The .pyc
file is not explicitly created as Python handles it internally but it can be viewed with the
following command:
-m and py_compile represent module and module name respectively. This module is
responsible to generate .pyc file. The compiler creates a directory named __pycache__
where it stores the first.cpython-310.pyc file.
Interpreter
The next step involves converting the byte code (.pyc file) into machine code.
This step is necessary as the computer can understand only machine code (binary
code). Python Virtual Machine (PVM) first understands the operating system and
processor in the computer and then converts it into machine code. Further, these
machine code instructions are executed by processor and the results are
displayed.
However, the interpreter inside the PVM translates the program line by line thereby
consuming a lot of time. To overcome this, a compiler known as Just In Time (JIT) is
added to PVM. JIT compiler improves the execution speed of the Python program. This
compiler is not used in all Python environments like CPython which is standard Python
software.
view the byte code of the file – first.py we can type the following command as :
first.py:
x = 10
y = 10
z=x+y
print(z)
The command python -m dis first.py disassembles the Python bytecode generated
from the source code in the file first.py.
When you run this command, Python compiles first.py into bytecode (if not
already compiled), and the dis module disassembles it. This helps you understand
the internal bytecode instructions that Python generates from your source code.
LOAD_CONST: Loads a constant value (like numbers 10 and 20).
STORE_NAME: Stores the value in a variable (like x, y, or z).
LOAD_NAME: Loads the value of a variable from memory.
BINARY_ADD: Adds two values (in this case, the values of x and y).
CALL_FUNCTION: Calls a function (like print).
RETURN_VALUE: Returns from a function (in this case, the main
program).
Token:-
In Python, a token is the smallest unit of the source code that the Python
interpreter recognizes during the process of lexical analysis (the first step in code
compilation or interpretation). Each token represents a meaningful element in
Python, such as
1. Keywords.
2. Punctuation/delimiters.
3. Identifiers.
4. Operators.
5. Literals
Keywords:
Punctuations:-
Operators:--
Literals in Python are constant values that are assigned to variables or used directly
in code. Python supports several types of literals:
1. String Literals: Enclosed in single ('...'), double ("..."), triple single ('''...'''),
or triple double quotes ("""...""").
2. Numeric Literals:
1. Integer Literals: Whole numbers, which can be written in
decimal, binary (0b...), octal (0o...), or hexadecimal (0x...)
form.
2. Float Literals: Numbers with a decimal point or in exponential
(scientific) notation.
3. Complex Literals: Numbers with a real and imaginary part,
defined by a number followed by a j or J.
3. Boolean Literals: True and False, which represent the two truth values of
Boolean logic.
4. Special Literal: None, which represents the absence of a value or a null
value.
5. Collection Literals: Literals for creating collections like lists, tuples,
dictionaries, and sets.
Variable in Python?
All the data which we create in the program will be saved in some memory
location on the system. The data can be anything, an integer, a complex number, a
set of mixed values, etc. A Python variable is a symbolic name that is a reference
or pointer to an object. Once an object is assigned to a variable, you can refer to the
object by that name.
3. Advance examples:-
Example:-
city = ["Bhopal", "Indore", "Jabalpur"]
x, y, z = city
print(x)
print(y)
print(z)
Python Comments:-
1. single line comments:--- ( # ---------------) ctrl+/
Ternary Operator – If the operator acts on three operands then it‟s called a
ternary operator. In general, the ternary operator is a precise way of writing
conditional statements.
Syntax:
x = true_value if condition else false_value
The three operands here are:
1. condition
2. true_value
3. False_value
# Ternary Operator
a, b = 10, 20
min = a if a < b else b
print("Ternary Operator(min): ",min)
O/P:- Ternary Operator(min): 10
a = 20
b = 12
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(ab)
print(a//b)
O/P:-
32
8
240
1.6666666666666667
8
4096000000000000
1
print(12//5)
print(12.0//5)
O/P:-
2
2.0
Relational Operators in Python:-
These are used to compare two values for some relation and return True or False
depending on the relation. Let‟s assume, a = 13 and b = 5.
O/P:-
True
True
False
False
False
True
Note: In logical operators, False indicates 0(zero) and True indicates non-zero
value. Logical operators on boolean types
1. and: If both the arguments are True then only the result is True
2. or: If at least one argument is True then the result is True
3. not: the complement of the boolean value
a = True
b = False
print(a and b)
print(a or b)
print(not a)
print(a and a)
O/P:-
False
True
False
True
and operator:
„A and B‟ returns A if A is False
„A and B‟ returns B if A is not False
Or Operator in Python:
„A or B‟ returns A if A is True
„A or B‟ returns B if A is not True
Not Operator in Python:
not A returns False if A is True
not B returns True if A is False
a=13
print(a)
a+=5
print(a)
O/P:-
13
18
O/P:-
10
-10
O/P:-
True
False
False
True
O/P:-
True
False
True
O/P:-
1487788114928
1487788114928
O/P:-
True
2873693373424
2873693373424
a = 25
b = 30
print(a is b)
print(id(a))
print(id(b))
O/P:-
False
1997786711024
1997786711184
Note: The „is‟ and „is not‟ operators are not comparing the values of the objects.
They compare the memory locations (address) of the objects. If we want to
compare the value of the objects. we should use the relational operator „==‟.
a = 25
b = 25
print(a == b)
O/P:-
True
age = 18
if age>=18:
print("eligible for vote")
else:
print("Not eligible for vote")
age = 17
if age>=18:
print("eligible for vote")
else:
print("Not eligible for vote")
O/P:-
eligible for vote
Not eligible for vote
A predefined function input() is available in python to take input from the
keyboard during runtime. This function takes a value from the keyboard and
returns it as a string type. Based on the requirement we can convert from string to
other types.
O/P:-
Enter Your age: 15
Traceback (most recent call last):
File "E:\DataSciencePythonBatch\input_output.py", line 16, in <module>
if age>=18:
TypeError: '>=' not supported between instances of 'str' and 'int'
We can convert the string to other data types using some inbuilt functions. We
shall discuss all the type conversion types in the later chapters. As far as this
chapter is concerned, it‟s good to know the below conversion functions.
1. string to int – int() function
2. string to float – float() function
age=input("Enter Your age: ")
print(type(age))
age=int(age)
print(type(age))
if age>=18:
print("eligible for vote")
else:
print("Not eligible for vote")
O/P:-
Enter Your age: 15
<class 'str'>
<class 'int'>
Not eligible for vote
z= x+y
print("Addition of x and y :",z)
O/P:-
Enter first No: 5
Enter second No: 4
Addition of x and y : 9
Eval() function in python:---
This is an in-built function available in python, which takes the strings as an input.
The strings which we pass to it should, generally, be expressions. The eval()
function takes the expression in the form of a string and evaluates it and returns the
result.
Examples,
print(eval('10+5'))
print(eval('10-5'))
print(eval('10*5'))
print(eval('10/5'))
print(eval('10//5'))
print(eval('10%5'))
O/P:-
15
5
50
2.0
2
0
O/P:
Enter expression: 12-2
10
Data Types:-
O/P---
emp_id type is: <class 'int'>
name type is: <class 'str'>
salary type is: <class 'float'>
O/P---
emp_id id is: 3146509648432
name id is: 3146515054320
salary id is: 3146510689840
emp_id = 11
name = 'Neeraj'
salary = 50000.40
print("My employee id is: ", emp_id)
print("My name is: ", name)
print("My salary is: ", salary)
O/P---
My employee id is: 11
My name is: Neeraj
My salary is: 50000.4
int data type:
The int data type represents values or numbers without decimal values. In python,
there is no limit for the int data type. It can store very large values conveniently.
a=10
type(a) O/P:- <class ‘int’>
Note: In Python 2nd version long data type was existing but in python 3rd version
long data type was removed.
1. Decimal form(base-10):
It is the default number system in Python. The allowed digits are: 0 to 9
Ex: a =10
2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Eg: a = 0B1111
a =0B123
a=b111
3. Octal Form(Base-8):
The allowed digits are : 0 to 7
Literal value should be prefixed with 0o or 0O.
Ex: a=0o123
a=0o786
Note: Being a programmer we can specify literal values in decimal, binary, octal
and hexa
decimal forms. But PVM will always provide values only in decimal form.
Base Conversions:--- Python provide the following in-built functions for base
conversions
# Base Conversions
# bin()
print(bin(15)) # o/p- 0b1111
print(bin(0o11)) # o/p- 0b1001
print(bin(0X10)) # o/p- 0b10000
# oct()
print(oct(10)) # o/p-0o12
print(oct(0B1111)) # o/p-0o17
print(oct(0X123)) # o/p-0o443
# hex()
print(hex(100)) # o/p-0x64
print(hex(0B111111)) # o/p-0x3f
print(hex(0o12345)) # o/p- 0x14e5
salary = 50.5
print(salary)
print(type(salary))
O/P---
50.5
<class 'float'>
O/P----
200.0
200.0
2000.0
20.0
<class 'float'>
O/P---
(3+5j)
(2-5.5j)
(3+10.5j)
A+B= (5-0.5j)
B+C= (5+5j)
C+A= (6+15.5j)
A*B= (33.5-6.5j)
B*C= (63.75+4.5j)
C*A= (-43.5+46.5j)
A+B+C= (8+10j)
A/B= (-0.6277372262773723+0.7737226277372262j)
a = True
b = False
print(a)
print(b)
print(a+a)
print(a+b)
O/P---
True
False
2
1
a = None
print(a)
print(type(a))
O/P------
None
<class 'NoneType'>
Sequences in python:
Sequences in Python are objects that can store a group of values. The below data
types are called sequences.
1. Str---Immutable
2. Bytes (as a list but in range of o to 256 (256 not included))--Immutable
3. Bytearray---- mutable
4. List-----mutable
5. Tuple----Immutable
6. Range
O/P---
Neeraj
Neeraj
Neeraj
Note: The bytes data type is immutable means we cannot modify or change the
bytes object. We can iterate bytes values by using for loop.
Example: creating a bytes data type:
O/P---<class 'bytes'>
O/P---
25
150
4
15
Example: Printing the byte data type values using for loop
O/P---
15
25
150
4
15
y = bytes(x)
y = bytes(x)
y[0] = 30
The bytearray data type is the same as the bytes data type, but bytearray is mutable
means we can modify the content of bytearray data type. To create a bytearray
1. We need to create a list
2. Then pass the list to the function bytearrray().
3. We can iterate bytearray values by using for loop.
y = bytearray(x)
print(y[0])
print(y[1])
print(y[2])
print(y[3])
print(y[4])
Example: Printing the byte data type values using for loop
x = [10, 20, 00, 40, 15]
y = bytearray(x)
for a in y:
print(a)
y = bytearray(x)
y = bytearray(x)
y[0] = 30
For example, if we have a string "HELLO", we can access the first letter "H" using
its index 0 by using the square bracket notation: string[0]
Positive Index 0 1 2 3 4
H E L L O
Negative Index -5 -4 -3 -2 -1
Python's built-in index() function is a useful tool for finding the index of a specific
element in a sequence. This function takes an argument representing the value to
search for and returns the index of the first occurrence of that value in the
sequence.
If the value is not found in the sequence, the function raises a ValueError. For
example, if we have a list [1, 2, 3, 4, 5], we can find the index of the value 3 by
calling list.index(3), which will return the value 2 (since 3 is the third element in
the list, and indexing starts at 0).
Python Index Examples
The method index() returns the lowest index in the list where the element searched
for appears. If any element which is not present is searched, it returns
a ValueError.
Example:--
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 3
print(list.index(element))
O/P:-
2
O/P:-
Traceback (most recent call last):
File "e:\DataSciencePythonBatch\index.py", line 7, in <module>
print(list.index(element))
ValueError: 3 is not in list
Example:--(Index of a string element)
list = [1, 'two', 3, 4, 5, 6, 7, 8, 9, 10]
element = 'two'
print(list.index(element))
O/P:-
1
What does it mean to return the lowest index?
list = [3, 1, 2, 3, 3, 4, 5, 6, 3, 7, 8, 9, 10]
element = 3
print(list.index(element))
O/P:-
0
Find element with particular start and end point:--
Example:- index() provides you an option to give it hints to where the value
searched for might lie.
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
element = 7
print(list.index(element, 5, 8))
O/P:-
6
-----: Slicing in Python:-----
P R O G R A M M I N G
P R O O G R A R A M M M I N G
Slicing is the extraction of a part of a string, list, or tuple. It enables users to access
the specific range of elements by mentioning their indices.
Step1:-- Need to check step direction by default it‟s goes to positive direction.
O/P:-
I love python
Ex:2
O/P:-
nohtyp evol I
Ex:-3
O/P:-
Ex:-4
O/P:-
Ex:-5
O/P:-
Ilv yhn
Ex:-6
Ex:-7,8,9,10,11,12
O/P:--
Welcome to 'python' learning
Welcome to "python" learning
Welcome "to" 'python' learning
In-built functions:--
str1="Neeraj"
print(max(str1))
print(min(str1))
print(len(str1))
print(type(str1))
O/P:--
r
N
6
<class 'str'>
78
101
101
114
97
106
ASCII value of X= 35
Indexing:
Indexing means a position of string‟s characters where it stores. We need to use
square brackets [] to access the string index. String indexing result is string type.
String indices should be integer otherwise we will get an error. We can access the
index within the index range otherwise we will get an error.
Python supports two types of indexing
O/P:--
Hello World
Hello World
Hello Wor
HloWr
ll
HloWrd
llo World
Hell
orl
name = "Python"
print(name)
print(name[0])
name[0]="X"
O/P:-
Python
P
Traceback (most recent call last):
File "e:\DataSciencePythonBatch\string.py", line 15, in <module>
name[0]="X"
TypeError: 'str' object does not support item assignment
O/P:--
PythonProgramming
a = "Python"
b = "Programming"
print(a+" "+b)
O/P:--
Python Programming
O/P:--
PythonPythonPython
O/P:--
Length of string is: 6
Membership Operators in Python:
We can check, if a string or character is a member/substring of string or not by
using the below operators:
1. In
2. not in
in operator:---
in operator returns True, if the string or character found in the main string.
print('p' in 'python')
print('z' in 'python')
print('on' in 'python')
print('pa' in 'python')
O/P:--
True
False
True
False
O/P:--
Enter main string:Neeraj
Enter substring:raj
raj is found in main string
Pre-define methods:--
O/P:--
converted to using upper(): PYTHON PROGRAMMING LANGUAGE
converted to using upper (): JAVA PROGRAMMING LANGUAGE
converted to using upper (): WE ARE SOFTWARE DEVELOPER
O/P:--
converted to using lover(): python programming language
converted to using lover (): java programming language
converted to using lover (): we are software developer
O/P:--
converted to using title(): PYTHON PROGRAMMING LANGUAGE
converted to using title(): java PROgRAMMING LAngUAGE
converted to using title(): we are software developer
4. title() – This method converts all character to title case (The first character
in every word will be in upper case and all remaining characters will be in
lower case)
O/P:--
converted to using title(): Python Programming Language
converted to using title(): Java Programming Language
converted to using title(): We Are Software Developer
5. capitalize() – Only the first character will be converted to upper case and all
remaining characters can be converted to lowercase.
str1 = 'python programming language'
print('converted to using capitalize():', str1.capitalize())
O/P:--
converted to using capitalize(): Python programming language
converted to using capitalize (): Java programming language
converted to using capitalize (): We are software developer
6. center():-Python String center() Method tries to keep the new string length
equal to the given length value and fills the extra characters using the
default character (space in this case).
new_str = str.center(40)
# here fillchar not provided so takes space by default.
print("After padding String is: ", new_str)
O/P:--
python programming language .
new_str = str.center(40,'#')
# here fillchar not provided so takes space by default.
print("After padding String is: ", new_str)
O/P:--
######python programming language#######
O/P:--
python programming language
O/P:--
ount of given charactor is: 2
O/P:--
count of given charactor is: 0
8. Join():--- The string join() method returns a string by joining all the
elements of an iterable (list, string, tuple), separated by the given separator.
The join() method takes an iterable (objects capable of returning its members one
at a time) as its parameter.Some of the example of iterables are: Native data types -
List, Tuple, String, Dictionary and Set.
O/P:--
Python is a programming language
str = ['Python', 'is', 'a', 'programming', 'language']
# join elements of text with space
print('_'.join(str))
O/P:-
Python_is_a_programming_language
O/P:--
1, 2, 3, 4
# .join() with tuples
numTuple = ('1', '2', '3', '4')
print(separator.join(numTuple))
O/P:--
1, 2, 3, 4
s1 = 'abc'
s2 = '123'
# each element of s2 is separated by s1
# '1'+ 'abc'+ '2'+ 'abc'+ '3'
print('s1.join(s2):', s1.join(s2))
O/P:--
s1.join(s2): 1abc2abc3
O/P:--
s2.join(s1): a123b123c
O/P:--
2, 3, 1
O/P:--
Ruby->->Java->->Python
O/P:--
mat->that
9. split():-- The split() method splits a string at the specified separator and
returns a list of substrings.
O/P:--
['Python', 'is', 'a', 'programming', 'language']
['Python is a programming language']
['Python is a programming language']
['Python', 'is a programming language']
['Python is a programming language']
---: List :---
Whenever we want to create a group of objects where we want below mention
properties, then we are using list sequence.
O/P:--
['neeraj', 10, 20, 30, 10, 20]
2. Order is preserved:
List=['neeraj', 10,20,30,10,20]
x=0
for i in List:
print('List[{}] = '.format(x),i)
x=x+1
O/P:--
List[0] = neeraj
List[1] = 10
List[2] = 20
List[3] = 30
List[4] = 10
List[5] = 20
O/P:--
List[0] = neeraj
List[1] = 10
List[2] = 20
List[3] = 30
List[4] = 10
List[5] = 20
['Arvind', 10, 20, 30, 10, 20]
O/P:--
neeraj
10
20
30
10
20
List=['neeraj', 10,20,30,10,20]
print(List[:5])
O/P:--
['neeraj', 10, 20, 30, 10]
List=['neeraj', 10,20,30,10,20]
print(List[::-1])
O/P:--
[20, 10, 30, 20, 10, 'neeraj']
1. len(list)
2. max(list) - homogeneous collection required
3. min(list) - homogeneous collection required
4. sum(list) - integer homogeneous collection required
5. list(tuple)
6. type(list)
7. id()
8. list()
Methos:--
O/P:--
Updated animals list: ['cat', 'dog', 'rabbit', 'rat']
O/P:--
Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]
O/P:--
Count of 2: 3
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
count = vowels.count('i')
print('The count of i is:', count)
count = vowels.count('p')
print('The count of p is:', count)
O/P:--
The count of i is: 2
The count of p is: 0
# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]
count = random.count(('a', 'b'))
print("The count of ('a', 'b') is:", count)
count = random.count([3, 4])
print("The count of [3, 4] is:", count)
O/P:--
The count of ('a', 'b') is: 2
The count of [3, 4] is: 1
# create a list
list1 = [2, 3, 5]
list2 = [1, 4]
list1.extend(list2)
print('List after extend():', list1)
O/P:--
List after extend(): [2, 3, 5, 1, 4]
list = ['Hindi']
tuple = ('Spanish', 'English')
set = {'Chinese', 'Japanese'}
list.extend(tuple)
print('New Language List:', list)
list.extend(set)
print('Newer Languages List:', list)
O/P:--
Example:---
numbers = ['Neeraj',2, 3, 5, 7]
numbers.reverse()
print('Reversed List:', numbers)
O/P:--
Reversed List: [7, 5, 3, 2, 'Neeraj']
Example:----
numbers = ['Neeraj',2, 3, 5, 7]
print(numbers[::-1])
O/P:--
[7, 5, 3, 2, 'Neeraj']
Example:----
numbers = ['Neeraj',2, 3, 5, 7]
# print(numbers[::-1])
list=[]
for i in reversed(numbers):
list.append(i)
print(list)
O/P:--
[7, 5, 3, 2, 'Neeraj']
8. list.sort(reverse=True/False) default-False
Example:---
numbers = [2, 3, 7, 5, 4]
numbers.sort()
print('Sort_List:', numbers)
O/P:--
Sort_List: [2, 3, 4, 5, 7]
Example:---
numbers = [2, 3, 7, 5, 4]
numbers.sort(reverse=True)
print('Sort_List:', numbers)
O/P:--
Sort_List: [7, 5, 4, 3, 2]
---:Tuple :---
In Python, tuples are immutables. Meaning, you cannot change items of a tuple
once it is assigned. There are only two tuple methods count() and index() that a
tuple object can call.
Tuple occupies less memory as compare to list, that‟s why tuple is more faster as
compare to list.
Example:--
list = [10,20,30,40,50,60,70]
tuple = (10,20,30,40,50,60,70)
print(sys.getsizeof('Size of list = ',list))
print(sys.getsizeof('Size of tuple',tuple))
O/P- 64
62
Built-in functions:-
# Creating tuples
Tuple = (0, 1, (2, 3), (2, 3), 1, [3, 2],'Neeraj', (0), (0,))
res = Tuple.count((2, 3))
print('Count of (2, 3) in Tuple is:', res)
res = Tuple.count(0)
print('Count of 0 in Tuple is:', res)
res = Tuple.count((0,))
print('Count of (0,) in Tuple is:', res)
O/P:--
Count of (2, 3) in Tuple is: 2
Count of 0 in Tuple is: 2
Count of (0,) in Tuple is: 1
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple.index(3)
print(res)
O/P:--
3
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
print(Tuple.index(3,4))
O/P:--
5
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
print(Tuple.index(3,0,4))
o/p:--
3
---: Dictionary :---
If we want to represent a group of objects as key-value pairs then we should go for
dictionaries.
Characteristics of Dictionary
1. Dictionary will contain data in the form of key, value pairs.
2. Key and values are separated by a colon “:” symbol
3. One key-value pair can be represented as an item.
4. Duplicate keys are not allowed.
5. Duplicate values can be allowed.
6. Heterogeneous objects are allowed for both keys and values.
7. Insertion order is not preserved.
8. Dictionary object having mutable nature.
9. Dictionary objects are dynamic.
10.Indexing and slicing concepts are not applicable
O/P:--
{}
<class 'dict'>
Adding the items in empty dictionary:--
d = {}
d[1] = "Neeraj"
d[2] = "Rahul"
d[3] = "Ravi"
print(d)
O/P:--
{1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
Accessing dictionary values by using keys:--
print(d[1])
print(d[2])
print(d[3])
O/P:--
Neeraj
Rahul
Ravi
Note:--- While accessing, if the specified key is not available then we will
get KeyError
print(d[1])
print(d[2])
print(d[3])
print(d[10])
O/P:--
Neeraj
Rahul
Ravi
Traceback (most recent call last):
File "E:\DataSciencePythonBatch\dict.py", line 16, in <module>
print(d[10])
KeyError: 10
if 10 in d:
print(d[10])
else:
print('Key Not found')
O/P:--
Key Not found
d={}
n=int(input("Enter how many student detail you want: "))
i=1
while i <=n:
name=input("Enter Employee Name: ")
email=input("Enter Employee salary: ")
d[name]=email
i=i+1
print(d)
O/P:--
Enter how many student detail you want: 3
Enter Employee Name: Neeraj
Enter Employee salary: [email protected]
Enter Employee Name: Rahul
Enter Employee salary: [email protected]
Enter Employee Name: Ravi
Enter Employee salary: [email protected]
{'Neeraj': '[email protected]', 'Rahul': '[email protected]', 'Ravi':
'[email protected]'}
d[key] = value
Case1: While updating the key in the dictionary, if the key is not available then a
new key will be added at the end of the dictionary with the specified value.
O/P:--
Old dict data {1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
Nwe dict data {1: 'Neeraj', 2: 'Rahul', 3: 'Ravi', 10: 'Arvind'}
Case2: If the key already exists in the dictionary, then the old value will be
replaced with a new value.
d={1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
print("Old dict data",d)
d[2]="Arvind"
print("New dict data",d)
O/P:--
Old dict data {1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
New dict data {1: 'Neeraj', 2: 'Arvind', 3: 'Ravi'}
O/P:--
New dict is {1: 'Neeraj', 2: 'Rahul'}
Delete entire dictionary object:- We can also use the del keyword to delete the
total dictionary object. Before deleting we just have to note that once it is deleted
then we cannot access the dictionary.
5. copy() # x.copy()
6. get() # x.get(„key‟)
7. clear() # x.clear()
8. pop() # x.pop(„key‟)
9. popitem() # x.popitem()
10. key() # x.keys()
11. values() # x.values()
12. items() # x.items()
dict() function:
This can be used to create an empty dictionary.
d=dict()
print(d)
print(type(d))
O/P:--
{}
<class 'dict'>
len() function: This function returns the number of items in the dictionary.
d={1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
print(len(d))
O/P:--
3
clear() method: This method can remove all elements from the dictionary.
d={1: 'Neeraj', 2: 'Rahul', 3: 'Ravi'}
print(d.clear())O/P:--
O/P:--
None
get() method:
This method used to get the value associated with the key. This is another way to
get the values of the dictionary based on the key. The biggest advantage it gives
over the normal way of accessing a dictionary is, this doesn‟t give any error if the
key is not present. Let‟s see through some examples:
Case1: If the key is available, then it returns the corresponding value otherwise
returns None. It won‟t raise any errors.
Syntax: d.get(key)
O/P:--
Neeraj
Rahul
Ravi
Case 2: If the key is available, then returns the corresponding value otherwise
returns the default value that we give.
Syntax: d.get(key, defaultvalue)
O/P:--
Neeraj
Neeraj
Neeraj
pop() method: This method removes the entry associated with the specified key
and returns the corresponding value. If the specified key is not available, then we
will get KeyError.
Syntax: d.pop(key)
O/P:
{1: 'Neeraj', 2: 'Rahul'}
O/P:--
(5, 'Santosh')
{1: 'Neeraj', 2: 'Rahul', 3: 'Ravi', 4: 'Jai'}
keys() method:This method returns all keys associated with the dictionary
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d)
for k in d.keys():
print(k)
O/P:--
1
2
3
values() method: This method returns all values associated with the dictionary
d = {1: 'Ramesh', 2: 'Suresh', 3: 'Mahesh'}
print(d)
for k in d.values():
print(k)
O/P:--
Ramesh
Suresh
Mahesh
O/P:--
1 --- Ramesh
2 --- Suresh
3 --- Mahesh
---: Set :---
If we want to represent a group of unique elements then we can go for sets. Set
cannot store duplicate elements.
# Creating a set
s = {10,20,30,40}
print(s)
print(type(s))
O/P:--
{40, 10, 20, 30}
<class 'set'>
O/P:--
{'20', True, 234.56, 10, 'Rahul'}
<class 'set'>
O/P:--
{0, 1, 2, 3, 4}
# Duplicates not allowed
s = {10, 20, 30, 40, 10, 10}
print(s)
print(type(s))
O/P:--
{40, 10, 20, 30}
<class 'set'>
O/P:--
set()
<class 'set'>
# Methods in set:----
s={10,20,30,50}
s.add(40)
print(s)
O/P:--
{40, 10, 50, 20, 30}
2. update(iterable_obj1,iterable_obj2)
s = {10,20,30}
l = [40,50,60,10]
s.update(l)
print(s)
O/P:--
{40, 10, 50, 20, 60, 30}
s = {10,20,30}
l = [40,50,60,10]
s.update(l, range(5))
print(s)
O/P:--
{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}
Difference between add() and update() methods in set:
3. We can use add() to add individual items to the set, whereas we can use
update() method to add multiple items to the set.
4. The add() method can take one argument whereas the update() method can
take any number of arguments but the only point is all of them should be
iterable objects.
s={10,20,30}
s1=s.copy()
print(s1)
O/P:--
{10, 20, 30}
4. pop()--- This method removes and returns some random element from the
set.
s = {40,10,30,20}
print(s)
print(s.pop())
print(s)
O/P:--
{40, 10, 20, 30}
40
{10, 20, 30}
5. remove(element) --- This method removes specific elements from the set. If
the specified element is not present in the set then we will get KeyError.
s={40,10,30,20}
s.remove(30)
print(s)
O/P:--
{40, 10, 20}
s={40,10,30,20}
s.remove(50)
print(s)
O/P:--
Traceback (most recent call last):
File "E:\DataSciencePythonBatch\sets.py", line 65, in <module>
s.remove(50)
KeyError: 50
6. discard(element) --- This method removes the specified element from the
set. If the specified element is not present in the set, then we won‟t get any
error.
s={10,20,30}
s.discard(10)
print(s)
O/P:--
{20, 30}
s={10,20,30}
s.discard(40)
print(s)
O/P:--
{10, 20, 30}
s={10,20,30}
print(s)
s.clear()
print(s)
O/P:--
{10, 20, 30}
set()
MATHEMATICAL OPERATIONS ON SETS
1. union() --- This method return all elements present in both sets.
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y))
O/P:--
{40, 10, 50, 20, 60, 30}
x = {10,20,30,40}
y = {30,40,50,60}
print(x.intersection(y))
print(x&y)
print(y.intersection(x))
print(y&x)
O/P:--
{40, 30}
{40, 30}
{40, 30}
{40, 30}
3. difference() --- This method returns the elements present in x but not in y
In programming languages, flow control means the order in which the statements
or instructions, that we write, get executed. In order to understand a program, we
should be aware of what statements are being executed and in which order. So,
understanding the flow of the program is very important. There are, generally,
three ways in which the statements will be executed. They are,
1. Sequential
2. Conditional
3. Looping
Sequential: In this type of execution flow, the statements are executed one after
the other sequentially. By using sequential statements, we can develop simple
programs
O/P:-
Welcome
to
python class
Example:-
O/P:
Enter any no: 10
out of if block statements
PS E:\DataSciencePythonBatch> python control.py
Enter any no: 18
if block statment executed
out of if block statements
Example:---
if condition:
print("if block statement executed")
else:
print("else block statement executed ")
Example:---
O/P:-
PS E:\DataSciencePythonBatch> python control.py
Enter any no: 18
if block statment executed
PS E:\DataSciencePythonBatch> python control.py
Enter any no: 15
else block statement executed
Example:---
O/P:-
Example:---
O/P:-
Enter your age: 35
You are eligible to vote.
Example:---
O/P:-
Enter a year: 2000
It's a leap year.
Nested-If else:--
O/P:-
Enter your score: 90
You got an A.
Example:--
if (condition1):
statement of if Block
elif(condition2):
statment of elif Block
elif(condition3):
statement if elif block
else:
ststement of else block
Example:---
O/P:-
Enter a number: 5
Beyond the range than specified
PS E:\DataSciencePythonBatch> python control.py
Please enter the values from 0 to 4
Enter a number: 4
You entered: 4
O/P:-
Enter a number: 4
The square root of 4.000 is 2.000
PS E:\DataSciencePythonBatch> python control.py
Enter a number: 8
The square root of 8.000 is 2.828
O/P:---
Enter first side: 5
Enter second side: 6
Enter third side: 7
The area of the triangle is : 14.696938456699069
Example:-- Python program to swap two variables.
# Python program to swap two variables
x = input('Enter value of x: ')
y = input('Enter value of y: ')
O/P:---
Enter value of x: 5
Enter value of y: 8
The value of x after swapping: 8
The value of y after swapping: 5
O/P:---
Enter value of x: 4
Enter value of y: 6
The value of x after swapping: 6
The value of y after swapping: 4
O/P:---
Enter value of x: 4
Enter value of y: 6
The value of x after swapping: 6
The value of y after swapping: 4
# By-using Multiplication and division.
x = int(input('Enter value of x: '))
y = int(input('Enter value of y: '))
x=x*y
y=x/y
x=x/y
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
O/P:---
Enter value of x: 2
Enter value of y: 5
The value of x after swapping: 5.0
The value of y after swapping: 2.0
O/P:--
Enter value of x: 10
Enter value of y: 20
The value of x after swapping: 20
The value of y after swapping: 10
Range()
Range() function is used to generate collection in python.
Syntax:
range(start,stop/end,step/direction)
Note :-
my_range = range(1,11)
print(list(my_range))
my_range = range(1,11,-1)
print(list(my_range))
my_range = range(-1,-11,-1)
print(list(my_range))
my_range = range(-1,-11,1)
print(list(my_range))
my_range = range(11)
print(list(my_range))
O/P:--
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[]
[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
[]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_range = range(2,11,2)
print(list(my_range))
my_range = range(1,10,2)
print(list(my_range))
my_range = range(-2,-11,-2)
print(list(my_range))
my_range = range(-1,-10,-2)
print(list(my_range))
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]
[-2, -4, -6, -8, -10]
[-1, -3, -5, -7, -9]
my_range = range(5,2,-1)
print(list(my_range))
my_range = range(-5,-2,1)
print(list(my_range))
my_range = range(5,6,1)
print(list(my_range))
my_range = range(-5,-6,-1)
print(list(my_range))
O/P:--
[5, 4, 3]
[5]
[-5]
----:LOOPING Statement in Python (Iterations):----
1. while loop
2. for loop
1. while loop:- The while loop contains an expression/condition. As per the syntax
colon (:) is mandatory otherwise it throws a syntax error. The condition gives the
result as bool type, either True or False. The loop keeps on executing the
statements until the condition becomes False. i.e. With the while loop we can
execute a set of statements as long as a condition is true.
This is the first part of the while loop. Before entering the condition section, some
initialization is required.
Condition:
Once the initializations are done, then it will go for condition checking which is the
heart of the while loop. The condition is checked and if it returns True, then
execution enters the loop for executing the statements inside.
print("End")
print(sum)
# print n even numbers
x= int(input("Enter how many even number you want :"))
n=1
while n<=x:
print(2*n)
n=n+1
Break statement:--- We can use break statement inside loops to break loop
execution based on some condition.
for i in range(10):
if i==7:
print("processing is enough.. plz break !!!!!!! ")
break
print(i)
O/P:---
0
1
2
3
4
5
6
processing is enough.. plz break !!!!!!!
list=[10,20,600,60,70]
for i in list:
if i>500:
print("no need to check next object of list")
break
print(i)
O/P:--
10
20
no need to check next object of list
continue statement:-- We can use continue statement to skip current iteration and
continue next iteration.
for i in range(10):
if i%2==0:
continue
print(i)
O/P:--
1
3
5
7
9
list=[10,20,600,60,70]
for i in list:
if i>500:
print("no need to print this object")
continue
print(i)
O/P:--
10
20
no need to print this object
60
70
list=[10,20,600,60,70]
for i in list:
if i>500:
continue
print(i)
O/P:--
10
20
60
70
pass statement:--
pass is a keyword in Python. In our programming syntactically if block is required
which won't do anything then we can define that empty block with pass keyword.
1. It is an empty statement
2. It is null statement
3. It won't do anything
for i in range(100):
if i%9==0:
print(i)
else:
pass
O/P:--
0
9
18
27
36
45
54
63
72
81
90
99
----: Some Important Pattern examples :---
# O/P:--
# 10
# 10 8
# 10 8 6
# 10 8 6 4
# 10 8 6 4 2
# code for above output
k=[]
for i in range(10,1,-2):
k.append(i)
for j in k:
print(j,end=" ")
print()
# O/P:-- {1: 2, 2: 3}
# code for above output
t=(1,1,2,2,4,2)
dict={}
for i in t:
count=0
for j in t:
if j==i:
count=count+1
if count>=2:
dict[i]=count
print(dict)
#*
#**
#***
#****
#*****
n=int(input("Enter the number of rows: "))
for i in range(1,n+1):
print("* "*i)
# *
# **
# ***
# ****
# *****
# *
# ***
# *****
# *******
# *********
#1
#12
#123
#1234
#12345
# *****
# ****
# ***
# **
# *
n=int(input("Enter the number of rows: "))
for i in range(n,0,-1):
print(" "*(n-i),"*"*i)
# *****
# ****
# ***
# **
#*
n=int(input("Enter the number of rows: "))
for i in range(n,0,-1):
print("*"*i)
# *****
# ****
# ***
# **
# *
n=int(input("Enter the number of rows: "))
for i in range(n,0,-1):
print(" "*(n-i)," *"*i)
# *
# **
# ***
# ****
# *****
# *****
# ****
# ***
# **
# *
n=int(input("Enter the number of rows: "))
for i in range(1,n+1):
print(" "*(n-i),"* "*i)
m=n-1
for i in range(m,0,-1):
print(" "*(m-i)," *"*i)
# *
# **
# ***
# ****
# *****
# *****
# ****
# ***
# **
#*
n=int(input("Enter the number of rows: "))
for i in range(0,n+1):
print(" "*(n-i),"*"*i)
for i in range(n,0,-1):
print("*"*i," "*(n-i))
#*
#**
#***
#****
#*****
#****
#***
#**
#*
n=int(input("Enter the number of rows: "))
for i in range(0,n+1):
print("* "*i)
m=n-1
for i in range(m,0,-1):
print("* "*i)
# *
# **
# ***
# ****
# *****
# *****
# ****
# ***
# **
# *
n=int(input("Enter the number of rows: "))
for i in range(0,n+1):
print(" "*(n-i),"*"*i)
for i in range(n,0,-1):
print(" "*(n-i),"*"*i)
IF-ELIF-ELSE STATEMENT EXAMPLES
Example 1: Write a program to check given no is positive. (Only if-statement)
Example 4: Write a program to swap two variables without using third variable.
Example 6: Write a program to swap two variables using using Addition and
Subtraction.
Example 10: Write a program to find largest no among the three inputs numbers.
Example 13: Write a program to find given year is leep year or not.
While-Loop EXAMPLES
Example 1: Write a program to display n natural numbers. (In Horizontal-
1,2,3,4,5…….. )
Example 7: Write a program to find how many vowels and consonants are present
in strings.
Example 2: Python program to print all the even numbers within the given range.
Example 3: Python program to calculate the sum of all numbers from 1 to a given number.
Example 4: Python program to calculate the sum of all the odd numbers within the given range.
Example 6: Python program to display numbers from a list using a for loop.
Example 8: .(madam=madam)
Example 9: Python program that accepts a word from the user and reverses it.
Example 11: Python program to count the number of even and odd numbers from a series of
numbers.
Example 12: Python program to display all numbers within a range except the prime numbers.
Example 15: Python program that accepts a string and calculates the number of digits and letters.
Example 16: Write a Python program that iterates the integers from 1 to 25.
Example 17: Python program to check the validity of password input by users.
Example 18: Python program to convert the month name to a number of days.
Python Practice question as per the interview requirement
1. Write a program to check if a given number is an Armstrong
number.(153=1**3+5**3+3**3).
5. Write a program to find how many vowels and consonants are present in strings.
9. Write a program to check given number is Harshad number/ Niven number or not.
( A Harshad number (also known as a Niven number) is a positive integer that is
divisible by the sum of its digits. Example – 18%(1+8)==0)
10. Write a program to check given number is neon number or not. ( A neon number
is a number where the sum of digits of square of the number is equal to the number.
Example- digit = 9 square of digit 9*9=81 sum of square digit 8+1=9)
11. Write a program to check given number is Peterson number or not. ( A number is
said to be a Peterson number if the sum of factorials of each digit of the number is
equal to the number itself. Example – n=145, sum of 1!+4!+5!=145)
12. Write a program to check given number is spy no or not. ( A number is said to be
a Spy number if the sum of all the digits is equal to the product of all digits.
Examples: Input : 1412. 1+4+1+2 == 1*4*1*2 Output : Spy Number.)
x=200
y=100
print("Addition of x & y =",x+y)
print("Addition of x & y =",x-y)
print("Addition of x & y =",x*y)
x=10
y=5
print("Addition of x & y =",x+y)
print("Addition of x & y =",x-y)
print("Addition of x & y =",x*y)
O/P:--
Addition of x & y = 30
Addition of x & y = -10
Addition of x & y = 200
Addition of x & y = 300
Addition of x & y = 100
Addition of x & y = 20000
Addition of x & y = 15
Addition of x & y = 5
Addition of x & y = 50
Now, repeated code can be bound into single unit that is called function.
The advantages of function:
calculate(10,20)
calculate(200,100)
calculate(10,5)
O/P:--
Addition of x & y = 30
Addition of x & y = -10
Addition of x & y = 200
Addition of x & y = 300
Addition of x & y = 100
Addition of x & y = 20000
Addition of x & y = 15
Addition of x & y = 5
Addition of x & y = 50
Types of function:---
1. In-built function :-- The functions which are coming along with Python
software automatically,are called built-in functions or pre defined functions.
Examples:--
1. print()
2. id()
3. type()
4. len()
5. eval()
6. sorted()
7. count() etc…….
2. User define function:--- The functions which are defined by the developer as
per the requirement are called user-defined functions.
Syntax:---
def fun_name(parameters….):
„„„ doc string….‟‟‟
Statment1…….
Statment2…….
Statment3…….
return (anything)
# call function
fun_name(arguments....)
Important terminology
def-keyword mandatory
return-keyword optional
arguments optional
parameters optional
fun_name mandatory
1. def keyword – Every function in python should start with the keyword
„def‟. In other words, python can understand the code as part of a function if
it contains the „def‟ keyword only.
2. Name of the function – Every function should be given a name, which can
later be used to call it.
3. Parenthesis – After the name „()‟ parentheses are required
4. Parameters – The parameters, if any, should be included within the
parenthesis.
5. Colon symbol ‘:’ should be mandatorily placed immediately after closing
the parentheses.
6. Body – All the code that does some operation should go into the body of the
function. The body of the function should have an indentation of one level
with respect to the line containing the „def‟ keyword.
7. Return statement – Return statement should be in the body of the function.
It‟s not mandatory to have a return statement. If we are not writing return
statement then default return value is None
8. Arguments:-- At the time of calling any function, in between the
parentheses we passes arguments.
Relation between parameters and arguments:--
Parameters are inputs to the function. If a function contains parameters, then at the
time of calling, compulsory we should provide values as a arguments, otherwise
we will get error.
calculate(10,20)
calculate(200,100)
calculate(10,5)
O/P:--
Addition of x & y = 30
Addition of x & y = -10
Addition of x & y = 200
Addition of x & y = 300
Addition of x & y = 100
Addition of x & y = 20000
Addition of x & y = 15
Addition of x & y = 5
Addition of x & y = 50
# Write a function to take number as input and print its square value
def square(x):
print("The Square of",x,"is", x*x)
square(4)
square(5)
O/P:--
The Square of 4 is 16
The Square of 5 is 25
# Write a function to check whether the given number is even or odd?
def even_odd(num):
if num%2==0:
print(num,"is Even Number")
else:
print(num,"is Odd Number")
even_odd(10)
even_odd(15)
O/P:--
10 is Even Number
15 is Odd Number
O/P:--
Enter any no 5
The Factorial of 5 is : 120
Returning multiple values from a function: In other languages like C, C++ and
Java, function can return almost one value. But in Python, a function can return
any number of values.
def add_sub(a,b):
add=a+b
sub=a-b
return add,sub
x,y=add_sub(100,50)
print("The Addition is :",x)
print("The Subtraction is :",y)
O/P:--
The Addition is : 150
The Subtraction is : 50
Or
def add_sub(a,b):
add=a+b
sub=a-b
return add,sub
x,y=int(input("Enter first value:")),int(input("Enter second value: "))
print("The Addition is :",x)
print("The Subtraction is :",y)
O/P:--
The Addition is : 100
The Subtraction is : 50
def calc(a,b):
add=a+b
sub=a-b
mul=a*b
div=a/b
return add,sub,mul,div
def square(x):
print("The Square of",x,"is", x*x)
square(4)
square(5)
O/P:-
The Square of 4 is 16
The Square of 5 is 25
2. keyword arguments:
def f1(a,b):
------
------
f1(a=10,b=20)
def square(x):
print("The Square of",x,"is", x*x)
square(x=4)
square(x=5)
O/P:--
The Square of 4 is 16
The Square of 5 is 25
3. default arguments:
def f1(a=0,b=0):
------
------
f1(10,20)
f1()
def square(x=0):
print("The Square of",x,"is", x*x)
square(x=4)
square()
O/P:--
The Square of 4 is 16
The Square of 0 is 0
def sum(*n):
total=0
for i in n:
total=total+i
print("The Sum=",total)
sum()
sum(10)
sum(10,20)
sum(10,20,30,40)
O/P:--
The Sum= 0
The Sum= 10
The Sum= 30
The Sum= 100
5. key word variable length arguments:
def f1(**n):
------
------
f1(n1=10, n2=20)
def display(**kwargs):
for k,v in kwargs.items():
print(k,"=",v)
display(n1=10,n2=20,n3=30)
print("-----------")
display(rno=100, name="Neeraj", marks=70, subject="Java")
O/P:--
n1 = 10
n2 = 20
n3 = 30
-----------
rno = 100
name = Neeraj
marks = 70
subject = Java
# ===============================================
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display_info(Name="Neeraj",age=37)
O/P:---
Name: Neeraj
age: 37
def args_and_kwargs(*args, **kwargs):
print("Positional arguments:")
for arg in args:
print(arg)
print("Keyword arguments:")
for key, value in kwargs.items():
print(f"{key}: {value}")
args_and_kwargs(1, 2, 3, name="Neeraj",age=37, quali="M.Tech")
O/P:--
Positional arguments:
1
2
3
Keyword arguments:
name: Neeraj
age: 37
quali: M.Tech
def a():
x=10
return "value of Local variable is:",x
def b():
return "value of Local variable is:",x
p=a()
print(p)
y=b()
print(y)
O/P:-
('value of Local variable is:', 10)
Traceback (most recent call last):
File "E:\Python Core_Advance\local.py", line 10, in <module>
y=b()
File "E:\Python Core_Advance\local.py", line 6, in b
return "value of Local variable is:",x
NameError: name 'x' is not defined
def b():
return "value of Local variable is:",x
p=a()
print(p)
print(x)
O/P:--
('value of Local variable is:', 10)
Traceback (most recent call last):
File "E:\Python Core_Advance\local.py", line 12, in <module>
print(x)
NameError: name 'x' is not defined
O/P:--
a from function m(): 11
b from function m(): 12
a from function n(): 11
b from function n(): 12
def m1():
global a
a=2
print("a value from m1() function: ", a)
def m2():
print("a value from m2() function:", a)
m1()
m2()
O/P:--
a value from m1() function: 2
a value from m2() function: 2
global and local variables having the same name in Python
a=1
def m1():
global a
a=2
print("a value from m1() function:", a)
def m2():
print("a value from m2() function:", a)
m1()
m2()
O/P:--
a value from m1() function: 2
a value from m2() function: 2
If we use the global keyword inside the function, then the function is able to read-
only global variables.
PROBLEM: This would make the local variable no more available.
a=1
def m1():
a=2
print("a value from m1() function:", a)
print("a value from m1() function:", globals()['a'])
m1()
O/P:--
a value from m1() function: 2
a value from m1() function: 1