Python Programming Demystified: Explore Key Concepts Through Hands-On Code

Beginner Level: Python Programs

Hello World

# Print Hello World

user_input = " Hello World"
print (user_input)

image 24

# Print Hello World

user_input = input("Enter the string to be printed: ")
print (user_input)

image 25

Basic Arithmetic

# Basic Arithmetic

a = int(input("Enter the first number: ")) # Integer
b = int(input("Enter the second number: ")) # Integer


print('Addition: ', a+b)
print('Subtraction: ', a-b)
print('Multiplication: ', a*b)
print('Float Division: ', a/b)
print('Floor Division: ', a//b)
print('Modulus Operation: ', a%b)
print('Exponential Operation: ', a**b)

image 26

Area of a Circle

# Area of a Circle

r = float(input("Enter the radius of a circle in cm: "))
pi = 3.14

area = pi*r*r

print(f'Area of a circle s {area} cm\u00B2')

image 40

# Area of a Circle

try:
r = float(input("Enter the radius of a circle in cm: "))
if r < 0:
raise ValueError("The radius cannot be negative.")

pi = 3.14
area = pi * r * r
print(f'The area of the circle is {area} cm\u00B2')
except ValueError:
print("Invalid input. Please enter a valid positive number for the radius.")

image

image

image

# Area of a Circle

while True:
try:
r = float(input("Enter the radius of a circle in cm: "))
if r < 0:
raise ValueError("The radius cannot be negative.")

pi = 3.14
area = pi * r * r
print(f'The area of the circle is {area} cm\u00B2')
break
except ValueError:
print("Invalid input. Please enter a valid positive number for the radius.")

image

Even or Odd

# Even or Odd

num = int(input("Enter the number "))

if num % 2 == 0:
print('Even Number')
else:
print('Odd Number')

image 28

image 29

# Including exception handling
try:
num = int(input('Enter the number: '))
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
except ValueError:
print("Invalid input. Please enter a valid number.")

image

image

# Including loop for valid input

while True:
try:
num = int(input('Enter the number: '))
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
break # Break out of the loop if input is valid
except ValueError:
print("Invalid input. Please enter a valid number.")

print('Bye')

image

Prime Number Check

# Prime Number Check

num = int(input("Enter the number: "))

count = 0

for i in range(1, num+1):
if num % i == 0:
count += 1
if count == 2:
print('Prime Number')
else:
print('Not a Prime Number')

image 30

image 31

# Prime number check

num = int(input('Enter the number: '))

if num < 2:
print('Not a prime')
else:
is_prime = True

for i in range(2, int(num**0.5)+1):
if num % i == 0:
is_prime = False
break
if is_prime:
print('Prime Number')
else:
print('Not a prime')

image 32

Factorial of a Number

# Factorial of a Number

count = 1
num = int(input('Enter the number: '))

if num == 0:
print('Factorial of 0 is 1')
else:
for i in range(1, num+1):
count = count * i
print(f'Factorial of a {num} is {count}')

image 33

Palindrome Check

# Check if a string is a palindrome or not

# Input from the user
user_input = input("Enter the string: ")

#Reverse the string using slicing
rev_str = user_input[::-1]

#Check if original and reverse string same
if user_input.lower() == rev_str.lower():
print('Palindrome')
else:
print('Not a Palindrome')

image 34

# Check if a number is a palindrome or not

# Input from the user and convert in string
user_input = int(input("Enter the number: "))
user_input_str = str(user_input)

#Reverse the string using slicing
rev_str = user_input_str[::-1]

#Check if original and reverse string same
if user_input_str == rev_str:
print('Palindrome')
else:
print('Not a Palindrome')

image 35

# Check if a string is a palindrome or not and provide palindrome string

# Input from the user
user_input = input("Enter the string: ")

#Reverse the string using slicing
rev_str = user_input[::-1]

#Check if original and reverse string same
if user_input.lower() == rev_str.lower():
print('Palindrome')
else:
print('Not a Palindrome')
palindrome_str = user_input + rev_str
print(f'Palindrome string will be {palindrome_str}')

image 36

# Check if a number is a palindrome or not and provide palindrome

# Input from the user and convert in string
user_input = int(input("Enter the number: "))
user_input_str = str(user_input)

#Reverse the string using slicing
rev_str = user_input_str[::-1]

#Check if original and reverse string same
if user_input_str == rev_str:
print('Palindrome')
else:
print('Not a Palindrome')
palindrome = user_input_str + rev_str
print(f'Required Palindrome will be {palindrome}')

image

Count Vowels

# Count the number of vowels in a string

user_input = input('Enter the string: ')
user_input = user_input.lower()

vowels = ['a', 'e', 'i', 'o', 'u']

vowels_count = 0

for i in user_input:
if i in vowels:
vowels_count += 1

print(f'No of vowels in a given string: {vowels_count}')

image 37

Eligibility for Casting a Vote

# Vote casting

voter_age = float(input("Enter your age: "))

if voter_age >= 18:
print('Eligible for Voting')
else:
print('Not Eligible')

image 38

Club Party Entry

# Entry in Club for party

visitor_age = float(input('Enter the visitor age: '))
has_ticket = int(input('''Enter the value:
1 if having ticket
0 is dont have ticket
='''))

if visitor_age >= 18 and has_ticket:
print('Entry Allowed')
else:
print('Not Allowed')

image 39

Admin Access

# If user have admin access ot not

user_name = input('Enter the username: ')
user_name = user_name.lower()

if user_name == 'john' or user_name == 'smith':
print('Admin')
else:
print('Not an Admin')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the username: Amir
Not an Admin

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the username: john
Admin

Process finished with exit code 0

Name of a month

# Display name of a month using if-elif-else

month_number = int(input('Enter the number of month from 1 to 12: '))

if month_number == 1:
print('January')
elif month_number == 2:
print('February')
elif month_number == 3:
print('March')
elif month_number == 4:
print('April')
elif month_number == 5:
print('May')
elif month_number == 6:
print('June')
elif month_number == 7:
print('July')
elif month_number == 8:
print('August')
elif month_number == 9:
print('September')
elif month_number == 10:
print('October')
elif month_number == 11:
print('November')
elif month_number == 12:
print('December')
else:
print('Invalid Month Number')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number of month from 1 to 12: 12
December

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number of month from 1 to 12: 13
Invalid Month Number

Process finished with exit code 0

# Display name of a month using Match Case

month_number = int(input('Enter the number of month from 1 to 12: '))

match month_number:
case 1:
print('January')
case 2:
print('February')
case 3:
print('March')
case 4:
print('April')
case 5:
print('May')
case 6:
print('June')
case 7:
print('July')
case 8:
print('August')
case 9:
print('September')
case 10:
print('October')
case 11:
print('November')
case 12:
print('December')
case _:
print('Invalid Input')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number of month from 1 to 12: 11
November

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number of month from 1 to 12: 14
Invalid Month Number

Process finished with exit code 0

Gender of a person

# Gender of a person

user_input = input('''Enter your gender:-
For male m or male
For female f or female
= ''')
user_input = user_input.lower()

male = ['m', 'male']
female = ['f', 'female']

if user_input in male:
print('Male')
elif user_input in female:
print('Female')
else:
print('Invalid Input')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter your gender:-
For male m or male
For female f or female
= m
Male

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter your gender:-
For male m or male
For female f or female
= f
Female

Process finished with exit code 0

Valid marks range of a subject

# Valid Marks Range

marks = float(input('Enter the marks given: '))

if marks >= 0 and marks <= 100:
print('Valid Range')
else:
print('Invalid Range')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the marks given: 49.5
Valid Range

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the marks given: 101
Invalid Range

Process finished with exit code 0

Net-payable amount after discount

# Net payable amount after discount

bill_amount = float(input("Enter the bill amount \u20B9: "))

net_payable = 0

# Discount slabs
dis_1 = 0.1 * bill_amount
dis_2 = 0.2 * bill_amount
dis_3 = 0.3 * bill_amount
dis_4 = 0.5 * bill_amount

if bill_amount <= 1000:
net_payable = bill_amount - dis_1
elif bill_amount > 1000 and bill_amount <= 5000:
net_payable = bill_amount - dis_2
elif bill_amount > 5000 and bill_amount <= 10000:
net_payable = bill_amount - dis_3
else:
net_payable = bill_amount - dis_4

print(f'Net Payable amount is {net_payable}\u20B9')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the bill amount ₹: 1000
Net Payable amount is 900.0₹

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the bill amount ₹: 11000
Net Payable amount is 5500.0₹

Process finished with exit code 0

Leap Year or Not

# Leap Year or Not

year = int(input("Enter the year: "))

if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print('Leap Year')
else:
print('Not a Leap Year')
else:
print('Leap Year')
else:
print('Not a Leap Year')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the year: 100
Not a Leap Year

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the year: 2024
Leap Year

Process finished with exit code 0

Multiplication Table

# Multiplication Table

user_input = int(input('Enter the number to print table: '))

for i in range(1,11):
print(user_input, 'x', '=', (user_input * i))

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number to print table: 5
5 x = 5
5 x = 10
5 x = 15
5 x = 20
5 x = 25
5 x = 30
5 x = 35
5 x = 40
5 x = 45
5 x = 50

Process finished with exit code 0

# Multiplication Table

user_input = int(input('Enter the number to print table: '))

for i in range(1,11):
print(f'{user_input} x {i} = {user_input*i}')

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number to print table: 10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100

Process finished with exit code 0

# Multiplication Table

user_input = int(input('Enter the number to print table: '))
count = 1
res = 0

while count <= 10:
res = count * user_input
print(user_input, '*', '=', res)
count += 1

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number to print table: 6
6 * = 6
6 * = 12
6 * = 18
6 * = 24
6 * = 30
6 * = 36
6 * = 42
6 * = 48
6 * = 54
6 * = 60

Process finished with exit code 0

Positive and Negative Number Loop

# Positive and Negative Number Loop

while True:
user_input = int(input('Enter the number: '))
if user_input > 0:
print('Positive')
elif user_input < 0:
print('Negative')

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number: 1
Positive
Enter the number: 3
Positive
Enter the number: -1
Negative
Enter the number: -11
Negative
Enter the number: 0
Enter the number:

Positive and Negative Number Loop Break

# Positive and Negative Number Loop

while True:
user_input = int(input('Enter the number: '))
if user_input > 0:
print('Positive')
elif user_input < 0:
print('Negative')
else:
break

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number: 1
Positive
Enter the number: -1
Negative
Enter the number: 0

Process finished with exit code 0

Guess a Number

# Guess a Number

import random

num = random.randint(1,25)
print(num)

while True:
guess = int(input("Enter your guess: "))
if guess > num:
print('Guess is Higher')
elif guess < num:
print('Guess is lower')
else:
print('Guess is correct')
break

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
20
Enter your guess: 5
Guess is lower
Enter your guess: 21
Guess is Higher
Enter your guess: 20
Guess is correct

Process finished with exit code 0

Number of digits in a number

# Count the number of digits in a number

user_input = int(input("Enter the number: "))
count = 0
user_input = str(user_input)

for i in user_input:
count += 1

print(count)

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number: 123456789
9

Process finished with exit code 0

Sum of digits in a number

# Sum of digits in a number

user_input = int(input("Enter the number: "))
digit_sum = 0
user_input = str(user_input)

for i in user_input:
i = int(i)
digit_sum += i

print(digit_sum)

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number: 123456
21

Process finished with exit code 0

Reverse a Number

# Reversing a Number

num = int(input("Enter the number: "))
num = str(num)
rev_num = ''

for i in num:
rev_num = i + rev_num

rev_num = int(rev_num)

print(rev_num)

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number: 123456789
987654321

Process finished with exit code 0

Temperature Conversion

# Temperature Conversion

user_selection = int(input('''Please choose the option for required conversion
Celsius to Fahrenheit - 1
Fahrenheit to Celsius - 2
Celsius to Kelvin - 3
Kelvin to Celsius - 4
Fahrenheit to Kelvin - 5
Kelvin to Fahrenheit - 6
: '''))

f = 0
c = 0
k = 0

req_temp = 0


# Celsius to Fahrenheit
if user_selection == 1:
user_input = float(input('Enter the temperature in \u2103: '))
f = (9/5)*user_input + 32
print(f'Required temperature is {f} \u2109 ')

# Fahrenheit to Celsius
elif user_selection == 2:
user_input = float(input('Enter the temperature in \u2109: '))
c = (5/9) * (user_input-32)
print(f'Required temperature is {c} \u2103 ')

# Celsius to Kelvin
elif user_selection == 3:
user_input = float(input('Enter the temperature in \u2103: '))
k = user_input + 273.15
print(f'Required temperature is {k} K ')

# Kelvin to Celsius
elif user_selection == 4:
user_input = float(input('Enter the temperature in K: '))
c = user_input - 273.15
print(f'Required temperature is {c} \u2109 ')

# Fahrenheit to Kelvin
elif user_selection == 5:
user_input = float(input('Enter the temperature in \u2109: '))
k = (5/9)*(user_input - 32) + 273.15
print(f'Required temperature is {k} K ')

# Kelvin to Fahrenheit
elif user_selection == 6:
user_input = float(input('Enter the temperature in K: '))
f = (9/5)*(user_input - 273.15) + 32
print(f'Required temperature in Fahrenheit is {f} \u2109 ')

else:
print("Invalid Selection")

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Please choose the option for required conversion
Celsius to Fahrenheit – 1
Fahrenheit to Celsius – 2
Celsius to Kelvin – 3
Kelvin to Celsius – 4
Fahrenheit to Kelvin – 5
Kelvin to Fahrenheit – 6
: 3
Enter the temperature in ℃: 37
Required temperature is 310.15 K

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Please choose the option for required conversion
Celsius to Fahrenheit – 1
Fahrenheit to Celsius – 2
Celsius to Kelvin – 3
Kelvin to Celsius – 4
Fahrenheit to Kelvin – 5
Kelvin to Fahrenheit – 6
: 5
Enter the temperature in ℉: 45
Required temperature is 280.3722222222222 K

Process finished with exit code 0

Simple Calculator

# Simple Calculator

# User inputs
num1 = float(input("Enter the first number: "))
operator = input('Enter the operator for operations: +,-,*,/,//,%,** = ')
num2 = float(input('Enter the second number: '))

res = 0

if operator == '+':
res = num1 + num2
elif operator == '-':
res = num1 - num2
elif operator == '*':
res = num1 * num2
elif operator == '/':
res = num1/num2
elif operator == '//':
res = num1//num2
elif operator == '%':
res = num1 % num2
elif operator == '**':
res = num1 ** num2
else:
print('Invalid Selection')

print('Required result: ', res)

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the first number: 20
Enter the operator for operations: +,-,,/,//,%,* = /
Enter the second number: 5
Required result: 4.0

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the first number: 10
Enter the operator for operations: +,-,,/,//,%,* = –
Enter the second number: 3
Required result: 7.0

Process finished with exit code 0

ASCII Value

# Print the ASCII value of a character

user_input = input('Enter the character to get ASCII value: ')

if len(user_input) != 1:
print('Please enter one character only')
else:
ascii_value = ord(user_input)
print(f'Required ASCII value of {user_input} is {ascii_value}')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the character to get ASCII value: A
Required ASCII value of A is 65

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the character to get ASCII value: 12
Please enter one character only

Process finished with exit code 0

BMI Calculator

# BMI Calculator

weight = float(input("Please enter your weight in Kg: "))
height = float(input("Please enter your height in meters: "))

bmi = weight / (height ** 2)

if bmi < 18.5:
category = 'Underweight'
elif 18.5 <= bmi < 24.9:
category = 'Normal Weight'
elif 25 <= bmi < 29.9:
category = 'Overweight'
else:
category = 'Obese'

print(f'Your BMI is {bmi}. You are {category}')

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Please enter your weight in Kg: 64
Please enter your height in meters: 5.5
Your BMI is 2.115702479338843. You are Underweight

Process finished with exit code 0

Calculate Age

# Calculate the age of a person given their birthdate.

from datetime import datetime

birthdate_input = input('Enter your birthdate in YYYY-MM-DD format: ')

# print(birthdate_input, type(birthdate_input))

# Convert birthdate input to a datetime object
birthdate = datetime.strptime(birthdate_input, "%Y-%m-%d")

# print(birthdate, type(birthdate))

current_date = datetime.now()

# print(current_date, type(current_date))

age_years = current_date.year - birthdate.year

if (current_date.month, current_date.day) < (birthdate.month, birthdate.day):
age_years = age_years - 1

print(f'Your current age is {age_years}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter your birthdate in YYYY-MM-DD format: 1988-05-25
Your current age is 36

Process finished with exit code 0

Sum of Natural Numbers

#  Calculate the sum of the first n natural numbers

user_input = int(input('Enter the natural number upto which sum is required: '))

if user_input <= 0:
print('Enter number greater than or equal to 1')
else:
result = user_input * (user_input + 1) // 2
print(f'Required sum is {result}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the natural number upto which sum is required: 10
Required sum is 55

Process finished with exit code 0

Reverse a String

# Reverse a given string or sentence

user_input = input("Enter the string/sentence: ")

rev_str = user_input[::-1]

print(f"Required reverse string/sentence of {user_input} is {rev_str}")

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the string/sentence: Reverse
Required reverse string/sentence of Reverse is esreveR

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the string/sentence: Reverse the string
Required reverse string/sentence of Reverse the string is gnirts eht esreveR

Process finished with exit code 0

Power Calculation

# Compute the power of a number

base = float(input("Enter the base: "))
exponent = float(input("Enter the exponent: "))
result = base ** exponent
print(f'Required result of {base} power {exponent} is {result}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the base: 2
Enter the exponent: 3
Required result of 2.0 power 3.0 is 8.0

Process finished with exit code 0

Sum of List Elements

# Sum of list elements

user_list = (input("Enter the list of numbers with spaces: "))

user_list = user_list.split( )
add = 0

for i in user_list:
i = int(i)
add = add + i
print(add)

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the list of numbers with spaces: 1 2 3
[‘1’, ‘2’, ‘3’]
6

Process finished with exit code 0

GCD/HCF Calculation

# HCF/GCD of two numbers

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

if a <= 0 or b <= 0:
print('Please enter positive integers only.')
else:
x, y = a, b
while y != 0:
x, y = y, x%y
gcd = x
print(f'HCF/GCD of {a} and {b} is {gcd}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the first number: 18
Enter the second number: 12
HCF/GCD of 18 and 12 is 6

Process finished with exit code 0

LCM Calculation

# LCM of two numbers

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

if a <= 0 or b <= 0:
print('Please enter positive integers only.')
else:
x, y = a, b
while y != 0:
x, y = y, x%y
gcd = x
lcm = abs(a * b) / gcd
print(f'LCM of {a} and {b} is {lcm}')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the first number: -1
Enter the second number: 3
Please enter positive integers only.

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the first number: 3
Enter the second number: 4
LCM of 3 and 4 is 12.0

Process finished with exit code 0

Count Words in a String

# Count Words in a String

user_input = input("Enter the string: ")
user_input = user_input.split()

count = 0

for i in user_input:
count += 1

print(f'Words in a given string: {count}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the string: The Boss is here
Words in a given string: 4

Process finished with exit code 0

Count Characters in String

# Count Characters in a String

user_input = input("Enter the string: ")
count = 0

for i in user_input:
count += 1
print(f'Words in a given string: {count}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the string: String
Words in a given string: 6

Process finished with exit code 0

# Count Characters in a String

user_input = input("Enter the string: ")
count = 0

for i in user_input:
if i == ' ' or i == '.':
continue
else:
count += 1

print(f'Words in a given string: {count}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the string: The Boss is here.
Words in a given string: 13

Process finished with exit code 0

Decimal to Binary Conversion: Convert a decimal number to a binary number.

# Decimal to Binary

user_input = int(input("Enter the integer whose binary is required: "))

binary = ''

while user_input > 0:
r = user_input % 2
r = str(r)
user_input = user_input // 2
binary = r + binary

print(binary)

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the integer whose binary is required: 7
111

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the integer whose binary is required: 99
1100011

Process finished with exit code 0

Binary to Decimal Conversion: Convert a binary number to a decimal number.

# Binary to Decimal
user_input = (input("Enter the binary value: "))

n = len(user_input)
decimal = 0

for i in user_input:
decimal = (int(i) * (2 ** (n-1))) + decimal
n = n - 1

print(f'Required decimal value is {decimal}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the binary value: 1010101
Required decimal value is 85

Process finished with exit code 0

Find Largest Element

# Maximum numbers from the list

user_input = int(input("Enter the count of numbers to be entered: "))

if user_input <= 0:
print('Invalid Input')
else:
num_max = int(input('Enter the first number: '))
for i in range(1, user_input):
num = int(input(f'Enter the {i+1} number: '))
if num > num_max:
num_max = num
print(f'Largest number from the given list is {num_max}')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the count of numbers to be entered: 5
Enter the first number: 10
Enter the 2 number: 20
Enter the 3 number: 30
Enter the 4 number: 40
Enter the 5 number: 50
Largest number from the given list is 50

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the count of numbers to be entered: 5
Enter the first number: -10
Enter the 2 number: -20
Enter the 3 number: 0
Enter the 4 number: 1
Enter the 5 number: 4
Largest number from the given list is 4

Process finished with exit code 0

Output 3:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the count of numbers to be entered: 3
Enter the first number: -9
Enter the 2 number: -11
Enter the 3 number: -12
Largest number from the given list is -9

Process finished with exit code 0

Find Smallest Element

# Smallest numbers from the list

user_input = int(input("Enter the count of numbers to be entered: "))

if user_input <= 0:
print('Invalid Input')
else:
num_min = int(input('Enter the first number: '))
for i in range(1, user_input):
num = int(input(f'Enter the {i+1} number: '))
if num < num_min:
num_max = num
print(f'Smallest number from the given list is {num_min}')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the count of numbers to be entered: 5
Enter the first number: 1
Enter the 2 number: 2
Enter the 3 number: 3
Enter the 4 number: 0
Enter the 5 number: 4
Smallest number from the given list is 0

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the count of numbers to be entered: 3
Enter the first number: -1
Enter the 2 number: 0
Enter the 3 number: 1
Smallest number from the given list is -1

Process finished with exit code 0

Fibonacci Sequence

# Generate the Fibonacci sequence up to n terms

n = int(input("Enter the number of terms: "))

a, b = 0, 1
fibonacci_sequence = []

for _ in range(n):
fibonacci_sequence.append(a)
a, b = b, a+b
print(f'Required FB is {fibonacci_sequence}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the number of terms: 5
Fibonacci sequence: [0, 1, 1, 2, 3]

Process finished with exit code 0

Arithmetic Progression

# Generate the Arithmetic Progression Series up to n terms

a = int(input("Enter the first term (a): "))
d = int(input("Enter the common difference (d): "))
n = int(input('Enter the number of terms (n): '))

ap_series = []

for i in range(n):
term = a + i * d
ap_series.append(term)

print(ap_series)

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the first term (a): 2
Enter the common difference (d): 3
Enter the number of terms (n): 5
[2, 5, 8, 11, 14]

Process finished with exit code 0

Pyramid Pattern

# Pyramid Pattern

n = int(input('Enter the levels: '))

for i in range(n):
print(' ' * (n-1), end='')
n = n - 1
print('x' * (2 * i + 1))

image 43

Inverted Pyramid Pattern

# Inverted Pyramid Pattern

n = int(input('Enter the levels: '))

for i in range(n, 0, -1):
print(' ' * (n-i), end='')
print('x' * (2 * i - 1))

Output:

image 44

Diamond Pattern

# Diamond Pattern

n = int(input('Enter the levels upto which top pyramid required: '))
p = n
q = 2 * n - 1
count = n - 1

for i in range(n):
print(' ' * (n-1), end='')
n = n - 1
print('x' * (2 * i + 1))
for j in range(p, q):
print(' ' * (p - count), end='')
print('x' * (2 * count - 1))
count = count - 1

Output:

image 45

Right-Angle Triangle Pattern

# Right angle triangle pattern

user_input = int(input('Enter the number of rows in triangle: '))

for i in range(0,user_input + 1):
print('*' * i)

Output:

image 41

Inverse Right-Angle Triangle Pattern

# Inverse Right angle triangle pattern

user_input = int(input('Enter the number of rows in triangle: '))

for i in range(user_input + 1,0,-1):
print('*' * i)

image 42

Number Pattern

# Number Pattern

n = int(input("Enter the number of rows: "))

for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=' ')
print()

Output:

image 46

Date and Time

# Display the current date and time

from datetime import datetime

current_datetime = datetime.now()

print(f'Current date and time is {current_datetime}')
print(type(current_datetime))

current_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(f'Current date and time is {current_datetime}')
print(type(current_datetime))

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Current date and time is 2024-06-14 12:42:30.779774

Current date and time is 2024-06-14 12:42:30

Process finished with exit code 0

Quadratic Equation Solver

# Solve a quadratic equation

import math

print('Solve quadratic equation ax\u00B2 + bx + c = 0 by entering coefficients a, b, and c')

a = int(input('Enter the value of a: '))
b = int(input('Enter the value of b: '))
c = int(input('Enter the value of c: '))

discriminant = b**2 - 4*a*c

if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
print(f'Required roots are as follows: {root1} and {root2}')

elif discriminant == 0:
root = -b / (2 * a)

else:
real_part = -b / (2 * a)
imaginary_part = math.sqrt(-discriminant) / (2 * a)
root1 = complex(real_part, imaginary_part)
root2 = complex(real_part, -imaginary_part)
print(f'Required roots are: {root1} and {root2}')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Solve quadratic equation ax² + bx + c = 0 by entering coefficients a, b, and c
Enter the value of a: 2
Enter the value of b: 3
Enter the value of c: 1
Required roots are as follows: -0.5 and -1.0

Process finished with exit code 0

Simple Quiz

# Simple questions and answers score program

quiz = [
('Which city is the capital of India? :', 'Delhi'),
('Result of 2+2? : ', '4'),
('Taj Mahal is in which state: ', 'Agra'),
('Opposite of good is: ', 'Bad'),
('Result of 2 power 4: ', '16')
]

score = 0
print('Quiz Time')
print('Please answer the following questions\n')

for question, correct_answer in quiz:
user_answer = input(question + ' ')

if user_answer.strip().lower() == correct_answer.strip().lower():
print('Correct\n')
score += 1
else:
print(f'Wrong! The correct answer is {correct_answer}\n')

print(f'Your final score is {score} out of {len(quiz)}.\n')

if score == len(quiz):
print(f'Excellent')
elif score > len(quiz) // 2:
print('Good')
else:
print('Better luck next time')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Quiz Time
Please answer the following questions

Which city is the capital of India? : Delhi
Correct

Result of 2+2? : 4
Correct

Taj Mahal is in which state: Agra
Correct

Opposite of good is: bad
Correct

Result of 2 power 4: 16
Correct

Your final score is 5 out of 5.

Excellent

Process finished with exit code 0

Sorting Letters of a String

# Sorting Letters of String

str1 = 'bsabfbjabdbdsadhkghksa'

sorted_str = sorted(str1)

print(sorted_str)


str2 = '' # Empty String used to join sorted_str

req_str = str2.join(sorted_str)

print(req_str)

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
[‘a’, ‘a’, ‘a’, ‘a’, ‘b’, ‘b’, ‘b’, ‘b’, ‘b’, ‘d’, ‘d’, ‘d’, ‘f’, ‘g’, ‘h’, ‘h’, ‘j’, ‘k’, ‘k’, ‘s’, ‘s’, ‘s’]
aaaabbbbbdddfghhjkksss

Process finished with exit code 0

Displaying Data

# Displaying Data

item = input('Enter the item name: ')
price = input('Enter the item price: ')
item_count

total_len = len(item) + len(price)

print(total_len)

dots = '.' * (30 - total_len)

print(item+dots+price)

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the item name: Afghani Chicken
Enter the item price: 500
18
Afghani Chicken…………500

Process finished with exit code 0

# Displaying Data: Items and Price

names = input('Enter the items name separated by space: ') #Example Chicken-Biryani Korma Kawab
prices = input('Enter the price of respective items separated by space: ')
char_count = int(input('Enter the number of characters to be printed: '))

item_names = names.split()
item_prices = prices.split()

if len(item_names) == len(item_prices) :
for i in range(len(item_names)):
dots = '.' * (char_count - len(item_prices) - len(item_names))
print(item_names[i]+dots+item_prices[i])
else:
print('Incorrect Values')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Test2.py
Enter the items name separated by space: Biryani Chicken Kawab
Enter the price of respective items separated by space: 350 450 50
Enter the number of characters to be printed: 30
Biryani……………………350
Chicken……………………450
Kawab……………………50

Process finished with exit code 0

Confirming Password

# Confirming Password

pswrd1 = input('Enter the password: ')
pswrd2 = input('Please re-enter the password: ')

if pswrd1 == pswrd2 :
print('Password Matched')
elif pswrd1.casefold() == pswrd2.casefold() :
print('Check the cases and retype')
else:
print('Please try again not matching')

Output 1:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the password: hi
Please re-enter the password: bye
Please try again not matching

Process finished with exit code 0

Output 2:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the password: hi
Please re-enter the password: Hi
Check the cases and retype

Process finished with exit code 0

Output 3:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the password: hi
Please re-enter the password: hi
Password Matched

Process finished with exit code 0

Display Credit Card Number

# Display credit card number

credit_card = input("Enter the credit card number: ") # Space after every 4 digit

hide = '**** '

print( hide * 3 + credit_card[15::])

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the credit card number: 1234 1234 1234 1234
**** **** **** 1234

Process finished with exit code 0

User ID and Domain Name from Email ID

# Domain and Username from email

email_id = input('Enter the email_id: ')
location = email_id.find('@')

# print(location)

print('Username:', email_id[:location])
print('Domain Name:', email_id[location+1:])

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the email_id: [email protected]
Username: xyz
Domain Name: gmail.com

Process finished with exit code 0

Display Date, Month and Year

# Display Date, Month and Year

user_input = input('Enter the data in format dd/mm/yyyy: ')

data = user_input.split('/')

print('Date:', data[0])
print('Month:', data[1])
print('Year:', data[2])

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the data in format dd/mm/yyyy: 25/05/1988
Date: 25
Month: 05
Year: 1988

Process finished with exit code 0

Anagram or Not

# Anagram or not

str1 = input('Enter the first string: ')
str2 = input('Enter the second string: ')

if sorted(str1) == sorted(str2) :
print('Anagram')
else:
print('Not Anagram')

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the first string: decimal
Enter the second string: medical
Anagram

Process finished with exit code 0

Rearranging Case

# Rearranging Case

str1 = input("Enter the string with lower and upper case alphabets: ")

lower = ''
upper = ''

for i in str1:
if i.islower():
lower += i
else:
upper += i

str2 = lower + upper
print(str2)

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the string with lower and upper case alphabets: jhdcAHJVHJjskkjsa
jhdcjskkjsaAHJVHJ

Process finished with exit code 0

# Rearranging Case and sorted output

str1 = input("Enter the string with lower and upper case alphabets: ")

lower = ''
upper = ''

for i in str1:
if i.islower():
lower += i
else:
upper += i

sorted_lower = sorted(lower)
req_lower = ''.join(sorted_lower)

sorted_upper = sorted(upper)
req_upper = ''.join(sorted_upper)

str2 = req_lower + req_upper
print(str2)

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
Enter the string with lower and upper case alphabets: jhsdjsdhjkAHJSHJDHdbcdkjhfjd
bcdddddfhhhjjjjjkkssADHHHJJS

Process finished with exit code 0

Removing Punctuations

# Removing Punctuations

punct = '''~!@#$%^&*()_{}[]|?<>?"':;.,'''

str1 = '[{[email protected]}]'

str2 = ''

for i in str1:
if i not in punct:
str2 += i

print(str2)

Output:

C:\Users\Thebo\PycharmProjects\Learning\venv\Scripts\python.exe C:\Users\Thebo\PycharmProjects\Learning\Practice.py
mycodepythoncom

Process finished with exit code 0

In Python, the f in front of a string indicates an f-string, which stands for “formatted string literal.” F-strings provide a way to embed expressions inside string literals, using curly braces {}. This allows for more readable and concise string formatting.

Here’s why and how f-strings are used in the provided examples:

Advantages of Using F-Strings:

  • Readability: F-strings make it easier to read and write formatted strings.
  • Efficiency: F-strings are faster than older methods of string formatting like str.format() and the % operator.
  • Flexibility: They allow embedding expressions directly inside the string, making the code more concise.

Explanation:

print(f”Decimal: {decimal_number}”): Here, decimal_number is evaluated and its value is inserted into the string at the position of {decimal_number}.
Similarly, other print statements use f-strings to embed the values of variables directly into the output strings.
This usage simplifies the code, making it more readable compared to older formatting methods. For instance, the equivalent using str.format() would be:

image 20

Using f-strings reduces the need for additional method calls and keeps the formatting inline with the string itself, which is both a cleaner and more efficient way to handle string interpolation in Python.