#different printing techniques
import sys
import base64
import argparse
import logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
logger = logging.getLogger(__name__)
def simple():
print("Pushpam Computers!")
def usingVariable():
message = "Pushpam Computers!"
print(message)
def joiningInPrint():
print("Welcome to ," + " " + "Programming World!")
def fstring_print():
greeting = "Good "
wish = "Morning!"
print(f"{greeting} {wish}")
def usingFormatToPrint():
template = "{} {}"
print(template.format("Hello,", "World!"))
def joinMethod():
words = ["Hello,", "World!"]
print(" ".join(words))
def multiline_print():
text = """Hello,
World!"""
print(text)
def escape_chars_print():
# Hex codes: \145 = 'e', \x20 = space, \127 = 'W'
print("H\145llo,\x20\127orld!")
def usingAscii():
bytes_data = [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]
print(''.join(chr(b) for b in bytes_data))
def base64_print():
encoded = base64.b64encode(b"Pushpam Computers!").decode()
print(base64.b64decode(encoded).decode())
def main():
parser = argparse.ArgumentParser(description="different printing techniques.")
parser.add_argument('--method', type=int, choices=range(1, 10), help='Run a specific method by number')
args = parser.parse_args()
methods = {
1: simple,
2: usingVariable,
3: joiningInPrint,
4: fstring_print,
5: usingFormatToPrint,
6: joinMethod,
7: multiline_print,
8: escape_chars_print,
10: usingAscii,
}
bonus_method = base64_print
logger.info("\nBonus method: base64 encoding")
bonus_method()
if __name__ == "__main__":
try:
main()
except Exception as e:
logger.error(f"Unexpected error: {e}")
sys.exit(1)
def main():
name = "Punam Shah"
age = 25
height = 1.85
is_student = False
print("Variable Types :")
print("--------------")
print(f"Name: {name} (Type: {type(name)})")
print(f"Age: {age} years (Type: {type(age)})")
print(f"Height: {height} meters (Type: {type(height)})")
print(f"Status: {is_student} (Type: {type(is_student)})")
print()
print("Type-Specific Operations:")
print("-------------------------")
print("\nString Operations:")
print(f"First name: {name.split()[0]}")
print(f"Name in uppercase: {name.upper()}")
print("\nInteger Operations:")
print(f"Age in dog years: {age * 7}")
print(f"Decade: {age // 10}")
print("\nFloat Operations:")
print(f"Height in centimeters: {height * 100:.1f} cm")
print(f"Height rounded: {round(height, 1)} m")
print("\nBoolean Operations:")
print(f"Not student status: {not is_student}")
print(f"Is adult student? {age >= 18 and is_student}")
if __name__ == "__main__":
main()
import math
def calculateArea():
"""Calculate areas of different geometric shapes based on user input"""
print("Geometric Shape Area Calculator")
print("===============================")
print("Choose a shape:")
print("1. Circle")
print("2. Square")
print("3. Rectangle")
print("4. Triangle")
print("5. Trapezium")
print("6. Rhombus")
print("7. Exit")
while True:
choice = input("\n Choice (1-7): ")
if choice == '1': # Circle
radius = float(input("Enter radius of circle: "))
area = math.pi * radius ** 2
print(f"Area of circle = π × r² = {area:.2f}")
elif choice == '2': # Square
side = float(input("Enter side length of square: "))
area = side ** 2
print(f"Area of square = side² = {area:.2f}")
elif choice == '3': # Rectangle
length = float(input("Enter length of rectangle: "))
width = float(input("Enter width of rectangle: "))
area = length * width
print(f"Area of rectangle = length × width = {area:.2f}")
elif choice == '4': # Triangle
base = float(input("Enter base length of triangle: "))
height = float(input("Enter height of triangle: "))
area = 0.5 * base * height
print(f"Area of triangle = ½ × base × height = {area:.2f}")
elif choice == '5': # Trapezium
a = float(input("Enter length of first parallel side: "))
b = float(input("Enter length of second parallel side: "))
h = float(input("Enter height: "))
area = 0.5 * (a + b) * h
print(f"Area of trapezium = ½ × (a + b) × h = {area:.2f}")
elif choice == '6': # Rhombus
d1 = float(input("Enter length of first diagonal: "))
d2 = float(input("Enter length of second diagonal: "))
area = 0.5 * d1 * d2
print(f"Area of rhombus = ½ × d1 × d2 = {area:.2f}")
elif choice == '7': # Exit
print(" Goodbye!")
break
else:
print("Invalid choice! .")
if __name__ == "__main__":
calculateArea()
import math
def main():
"""Main function to handle user interaction"""
print("Academic Unit Conversion Tool")
print("=============================")
while True:
print("\nChoose Conversion Category:")
print("1. Temperature Conversions")
print("2. Angle Conversions")
print("3. Distance Conversions")
print("4. Mass Conversions")
print("5. Volume Conversions")
print("6. Exit Program")
category = input("\nEnter category number (1-6): ")
if category == '1':
temperature_conversions()
elif category == '2':
angle_conversions()
elif category == '3':
distance_conversions()
elif category == '4':
mass_conversions()
elif category == '5':
volume_conversions()
elif category == '6':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice! Please enter a number between 1-6.")
def temperature_conversions():
"""Handle temperature conversions"""
print("\nTemperature Conversions:")
print("1. Fahrenheit to Celsius")
print("2. Celsius to Fahrenheit")
print("3. Celsius to Kelvin")
print("4. Kelvin to Celsius")
print("5. Fahrenheit to Kelvin")
print("6. Kelvin to Fahrenheit")
choice = input("Enter conversion type (1-6): ")
value = float(input("Enter value to convert: "))
if choice == '1':
# F to C: (F - 32) * 5/9
result = (value - 32) * 5/9
print(f"{value}°F = {result:.2f}°C")
elif choice == '2':
# C to F: (C * 9/5) + 32
result = (value * 9/5) + 32
print(f"{value}°C = {result:.2f}°F")
elif choice == '3':
# C to K: C + 273.15
result = value + 273.15
print(f"{value}°C = {result:.2f} K")
elif choice == '4':
# K to C: K - 273.15
result = value - 273.15
print(f"{value} K = {result:.2f}°C")
elif choice == '5':
# F to K: (F - 32) * 5/9 + 273.15
result = (value - 32) * 5/9 + 273.15
print(f"{value}°F = {result:.2f} K")
elif choice == '6':
# K to F: (K - 273.15) * 9/5 + 32
result = (value - 273.15) * 9/5 + 32
print(f"{value} K = {result:.2f}°F")
else:
print("Invalid choice for temperature conversion")
def angle_conversions():
"""Handle angle conversions"""
print("\nAngle Conversions:")
print("1. Degrees to Radians")
print("2. Radians to Degrees")
choice = input("Enter conversion type (1-2): ")
value = float(input("Enter angle value: "))
if choice == '1':
# deg * π/180
result = value * math.pi/180
print(f"{value}° = {result:.4f} radians")
elif choice == '2':
# rad * 180/π
result = value * 180/math.pi
print(f"{value} radians = {result:.2f}°")
else:
print("Invalid choice for angle conversion")
def distance_conversions():
print("\nDistance Conversions:")
print("1. Kilometers to Miles")
print("2. Miles to Kilometers")
print("3. Meters to Feet")
print("4. Feet to Meters")
print("5. Centimeters to Inches")
print("6. Inches to Centimeters")
choice = input("Enter conversion type (1-6): ")
value = float(input("Enter distance value: "))
conversions = {
'1': (value * 0.621371, "km", "miles"),
'2': (value * 1.60934, "miles", "km"),
'3': (value * 3.28084, "m", "feet"),
'4': (value * 0.3048, "feet", "m"),
'5': (value * 0.393701, "cm", "inches"),
'6': (value * 2.54, "inches", "cm")
}
if choice in conversions:
result, from_unit, to_unit = conversions[choice]
print(f"{value} {from_unit} = {result:.4f} {to_unit}")
else:
print("Invalid choice for distance conversion")
def mass_conversions():
"""Handle mass conversions"""
print("\nMass Conversions:")
print("1. Kilograms to Pounds")
print("2. Pounds to Kilograms")
print("3. Grams to Ounces")
print("4. Ounces to Grams")
choice = input("Enter conversion type (1-4): ")
value = float(input("Enter mass value: "))
conversions = {
'1': (value * 2.20462, "kg", "lbs"),
'2': (value * 0.453592, "lbs", "kg"),
'3': (value * 0.035274, "g", "oz"),
'4': (value * 28.3495, "oz", "g")
}
if choice in conversions:
result, from_unit, to_unit = conversions[choice]
print(f"{value} {from_unit} = {result:.4f} {to_unit}")
else:
print("Invalid choice for mass conversion")
def volume_conversions():
"""Handle volume conversions"""
print("\nVolume Conversions:")
print("1. Liters to Gallons (US)")
print("2. Gallons (US) to Liters")
print("3. Milliliters to Fluid Ounces")
print("4. Fluid Ounces to Milliliters")
choice = input("Enter conversion type (1-4): ")
value = float(input("Enter volume value: "))
conversions = {
'1': (value * 0.264172, "L", "gal"),
'2': (value * 3.78541, "gal", "L"),
'3': (value * 0.033814, "mL", "fl oz"),
'4': (value * 29.5735, "fl oz", "mL")
}
if choice in conversions:
result, from_unit, to_unit = conversions[choice]
print(f"{value} {from_unit} = {result:.4f} {to_unit}")
else:
print("Invalid choice for volume conversion")
if __name__ == "__main__":
main()
# using Escape Sequences
def main():
print("=" * 50)
print("Escape Sequences ")
print("=" * 50)
print("\n1. Basic Escape Sequences:")
print("Newline: First line\nSecond line")
print("Tab: Column1\tColumn2\tColumn3")
print("Backslash: This is a backslash: \\")
print("Single Quote: It\'s a beautiful day")
print("Double Quote: He said, \"Hello World!\"")
print("Backspace: Hello\b World") # Removes the 'o' before backspace
print("Carriage Return: 12345\rABC") # Overwrites the beginning
print("Form Feed: Before\fafter") # May appear as page break in some environments
print("\n2. Unicode and Hexadecimal Escapes:")
print("Hex escape: \x48\x65\x6c\x6c\x6f")
print("Unicode escape: \u03A9 \u03B1 \u03B2") # Ω α β
print("\n3. Raw Strings (ignore escapes):")
print(r"Newline in raw string: \n remains as text")
print(r"Path example: C:\Users\Documents\file.txt")
print("\n4. Multi-line Strings:")
print(""" multi-line string
that spans across several lines
without needing escape characters""")
print("\n" + "=" * 50)
print("String Formatting Techniques")
print("=" * 50)
name = "Sarswati"
age = 28
height = 1.68
score = 95.4567
items = ["watermelon", "banana", "cherry"]
print("\n1. %-formatting (Old Style):")
print("Name: %s, Age: %d" % (name, age))
print("Height: %.2f meters" % height)
print("Score: %04d" % score)
# format() method
print("\n2. str.format() Method:")
print("Name: {}, Age: {}, Height: {:.2f}".format(name, age, height))
print("Items: {0}, {1}, and {2}".format(*items))
print("Coordinates: (x:{x}, y:{y})".format(x=5, y=12))
print("\n3. f-strings (Formatted String Literals):")
print(f"Name: {name}, Age: {age}, Height: {height:.2f}")
print(f"Next year: {age + 1} years old")
print(f"Score: {score:.1f}% ({'Excellent' if score > 90 else 'Good'})")
print(f"List: {items} has {len(items)} items")
from string import Template
print("\n4. Template Strings:")
t = Template("$name owes $amount dollars")
print(t.substitute(name="Hanuman", amount=25.5))
print("\n5. Advanced Formatting:")
number = 1234567.89123456
print(f"Commas: {number:,.2f}")
print(f"Percentage: {0.456:.2%}")
print(f"Hexadecimal: {255:#x}")
print(f"Binary: {10:b}")
print(f"Scientific: {0.000045678:.3e}")
print("\n6. Column Alignment:")
data = [
("Ram", 95, 1.68),
("Sita", 88, 1.82),
("Lakshman", 92, 1.75)
]
print(f"{'Name':<10} {'Score':>5} {'Height':>7}")
for name, score, height in data:
print(f"{name:<10} {score:>5} {height:>7.2f}")
if __name__ == "__main__":
main()
# use of type() function to find datatype
# Program to demonstrate different data types using type()
def main():
int_value = 42
print(f"1. Value: {int_value} | Type: {type(int_value)}")
float_value = 3.14159
print(f"2. Value: {float_value} | Type: {type(float_value)}")
string_value = "Hello, Python!"
print(f"3. Value: '{string_value}' | Type: {type(string_value)}")
bool_value = True
print(f"4. Value: {bool_value} | Type: {type(bool_value)}")
list_value = [1, 2, 3, "four", 5.0]
print(f"5. Value: {list_value} | Type: {type(list_value)}")
tuple_value = (10, 20, "thirty", 40.0)
print(f"6. Value: {tuple_value} | Type: {type(tuple_value)}")
dict_value = {"name": "Pari", "age": 30, "is_student": False}
print(f"7. Value: {dict_value} | Type: {type(dict_value)}")
set_value = {1, 2, 3, 3, 4, 4, 5}
print(f"8. Value: {set_value} | Type: {type(set_value)}")
none_value = None
print(f"9. Value: {none_value} | Type: {type(none_value)}")
complex_value = 3 + 4j
print(f"10. Value: {complex_value} | Type: {type(complex_value)}")
print("\nBonus Types:")
def sample_function():
return "I'm a function"
print(f"11. Value: {sample_function} | Type: {type(sample_function)}")
class SampleClass:
pass
class_instance = SampleClass()
print(f"12. Value: {class_instance} | Type: {type(class_instance)}")
range_value = range(5)
print(f"13. Value: {range_value} | Type: {type(range_value)}")
bytes_value = b"binary_data"
print(f"14. Value: {bytes_value} | Type: {type(bytes_value)}")
if __name__ == "__main__":
main()
def main():
a = int(input("First number: "))
b = int(input("Second number: "))
print("\nOriginal values:")
print(f"a = {a}, b = {b}")
# 1. Using temporary variable
temp = a
a = b
b = temp
print("\n1. Using temporary variable:")
print(f"a = {a}, b = {b}")
# Reset values
a, b = b, a
# 2. Using arithmetic operators (addition/subtraction)
a = a + b
b = a - b
a = a - b
print("\n2. Using arithmetic operators (addition/subtraction):")
print(f"a = {a}, b = {b}")
# Reset values
a, b = b, a
# 3. Using arithmetic operators (multiplication/division)
a = a * b
b = a // b # Integer division
a = a // b
print("\n3. Using arithmetic operators (multiplication/division):")
print(f"a = {a}, b = {b}")
# Reset values
a, b = b, a
# 4. Using XOR (bitwise operator)
a = a ^ b
b = a ^ b
a = a ^ b
print("\n4. Using XOR bitwise operator:")
print(f"a = {a}, b = {b}")
# Reset values
a, b = b, a
# 5. Using tuple unpacking (Pythonic way)
a, b = b, a
print("\n5. Using tuple unpacking (Pythonic way):")
print(f"a = {a}, b = {b}")
# Reset values
a, b = b, a
# 6. Using dictionary
swap_dict = {'a': b, 'b': a}
a, b = swap_dict['a'], swap_dict['b']
print("\n6. Using dictionary method:")
print(f"a = {a}, b = {b}")
# Reset values
a, b = b, a
# 7. Using comma
b, a = a, b
print("\n7. Using comma operator in single line:")
print(f"a = {a}, b = {b}")
if __name__ == "__main__":
main()
from datetime import datetime, timedelta
def get_tarikh_details(dt):
return (f"Year: {dt.year}, Month: {dt.month}, Day: {dt.day}, "
f"Hour: {dt.hour}, Minute: {dt.minute}, Second: {dt.second}")
def main():
current = datetime.now()
yesterday = current - timedelta(days=1)
tomorrow = current + timedelta(days=1)
output = [
get_tarikh_details(current),
"\nYesterday:",
get_tarikh_details(yesterday),
"\nTomorrow:",
get_tarikh_details(tomorrow)
]
print("\n".join(output))
if __name__ == "__main__":
main()
# Program to format full name to initials
full_name = input("Enter full name: ").strip()
namestringarray = full_name.split()
firstname = namestringarray[0][0]+'.'
middlename = namestringarray[1][0]+'.'
lastname = namestringarray[2]
print("",firstname, middlename, lastname)