0% found this document useful (0 votes)
3 views22 pages

Python Notes_copy - Converted-1

The document is a comprehensive guide on programming languages, focusing on Python. It covers concepts such as features of good programming languages, types of programming languages, language translators, and Python's syntax, variables, data types, and operators. Additionally, it provides practical examples and explanations of Python programming concepts, including conditional statements, loops, and library functions.

Uploaded by

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

Python Notes_copy - Converted-1

The document is a comprehensive guide on programming languages, focusing on Python. It covers concepts such as features of good programming languages, types of programming languages, language translators, and Python's syntax, variables, data types, and operators. Additionally, it provides practical examples and explanations of Python programming concepts, including conditional statements, loops, and library functions.

Uploaded by

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

Lesson 1: Concept of Programming Language ...........................................................................................................

1
1.1 Features of a Good Programming Language ............................................................................................... 1
1.2 Types of Programming Language .................................................................................................................... 1
1.3 Language Translator ............................................................................................................................................. 1
1.3.1 Compiler............................................................................................................................................................ 2
1.3.2 Interpreter ....................................................................................................................................................... 2
Lesson 2: Introduction of Python .................................................................................................................................... 3
2.1 Python can do the following: ............................................................................................................................. 3
2.2 Why Python? ............................................................................................................................................................ 3
2.3 Python Syntax compared to other programming languages................................................................. 3
2.4 Run first python program ................................................................................................................................... 3
2.5 Python Indentation................................................................................................................................................ 4
Lesson 3: Variable and Datatype...................................................................................................................................... 5
3.1 Variable ...................................................................................................................................................................... 5
3.1.1 Assigning multiple value to variable...................................................................................................... 6
3.1.2 Output Variables ............................................................................................................................................ 6
3.1.3 Global Variable ............................................................................................................................................... 7
3.1.4 The global keyword ...................................................................................................................................... 8
3.2 Datatype..................................................................................................................................................................... 8
3.2.1 Mutable Datatypes ........................................................................................................................................ 9
3.2.2 Immutable Datatypes................................................................................................................................ 12
Lesson 4: Types of Casting Concept ............................................................................................................................. 13
4.1 Implicit Type Conversion ................................................................................................................................. 13
4.2 Explicit Type Conversion ................................................................................................................................. 13
Lesson 5: Operators ........................................................................................................................................................... 15
5.1 Arithmetic Operator ........................................................................................................................................... 15
5.2 Relational Operators .......................................................................................................................................... 16
5.3 Logical Operator .................................................................................................................................................. 16
5.4 Assignment Operators....................................................................................................................................... 17
5.5 Bitwise Operators ............................................................................................................................................... 17
5.5.1 Bitwise AND operator (&) ....................................................................................................................... 17
5.5.2 Bitwise OR operator ( | ) .......................................................................................................................... 19
5.5.3 Bitwise XOR Operator (^) ....................................................................................................................... 19
5.5.4 Bitwise NOT operator ( ~ ) ..................................................................................................................... 20

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]


Basics | Grade-9 +977-9814 896 965
1
1
Lesson 6: Conditional Statement in python .............................................................................................................. 21
6.1 IF Statement .......................................................................................................................................................... 21
Lesson 1: Concept of Programming Language
6.2 If...else Statement ................................................................................................................................................ 22 A programming language is a way for humans to give instructions to computers. Just like human use english,
6.3 If…elif…else Statement ...................................................................................................................................... 22 Hindi, or Nepali to talk, computer understand programming languages. Programming language helps
us to write program that solve problems, do calculations, display information and much more.
6.4 Nested if Statements .......................................................................................................................................... 23
Programming languages are designed for specific purposes, such as web development, data analysis,
Lesson 7: Iteration (Loop) ............................................................................................................................................... 24 system programming, etc. Python is a general-purpose language, meaning it can be used for a wide
7.1 For Loop .................................................................................................................................................................. 24 variety of tasks.
7.2 break and continue Statement ....................................................................................................................... 26 Because of following reasons, we need programming language:
7.2.1 break Statement .......................................................................................................................................... 26 • Computers don't understand human languages.
7.2.2 Continue Statement ................................................................................................................................... 26 • They understand only binary language (0s and 1s).
7.3 While Loop ............................................................................................................................................................. 26 • It’s very hard for humans to write programs in 0s and 1s. So, programming languages like Python,
C, Java, C++, etc., were created to make programming easier.
Lesson 8: Library Function ............................................................................................................................................. 28
8.1 String Function..................................................................................................................................................... 28 1.1 Features of a Good Programming Language
• Easy to learn.
8.2 Numeric functions .............................................................................................................................................. 29
• Easy to write and read.
8.3 Mathematical Function ..................................................................................................................................... 30 • Fast and efficient.
Lesson 9: Programs ............................................................................................................................................................ 31 • Portable (can run on different types of computers).
• Secure and reliable.

1.2 Types of Programming Language


a) Low-Level Language (ML and AL)
• Very close to machine (binary) language.
• Example: Assembly Language.
• Difficult for humans to understand.
b) High-Level Language
• Easy to read and write for humans.
• Examples: Python, Java, C++, JavaScript.
• Python is a high-level language.

Fun Fact about Python

• Python was created by Guido van Rossum in 1991.


• It is named after a TV show called “Monty Python’s Flying circus”, not after the snake!

1.3 Language Translator


It can be defined as the system software that converts codes written in one programming language
(like C,C++, Python, Qbasic, etc) into machine code. Assembler, Compiler, and interpreter are
example of language translator.

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
2 3
2 3

1.3.1 Compiler Lesson 2: Introduction of Python


A compiler is a program that translates the entire source code (written in a high level language like Python is an interpreted based popular programming language which is created by Guido van Rossum
Python, C, Java) into machine language at once before the program is executed.. in 1991 used for web development, software development, mathematics, system scripting and many
more.
After compiling, you get a separate executable file (.exe). if there are errors, the compiler shows all the
When you write a python program, it usually follows this simple structure.
errors after checking the entire program.
# 1. Comments (optional)
Example of compilers # This is a sample Python program
# 2. Define variables
• C compiler (gcc)
x=5
• Java compiler (javac)
y = 10
1.3.2 Interpreter # 3. Write logic (processing)
An interpreter is a program that translates and runs the program line by line at runtime. sum = x + y
It checks each line: # 4. Display output
o If there’s an error, it stops immediately and shows the error. print("Sum is:", sum)
o You have to fix the error before continuing. 2.1 Python can do the following:
Example of interpreters. • Python can be used on a server to create web applications.
• Python interpreter (CPython) • Python can be used alongside software to create workflows.
• JavaScript interpreter (Node.js) • Python can connect to database systems. It can also read and modify files.
Compiler Interpreter • Python can be used to handle big data and perform complex mathematics.
It translates whole program at once. It translate line by line. • Python can be used for rapid prototyping, or for production-ready software development.
Shows all errors after compiling. Shows one error at a time.
2.2 Why Python?
Faster because the translation is done only once. Slower because it checks line by line.
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Hard to debug the code. Easier to debug the code.
It detect error during compile time. It may detect error during runtime. • Python has a simple syntax similar to the English language.
C, C++, Java, etc uses compiler. Python, Qbasic, JavaScript, etc uses interpreter. • Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
PYTHON CASE This means that prototyping can be very quick.
Python uses an interpreter. When you run a python script, the python interpreter reads your code • Python can be treated in a procedural way, an object-oriented way or a functional way.
line by line and executes it. However, python also compiles the source code into an intermediate 2.3 Python Syntax compared to other programming languages.
bytecode(.pyc files) when it’s imported as a module. This bytecode is then executed by the python • Python was designed for readability, and has some similarities to the English language.
virtual machine (PVM). This bytecode compilation is done for optimization, so that the interpreter • Python uses new lines to complete a command, as opposed to other programming languages
doesn’t have to re-parse (convert) the source code every time the module is used. which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this purpose.
2.4 Run first python program
Python is an interpreted programming; this means that as a developer you write python (.py) files in a
text editor and then put those files into the python interpreter to be executed.
The way to run a python file is like this on the command line:
C:\Users\Your Name>python helloworld.py
Where "helloworld.py" is the name of your python file.

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
4 5
4 5

2.5 Python Indentation Lesson 3: Variable and Datatype


