Sample codes in Python

GCD & LCMGreatest common divisor (GCD) & Lowest Common Multiple (LCM).
factorialFactorial of an input number by looping and by recursive functions
factorsFactors of an input number
Prime NumbersPrime Numbers
FibonacciFibonacci numbers by looping and by recursive functions
Sum of DigitsSum of digits of an input number
Multiplication tableMultiplication table using nested for loops
strong numberCheck input number is strong number or not
Armstrong numberCheck input number is Armstrong number or not
Digit CubesNumber equal to sum of cubes of its digits
recursionGetting and setting recursion limits
DateExercise on Date & time
SalaryEmployee Salary calculation

Sum of three user input numbers

int() to get Integer from String
a=int(input("Enter first Number"))
b=int(input("Enter second Number"))
c=int(input("Enter third Number"))
sum=a+b+c
print(sum)

Enter mark to get status of your division

 m=int(input("Enter your marks"))
if(m>=90):
    print("You have Passed with First Distinction")

else:
    if(m>=60):
        print("You have passed with Second Distinction")
    else:
        if(m>=35):
            print("You have just passed work hard next time")
        else:
            print("Failed")
In place of using multiple if else , it is better to use elif.
Read more how to use elif to get the grade from input mark.

Converting Decimal to Binary number

def my_binary(n):
    i=''
    while n>1:
        a = n%2
        n = n//2
        i=str(a)+i
    i=  str(n%2) +i   
    print (i)
    
a=my_binary(156) 

round a number without using round() function

x=float(input("input number "))
y=int(x+0.5)
print(y)


1. Positive, Negative, or Zero Check

Demonstrates multi-way decision logic using an if-elif-else ladder to evaluate numerical state.

# Program to check if a number is positive, negative, or zero
num = float(input("Enter a number: "))

if num > 0:
    print("The number is Positive.")
elif num < 0:
    print("The number is Negative.")
else:
    print("The number is Zero.")

2. Print Even Numbers (1 to 20)

Combines a for loop with a modulo (%) conditional check to filter even numbers.

# Program to print all even numbers from 1 to 20
print("Even numbers between 1 and 20:")

for i in range(1, 21):
    if i % 2 == 0:
        print(i, end=" ")

3. Vowel or Consonant Checker

Uses membership evaluation (in) and string validation methods to route inputs safely.

# Program to check whether a letter is a vowel or consonant
char = input("Enter a single letter: ").lower()

if len(char) == 1 and char.isalpha():
    if char in 'aeiou':
        print(f"'{char}' is a Vowel.")
    else:
        print(f"'{char}' is a Consonant.")
else:
    print("Invalid input! Please enter a single alphabetic character.")

4. Find the Largest of Three Numbers

Demonstrates compound logical statements using the and operator to validate conditions.

# Program to find the largest among three numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if num1 >= num2 and num1 >= num3:
    largest = num1
elif num2 >= num1 and num2 >= num3:
    largest = num2
else:
    largest = num3

print(f"The largest number is: {largest}")

5. Multiplication Table Generator

Uses a standard for loop with formatted strings to generate structured outputs.

# Program to generate multiplication table for a given number
num = int(input("Enter a number for the multiplication table: "))

print(f"\nMultiplication Table for {num}:")
for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")

6. Count Vowels in a Sentence

Iterates through string characters and increments a counter variable when conditions match.

# Program to count total vowels in a sentence
text = input("Enter a sentence: ")
vowel_count = 0

for char in text.lower():
    if char in 'aeiou':
        vowel_count += 1

print(f"Total number of vowels: {vowel_count}")

7. Leap Year Checker

Illustrates complex boundary evaluation using precedence with and & or operators.

# Program to check if a year is a leap year
year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} is a Leap Year.")
else:
    print(f"{year} is NOT a Leap Year.")

8. Sum of N Natural Numbers

Demonstrates accumulation logic inside a loop construct over a designated range.

# Program to calculate sum of numbers from 1 to N
n = int(input("Enter a positive integer N: "))
total = 0

for i in range(1, n + 1):
    total += i

print(f"The sum of numbers from 1 to {n} is: {total}")

PageSpeed Insights (PSI)

PageSpeed Insights analyzes the content of a web page and generates suggestions to make it faster. This service evaluates web performance using both lab and field data to provide recommendations for improvement.

By leveraging both real-user experiences and simulated environments, PageSpeed Insights offers a comprehensive view of a page's performance. This helps developers optimize their sites, ensuring faster load times and a better user experience. For more information, visit Google's PageSpeed Insights.
import urllib.request, json
key='YOUR_API_KEY' # Use your API key here 

x = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url="
x= x + 'https://www.plus2net.com/python/pdf-grid.php'
x= x + '&strategy=desktop' # other value is mobile 
x= x + '&locale=en'
x= x + '&key='+key

response = urllib.request.urlopen(x)
data = json.loads(response.read()) # get the return Json data 
score = data["lighthouseResult"]["categories"]["performance"]["score"]
print(score) 
  • FCP (First Contentful Paint): The time it takes for the first piece of content to appear on the screen.
  • LCP (Largest Contentful Paint): Measures the loading performance of the largest content element visible in the viewport.
  • CLS (Cumulative Layout Shift): Evaluates the visual stability by measuring unexpected layout shifts during the page load.
  • INP (Interaction to Next Paint): Measures the responsiveness by evaluating the time from user interaction to the next frame painted.
fcp = data["loadingExperience"]["metrics"]["FIRST_CONTENTFUL_PAINT_MS"]["percentile"] 
fid = data["loadingExperience"]["metrics"]["FIRST_INPUT_DELAY_MS"]["percentile"]
lcp = data["loadingExperience"]["metrics"]["LARGEST_CONTENTFUL_PAINT_MS"]["percentile"]
cls = data["loadingExperience"]["metrics"]["CUMULATIVE_LAYOUT_SHIFT_SCORE"]["percentile"]/100

print('fcp:',fcp,'fid: ',fid,'lcp:',lcp,'cls:',cls) 
Learn Python basics through ONLINE classes


Podcast on Python Basics


Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer