Welcome To RajeshSir.com
Introduction to Python:
Python is a high-level, interpreted programming language known for its simplicity and readability.
Created by Guido van Rossum and first released in 1991.
Installation:
Visit the official Python website (https://www.python.org) to download the latest version.
Python comes with an interactive shell (REPL) that allows you to execute code line by line.
Printing and Comments:
Printing to the console: print("Hello, World!")
Comments are denoted by the hash symbol (#): # This is a comment
Variables and Data Types:
Variables store data and their type is dynamically inferred.
Common data types: int, float, str, bool, list, tuple, dict.
Basic Operations:
Arithmetic: +, -, *, /, % (modulus), ** (exponentiation).
Comparison: ==, !=, >, <, >=, <=.
Logical: and, or, not.
Conditional Statements:
Use if, elif, and else to perform different actions based on conditions.
Example:
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
7. Loops:
Use for and while loops for repetitive tasks.
Example:
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
8. Lists:
Lists are ordered, mutable collections of items.
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Accessing elements
fruits.append("orange") # Adding elements
9. Functions:
Functions allow you to group code into reusable blocks.
Example:
def add(a, b):
return a + b
10. Modules:
Python has a rich standard library and additional third-party libraries.
Import modules using import to extend functionality.
11. Input from Users:
To get input from the user, use the input() function.
Example:
name = input("Enter your name: ")
print("Hello,", name)
12. Exception Handling
Use try, except, else, and finally to handle errors gracefully.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
13. File Handling:
Python provides functions to read from and write to files.
Example (reading from a file):
with open("myfile.txt", "r") as file:
content = file.read()
print(content)
Numeric Types:
int: Integer type represents whole numbers (e.g., 5, -10, 100).
float: Floating-point type represents decimal numbers (e.g., 3.14, -0.5, 2.0).
String Type:
str: String type represents sequences of characters enclosed in single (' '), double (" "), or triple (''' ''' or """ """) quotes. (e.g., "Hello", 'Python', "123").
Boolean Type:
bool: Boolean type represents the truth values True or False. Used in logical operations and control flow statements.
Sequence Types:
list: A mutable ordered collection that allows duplicate elements (e.g., [1, 2, 3]).
tuple: An immutable ordered collection that allows duplicate elements (e.g., (1, 2, 3)).
range: Represents an immutable sequence of numbers used in loops and iterations (e.g., range(5) represents 0 to 4).
Mapping Type:
dict: A mutable collection of key-value pairs, also known as dictionaries (e.g., {'name': 'John', 'age': 30}).
Set Types:
set: A mutable, unordered collection of unique elements (e.g., {1, 2, 3}).
frozenset: An immutable version of a set (e.g., frozenset({1, 2, 3})).
None Type:
None: Represents the absence of a value or a null value. Used to indicate that a variable has no value assigned to it.
Binary Types:
bytes: Immutable sequence of bytes (e.g., b'Hello').
bytearray: Mutable sequence of bytes (e.g., bytearray(b'Hello')).
Complex Type:
complex: Represents complex numbers with a real and imaginary part (e.g., 3 + 5j).
Example:
x =10
print(type(x)) # Output: <class 'int'>
y = "Hello"
print(type(y)) # Output: <class 'str'>
Keywords in Python are reserved words that have special meanings and purposes within the language. These keywords cannot be used as identifiers (variable names, function names, etc.) because they have predefined functionalities. As of my knowledge cutoff in September 2021, here is a list of Python keywords:
and del from not while
as elif global or with
assert else if pass yield
break except import raise
class False in return
continue finally is True
def for lambda try
\\: Backslash itself (escaping the backslash).
\': Single quote.
\": Double quote.
\n: Newline - Moves the cursor to the beginning of the next line.
\t: Tab - Inserts a horizontal tab.
\r: Carriage Return - Moves the cursor to the beginning of the current line.
\b: Backspace - Moves the cursor one character back.
\f: Form Feed - Inserts a page break.
# Using backslash to escape single and double quotes
print('It\'s a beautiful day.') # Output: It's a beautiful day.
print("He said, \"Hello!\"") # Output: He said, "Hello!"
# Newline and tab
print("Hello\nWorld") # Output: Hello
# World
print("Hello\tWorld") # Output: Hello World
# Backspace and carriage return
print("Hello\bWorld") # Output: HellWorld
print("Hello\rWorld") # Output: Worldlo
Python provides various mechanisms for data handling, manipulation, and storage. Here are some essential techniques for data handling in Python:
Variables and Data Types:
Use variables to store data in memory during the program execution.
Python supports various data types like integers, floats, strings, lists, tuples, dictionaries, sets, etc.
Input and Output:
Use input() to get input from the user.
print() is used to display output to the console.
Lists, Tuples, and Sets:
Lists ([]) are mutable collections of items that can contain elements of different data types.
Tuples (()) are similar to lists, but they are immutable once defined.
Sets ({}) are unordered collections of unique elements.
Dictionaries:
Dictionaries ({key: value}) are collections of key-value pairs.
Keys are unique and used to access corresponding values quickly.
String Manipulation:
Strings can be manipulated using various methods such as concatenation, slicing, formatting, etc.
File Handling:
Python provides functions to read from and write to files.
open() is used to open a file, read() and write() to read from and write to it.
CSV and JSON Handling:
The csv module is used for reading and writing CSV (Comma-Separated Values) files.
The json module is used for encoding and decoding JSON (JavaScript Object Notation) data.
Exception Handling:
Use try, except, else, and finally to handle errors gracefully.
Prevents programs from crashing due to unexpected exceptions.
Data Analysis Libraries:
NumPy: Provides support for large, multi-dimensional arrays and matrices, along with various mathematical functions.
Pandas: Offers data structures like DataFrame for efficient data manipulation and analysis.
Matplotlib and Seaborn: Libraries for creating visualizations and plots.
Data Cleaning and Preprocessing:
Data cleaning involves handling missing values, duplicates, and outliers.
Preprocessing prepares data for analysis by transforming, scaling, or encoding it.
Data Storage and Databases:
SQLite and MySQL are popular databases for storing and retrieving data in Python.
ORM (Object-Relational Mapping) libraries like SQLAlchemy simplify database interactions.
Data Visualization:
Libraries like Matplotlib, Seaborn, and Plotly allow creating various charts and plots.
Python provides a wide range of tools and libraries to efficiently work with data in different formats and structures.
1) WAP to take input as first and last name, and print it in screen with proper gap.
a = input("Enter First Name = ")
b = input("Enter Last Name = ")
print(a,b) #you can also write this code: print(a + ' ' + b)
2) WAP to take input as any number and print sum of its individual digits.
n = int(input("Enter any numbers = "))
s = 0
while n>0:
d = n % 10
s = s + d
n = n // 10
print("Sum of digits =",s)
3) WAP to take input as any number and check if its last digit is divisible by 3 or not.
n = int(input("Enter any numbers = "))
d = n%10
if(d%3==0):
print("The last digit",d,"is divisible by 3.")
else:
print("The last digit",d,"is not divisible by 3.")'''
4) WAP to print all numbers between 1 to 10 except 2 and 7.
for i in range(1,11):
if(i==2) or (i==7):
continue
else:
print(i, end = " ")'''
5) WAP to print all numbers between 1 to 10 except 7.
for i in range(1,11):
if(i==7):
continue
else:
print(i, end = " ")
6) WAP to print the sum of odd and even numbers separately from 1 to 10.
se = 0
so = 0
for i in range(1,11):
if(i%2 == 0):
se = se + i
else:
so = so + i
print("Sum of Even numbers = ", se)
print("Sum of Odd numbers = ", so)
7) WAP to print the sum of odd and even numbers separately from 1 to 10. User will take input the desired numbers.
se = 0
so = 0
for i in range(1,11):
n = int(input("Enter any number = "))
if(i%2 == 0):
se = se + n
else:
so = so + n
print("Sum of Even numbers = ", se)
print("Sum of Odd numbers = ", so)
8) WAP to take input as any number and print its multiplication table.
n = int(input("Enter any numbers = "))
for i in range(1,11):
print(n, "x", i, "=", n*i)
9) WAP to take input as age of 10 voters and find how many voters can vote. Also find the number of voters who can’t vote.
count = 0
for i in range(1,11):
age = int(input("Enter Voter's Age: "))
if(age >= 18):
count = count + 1
print("Total Eligible Voters = ", count)
print("Total numbers of voters who cann't vote = ", 10-count)
10) WAP to print sum of first 10 natural numbers.
s = 0 #initialiazation
for i in range(1,11):
s = s + i
print("Sum of Numbers = ", s)
11) WAP to print product of first 10 natural numbers.
s = 1 #initialiazation
for i in range(1,11):
s = s * i
print("Product of Numbers = ", s)
12) WAP to take input as five numbers and print their sum.
s = 0
for i in range(1,6):
n = int(input("Enter any five numbers = "))
s = s + n
print("Sum of Numbers = ", s)
13) WAP to print even number from 1 to 20.
#Method I
for i in range(1,21):
if(i%2==0):
print(i, end=' ')
#Method II
for i in range(2,21,2):
print(i, end=' ')
14) WAP to print odd number from 1 to 20.
#Method I
for i in range(1,21):
if(i%2!=0):
print(i, end=' ')
print()
#Method II
for i in range(1,21,2):
print(i, end=' ')
15) WAP to print first 10 natural numbers.
for i in range(1,11):
print(i)
16) WAP to take input as 'n' number of bottles. A box can hold 24 bottles. Find how many boxes are
required for 'n' numbers of bottles. Also, find how many bottles remain free.
n = int(input("Enter numbers of bottles:"))
print("Total number of boxes = ",n//24)
print("Bottles remained free = ",n%24)
17) WAP to take input as cost price and selling price and display profit and loss, along with the amount.
cp = int(input("Enter cost price = "))
sp = int(input("Enter selling price = "))
if(sp>cp):
print("Profit")
print("Profit Amount = ",sp-cp)
else:
print("Loss")
print("Loss Amount = ",cp-sp)
18) WAP to take input as cost price and selling price and display profit and loss, along with the
amount. Also display message for no profit-no loss condition.
cp = int(input("Enter cost price = "))
sp = int(input("Enter selling price = "))
if(cp==sp):
print("No Profit - No Loss")
else:
if(sp>cp):
print("Profit")
print("Profit Amount = ",sp-cp)
else:
print("Loss")
print("Loss Amount = ",cp-sp)
19) WAP to take input as any number and check if it is positive, negative or zero.
n = int(input("Enter any number = "))
if(n==0):
print("ZERO")
else:
if(n>0):
print("Positive")
else:
print("Negative")
20) WAP to take input as three numbers and display the largest one.
a = int(input("Enter 1st number = "))
b = int(input("Enter 2nd number = "))
c = int(input("Enter 3rd number = "))
if(a>b and a>c):
print(a,"is the largest number.")
elif(b>a and b>c):
print(b,"is the largest number.")
else:
print(c,"is the largest number.")
21) WAP to take input as a radius and find area and circumference of a circle.
r = int(input("Enter Radius = "))
area = 3.14 * r * r
c = 2 * 3.14 * r
print("Area = ", area)
print("Circumference = ", c)
Hello World
print("Hello, World!")
Sum of Two Numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum = num1 + num2
print("The sum is:", sum)
Even and Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")
Leap Year
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Factorial
num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print("The factorial of", num, "is", factorial)
Prime Number
num = int(input("Enter a number: "))
is_prime = True
if num > 1:
for i in range(2, num):
if (num % i) == 0:
is_prime = False
break
if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
else:
print(num, "is not a prime number")
Fibonacci Series
n = int(input("Enter the number of terms: "))
a, b = 0, 1
count = 0
while count < n:
print(a)
nth = a + b
a = b
b = nth
count += 1
Palindrome String
s = input("Enter a string: ")
if s == s[::-1]:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
Reverse String
s = input("Enter a string: ")
reversed_s = s[::-1]
print("Reversed string is:", reversed_s)
Sum of Digits
num = int(input("Enter a number: "))
sum_of_digits = sum(int(digit) for digit in str(num))
print("The sum of digits is:", sum_of_digits)
Count Vowels
s = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = sum(1 for char in s if char in vowels)
print("The number of vowels in the string is:", count)
Armstrong Number
num = int(input("Enter a number: "))
order = len(str(num))
sum = sum(int(digit) ** order for digit in str(num))
if num == sum:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
Greatest of three numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
greatest = max(num1, num2, num3)
print("The greatest number is:", greatest)
Simple Calculator
print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", num1 + num2)
elif choice == '2':
print(num1, "-", num2, "=", num1 - num2)
elif choice == '3':
print(num1, "*", num2, "=", num1 * num2)
elif choice == '4':
print(num1, "/", num2, "=", num1 / num2)
else:
print("Invalid input")
Area of Circle
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * (radius ** 2)
print("The area of the circle is:", area)
Merge Two Lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print("Merged list is:", merged_list)
Find Largest Element
lst = [1, 2, 3, 4, 5]
largest = max(lst)
print("The largest element is:", largest)
Remove duplicate from list
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(set(lst))
print("List after removing duplicates:", unique_lst)
Binary to Decimal
binary = input("Enter a binary number: ")
decimal = int(binary, 2)
print("The decimal representation is:", decimal)
Linear Search
lst = [1, 2, 3, 4, 5]
target = int(input("Enter the element to search: "))
found = False
for i in range(len(lst)):
if lst[i] == target:
found = True
break
if found:
print("Element found at index", i)
else:
print("Element not found")
Bubble Sort
lst = [64, 34, 25, 12, 22, 11, 90]
n = len(lst)
for i in range(n):
for j in range(0, n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
print("Sorted list is:", lst)
Matrix Addition
X = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Y = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
print("Resultant matrix is:")
for r in result:
print(r)
Transpose Matrix
X = [[1, 2],
[3, 4],
[5, 6]]
result = [[0, 0, 0],
[0, 0, 0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
print("Transposed matrix is:")
for r in result:
print(r)
GCD of two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
while num2:
num1, num2 = num2, num1 % num2
print("The GCD is:", num1)
LCM of two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
greater = max(num1, num2)
while True:
if (greater % num1 == 0) and (greater % num2 == 0):
lcm = greater
break
greater += 1
print("The LCM of", num1, "and", num2, "is", lcm)