Indentation refers to the spaces at the beginning of a code line. 3.1 Variable
Where in other programming languages the indentation in code is for readability only, the indentation The reference of data stored in the program which value get changed during the program execution is known as
in Python is very important. variable. Those entity whose value get changed during program execution time is known as variable. A
Python uses indentation to indicate a block of code. variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Example:
• Python has no command for declaring a variable.
if 5 > 2: Example:
print("Five is greater than two!") x=5
y = "John"
Python will give you an error if you skip the indentation: print(x)
Example print(y)
if 5 > 2: • Variables do not need to be declared with any particular type, and can even change type after they
print("Five is greater than two!") have been declared.
Example:
x=4 # x is of type int
The number of spaces is up to you as a programmer, the most common use is four, but it has to be at x = "Sally" # x is now of type str
least one. print(x)
Example: • You can get the data type of a variable with the type() function.
if 5 > 2: Example
print("Five is greater than two!") x=5
if 5 > 2: y = "John"
print("Five is greater than two!") print(type(x))
print(type(y))
You have to use the same number of spaces in the same block of code, otherwise Python will give you • String variables can be declared either by using single or double quotes:
an error: Example:
x = "John"
Example # is the same as
Syntax Error x = 'John'
if 5 > 2: • If you want to specify the data type of a variable, this can be done with casting.
print("Five is greater than two!") Example
print("Five is greater than two!") x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Rules for Python variables:
• A variable name must start with a letter or the underscore character.
• A variable name cannot begin with a number.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A Reserved keyword cannot be used as a variable name.
Following are the techniques that are used to make variables:

Keyword
Those words which are already reserved in the library of python which have special meaning in the
python program are known as keyword. 36 keywords are currently in python.
and as assert break class continue def del elif else while
except false finally for from global if import in is with
lambda none nonlocal not or pass raise return true try yield

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
6 7
6 7

1. Camel Case You can also use the + operator to output multiple variables:
Each word, except the first, starts with a capital letter: Example:
Example: myVariableName = "John" x = "Python "
2. Pascal Case y = "is "
Each word starts with a capital letter: z = "awesome"
Example: MyVariableName = "John" print(x + y + z)
Notice the space character after "Python " and "is ", without them the result would be "Pythonisawesome".
3. Snake Case
Each word is separated by an underscore character: For numbers, the + character works as a mathematical operator:
Example: my_variable_name = "John" Example:
X =5
3.1.1 Assigning multiple value to variable y = 10
a) Many values to multiple variables. print(x + y)
Python allows you to assign values to multiple variables in one line.
Example: When you try to combine a string and a number with the + operator, Python will give you an error:
x, y, z = "Orange", "Banana", "Cherry" Example:
print(x) x=5
print(y) y = "John"
print(z) print(x + y)

Note: Make sure the number of variables matches the number of values, or else you will get an error. The best way to output multiple variables in the print() function is to separate them with commas.
Example:
b) One Value To Multiple Variables
x=5
You can assign the same value to multiple variables in one line:
Example: y = "John"
x = y = z = "Orange" print(x, y)
print(x) 3.1.3 Global Variable
print(y) The variables that are created outside of a function are known as global variables. Global variables can
print(z) be used by everyone, both inside of functions and outside.
c) Unpack a collection Example:
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into Create a variable outside of a function, and use it inside the function
variables. This is called unpacking. x = "awesome"
Example def myfunc():
Unpack a list:
print("Python is " + x)
fruits = ["apple", "banana", "cherry"]
myfunc()
x, y, z = fruits
print(x,y,z)
Output: apple, banana, cherry whenever we create a variable with the same name inside a function, this variable will be local and can
only be used inside the function. And the global variable with the same name will remain as it was.
3.1.2 Output Variables Example
The Python print() function is often used to output variables. Create a local and global variable with the same name.
Example x = "awesome" it is global variable
x = "Python is awesome" def myfunc():
print(x) x = "fantastic" it is local variable
print("Python is " + x)
In the print() function, you output multiple variables, separated by a comma:
myfunc()
Example:
print("Python is " + x)
x = "Python"
y = "is"
O/P:
z = "awesome"
Python is fantastic
print(x, y, z) Python is awesome

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
8 9
8 9

3.1.4 The global keyword Example:


Normally whenever we create a variable inside a function, that variable is local, and it can only be used # create a variable with integer value.
inside that function. But To create a global variable inside a function, we can use the global keyword. A = 100
Example: print(“The type of variable having value”, a, “is”, type(A))
def myfunc():
#create a variable with complex value.
global x
c=100+3j
x = "fabulous"
print("The type of variable having value", c, " is ", type(c))
myfunc()
print("Python is " + x)
Output: Python is fabulous output:
The type of variable having value 100 is <class 'int'>
The type of variable having value 100+3j is <class 'complex'>
Also. We can use the global keyword to change the value of global variable inside a function.
Example: 3.2.1 Mutable Datatypes
x = "awesome" Those objects or datatypes whose value can be modified after they are created are known as mutable
def myfunc(): object or datatype. Example: List, Dictionary, Set
global x 1. List datatype
x = "fantastic" The list is a versatile data type exclusive in python it is the same as the array in C/C++. But the interesting
myfunc() thing about the list in python is that it can simultaneously hold different types of data. formally list is
print("Python is " + x) an ordered sequence of some data written using brackets [ ] and commas (,). A list can contain
Output: Python is fantastic heterogeneous types of elements which means elements can have different data-types like integers,
3.2 Datatype strings, floats, Booleans etc.
Datatype means what kind of data you are working with. Datatypes classify the kind of values that a Example:
variable can hold. In python we do not need to declare a datatype while declaring a variable like C or #list of having only integers
C++. We just simply assign values in a variable, but if we want to check what type of data is holding a= [1,2,3,4,5,6]
right now then we can use type() function. print(a)
Datatypes are of 2 types in python: #list of having only strings
b=["hello","siya","Nikku"]
DataTypes print(b)
#list of having both integers and strings
c= ["hey","you",1,2,3,"go"]
Mutuable Immutable print(c)
#index are 0 based.
print(c[1]) #this will print "you" in list c
List Integer Example2:
my_list = [1, 2, 3]
my_list.append(4) #If we add new elements in list, the new element will hold the last position of list.
Sets
Float print(my_list)
my_list.insert(1, 5)
Dictionary print(my_list)
Tuples my_list.remove(2)
print(my_list)
del my_list[2]
String print(my_list)

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
10 11
10 11

Output:
popped_element = my_list.pop(0)
first name
print(my_list)
last name
print(popped_element)
33
Output:
New York
[1, 2, 3, 4]
[1, 5, 2, 3, 4]
[1, 5, 3, 4] Duplicate keys are not allowed: In the Python dictionary, two values with the same key cannot exist. If
[5, 3, 4] the same key has two or more values, the new value will replace the old value.
1 a = {
1: "first name",
To find the numbers of elements present in the list, we use len() function. The len() function gives us 2: "last name",
the number of list elements present in the list. 2: "last",
Example }
my_list=["computer", "Math", 20, True] print(a[1])
a=len(my_list)
print(a[2])
print(a)
output
Loop Through List first name
We can loop through the list elements using the for loop to print all the elements one by one. last
Example Example2:
my_list=["computer", "Math", 20, True] Example of dictionary that are mutable i.e., we can make changes in the Dictionary.
for X in my_list: my_dict = {"name": "Ram", "age": 25}
print(X) new_dict = my_dict
new_dict["age"] = 37
2. Dictionary Type print(my_dict)
Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table print(new_dict)
type. Dictionaries are written within curly braces in the form key:value. It is very useful to retrieve data
Output:
in an optimized way among a large amount of data.
{'name': 'Ram', 'age': 37}
Example: {'name': 'Ram', 'age': 37}
a={ 1. The del keyword is used to remove specified key names in the dictionary.
1: "first name", my_dict = {
2: "last name", 1: "first name",
"age":33, 2: "last name",
“is_present” : True }
} print(my_dict)
#print value having key=1 del my_dict[1]
print(a[1]) print(my_dict)
#print value having key=2 2. To determine the numbers of key:values present in the dictionary, len() function is used.
print(a[2]) my_dict = {
#print value having key="age" "firstname": "Saroj",
print(a["age"]) "lastname": "Yadav",
info = {'city': 'New York', }
'country': 'USA' print(my_dict)
} print(len(my_dict))
print(info['city'])

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
12 13
12 13

List Dictionary tuple1 = (0, 1, 2, 3)


