Basic Python Programs on "Python Interpreter"
1. Running Python as a Calculator
# Basic Arithmetic Operations
print(5 + 3) # Addition
print(10 - 4) # Subtraction
print(6 * 7) # Multiplication
print(20 / 5) # Division
print(2 ** 3) # Exponentiation
Output:
CopyEdit
8
6
42
4.0
8
2. Checking Python Version
import sys
print("Python Version:", sys.version)
Output (Example Output, may vary based on system):
Python Version: 3.10.2
3. Printing "Hello, World!"
print("Hello, World!")
Output:
Hello, World!
4. Assigning and Printing Variables
x = 10
y = 5.5
name = "Python"
print(x)
print(y)
print(name)
Output:
10
5.5
Python
5. Taking User Input
name = input("Enter your name: ")
print("Hello,", name)
Input:
Pramod Kumar
Output:
Hello, Pramod Kumar
6. Using Python Interpreter for Boolean Logic
print(5 > 3) # True
print(2 < 1) # False
print(True and False) # False
print(True or False) # True
Output:
True
False
False
True
7. Checking Data Types Using Python Interpreter
print(type(10)) # int
print(type(3.14)) # float
print(type("Python")) # str
print(type(True)) # bool
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
8. Using Python to Find Square Root
import math
print(math.sqrt(25))
Output:
5.0
9. Using Python to Calculate Factorial
import math
print(math.factorial(5))
Output:
120
10. Using Python to Get the Current Date & Time
from datetime import datetime
print("Current Date and Time:", datetime.now())
Output (Example Output, will vary based on time of execution):
Current Date and Time: 2025-04-02 15:45:30.123456
Python Programs: Using Python as a Calculator
1. Basic Arithmetic Operations
a = 15
b = 4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Output:
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
2. Taking User Input for Calculations
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
print("Quotient:", a / b)
Input:
Enter first number: 10
Enter second number: 5
Output:
Sum: 15.0
Difference: 5.0
Product: 50.0
Quotient: 2.0
3. Simple Calculator Using User Choice
def 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("Result:", num1 + num2)
elif choice == '2':
print("Result:", num1 - num2)
elif choice == '3':
print("Result:", num1 * num2)
elif choice == '4':
if num2 != 0:
print("Result:", num1 / num2)
else:
print("Error! Division by zero.")
else:
print("Invalid input")
calculator()
Input:
Enter choice (1/2/3/4): 1
Enter first number: 8
Enter second number: 2
Output:
Result: 10.0
4. Square and Cube Calculation
num = int(input("Enter a number: "))
print("Square:", num ** 2)
print("Cube:", num ** 3)
Input:
Enter a number: 4
Output:
Square: 16
Cube: 64
5. Trigonometric Calculator (Using Math Library)
import math
angle = float(input("Enter angle in degrees: "))
radians = math.radians(angle)
print("Sine:", math.sin(radians))
print("Cosine:", math.cos(radians))
print("Tangent:", math.tan(radians))
Input:
yaml
CopyEdit
Enter angle in degrees: 45
Output:
Sine: 0.7071067811865475
Cosine: 0.7071067811865476
Tangent: 0.9999999999999999
6. Logarithm and Square Root
import math
num = float(input("Enter a number: "))
print("Square Root:", math.sqrt(num))
print("Natural Log:", math.log(num))
print("Base-10 Log:", math.log10(num))
Input:
Enter a number: 100
Output:
Square Root: 10.0
Natural Log: 4.605170185988092
Base-10 Log: 2.0
7. Percentage Calculator
total_marks = float(input("Enter total marks: "))
obtained_marks = float(input("Enter obtained marks: "))
percentage = (obtained_marks / total_marks) * 100
print("Percentage:", percentage, "%")
Input:
yaml
CopyEdit
Enter total marks: 500
Enter obtained marks: 450
Output:
Percentage: 90.0 %
8. Simple Interest Calculator
p = float(input("Enter principal amount: "))
r = float(input("Enter rate of interest: "))
t = float(input("Enter time (years): "))
simple_interest = (p * r * t) / 100
print("Simple Interest:", simple_interest)
Input:
Enter principal amount: 1000
Enter rate of interest: 5
Enter time (years): 3
Output:
Simple Interest: 150.0
9. Compound Interest Calculator
p = float(input("Enter principal amount: "))
r = float(input("Enter rate of interest: "))
t = float(input("Enter time (years): "))
amount = p * (1 + r / 100) ** t
compound_interest = amount - p
print("Compound Interest:", compound_interest)
Input:
Enter principal amount: 1000
Enter rate of interest: 5
Enter time (years): 3
Output:
Compound Interest: 157.625
10. Currency Converter (USD to INR)
usd = float(input("Enter amount in USD: "))
exchange_rate = 83.5 # Example exchange rate
inr = usd * exchange_rate
print("Equivalent amount in INR:", inr)
Input:
Enter amount in USD: 10
Output:
Equivalent amount in INR: 835.0
Python Programs on "Python Shell"
1. Running Python Commands in the Shell
Simply open the Python shell by typing python or python3 in your terminal or command
prompt, then enter commands interactively.
>>> print("Hello, Python Shell!")
Output:
Hello, Python Shell!
2. Performing Arithmetic Calculations
>>> 5 + 3
8
>>> 10 - 4
6
>>> 6 * 7
42
>>> 20 / 5
4.0
>>> 2 ** 3
8
>>> 15 // 4
3
>>> 15 % 4
3
3. Checking Data Types in the Shell
>>> type(10)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("Python")
<class 'str'>
>>> type(True)
<class 'bool'>
4. Assigning and Printing Variables
>>> x = 10
>>> y = 5.5
>>> name = "Python"
>>> print(x, y, name)
Output:
10 5.5 Python
5. Taking User Input in the Shell
>>> name = input("Enter your name: ")
Enter your name: Pramod
>>> print("Hello,", name)
Output:
CopyEdit
Hello, Pramod
6. Checking Boolean Logic
>>> 5 > 3
True
>>> 2 < 1
False
>>> True and False
False
>>> True or False
True
>>> not True
False
7. Using String Operations in Python Shell
>>> text = "Python"
>>> text.upper()
'PYTHON'
>>> text.lower()
'python'
>>> text[::-1]
'nohtyP'
>>> len(text)
6
8. List Operations in Python Shell
>>> numbers = [1, 2, 3, 4, 5]
>>> numbers.append(6)
>>> numbers
[1, 2, 3, 4, 5, 6]
>>> numbers.pop()
6
>>> numbers[2]
3
>>> len(numbers)
5
9. Using Loops in Python Shell
>>> for i in range(1, 6):
... print(i)
...
Output:
1
2
3
4
5
10. Defining a Function in the Python Shell
>>> def greet(name):
return "Hello, " + name + "!"
>>> greet("Pramod")
'Hello, Pramod
11. Checking Python Version in the Shell
>>> import sys
>>> print(sys.version)
Output (example output, may vary):
3.10.2
12. Generating Random Numbers in Python Shell
>>> import random
>>> random.randint(1, 100)
42
13. Getting the Current Date and Time in Python Shell
>>> from datetime import datetime
>>> print(datetime.now())
Output (varies based on current time):
2025-04-02 15:45:30.123456
14. Finding the Square Root of a Number
>>> import math
>>> math.sqrt(25)
5.0
15. Using List Comprehension in Python Shell
>>> squares = [x**2 for x in range(1, 6)]
>>> squares
[1, 4, 9, 16, 25]
Python Programs on "Indentation, Atoms, Identifiers, Keywords, and
Literals"
1. Indentation in Python
Python uses indentation instead of braces {} to define blocks of code.
Correct Indentation Example:
def greet():
print("Hello!") # Proper indentation
greet()
Output:
Hello!
Incorrect Indentation Example:
def greet():
print("Hello!") # IndentationError
Error Output:
IndentationError: expected an indented block
2. Atoms in Python
Atoms are the smallest elements in Python, such as identifiers, literals, and constants.
✅ Example of Atoms:
x = 5 # Integer literal (atom)
y = 3.14 # Floating-point literal (atom)
name = "Pramod" # String literal (atom)
is_active = True # Boolean literal (atom)
print(x, y, name, is_active)
Output:
5 3.14 Pramod True
3. Identifiers in Python
Identifiers are names used for variables, functions, and classes.
Valid Identifiers Example:
age = 25
_name = "John"
my_var = 100
PI = 3.14159
print(age, _name, my_var, PI)
Output:
25 John 100 3.14159
Invalid Identifier Example:
2name = "Alice" # SyntaxError: Identifiers cannot start with a number
my-var = 10 # SyntaxError: Identifiers cannot contain hyphens
if = 50 # SyntaxError: Cannot use keywords as identifiers
4. Keywords in Python
Python keywords are reserved words that cannot be used as identifiers.
✅ List of Keywords in Python:
import keyword
print(keyword.kwlist)
Output (Example):
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']
Using Keywords Correctly:
if True:
print("This is an if statement") # Correct use of 'if' keyword
Output:
This is an if statement
Incorrect Usage (Causes Error):
if = 10 # SyntaxError: 'if' is a keyword and cannot be used as a variable
5. Literals in Python
Literals are fixed values used in Python programs.
Example of Different Types of Literals:
# Integer literal
int_lit = 100
# Floating-point literal
float_lit = 3.14
# String literal
string_lit = "Python"
# Boolean literal
bool_lit = True
# None literal
none_lit = None
print(int_lit, float_lit, string_lit, bool_lit, none_lit)
Output:
100 3.14 Python True None
6. Using Literals in Expressions
a = 10 # Integer literal
b = 2.5 # Float literal
c = a + b # Expression using literals
print("Sum:", c)
Output:
Sum: 12.5
Python Programs Based on Strings
1. Creating and Printing a String
# Defining strings
str1 = "Hello, Python!"
str2 = 'Welcome to Strings in Python'
print(str1)
print(str2)
Output:
Hello, Python!
Welcome to Strings in Python
2. Accessing Characters in a String
text = "Python"
print("First character:", text[0]) # First character (index 0)
print("Last character:", text[-1]) # Last character (negative index)
Output:
First character: P
Last character: n
3. String Slicing
text = "Programming"
print("First 5 characters:", text[:5]) # Slicing first 5 characters
print("Last 5 characters:", text[-5:]) # Slicing last 5 characters
print("Alternate characters:", text[::2]) # Skipping characters
Output:
First 5 characters: Progr
Last 5 characters: mming
Alternate characters: Pormig
4. String Length
text = "Python Programming"
print("Length of string:", len(text))
Output:
Length of string: 18
5. Looping Through a String
text = "Hello"
for char in text:
print(char)
Output:
H
e
l
l
o
6. String Concatenation
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)
Output:
Hello World
7. String Repetition
python
CopyEdit
text = "Python "
print(text * 3) # Repeat string 3 times
Output:
Python Python Python
8. Checking Substring Presence
text = "Learning Python is fun!"
print("Python" in text) # Returns True
print("Java" in text) # Returns False
Output:
True
False
9. String Methods
text = "python programming"
print(text.upper()) # Convert to uppercase
print(text.lower()) # Convert to lowercase
print(text.title()) # Convert to title case
print(text.capitalize()) # Capitalize first letter
Output:
PYTHON PROGRAMMING
python programming
Python Programming
Python programming
10. Removing Whitespaces
text = " Hello, World! "
print(text.strip()) # Removes spaces from both sides
print(text.lstrip()) # Removes spaces from left
print(text.rstrip()) # Removes spaces from right
Output:
Hello, World!
Hello, World!
Hello, World!
11. Finding and Replacing in Strings
text = "I love Python"
print(text.replace("Python", "Java"))
print(text.find("Python")) # Returns the starting index
Output:
I love Java
7
12. Splitting and Joining Strings
text = "apple,banana,grapes"
words = text.split(",") # Splitting string by comma
print(words)
new_text = "-".join(words) # Joining list back to string
print(new_text)
Output:
['apple', 'banana', 'grapes']
apple-banana-grapes
13. Counting Character Occurrences
text = "Hello, how are you?"
print("Count of 'o':", text.count('o'))
Output:
Count of 'o': 3
14. Checking String Start and End
text = "Hello, World!"
print(text.startswith("Hello")) # True
print(text.endswith("Python")) # False
Output:
True
False
15. Checking If String is Numeric or Alphabetic
text1 = "12345"
text2 = "Python123"
text3 = "Python"
print(text1.isdigit()) # True (only numbers)
print(text2.isalnum()) # True (letters + numbers)
print(text3.isalpha()) # True (only letters)
Output:
True
True
True
16. Reversing a String
text = "Python"
reversed_text = text[::-1]
print("Reversed String:", reversed_text)
Output:
Reversed String: nohtyP
17. Formatting Strings (f-strings)
name = "Pramod"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Pramod and I am 25 years old.
18. Checking Palindrome
def is_palindrome(text):
return text == text[::-1]
print(is_palindrome("madam")) # True
print(is_palindrome("hello")) # False
Output:
True
False
19. ASCII Value of Characters
char = 'A'
print("ASCII value of A:", ord(char))
Output:
ASCII value of A: 65
20. Convert ASCII to Character
ascii_value = 97
print("Character for ASCII 97:", chr(ascii_value))
Output:
Character for ASCII 97: a
Python Programs on Operators
1. Arithmetic Operators
Arithmetic operators perform mathematical calculations.
Example:
a = 10
b = 3
print("Addition:", a + b) # 10 + 3 = 13
print("Subtraction:", a - b) # 10 - 3 = 7
print("Multiplication:", a * b) # 10 * 3 = 30
print("Division:", a / b) # 10 / 3 = 3.3333
print("Floor Division:", a // b)# 10 // 3 = 3
print("Modulus:", a % b) # 10 % 3 = 1
print("Exponentiation:", a ** b)# 10^3 = 1000
Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponentiation: 1000
2. Relational (Comparison) Operators
These operators compare values and return True or False.
Example:
x = 5
y = 10
print("x > y:", x > y) # False
print("x < y:", x < y) # True
print("x == y:", x == y) # False
print("x != y:", x != y) # True
print("x >= y:", x >= y) # False
print("x <= y:", x <= y) # True
Output:
x > y: False
x < y: True
x == y: False
x != y: True
x >= y: False
x <= y: True
3. Logical (Boolean) Operators
Logical operators work with boolean values (True or False).
Example:
a = True
b = False
print("a and b:", a and b) # False
print("a or b:", a or b) # True
print("not a:", not a) # False
Output:
a and b: False
a or b: True
not a: False
4. Assignment Operators
Assignment operators assign values to variables.
Example:
x = 10
print("x:", x)
x += 5 # x = x + 5
print("x += 5:", x)
x -= 3 # x = x - 3
print("x -= 3:", x)
x *= 2 # x = x * 2
print("x *= 2:", x)
x /= 4 # x = x / 4
print("x /= 4:", x)
x %= 3 # x = x % 3
print("x %= 3:", x)
Output:
x: 10
x += 5: 15
x -= 3: 12
x *= 2: 24
x /= 4: 6.0
x %= 3: 0.0
5. Ternary (Conditional) Operator
Ternary operator (a if condition else b) provides shorthand for if-else statements.
Example:
a, b = 10, 20
min_value = a if a < b else b
print("Smaller value:", min_value)
Output:
Smaller value: 10
6. Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.
Example:
a = 5 # Binary: 0101
b = 3 # Binary: 0011
print("a & b (AND):", a & b) # 0101 & 0011 = 0001 (1)
print("a | b (OR):", a | b) # 0101 | 0011 = 0111 (7)
print("a ^ b (XOR):", a ^ b) # 0101 ^ 0011 = 0110 (6)
print("~a (NOT a):", ~a) # NOT 0101 = -6
print("a << 1 (Left Shift):", a << 1) # 0101 << 1 = 1010 (10)
print("a >> 1 (Right Shift):", a >> 1) # 0101 >> 1 = 0010 (2)
Output:
a & b (AND): 1
a | b (OR): 7
a ^ b (XOR): 6
~a (NOT a): -6
a << 1 (Left Shift): 10
a >> 1 (Right Shift): 2
7. Increment and Decrement Operators
Python does not have ++ or -- like C or Java. Instead, we use += or -=.
Example:
x = 5
x += 1 # Equivalent to x = x + 1
print("Incremented value:", x)
x -= 2 # Equivalent to x = x - 2
print("Decremented value:", x)
Output:
Incremented value: 6
Decremented value: 4
Python Programs Based on Input and Output Statements
1. Basic Input and Output
Example:
name = input("Enter your name: ")
print("Hello,", name)
Output (Example):
Enter your name: Alice
Hello, Alice
2. Taking Integer Input
✅ Example:
age = int(input("Enter your age: "))
print("You are", age, "years old.")
Output (Example):
Enter your age: 25
You are 25 years old.
3. Taking Multiple Inputs
✅ Example:
name, age = input("Enter your name and age (separated by space): ").split()
print("Name:", name)
print("Age:", age)
Output (Example):
Enter your name and age (separated by space): Pramod 30
Name: John
Age: 30
4. Input with Type Conversion
Example:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
sum_result = a + b
print("Sum:", sum_result)
Output (Example):
Enter first number: 5.2
Enter second number: 3.8
Sum: 9.0
5. Printing Multiple Values Using sep and end
Example:
print("Python", "is", "awesome", sep="-", end="!\n")
Output:
Python-is-awesome!
6. Formatted Output Using format()
Example:
name = "Pramod"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Pramod and I am 25 years old.
7. Using f-strings for Output Formatting
Example:
name = "Pramod"
marks = 95.5
print(f"{name} scored {marks}% in the exam.")
Output:
Pramod scored 95.5% in the exam.
8. Printing a List with join()
Example:
words = ["Python", "is", "fun"]
print(" ".join(words))
Output:
Python is fun
9. Taking Input in a List
Example:
numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print("You entered:", numbers)
Output (Example):
Enter numbers separated by space: 10 20 30
You entered: [10, 20, 30]
10. Printing a Table (Formatted Output)
Example:
num = int(input("Enter a number: "))
print(f"Multiplication Table of {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Output (Example):
Enter a number: 5
Multiplication Table of 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50