Python Notes_copy - Converted-1
Python Notes_copy - Converted-1
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] 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
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
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
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
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
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
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
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
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
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
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
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