A list stores elements in a sequence. A dictionary stores data in key:value pairs. tuple1[0] = 4
List elements are accessed by index. Dictionary values are accessed by keys. print(tuple1)
List elements have an order. Dictionary values don’t have any specific order. Output:
File "d:\programming\python\global.py", line 4, in <module>
List elements can be added & removed. Dictionary values are added as key:value pair & removed
tuple1[0] = 4
by key .
~~~~~~^^^
TypeError: 'tuple' object does not support item assignment
3.2.2 Immutable Datatypes Mutable Immutable
1. Numeric Types Objects whose state or value can be changed after Objects whose state or value can’t be changed
Those datatypes that hold numeric value like int, float and complex are known as numeric datatypes.
they are created. once they are created.
a. int: integers (whole numbers). Eg. 10, -5, 0, etc
Data can modify in place without creating a new Creating a new object is required when
b. float: it holds floating-point numbers (numbers with a decimal point). Eg. 3.14, 0.001, -0.342, etc.
c. complex: it hold complex numbers with a real and imaginary part. Eg. 3+2j, 1i+1, etc object. attempting to modify.
2. String: The string is a sequence of characters. Python supports Unicode characters generally, string More memory efficient as they allow changes Less memory efficient as new objects are created
are represented by either single or double-quotes. without allocating new memory. for any modification.
Example: Example: List, Dictionary, Sets. Example: Integers, floats, strings, tuples.
a = "string in a double quote"
b= 'string in a single quote' Lesson 4: Types of Casting Concept
print(a) Type casting means changing one datatype into another datatype. It is important when mixing
print(b) different types of data.
# using ',' to concatenate the two or several strings For example:
print(a,"concatenated with",b) • Changing an integer into a string.
#using '+' to concate the two or several strings • Changing a float into an integer.
print(a+" concated with "+b)
Casting
Output:
string in a double quote
string in a single quote Implicit type conversion Explicit type conversion
string in a double quote concatenated with string in a single quote
string in a double quote concated with string in a single quote 4.1 Implicit Type Conversion
3. Tuple datatype Python interpreter automatically converts data from one type to another types. Users don’t have to
The tuple is another data type which is a sequence of data similar to a list. But it is immutable. That means data involve in this process. It avoids the loss of data.
in a tuple is write-protected. Data in a tuple is written using parenthesis and commas. Example:
Example: x=5
#tuple having only integer type of data. y = 2.0
a=(1,2,3,4) z=x+y
print(a) #prints the whole tuple print(z) # Output: 7.0
#tuple having multiple type of data. Explanation: 5 (int) becomes 5.0 (float) automatically.
b=("hello", 1,2,4,"go")
print(b) #prints the whole tuple 4.2 Explicit Type Conversion
#index of tuples are also 0 based. In Explicit users need to convert the data type of an object to their required data type. In this method
Print(b[0]) #this will print “hello” in tuple user involvement is necessary. Explicit conversion is known as the actual type casting. It many occur
Example2: In this example, we will take a tuple and try to modify its value at a particular index loss of data as we enforce the object to a specific data type.
and print it. As a tuple is an immutable object, it will throw an error when we try to modify it. Example1:
# Python code to test that tuples are immutable num_string = '12'
num_integer = 23

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
14 15
14 15

print("Data type of num_string before Type Casting:",type(num_string)) Lesson 5: Operators


Operators are sign or symbols that perform operations like arithmetic, logical and relational on
# explicit type conversion
different operands. Example:
num_string = int(num_string)
a=5+3
print("Data type of num_string after Type Casting:",type(num_string))
# '+' is an operator and 5 and 3 are operands.
num_sum = num_integer + num_string
Types of operators
print("Sum:",num_sum)
1. Arithmetic Operators
print("Data type of num_sum:",type(num_sum)) 2. Relational (comparison) Operators
3. Logical Operators
Output: 4. Assignment Operators
Data type of num_string before Type Casting: <class 'str'> 5. Bitwise Operator
Data type of num_string after Type Casting: <class 'int'> 5.1 Arithmetic Operator
Sum: 35 Arithmetic operators are those operators that are used to perform mathematical operations like
Data type of num_sum: <class 'int'> addition, subtraction, multiplication, etc. on operands.
Python mainly supports three types of explicit casting: Example:
Type Function Example a = 7
int() Converts to integer int(5.9) → 5 b = 2
float() Converts to floating number float(3) → 3.0 #addition
str() Converts to string (text) str(100) → "100" print ('Sum: ', a + b) # + to add a and b
Example: #subtraction
y = int(2.8) # y will be 2 print ('Subtraction: ', a - b) # - to subtract b from a
x = float(1) # x will be 1.0 #multiplication
z = str("s1") # z will be 's1' print ('Multiplication: ', a * b) # * to multiply a and b

Example: Useful when joining numbers with text #division


name = "John" print ('Division: ', a / b) # / is float division it always return a float number
age = 16 no matter two number are integers or float number.
print("Name: " + name + ", Age: " + str(age)) #floor division or integer division
Output: Name: John, Age: 16 print ('Floor Division: ', a // b) # // to floor divide a by b
#modulo
print ('Modulo: ', a % b) # % to get the remainder
#a to the power b
print ('Power: ', a ** b) # ** to get a to the power b
Output:
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
📝Floor division in Python is performed using the // operator. It divides two numbers and rounds the
result down to the nearest whole number (integer) and discard the fractional part.
When dealing with negative numbers, floor division rounds down towards negative infinity.
Example: e = -10
f = 3
result = e // f
print(result) # Output: -4

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
16 17
16 17

5.2 Relational Operators


it compares two operands and return a Boolean value (i.e. either True or False) Logical OR operator table
It returns true value when any one of the given Expression is true else it will return false.
Example:
a = 5 Expression 1 Expression 2 Result
b = 2 T T T
# equal to operator T F T
print('a == b =', a == b) F T T
# not equal to operator F F F
print('a != b =', a != b)
# greater than operator Logical NOT operator table
print('a > b =', a > b)
Not operator simply reverse the result of a logical expression.
# less than operator Expression Result
print('a < b =', a < b)
T F
# greater than or equal to operator
F T
print('a >= b =', a >= b)
# less than or equal to operator
print('a <= b =', a <= b)
5.4 Assignment Operators
Assignment operators are used to assign value to variables.
Example1 :
Output:
# assign 5 to x
5 == 2 [False ] x = 5
5 != 2 [True ] Operator Name Example
5 > 2 = [True ] = Assignment Operator a=7
5 < 2 = [False ] += Addition Assignment a += 1 # a = a + 1
5 >= 2 = [True ] -= Subtraction Assignment a -= 3 # a = a - 3
5 <= 2 = [False ] *= Multiplication Assignment a *= 4 # a = a * 4
/= Division Assignment a /= 3 # a = a / 3
5.3 Logical Operator %= Remainder Assignment a %= 10 # a = a % 10
Logical operator are used to check whether an expression is true or false. They are used in decision **= Exponent Assignment a **= 10 # a = a ** 10
making.
5.5 Bitwise Operators
Example: Bitwise operators are used to perform bitwise calculations only on integers. The integers are first
a=5 converted into binary and then operations are performed on each corresponding pair of bits. After
b=6 that result is returned in decimal.
print((a > 2) and (b >= 6)) #O/P: True Following are the bitwise operators in python:
1. Bitwise AND Operator
Logical AND Operator table 2. Bitwise OR Operator
It returns true value when all of the given expression are true else it will return false. 3. Bitwise XOR Operator
Expression 1 Expression 2 Result 4. Bitwise NOT Operator
5. Bitwise Left Shift Operator
T T T
6. Bitwise Right Shift Operator
T F F
5.5.1 Bitwise AND operator (&)
F T F
Bitwise AND operator is similar to logical AND operator.it return True only if both the bit of operands
F F F are 1 (i.e. True) Combinations are:
0 & 0 is 0
1 & 0 is 0
0 & 1 is 0
1 & 1 is 1

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
18 19
18 19

Example1: The result in binary is 00001100. Let's convert this back to our regular number system:
a = 10 • 0 in the 1s place
b=4 • 0 in the 2s place
# Print bitwise AND operation • 1 in the 4s place (which is 4)
print("a & b =", a & b) O/P: 0 • 1 in the 8s place (which is 8)
• 0 in the 16s, 32s, 64s, and 128s places.
Example2: So, 4 + 8 = 12. That's why a & b is 12 in the second example!
a=60
b=13 5.5.2 Bitwise OR operator ( | )
print ("a & b:",a&b) O/p: 12 The “|” symbol (called pipe) is the bitwise OR operator. If any bit operand is 1, the result is 1 otherwise
it is 0.
why the example1 return 0 and example2 return 12 ?
Answer: Combinations are:
Example1 0 | 0 is 0
Let’s see how 10 and 4 look in binary
0 | 1 is 1
• a = 10 in binary is 1010 (from right to left, this means 0 in the 1s place, 1 in the 2s place, 0 in the 4s
place and 1 in the 8s place: 0+2+0+8=10) 1 | 0 is 1
• b = 4 in binary is 0100 (0 in the 1s, 0 in the 2s, 1 in the 4s, and 0 in the 8s place: 0+0+4+0=4) 1 | 1 is 1
Now, the bitwise AND operator (&) is like Example:
1 0 1 0 (a = 10) a=60
&0 1 0 0 (b = 4) b=13
0 0 0 0 print("a or b is:",a|b)
• Rightmost bit: 0 (from 'a') AND 0 (from 'b') = 0
• Next bit: 1 (from 'a') AND 0 (from 'b') = 0 Output: a or b is: 61
• Next bit: 0 (from 'a') AND 1 (from 'b') = 0 To perform the "|" operation manually, use the 8-bit format.
• Leftmost bit: 1 (from 'a') AND 0 (from 'b') = 0 0 0 1 1 1 1 0 0
So, the result in binary is 0000, which is 0 in our regular number system. That's why a & b is 0 in the |0 0 0 0 1 1 0 1
first example!
0 0 1 1 1 1 0 1 is equal to 61 so output is 61.
5.5.3 Bitwise XOR Operator (^)
Example2:
The term XOR stands for exclusive OR. It means that the result of OR operation on two bits will be 1 if
Let's do the same for 60 and 13:
only one of the bits is 1.
• a = 60 in binary is 00111100 (Let's use 8 bits to be safe) (0*128 + 0*64 + 1*32 + 1*16 + 1*8 + 1*4 + 0*2
Combinations are:
+ 0*1 = 60)
0 ^ 0 is 0
• b = 13 in binary is 00001101 (0*128 + 0*64 + 0*32 + 0*16 + 1*8 + 1*4 + 0*2 + 1*1 = 13)
0 ^ 1 is 1
Now, let's apply the bitwise AND operator (&): 1 ^ 0 is 1
0 0 1 1 1 1 0 0 (a = 60) 1 ^ 1 is 0
& 0 0 0 0 1 1 0 1 (b = 13) Example:
00001100 a=60
Let's compare bit by bit: b=13
• Rightmost bit: 0 AND 1 = 0 print("a xor b is:",a^b)
• Next bit: 0 AND 0 = 0
Output: a xor b is: 49
• Next bit: 1 AND 1 = 1
• Next bit: 1 AND 1 = 1
Let’s perform XOR manually
• Next bit: 1 AND 0 = 0 0011 1100
• Next bit: 1 AND 0 = 0
^00001101
• Next bit: 0 AND 0 = 0
0 0 1 1 0 0 0 1 is equal to 49 in decimal so output is 49
• Leftmost bit: 0 AND 0 = 0

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
20 21
20 21

5.5.4 Bitwise NOT operator ( ~ ) Lesson 6: Conditional Statement in python


Example: Conditional statements allow a program to make decisions and execute different code depending on
a = 5 different conditions. The if keyword requires a Boolean expression, followed by colon (:) symbol. The
print("~a =", ~a) colon (:) symbol starts an indented block. The statements with the same level of indentation are
Output: ~a = -6 executed if the Boolean expression in if statement is True. If the expression is not True (False), the
How 5 becomes -6 with bitwise NOT operator? interpreter bypasses the indented block and proceeds to execute statements at earlier indentation level.
Step1: Represent 5 in Binary (with 4 bits) Note: Python programming language assumes any non-zero and non-null values as TRUE, and if it is
Decimal 5 = 0101 in binary (4 bits) either zero or null, then it is assumed as FALSE value.
But remember, Python uses 32-bit or 64-bit signed integers depending on the system, so we should understand Example:
the concept in at least 8 bits to see how the result becomes -6. If it is raining, take an umbrella. Otherwise, enjoy your walk.
Types of Conditional Statements are:
So, +5 in 8-bit binary: 00000101
1. if Check a condition and run code if it is True
Step2: Apply the Bitwise NOT Operator (~)
2. if-else Run one block if condition is True, another if False
• The NOT operator flips every bit:
3. if-elif-else Check multiple conditions
➢ 0 becomes 1
4. Nested if if statement inside another if
➢ 1 becomes 0
➢ So, inverting 00000101 gives: 6.1 IF Statement
• ~00000101 → 11111010 An if statement executes a block of code
Step 3: Interpret the Result (Two's Complement Form) only when the specified condition is met.
➢ Now, 11111010 is the two's complement representation of a negative number. Syntax
To find what negative number it is: if condition:
Step A: Invert the bits #body of if statement
11111010 → 00000101 Example:
Step B: Add 1 number = int(input('Enter a number: '))
00000101 + 1 = 00000110 → This is 6 in decimal #check if number is greater than 0
So, 11111010 = -6 in two's complement form. if number > 0:
print(f'{number} is a positive number.')
OR
Shortcut Rule: print('A statement outside the if statement.')
~n = -n - 1 Note: The f before the string is short for "formatted string literal", also known as an f-string. It was
→ ~5 = -5 - 1 = -6 introduced in Python 3.6 and allows you to easily include variables inside your string using curly braces {}.
O/p: Enter a number: 20
20 is a positive number.
A statement outside the if statement.

Indentation in Python
Python uses indentation to define a block of code, We usually use
four spaces for indentation in Python, although any number of spaces works as long as we are
consistent.
we will get an error if we write the above code like this:
number = int(input('Enter a number: '))
#check if number is greater than 0
if number > 0:
print(f'{number} is a positive number.')

Here, we haven't used indentation after the if statement. In this case, Python thinks
our if statement is empty, which results in an error.

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
22 23
22 23

6.2 If...else Statement 6.4 Nested if Statements


An if statement can have an A nested if is another decision making statement
optional else clause. in which one if statement resides inside another.
The else statement executes if the It allows us to check multiple conditions
condition in the if statement sequentially.
evaluates to False. Example
Syntax number = 5
if condition: # outer if statement
#body of if statement if number >= 0:
else: # inner if statement
#body of else statement if number == 0:
Example: print('Number is 0')
# inner else statement
number = int(input('Enter a number: '))
else:
if number > 0:
print('Number is positive')
print('Positive number') # outer else statement
else: else:
print('Not a positive number') print('Number is negative')
print('This statement always executes')
Output: Note
Enter a number: 23 1. Compact if Statement
Positive number In certain situations, the if statement can be simplified into a single line. For example,
This statement always executes number = 10
6.3 If…elif…else Statement if number > 0:
print('Positive')
The if...else statement is used to execute a block of code among two alternatives. However, if we
Alternatively, This can be written as
need to make a choice between more than two alternatives, we use
the if...elif...else statement. number = 10
if number > 0: print('Positive')
Syntax
2. Ternary Operator in Python if...else
if condition1:
# code block 1 Python doesn't have a ternary operator. However, we can use if...else to work like a ternary
elif condition2: operator in other languages. For example,
# code block 2 grade = 40
else: if grade >= 50:
# code block 3 result = 'pass'
else:
Example:
result = 'fail'
number = -5 print(result)
if number > 0: Alternatively, can be written as
print('Positive number') grade = 40
elif number < 0: result = 'pass' if number >= 50 else 'fail'
print('Negative number') print(result)
else: 3. Logical Operators to Add Multiple Conditions
print('Zero') If needed, we can use logical operators such as and and or to create complex conditions to work with
print('This statement is always executed') an if statement. Example
age = 35
salary = 6000
if age >= 30 and salary >= 5000:
print('Eligible for the premium membership.')
else:
print('Not eligible for the premium membership')

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
24 25
24 25

Lesson 7: Iteration (Loop) This is how the above program works.


Python loops allow us to execute a statement or group of statements multiple times. Or, Iteration means Iteration Value of i print(i) Last item in sequence?
repeating a set of instructions a number of times or until a condition is met. For example: If you have 5 1st 0 Prints 0 No The body of the loop executes.
apples and you eat one after another, you are repeating the action. In general, statements are executed 2nd 1 Prints 1 No The body of the loop executes.
sequentially: The first statement in a function is executed first, followed by the second, and so on. There 3rd 2 Prints 2 No The body of the loop executes.
may be a situation when you need to execute a block of code several number of times.
4th 3 Prints 3 Yes The body of the loop executes and the loop terminates.

In Python, range is a function that helps you make a list of numbers in a certain order. It returns a
sequence of numbers, starting from 0 by default and increments from 1 (by default), and stops
before a given number by user.
Pass statement
In Python programming, the pass statement is a null statement which can be used as a placeholder
for future code.
There are 3 types of iterations Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
1. for loop Repeats for a fixed number of times the future. In such cases, we can use the pass statement.
2. while loop Repeats until a condition becomes False Example:
3. Nested loop using one or more loop inside any another (like while, for or do..while loop. if condition:
7.1 For Loop # Some code here
In Python, we use a for loop to iterate over sequences such as lists, strings, dictionaries, etc. else:
The for loop is particularly useful when the number of iterations is known. For example, pass # Nothing happens in the “else” case
Example:
Syntax
n = 10
for val in sequence:
# use pass inside if statement
# run this code
if n > 10:
Example
pass
languages = ['Swift', 'Python', 'Go']
print('Hello')
# start of the loop
Suppose we didn't use pass or just put a comment as: Here, we will get an error message: Indentation
for lang in languages:
print(lang) error: expected an indented block
print('-----') n = 10
# end of the for loop if n > 10:
Output # write code later
print('Last statement')
P print('Hello')
Example: Loop Through a String
y
language = 'Python' Note: The difference between a comment and a pass statement in Python is that while the
t
# iterate over each character in language interpreter ignores a comment entirely, pass is not ignored.
h
for x in language:
o
print(x)
n
For Loop with Python range( )
In Python, the range( ) function returns a sequence of numbers. For example,
#generate numbers from 0 to 3
values = range(0, 4) here 0 is starting value , 4 is stop value(excluded).
Here, range(0, 4) returns a sequence of 0, 1, 2 ,and 3.
Since the range() function returns a sequence of numbers, we can iterate over it using a for loop. For
example,
#iterate from i = 0 to i= 3
for i in range(0, 4):
print(i)

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
26 27
26 27

7.2 break and continue Statement In the above example, continue statement skips the current iteration when the number is even and
The break and continue statements are used to alter the flow of starts the next iteration.
loops. Example
7.2.1 break Statement # Using while loop to print numbers from 1 to 5
count = 1
The break statement terminates the for loop immediately
while count <= 5:
before it loops through all the items. The break statement is print(count)
usually used inside decision-making statements such count += 1
as if...else.
For example, Infinite while Loop
languages = ['Swift', 'Python', 'Go', 'C++'] If the condition of a while loop always evaluates to True , the loop runs continuously, forming
for lang in languages: an infinite while loop. For example,
if lang == 'Go': age = 32
break # the test condition is always True
print(lang) while True:
Output print('You can vote')
Swift let’s see where infinite loop is used in real life problem to solve that problem
Python Problem: A small shop in Bandipur wants to implement a simple automated system for managing their
Note: Here, when lang is equal to 'Go', the break statement inside the if condition executes which daily sales. They want a program that continuously takes sales input, calculates the total, and provides
terminates the loop immediately. This is why Go and C++ are not printed. a way to exit the system at the end of the day.
7.2.2 Continue Statement Program:
def daily_sales_system():
The continue statement skips the current iteration of the loop and continues with the next total_money = 0 # Start with no money
iteration. For example,
languages = ['Swift', 'Python', 'Go', 'C++'] print("Welcome to our Shop Game!")
for lang in languages: print("Tell me the price of each thing you sell. When you are finished, type 'done'.")
if lang == 'Go': while True: # Keep asking for prices until we are 'done'
continue price_text = input("What's the price? ")
print(lang)
output if price_text.lower() == 'done':
break # If you type 'done', we stop asking
Swift
Python try:
C++ price = float(price_text) # Try to turn what you typed into a number
Note: Here, when lang is equal to 'Go' ,
the continue statement executes, which skips the if price >= 0: # If the price is okay (not a bad number)
remaining code inside the loop for that iteration. total_money = total_money + price # Add the price to our total money
print(f"Okay, added Rs. {price:.2f}. We have made Rs. {total_money:.2f} so far!")
However, the loop continues to the next iteration. else:
This is why C++ is displayed in the output. print("Hmm, that doesn't look like a right price. Please tell me a number or 'done'.")
7.3 While Loop
We use a while loop when we don't know in advance how many times to repeat. It’s like having a set of except ValueError:
instructions for a computer to keep doing something over and over until a specific goal is achieved or print("Oops! That wasn't a number. Please type the price like '10' or '25.50', or type 'done'.")
a condition is no longer met.
print("\n--- That's the end of the day! ---")
Example: Output:
print(f"We made a total of Rs. {total_money:.2f} today!")
# Program to print odd numbers from 1 to 10 1
num = 0 3 if __name__ == "__main__":
while num < 10: 5 daily_sales_system()
num += 1 7
if (num % 2) == 0: 9
continue
print(num)

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
28 29
28 29

For loop While loop For loop While loop Syntax: string.upper()
For loop is used when we know the number of While loop is used when we don’t know the Example:
iterations. number of iterations.
text = "Python is awesome"
This loop iterates an infinite number of times if If the condition is not specified, it shows
print(text.upper())
the condition is not specified. compilation error.
The increment is done after the execution of the The increment can be done before or after the How do we know that it doesn’t changes the original string and returned a new one?
statement. execution of a statement. Answer: you can verify that .upper() doesn't change the original string by printing the string before and after
The nature of increment is simple. The nature of increment is complex. calling .upper(). This proves that .upper() does not modify the original string—it just returns a new uppercase
Initialization can be in or out of the loop. Initialization is always out of the loop. version.
Example:
Let’s check! Which loop is used when the number of iterations is known beforehand?
text = "Python is awesome"
a. For loop b. While loop c. Do-while loop d. None of the above
upper_text = text.upper()
print("Original Text:", text)
print("Uppercase Text:", upper_text)
Lesson 8: Library Function
A library function is a predefined function that is already written and stored in Python's libraries In Python, when you "change" an immutable string, does the original string's memory
(or modules). You can use these functions without writing their code from scratch, which saves become garbage?
time and effort. Yes, when you "change" an immutable string in Python, a new string is created. If the original
string is no longer referenced by any variables, its memory becomes garbage and will be reclaimed by
8.1 String Function Python's garbage collector.
Python provides several built-in methods to manipulate strings.
Does garbage create problem in RAM?
1. center()
Yes, "garbage" can potentially create problems (like Increased Memory Usage, Out of Memory, etc.) in
Syntax: string.center(width) RAM if it's not managed effectively.
• width: The total length of the resulting string after centering.
Imagine there is a tea stall in road-side and every second customer get a cup of tea and after
• If width is greater than the length of the string, spaces are added on both sides.
• If width is less than or equal to the string's length, the original string is returned.
drinking he/she throw that cup and there is no one to regularly collect and dispose the used cups so,
Example: now you might run out of space.
string = "Python is awesome" 3. lower()
new_string = string.center(24) The .lower() function in Python is a string method used to convert all characters in a string to
print("Centered String:", new_string) lowercase.
Explanation: Syntax:
• Original string: "Python is awesome" → length = 17 string.lower()
• width = 24, so 24 - 17 = 7 spaces are needed Example:
• Spaces are added evenly: 3 on the left, 4 on the right text = "Python is awesome"
print(text.lower())
✅Syntax with padding character
string.center(width, fillchar) 4. len()
• width: Total desired length after centering. It returns the number of characters (including spaces, punctuation, etc.) present in the string.
• fillchar: A single character (like ' * ', ' - ', ' #', etc.) used to fill the empty spaces. Syntax:
Example: Len()
string = "Python is awesome" Example:
new_string = string.center(24,”*”) total = "Computer"
print("Centered String:", new_string) print(“Length of string:”,len(total))
Output: ***Python is awesome**** 8.2 Numeric functions
Numeric functions are built-in functions used to perform operations on numbers.
2. upper()
1. abs()
The .upper() function in Python is a string method used to convert all characters in a string to It always returns the positive value of a number.
uppercase. It does not change the original string (strings are immutable, This means that once a Example:
string is created, its content cannot be directly changed), but returns a new one. print(abs(-5)) # Output: 5

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
30 31
30 31

2. round() Lesson 9: Programs


Rounds a float to the nearest whole number (or to specified decimal places). 1. What is Armstrong Number?
Example: An Armstrong number (also known as a narcissistic number, pluperfect number, or pluperfect digital invariant) is a
print(round(3.6)) # Output: 4 number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, in a 3-
print(round(3.1416, 2)) # Output: 3.14 digit number, the sum of each digit raised to the power of three equals the number itself.
3. pow() Example
It raises a number to the power of another (same as **)
Example:
print(pow(2, 4)) #Output: 16 2^4
2. What is Palindrome?
4. max() and min()
It is used to find the largest or smallest number from arguments. A palindrome is a word, number, phrase, or other sequences of characters that reads the same forward
Example: and backward (ignoring spaces, punctuation, and capitalization).
print(max(5, 10, 3)) # Output: 10 Example
print(min(5, 10, 3)) # Output: 3 • Number: 121, 1331, 12321
5. divmod() • Word: "radar", "level", "madam"
Returns a tuple of (quotient, remainder) • Phrase: "A man, a plan, a canal, Panama"
Example: print(divmod(10, 3)) #Output: (3, 1) 3. What is perfect number?
8.3 Mathematical Function A perfect number is a positive integer that is equal to the sum of its proper divisors (the positive
divisors excluding the number itself).
In python a math module is used to access mathematical functions. All methods of math() function are
Example:
used for integer or real type objects but not for complex numbers.
• The proper divisors of 6 are 1, 2, and 3.
To use mathematical function first import math function. • The sum of these proper divisors is 1 + 2 + 3 = 6.
1. math.sqrt() • Since the sum of the proper divisors of 6 is equal to 6, 6 is a perfect number.
Returns the square root of a number. 4. what is strong number?
Example: A strong number is a special number where the sum of the factorial of each digit equals the number
import math itself. Example: 145 is a strong number
print(math.sqrt(25)) # Output: 5.0 • Digits of 145 are: 1, 4, and 5
• Factorials:
2. math.floor() o 1! = 1
Rounds down to the nearest whole number. o 4! = 4 * 3 * 2 * 1 = 24
o 5! = 5 * 4 * 3 * 2 * 1 = 120
Example:
import math • Sum of factorials: 1 + 24 + 120 = 145
print(math.floor(3.9)) # Output: 3 5. What are amicable number?
Amicable numbers are a pair of two different numbers so related that the sum of the proper divisors of
3. math.ceil()
each is equal to the other number.
Rounds up to the nearest whole number. If the sum of the proper divisors of the first number equals the second number, AND the sum of the proper divisors
Example: of the second number equals the first number, then the two numbers are amicable.
import math Example:
print(math.ceil(3.1)) # Output: 4 • The proper divisors of 220 are: 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, and 110. Their sum is 284.
4. math.pi() • The proper divisors of 284 are: 1, 2, 4, 71, and 142. Their sum is 220.
It return the value of pi. 6. What is pangram string?
A pangram is a sentence or phrase that contains every letter of the alphabet at least once.
Example:
Example: "The quick brown fox jumps over the lazy dog."
Import math 7. What is Anagram String?
Print(math.pi) # Output: 3.141592653589793 An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using
5. math.factorial() all the original letters exactly once.
Returns the factorial of a number. Examples:
Example: print(math.factorial(5)) # Output: 120 • "listen" is an anagram of "silent"
6. math.sin(), math.cos(), math.tan(): Return the sine, cosine, and tangent of a number (in radians). • "eleven plus two" is an anagram of "twelve plus one"
Example: print(math.sin(math.pi/2)) #output: 1.0 • "Astronomer" is an anagram of "Moon starer"

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
32 33
32 33

1. write a program to calculate the average of 2. write a program to input any five numbers and 15. Find Factorial of number. 16. Program to find Fibonacci series.
three numbers. display their sum using array. n = int(input("Enter a number: ")) n = int(input("Enter number of terms: "))
num1 = float(input("Enter the first number: ")) numbers = [] factorial = 1 a, b = 0, 1
num2 = float(input("Enter the second number: ")) for i in range(5): for i in range(1, n + 1): for _ in range(n):
num3 = float(input("Enter the third number: ")) num = float(input(f"Enter number {i+1}: ")) factorial *= i print(a, end=' ')
average = (num1 + num2 + num3) / 3 numbers.append(num) print("Factorial of", n, "is:", factorial) a, b = b, a + b
print("The average of the three numbers is:", average) total_sum = sum(numbers) 17. Check whether number is Armstrong or not. 18. Program to check whether palindrome or not.
print("The sum of the five numbers is:", total_sum) num = int(input("Enter a number: ")) num = int(input("ENTER A NUMBER: "))
3. write a program to find square of a given 4. Write a program to find area of rectangle original = num # Store the original number for comparison
number. length = float(input("Enter the length: ")) digits = len(str(num)) temp = num
num = float(input("Enter a number: ")) breadth = float(input("Enter the breadth: ")) sum = 0 reverse = 0
square = num ** 2 area = length * breadth # Reverse the number
print("The square of", num, "is:", square) print("Area of the rectangle:", area) while num > 0: while num > 0:
5. Write a program to swap two number. 6. program to Check whether a number is odd or digit = num % 10 digit = num % 10
a = input("Enter the first number: ") even. sum += digit ** digits reverse = reverse * 10 + digit
b = input("Enter the second number: ") num = int(input("Enter a number: ")) num //= 10 num = num // 10 # Integer division
a, b = b, a if num % 2 == 0: # Check if it's a palindrome and print the result
print("After swapping:") print("Even number") if sum == original: if temp == reverse:
print("First number:", a) else: print("Armstrong number") print(temp, "IS A PALINDROME NUMBER")
print("Second number:", b) print("Odd number") else: else:
7. Program to generate Multiplication table. 8. Find the largest number between two numbers print("Not an Armstrong number") print(temp, "IS NOT A PALINDROME NUMBER")
n = int(input("Enter a number: ")) a = input("Enter first number: ") 19. program to check string is palindrome or not. 20. write a program that ask to enter sentence and
b = input("Enter second number: ") word = input("Enter a word: ") count the number of words in it.
for i in range(1, 11): if a > b: word = word.lower() # Get input from the user
print(f"{n} * {i} = {n * i}") print("Largest number is:", a) sentence = input("Enter a sentence: ")
else: # Reverse the word!
print("Largest number is:", b) rev = word[::-1] # Split the sentence into words
9. Find the largest number between three 10. Check whether a number is positive, negative, words = sentence.split()
numbers or zero. if word == rev:
a = float(input("Enter first number: ")) num = float(input("Enter a number: ")) print("Yay! It's a palindrome!") word_count = len(words)
b = float(input("Enter second number: ")) if num > 0: else:
c = float(input("Enter third number: ")) print("Positive number") print("Nope, not a palindrome.") print("The number of words in the sentence is:",
if a >= b and a >= c: elif num < 0: word_count)
print("Largest number is:", a) print("Negative number") 21. write a program to generate the following 22. write a program to print only vowels from a
elif b >= a and b >= c: else: series: 1, 12, 123, 1234, 12345 given word.
print("Largest number is:", b) print("Zero") n = 5 # Number of terms to generate word = input("Enter a word: ")
else: for i in range(1, n + 1): vowels = "aeiouAEIOU"
print("Largest number is:", c) series= ""
11. Write a program to calculate simple interest. 12. program that will Reverse a number for j in range(1, i + 1): for char in word:
p = float(input("Enter principal amount: ")) num = int(input("Enter a number: ")) series += str(j) if char in vowels:
t = float(input("Enter time in years: ")) reverse = 0 print(series, end=", ") print(char, end=" ")
r = float(input("Enter rate of interest: ")) while num > 0: 23. write a python code to generate the series with 24. write a program that will ask to enter word
digit = num % 10 their sum 1,2,3,4,...., upto 10th terms. and reverse it.
si = (p * t * r) / 100 reverse = reverse * 10 + digit sum = 0 word = input("Enter a word: ")
print("Simple Interest:", si) num //= 10 # floor or int division print("The series is:", end=" ") #[:] selects the entire string.
print("Reversed number:", reverse) for i in range(1, 11): # [::-1] adds a step value of -1
13. program to check given year is leap year or not. 14. Program to find sum of N number. print(i, end=" ") reversed = word[::-1]
year = int(input("Enter a year: ")) n = int(input("Enter a number: ")) sum += i
if (year % 4 == 0 and year % 100 != 0) or (year % 400 sum = 0 print() # it will print a newline # Print the reversed word
== 0): for i in range(1, n + 1): print("Reversed word:", reversed)
print("Leap year") sum += i print("The sum of the series is:", sum)
else:
print("Not a leap year") print("Sum of first", n, "numbers is:", sum)

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
34 35
34 35

25. Write a program to find LCM of any two 26. Write a program to find HCF of any two 33. Program to read a number n and compute 34. Program to print all the prime numbers within
numbers. numbers. n+nn+nnn. (Hint: if n is 5,then calculate 5 + 55 + a given range.
# Get input from the user num1 = int(input("Enter first number: ")) 555) r=int(input("Enter upper limit: "))
num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) n=int(input("Enter a number n: ")) for a in range(2,r+1):
num2 = int(input("Enter second number: ")) temp=str(n) k=0
if num1 > num2: # Calculate HCF using the Euclidean Algorithm t1=temp+temp for i in range(2,a//2+1):
greater = num1 x = num1 t2=temp+temp+temp if(a%i==0):
else: y = num2 comp=n+int(t1)+int(t2) k=k+1
greater = num2 print("The value is:",comp) if(k<=0):
# Calculate LCM while y: print(a)
while True: x, y = y, x % y 35. Program to check given number is prime or 36. Program to check if a number is a Perfect
if (greater % num1 == 0) and (greater % num2 == hcf = x # The HCF is the last non-zero value of x not. number.
0): a=int(input("Enter number: ")) n = int(input("Enter any number: "))
lcm = greater print("The HCF of", num1, "and", num2, "is", hcf) k=0 sum1 = 0
break # Exit the loop when LCM is found for i in range(2,a//2+1): for i in range(1, n):
greater += 1 if(a%i==0): if(n % i == 0):
print("The LCM of", num1, "and", num2, "is", lcm) k=k+1 sum1 = sum1 + i
27. Program to find the sum of digits in a number. 28. Program to count the number of digits in a if(k<=0): if (sum1 == n):
n=int(input("Enter a number:")) number. print("Number is prime") print("The number is a Perfect number!")
total=0 n=int(input("Enter number:")) else: else:
while(n>0): count=0 print("Number isn't prime") print("The number is not a Perfect number!")
digit=n%10 while(n>0): 37. Program to find the sum of first N Natural 38. Program to find the area of a triangle given all
total=total + digit count=count+1 Numbers. three sides.
n=n//10 n=n//10 n=int(input("Enter a number: ")) import math
print("The total sum of digits is:", total) print("The number of digits in the number are:", sum = 0 a=int(input("Enter first side: "))
count) while(n > 0): b=int(input("Enter second side: "))
29. Program to generate all the divisors of an integer. 30. Program to find the smallest divisor of an integer. sum=sum+n c=int(input("Enter third side: "))
n=int(input("Enter an integer:")) n=int(input("Enter an integer:")) n=n-1 s=(a+b+c)/2
print("The divisors of the number are:") a=[ ] print("The sum of first n natural numbers is", sum) area=math.sqrt(s*(s-a)*(s-b)*(s-c))
for i in range(1,n+1): for i in range(2,n+1): print("Area of the triangle is: ",round(area,2))
if(n%i==0): if(n%i==0): 39. Program to check number is amicable or not. 40. Program to find whether a number is a power
print(i) a.append(i) x=int(input('Enter number 1: ')) of two.
a.sort() y=int(input('Enter number 2: ')) num = int(input("Enter a number: "))
print("Smallest divisor is:",a[0]) sum1=0
31. Program to take in the marks of 5 subjects and 32. Program to check if a number is a strong sum2=0 if num <= 0:
display the grade. number. for i in range(1,x): is_power = False
sub1 = int(input("Enter marks of the first subject: ")) sum=0 if x%i==0: else:
sub2 = int(input("Enter marks of the second subject: num=int(input("Enter a number:")) sum1+=i # Check if it's a power of two using bitwise AND
")) temp=num for j in range(1,y): is_power = (num & (num - 1)) == 0
sub3 = int(input("Enter marks of the third subject: ")) while(num): if y%j==0:
sub4 = int(input("Enter marks of the fourth subject: i=1 sum2+=j if is_power:
")) fact=1 if(sum1==y and sum2==x): print(num, "is a power of two")
sub5 = int(input("Enter marks of the fifth subject: ")) r=num%10 print('Amicable!') else:
avg = (sub1 + sub2 + sub3 + sub4 + sub5) / 5 while(i<=r): else: print(num, "is not a power of two")
if avg >= 90: fact=fact*i print('Not Amicable!')
print("Grade: A") i=i+1
elif avg >= 80 and avg < 90: sum=sum+fact
print("Grade: B") num=num//10
elif avg >= 70 and avg < 80: if(sum==temp):
print("Grade: C") print("The number is a strong number")
elif avg >= 60 and avg < 70: else:
print("Grade: D") print("The number is not a strong number")
else:
print("Grade: F")

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
36 37
36 37

41. Program to accept three distinct digits and 42. Program to check if a string is a pangram or 53. Program to count the number of lowercase 54. Program to calculate the number of digits and
prints all possible combinations from the digits. not. characters and uppercase characters in a string. letters in a string.
a=int(input("Enter first number:")) word = input("Enter string:") word = input("Enter string:")
b=int(input("Enter second number:")) from string import ascii_lowercase as asc_lower count1=0 count1=0
c=int(input("Enter third number:")) count2=0 count2=0
d=[] def check(s): for i in word: for i in word:
d.append(a) return set(asc_lower) - set(s.lower()) == set([]) if(i.islower()): if(i.isdigit()):
d.append(b) count1=count1+1 count1=count1+1
d.append(c) word = input("Enter string:") elif(i.isupper()): count2=count2+1
for i in range(0,3): count2=count2+1 print("The number of digits is:")
for j in range(0,3): if(check(word) == True): print("Total lowercase characters is:") print(count1)
for k in range(0,3): print("The string is a pangram") print(count1) print("The number of characters is:")
if(i!=j&j!=k&k!=i): else: print("Total uppercase characters is:") print(count2)
print(d[i],d[j],d[k]) print("The string isn't a pangram") print(count2)
43. Program to take the temperature in Celsius 44. Program to read a number n and print an 55. Program to check common letters in the two 56. Program to Swap First & Last Character of a
and convert it to Fahrenheit. inverted star pattern of the desired size. input strings. String
celsius=int(input("Enter the temperature in s1= input("Enter first string:") def change(string):
celcius:")) n=int(input("Enter number of rows: ")) s2= input("Enter second string:") return string[-1:] + string[1:-1] + string[:1]
f=(celsius*1.8)+32 for i in range (n,0,-1): a=list(set(s1)&set(s2)) string=input("Enter string:")
print("Temperature in Fahrenheit is:" , f) print((n-i) * ' ' + i * '*') print("The common letters are:") print("Modified string:")
45. Program to read two numbers and print their 46. Program to swap two numbers without using for i in a: print(change(string))
quotient and remainder. third variable. print(i)
a=int(input("Enter the first number: ")) a=int(input("Enter first Number: ")) 57. Program to Check two Strings are anagram or 58. Program to find square root of given number.
b=int(input("Enter the second number: ")) b=int(input("Enter second Number: ")) not.
quotient=a//b a=a+b s1= input("Enter first string:") num = int(input("enter Number: "))
remainder=a%b b=a-b s2= input("Enter second string:") S = num ** 0.5
print("Quotient is:",quotient) a=a-b if(sorted(s1)==sorted(s2)): print("The square root of number is:", round(S,2))
print("Remainder is:",remainder) print("a is:",a," b is:",b) print("The strings are anagrams.")
47. Program to find the gravitational force 48. Program to read a number n and print an else:
between two objects (like Earth and sun). identity matrix of the desired size. print("The strings aren't anagrams.")
m1=float(input("Enter first obj mass: ")) n=int(input("Enter a number: ")) 59. Program to ask radius of the circle and display 60. Write a program to convert USD into NPR.
m2=float(input("Enter second obj mass: ")) for i in range(0,n): the area. [Hint: A = pi*R ^ 2] dollar = float(input("Enter The USD: "))
r=float(input("Enter distance between their centres: for j in range(0,n): radius = float(input("Enter Radius")) NC = dollar * 110
")) if(i==j): pi=3.14 print(f"Total Nepali currency of {dollar} is:", NC)
G=6.673*(10**-11) print("1",sep=" ",end=" ") Area= pi*radius**2
f=(G*m1*m2)/(r**2) else: print("Area of circle is", Area)
print("Gravitational force is: ", round(f,2),"N") print("0",sep=" ",end=" ") 61. program to input days and convert into years, 62. program to input seconds and convert into
print() months and days. hours minutes and seconds.
49. Program to replace all occurrences of ‘a’ with 50. Program to take a string and replace every seconds = int(input("Enter Second: "))
‘$’ in a string. blank space with a hyphen. days = int(input("Enter the number of days: "))
string=input("Enter string:") string=input("Enter string:") hour = seconds // 3600
string=string.replace('a','$') string=string.replace(' ','-') years = days // 365 minute = seconds % 3600
string=string.replace('A','$') print("Modified string:") rem_days = days % 365 rem_minute = minute // 60
print("Modified string:") print(string) months = rem_days // 30 second = minute % 60
print(string) days = rem_days % 30
51. Program to calculate the length of a string 52. Program to count number of lowercase print(f"{hour} Hours {rem_minute} Minute {second}
without using library functions. characters in a string. print(f"{years} years {months} Month {days} Days") Seconds")
word = input("Enter string:") word = input("Enter string:")
count=0 count=0
for i in word: for i in word:
count=count+1 if(i.islower()):
print("Length of the string is:") count=count+1
print(count) print("Total lowercase characters is:")
print(count)

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
38 39
38 39

63. program to input number and find sum of even 64. Program to find the product of its digits. 70. Program check Composite or not. 71. Program to print pattern 5, 55, 555, … up to 5th
digits. num = int(input("Enter a number: ")) terms
n = int(input("Enter a number: ")) N = int(input("Enter a number: ")) if num <= 1: A=5
s=0 p=1 print(num, "is not composite") for i in range(1,6):
else: print(A)
while n != 0: while N != 0: i=2 A = A * 10 + 5
r = n % 10 R = N % 10 while i * i <= num: 72. program to print series: 1, 11, 111, 1111,
if r % 2 == 0: p=p*R if num % i == 0: 11111
s=s+r N = N // 10 print(num, "is a composite number") A=1
n = n // 10 break for i in range(1,6):
print("Sum of even digits:", s) print("Products of digits:", p) i += 1 print(A)
65. Program to input number and display only odd 66. Program to input number and count total no. else: A = A * 10 + 1
digits. of digits. print(num, "is not a composite number")
N = int(input("Enter Number")) 73. program to display pattern 33333, 3333, 333, 74. Program to display pattern: 1, 12, 123, 1234,
N = int(input("Enter a number: ")) C=0 33, 3 12345

while N != 0: while N != 0: A = 33333 for i in range(1, 7):


R = N % 10 # extract the last digit of an integer C=C+1 for i in range(1,6): for j in range(1, i):
if R % 2 == 1: N = N // 10 print(A) print(j, end=" ")
print(R) A = A //10 print()
N = N // 10 print(C) 74. Program to print pattern: 1, 22, 333, 4444, 75. program to print: 12345, 1234, 123, 12, 1
67. program to input digits and reverse the digits.
68. program to input digits and reverse the digits 55555
N = int(input("Enter Number")) and generate pattern in reverse order. Enter for i in range(1, 6): for i in range(6, 1, -1):
reverse = 0 number: 123 for j in range(0, i): for j in range(1, i):
while N > 0: 3 print(i, end=" ") print(j, end=" ")
digit = N % 10 32 print() print()
reverse = reverse * 10 + digit 321 76. program to print : 55555, 4444, 333, 22, 1
77. Program to print: 1, 121, 12321, 1234321,
N = N // 10 N = int(input("Enter Number: ")) 123454321
print(reverse) pattern = 0 for i in range(5, 0, -1): A=1
while N > 0: for j in range(0, i): for i in range(1,6):
digit = N % 10 print(i, end=" ") print(A**2)
pattern = pattern * 10 + digit print() A = A*10+1
N = N // 10 78. Program to print: 123454321, 1234321, 79. Program to print : 9, 28, 14, 7, 22, 11,..10th
print(pattern) 12321, 121, 1 term
69. program to input digits and generate pattern 69 number question of another solution. A=9
in order. Enter number: 123 N = int(input("Enter Number: ")) A = 11111 for i in range(1, 11):
1 for i in range(1,6): print(A, end=(","))
12 # Reverse the number first print(A**2) if A % 2 == 0:
123 rev = 0 A = A // 10 A = A // 2
while N > 0: else:
number = input("Enter number: ") rev = rev * 10 + N % 10 A=A*3+1
N //= 10 80. Program to generate: 7,22,11,34……………10th 81. Program to generate: 22, 11, 34, 17, … upto 10th
pattern = " " terms. terms.
# Print digits in order A = 22
for digit in number: pattern = 0 A=7 for i in range(1, 11):
pattern += digit while rev > 0: for i in range(1, 11): print(A, end=(","))
print(pattern) pattern = pattern * 10 + rev % 10 print(A, end=(",")) if A % 2 == 0:
rev //= 10 if A % 2 == 0: A = A // 2
print(pattern) A = A // 2 else:
else: A=A*3+1
A=A*3+1

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965
40 41
40 41

82. Program to generate: 1, 4, 9, 16.....upto 10th 83. Program to generate: 1, 8, 27, 64.....upto 10th 94. Program to generate: 1,2,3,5,8, ….10th terms. 95. Program to generate: 5, 10, 15,25 .... up to10th
term. term. term.
A=1 A=5
for i in range(1, 11): for i in range(1, 11): B=2 B = 10
print(i**2, end=(",")) print(i**3, end=(",")) for i in range(1, 11): for i in range(1, 11):
84. Program to generate: 999, 728, 511.........upto 85. Program to generate: 315, 270, 215, 150 ........ print(A, end=(",")) print(A, end=(","))
10th term. upto 10th term. C=A+B C=A+B
A=B A=B
a = 999 a = 315 B=C B=C
b = 271 b = 45 96. Program to generate: 1, 0, 1, 1, 2, 3..... upto 10th 96. Program to generate: 1, 0, 1, 1, 2, 3..... upto 10th
c = 54 for i in range(1, 11): term. term.
for i in range(1, 11): print(a, end=(",")) a=1
print(a, end=(",")) a=a-b b=0 a=1
a=a-b b = b + 10 count = 0 b=0
b=b-c while count < 10:
c=c-6 print(a, end=", ") for i in range(10): # Loop to print 10 terms
86. Program to generate: 5, 10, 20, 35, 55.........upto 87. Program to generate: 2, 8, 18, 32,.. upto 10th temp = a # Store the current value of a print(a, end=", ")
10th term. terms a=b # Update a to the current value of b temp = a
b = temp + b # Update b to the sum of old a and b a=b
a=5 a=2 count += 1 b = temp + b
b=5 b=6 97. Program to generate: 3, 3, 6, 9, 15,.. upto 10th 98. Program to generate: 100, 90, 80, ...upto 10th
for i in range(1, 11): for i in range(1, 11): term. term.
print(a, end=(",")) print(a, end=(",")) A=3 term = 100
a=a+b a=a+b B=3 for i in range(10): # Loop for 10 terms
b=b+5 b=b+4 print(term, end=", ")
88. Program to generate: 2 , 4, 8, 14, 22 …upto 10th 89. Program to generate: 2, 4, 7, 11, 16 up to 10th for i in range(10): # Loop to print 10 terms
term -= 10
terms. terms. print(A, end=", ")
C = A+B
a=2 a=2 A=B
b=2 b=2 B=C
for i in range(1, 11): for i in range(1, 11): 99. Check the shortest word among the three 100. Enter any word and print alternate case of
print(a, end=(",")) print(a, end=(",")) different word input by the user and print it. each character Eg. Nepal to NePaL.
a=a+b a=a+b word1 = input("Enter first word: ")
b=b+2 b=b+1 word = input("Enter a word: ")
word2 = input("Enter second word: ")
90. Program to generate: 2,6,12,20,30, …upto 10th 91. Program to generate: 0,1, 3, 6, 10, … upto 10th word3 = input("Enter third word: ") result = ""
term terms. for i in range(len(word)):
shortest = word1 if i % 2 == 0:
a=2 a=0 if len(word2) < len(shortest): result += word[i].upper()
b=4 b=1 shortest = word2 else:
for i in range(1, 11): for i in range(1, 11): if len(word3) < len(shortest): result += word[i].lower()
print(a, end=(",")) print(a, end=(",")) shortest = word3
a=a+b a=a+b print("The shortest word is:", shortest) print("Alternate case:", result)
b=b+2 b=b+1 101. Print the following string: 102. print the following string pattern:
92. Program to generate: 1, 2, 4, 7, 11, …upto 10th 93. Program to generate: 2, 8, 18, 32, ..upto 10th NEPAL H
term. terms. NEPA KHA
NEP OKHAR
a=1 for i in range(1, 11): NE POKHARA
b=1 print((i**2)*2, end=(",")) N
for i in range(1, 11): word = "POKHARA"
print(a, end=(",")) word = "NEPAL" steps = ["H", "KHA", "OKHAR", "POKHARA"]
a=a+b for i in range(len(word), 0, -1):
b=b+1 print(word[:i]) for step in steps:
print(step)

Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA] Python Notes WWW.CODEPLUS.COM.NP Saroj Yadav [BCA]
Basics | Grade-9 +977-9814 896 965 Basics | Grade-9 +977-9814 896 965

You might also like