- Python Programs
- Python Programs - Home
- Introduction to Python
- Print "Hello, World!"
- Print your name, age, and country
- Print the result of a simple arithmetic expression
- Use sep and end in print()
- Print a poem or song lyrics
- Print a multi-line quote using triple quotes
- Display ASCII art using print()
- Format and print full name using + and ,
- Print today's date using formatted output
- Display types of several variables with type()
- Print truth values of Boolean expressions
- Print Python keywords using the keyword module
- Variables and Data Types
- Assign values to different types (int, float, str, bool)
- Perform all arithmetic operations on two numbers
- Swap two variables using a temporary variable
- Swap variables without using a third variable
- Convert string to int and float
- Convert float to int and round to N decimal places
- Evaluate a complex expression using variables
- Get the memory size of a variable using sys.getsizeof()
- Demonstrate dynamic typing in Python
- Accept string input and display its ASCII values
- Display the binary, octal, and hex of a number
- Use isinstance() to check variable type
- Show precision differences between float and Decimal
- Display formatted currency and percentage
- Display a boolean expression result with explanation
- Input and Output
- Take user input and print greeting
- Input two numbers and print their sum
- Input radius and print area and circumference of a circle
- Input name and marks of a student, print formatted result
- Take input in one line and split into variables
- Read multiple lines of input and print each line reversed
- Print formatted date using f-strings
- Format and align strings using format()
- Display table of values using tabular format
- Input three numbers and display average
- Input a character and print its ASCII code
- Accept time input and display it in 12/24 hour format
- Read a password and hide it using getpass
- Format large numbers using underscores and separators
- Operators and Expressions
- Calculate the perimeter and area of a rectangle
- Compute compound interest
- Check if a number is even or odd using modulo
- Check if a number is divisible by 3 and 5
- Use relational operators between two inputs
- Use logical and, or, not to combine conditions
- Perform bitwise AND, OR, XOR on two numbers
- Evaluate an expression using parentheses and priorities
- Use augmented assignment (+=, *=, etc.) operators
- Calculate the average of a list of numbers
- Find the power of a number using ** and pow()
- Implement a basic BMI calculator
- Convert minutes to hours and minutes
- Check whether a number is in a given range
- Calculate speed = distance/time and convert units
- Module 2: Control Structures
- Conditional Statements
- Check if a number is positive, negative, or zero
- Find the largest of three numbers
- Check whether a number is even or odd
- Check if a year is a leap year
- Determine grade based on marks
- Check if a character is a vowel or consonant
- Find if a number is divisible by both 3 and 5
- Validate user login credentials (hardcoded username/password)
- Check if a person is eligible to vote
- Compare three strings and print the longest
- Check if a number is a multiple of another
- Determine if a triangle is scalene, isosceles, or equilateral
- Check if a number lies within a given range
- Convert temperature from Celsius to Fahrenheit and categorize (hot/cold)
- Simple interest or compound interest calculator with user choice
- Determine electricity bill category based on units consumed
- Find roots of a quadratic equation (real/imaginary)
- Check if a character is uppercase, lowercase, digit, or special character
- Find the absolute value of a number
- Check if a string starts with a specific letter
- Looping Statements
- Print numbers from 1 to 100
- Print even numbers between 1 to 50
- Print multiplication table of a given number
- Calculate factorial using a while loop
- Calculate the sum of digits of a number
- Count digits, alphabets, and special characters in a string
- Find the sum of first n natural numbers
- Reverse a number using loop
- Check if a number is prime
- Generate Fibonacci series up to n terms
- Print all prime numbers in a given range
- Display a pattern (e.g., pyramid, triangle using *)
- Find the Least Common Multiple (LCM) of two numbers
- Display numbers divisible by 7 but not by 5
- Calculate the power of a number using a loop
- Count how many times a digit occurs in a number
- Sum of even and odd numbers in a list
- Create a menu-driven program with loop and conditions
- Print ASCII values of all characters from A to Z
- Check if a number is an Armstrong number
- Module 3: Functions and Recursion
- Defining and Using Functions
- Function to add two numbers
- Function to check if number is even or odd
- Function to return the factorial of a number
- Function to convert Celsius to Fahrenheit
- Function to calculate the square and cube of a number
- Function to calculate the area of a circle
- Function to find the maximum of three numbers
- Function to check if a string is a palindrome
- Function to calculate BMI and categorize
- Function to reverse a string
- Function to compute compound interest
- Function to return number of vowels in a string
- Function to find sum and average of a list
- Function to count the number of uppercase and lowercase letters
- Function to sort a list without using sort()
- Function to find GCD using Euclidean method
- Function to return nCr (combinations)
- Function with default arguments (e.g., greeting message)
- Function to generate a list of prime numbers in a range
- Function to check if a number is perfect or not
- Recursion Basics
- Recursive function for factorial
- Recursive function for Fibonacci
- Recursive function to compute GCD
- Recursive function to compute sum of first N numbers
- Recursive function to reverse a string
- Recursive function to calculate power of a number
- Recursive function to find max element in a list
- Recursive function to convert decimal to binary
- Recursive function to print elements of a list
- Recursive function to find length of a string
- Recursive function to find LCM
- Recursive function to flatten a nested list
- Recursive function to calculate sum of digits
- Recursive palindrome check
- Recursive function to print numbers from N to 1
- Recursive function to check if a list is sorted
- Recursive function for binary search
- Recursive function to find all permutations of a string
- Recursive function to check if a number is prime
- Recursive function to count total vowels in a sentence
- Recursive function to count the frequency of characters in a string
- Module 4: Strings and Collections
- String Manipulation
- Count vowels and consonants in a string
- Check if a string is a palindrome
- Convert all characters in a string to uppercase
- Find the frequency of each character
- Replace spaces with hyphens
- Remove all punctuation from a string
- Count the number of words in a sentence
- Find the longest word in a sentence
- Swap case of all characters in a string
- Check if two strings are anagrams
- Remove duplicate characters from a string
- Find common characters between two strings
- Reverse a string using slicing and loop
- Capitalize the first letter of each word
- Find substring occurrences in a string
- Remove leading and trailing spaces
- Extract numbers from a string
- Split a string and join using hyphen
- Sort characters in a string alphabetically
- Find ASCII value of each character
- Lists and Tuples
- Create a list of N numbers from user input
- Find sum and average of list elements
- Count occurrences of an element
- Find the maximum and minimum in a list
- Sort a list without using built-in functions
- Remove duplicates from a list
- Add and remove elements from a list
- Reverse a list using slicing and loop
- Merge two lists
- Find the second largest number in a list
- Check if a list is sorted
- List comprehension: squares of even numbers
- Create a nested list and access elements
- Create and unpack a tuple
- Convert list to tuple and vice versa
- Find common elements in two lists
- Find the intersection and difference of two lists
- Delete all occurrences of an element from a list
- Find the most frequent element in a list
- Rotate elements of a list to the right by k positions
- Dictionaries and Sets
- Create a dictionary of student names and marks
- Count frequency of words in a sentence
- Merge two dictionaries
- Add, update, and delete a key-value pair
- Iterate over dictionary keys and values
- Find the key with the highest value
- Sort a dictionary by values
- Invert a dictionary (swap keys and values)
- Check if a key exists in dictionary
- Convert two lists into a dictionary
- Remove duplicates from a list using set
- Find union, intersection, difference of two sets
- Check if one set is a subset of another
- Add and remove elements from a set
- Count number of unique words in a sentence
- Create a set of vowels from a string
- Find common characters using set intersection
- Create dictionary from a string with character counts
- Dictionary comprehension to map numbers to their squares
- Find symmetric difference between two sets
- Module 5: Object-Oriented Programming (OOP)
- Lesson 1: Classes and Objects
- Create a Person class and print name and age
- Create a Rectangle class with area and perimeter methods
- Define a Book class and display book details
- Create a Car class with attributes and a display method
- Define a BankAccount class with deposit and withdrawal
- Create a Circle class to compute area and circumference
- Create a Student class with method to calculate grade
- Define a Product class with method to apply discount
- Create an Employee class and print full profile
- Define a class to convert Celsius to Fahrenheit
- Add a method to update an attribute after initialization
- Add class variables and track instance count
- Create a Laptop class with warranty checker method
- Demonstrate instance, class, and static methods
- Create a class to store and display contact details
- Define a Movie class to show ratings and reviews
- Create a class with list attributes and methods to append
- Design a Triangle class and check for valid triangle
- Define a Clock class to show current time
- Create a class to manage inventory items
- Constructors and Methods
- Use __init__ to initialize student details
- Constructor with default parameters
- Create a class to manage bank accounts with init balance
- Define methods to increment and decrement a counter
- Create a Timer class with start/stop functionality
- Define a Point class and calculate distance from origin
- Constructor to create list of items, method to sort them
- Add a method to validate data inside a class
- Define a class Laptop with a discount method
- Create a class Course to register and drop students
- Initialize employee details and method to promote
- Define a class with method to check palindrome names
- Constructor chaining using default values
- Define an Invoice class with total price calculator
- Class with init method validating input type (int/str)
- Use method to return string representation of object
- Constructor initializing user login credentials
- Constructor-based multiplication table printer
- Define a class with password validator
- Constructor that reads user input at object creation
- Inheritance and Polymorphism
- Create a base class Animal and subclass Dog
- Use super() to call parent class constructor
- Define a Shape class and subclass Rectangle, Circle
- Override a method in child class
- Demonstrate multi-level inheritance
- Create a Person base class and Teacher, Student subclasses
- Implement multiple inheritance (e.g., Artist, Engineer)
- Create a base class Vehicle with subclasses Car, Bike
- Demonstrate method overriding and polymorphism
- Base class Account with methods deposit(), withdraw()
- Use isinstance() to check object type
- Polymorphic function that works with different data types
- Create abstract base class with abc module
- Demonstrate duck typing with walk() method
- Create a Media class with play() method overridden
- Inherit constructor and add extra attributes in child
- Use hasattr() and getattr() to access object info
- Demonstrate inheritance with __str__() method
- Extend parent class with new method in child class
- Base class Polygon with triangle, square subclasses
- Module 6: File and Exception Handling
- Reading/Writing Files
- Write a string to a text file
- Read and print contents of a text file
- Append text to an existing file
- Count number of lines in a file
- Count number of words and characters in a file
- Copy contents from one file to another
- Merge contents of two files into a third file
- Write a list of strings to a file (one per line)
- Read file and print lines with line numbers
- Remove all blank lines from a file
- Write user-entered data repeatedly into a file until "exit"
- Find and replace a word in a file
- Check if a file exists before reading (using os.path.exists())
- Read a large file line-by-line (memory-efficient)
- Read a file and extract only numeric data
- Write and read Unicode characters
- Create a file from scratch with student records
- Sort lines of a text file alphabetically
- Write reversed lines of a file to another file
- Save execution logs with timestamps into a log file
- CSV and JSON Files
- Read a CSV file and print each row
- Write a list of dictionaries to a CSV file
- Append a row to an existing CSV
- Read a CSV with headers using DictReader
- Filter rows from a CSV file (e.g., students > 80 marks)
- Convert CSV file to JSON format
- Write Python dictionary to a JSON file
- Read JSON file and access nested data
- Validate JSON using json.loads()
- Convert JSON to dictionary and loop through data
- Extract all values of a specific key from JSON
- Read a list of dictionaries from JSON and print in table
- Store user preferences/settings in a JSON file
- Append data to an existing JSON array
- Pretty-print JSON with indentation
- Read CSV and calculate statistics (mean, median)
- Write dictionary with non-ASCII characters to JSON
- Convert list of tuples into JSON array
- Update values in a loaded JSON object and save
- Build a JSON file containing user data entered via input
- Try-Except Blocks
- Handle division by zero
- Catch invalid input and convert it to integer
- Handle file not found error
- Multiple exception handling (ValueError, ZeroDivisionError)
- Use else and finally with try block
- Catch and print stack trace using traceback
- Nested try-except blocks
- Custom exception: raise error if age < 18
- Handle type errors in addition of incompatible types
- Validate file extension before opening file
- Use assertions to check preconditions
- Exception handling in list indexing
- Exception handling while opening URL (mocked)
- Raise exception if string is not alphabetic
- Try-except-finally to manage database connection (mock)
- Raise exception for password too short
- Log exception details to a file
- Retry block until valid integer input is entered
- Handle key errors in dictionary access
- Handle invalid JSON format using try-except
- Module 7: Advanced Python Features
- Lambda, Map, Filter, Reduce
- Use lambda to square a number
- Use lambda to check if a number is even
- Sort a list of tuples by the second item using lambda
- Map: convert list of strings to uppercase
- Map: square each number in a list
- Filter: extract only odd numbers from a list
- Filter: select strings longer than 5 characters
- Reduce: calculate the sum of a list
- Reduce: find the maximum in a list
- Apply map and filter together (e.g., square only even numbers)
- Use lambda to create a mini calculator
- Map: convert temperatures from Celsius to Fahrenheit
- Filter: extract palindromes from a list
- Use reduce() to calculate factorial
- Use lambda to return the length of each string in a list
- Combine map() and zip() for parallel processing
- Use lambda inside sorted() for custom sort
- Remove all negative numbers from a list using filter
- Multiply all elements using reduce()
- Map: convert list of names to title case
- Comprehensions
- List of squares from 1 to 10 using list comprehension
- Create a list of even numbers between 1–50
- Create a list of strings with length > 5
- Create a dictionary of numbers and their cubes
- Create a set of first letters of all words in a list
- Reverse each string in a list using comprehension
- Convert all vowels in a string to uppercase using list comprehension
- Dictionary: word lengths from a sentence
- Matrix transpose using nested list comprehension
- Filter out None values from a list
- Flatten a 2D list using list comprehension
- Get only unique vowels from a string
- Dictionary: count occurrences of characters
- Remove whitespace from each string in a list
- Convert a list of Fahrenheit to Celsius
- Filter only prime numbers from a range
- List comprehension to remove punctuation from string
- Convert a list of tuples into a dictionary
- Create a list of perfect squares less than 100
- Convert string of digits into a list of integers
- Decorators and Generators
- Create a basic decorator to log function call
- Decorator to measure execution time
- Decorator to check user authentication
- Decorator to convert output to uppercase
- Chained decorators: log and format return value
- Generator: yield numbers from 1 to N
- Generator to yield even numbers up to N
- Generator to yield Fibonacci sequence
- Generator to read large file line by line
- Use generator expression to sum squares of numbers
- Decorator to validate function input (e.g., age > 0)
- Create a generator for infinite odd numbers
- Decorator to retry a function N times on failure
- Generator to yield prime numbers under 100
- Decorator to catch and log exceptions
- Generator to yield all substrings of a string
- Create a decorator that adds a greeting to function output
- Generator to simulate countdown
- Decorator that prevents function from executing twice
- Use next() to manually iterate through a generator
- Module 8: Data Structures
- Manual Implementation - Stack (LIFO) and Queue (FIFO)
- Stack (LIFO)
- Implement queue using list (enqueue, dequeue)
- Implement circular queue using list
- Simulate a ticket booking queue system
- Priority queue implementation using list of tuples
- Implement queue using two stacks
- Implement deque (double-ended queue)
- Simulate printer queue with priorities
- Implement queue using a linked list
- Patient registration system using queue
- Circular buffer simulation
- Queue (FIFO)
- Implement queue using list (enqueue, dequeue)
- Implement circular queue using list
- Simulate a ticket booking queue system
- Priority queue implementation using list of tuples
- Implement queue using two stacks
- Implement deque (double-ended queue)
- Simulate printer queue with priorities
- Implement queue using a linked list
- Patient registration system using queue
- Circular buffer simulation
- Built-in Structures (from collections and heapq)
- Use deque for append and pop from both ends
- Implement stack and queue using deque
- Palindrome checker using deque
- Use Counter to count frequency of words in a paragraph
- Use defaultdict to categorize list of tuples by key
- Group words by their starting letter using defaultdict
- Use OrderedDict to remember order of insertions
- Use heapq to implement a min-heap
- Use heapq to get top N smallest/largest elements
- Create a priority queue with heapq and tuples
- Convert list into heap and perform heapify
- Merge multiple sorted lists using heap
- Use Counter to find the most common element
- Use deque to rotate a list
- Use namedtuple to create structured records
- Compare dict vs OrderedDict for insertion order
- Implement leaderboard with top scores using heapq
- Use ChainMap to merge multiple dictionaries
- Use Counter to compare frequency of characters
- Create a min-heap for task scheduling
- Module 9: Data Science with Python (Intro)
- NumPy Basics
- Create a 1D, 2D, and 3D NumPy array
- Create arrays with zeros(), ones(), arange(), and linspace()
- Reshape a 1D array into a 2D array
- Perform element-wise arithmetic operations
- Slice and index a NumPy array
- Find mean, median, standard deviation, and variance
- Matrix multiplication and dot product
- Transpose a matrix
- Create identity and diagonal matrices
- Stack arrays vertically and horizontally
- Filter elements using boolean indexing
- Replace negative numbers with 0 in an array
- Flatten a multi-dimensional array
- Use broadcasting to add scalar to array
- Find max and min value in a NumPy array
- Sort rows and columns of a 2D array
- Generate a random matrix
- Check memory usage of array vs Python list
- Create a histogram of random normal data
- Solve linear equations using NumPy
- Pandas for DataFrames
- Create a DataFrame from a dictionary
- Read a CSV file into a DataFrame
- Display column names and basic statistics (.describe())
- Access rows and columns using loc and iloc
- Filter rows based on condition
- Add and drop columns in a DataFrame
- Group data by a column and calculate average
- Handle missing values (fill, drop, interpolate)
- Sort DataFrame by a column
- Rename columns and indexes
- Merge two DataFrames (inner, outer joins)
- Apply a function to a column
- Convert a column to datetime
- Create a new column from existing ones
- Export DataFrame to CSV and Excel
- Plot bar chart from column values
- Filter rows where string column contains a keyword
- Load and analyze Excel files using read_excel()
- Concatenate multiple DataFrames
- Pivot and unpivot tables using pivot_table() and melt()
- Matplotlib and Seaborn
- Plot a simple line chart with labels
- Plot bar chart of student scores
- Plot pie chart of product sales
- Create a histogram of ages
- Plot multiple lines on one graph
- Customize chart titles, axis labels, grid
- Plot scatter plot of two variables
- Create subplots in one figure
- Read data from CSV and plot graph
- Save a plot to a file (PNG, JPG)
- Create boxplot to compare distributions
- Create heatmap using Seaborn
- Plot pairplot of numeric features
- Show correlation matrix using heatmap
- Plot distribution plot of scores using Seaborn
- Customize colors and styles of plots
- Plot bar chart with error bars
- Add annotations and labels to data points
- Compare multiple categories using grouped bar chart
- Visualize time series data using line plots
- Module 10: Working with APIs and Web
- requests and APIs
- Make a GET request to a public API (e.g., JSONPlaceholder)
- Print the status code and headers of a response
- Parse and display JSON from an API response
- Make a POST request with JSON payload
- Send parameters with a GET request using params
- Download an image or file from a URL
- Get current weather data using OpenWeatherMap API
- Fetch a random joke or quote from an API
- Validate and format API response using json module
- Handle 404 or failed API requests with try-except
- Create a reusable function to call any API endpoint
- Access GitHub user data using GitHub REST API
- Send data to a mock server (e.g., reqres.in) using POST
- Parse nested JSON and display it in tabular form
- Build a function that returns COVID stats for a country
- Automate currency conversion using a Forex API
- Display top headlines using NewsAPI
- Monitor a website’s uptime using repeated API pings
- Extract NASA Astronomy Picture of the Day using their API
- Store API responses in a JSON file locally
- Web Scraping with BeautifulSoup
- Scrape the title of a web page
- Extract all hyperlinks from a page
- Scrape all
to
tags from a site
- Extract text from all
tags
- Get article titles from a news site homepage
- Scrape job listings from a job portal
- Scrape product names and prices from an e-commerce site
- Extract table data from a webpage (e.g., Wikipedia)
- Scrape weather forecast from a local site
- Download all images from a webpage
- Scrape blog post titles and URLs
- Extract all email addresses from a website
- Use CSS selectors to target specific elements
- Handle pagination in scraping (next page button)
- Store scraped data in CSV format
- Store scraped data in a JSON file
- Build a mini command-line scraper for quotes
- Filter scraped elements using tag attributes
- Detect and skip broken URLs
- Integrate requests + BeautifulSoup in a scraper pipeline
- JSON Handling
- Convert a Python dictionary to JSON string
- Convert JSON string to dictionary
- Write dictionary data to a JSON file
- Read JSON file and access nested values
- Pretty-print JSON with indentation
- Load JSON from a web API and parse it
- Handle invalid JSON with try-except
- Update a value inside a loaded JSON object
- Delete a key from a JSON object and save
- Add new key-value pairs to an existing JSON file
- Merge two JSON objects into one
- Convert a JSON array to a list of Python objects
- Search for a value in nested JSON
- Save a list of students' data into a JSON file
- Load and loop through JSON to print formatted output
- Convert a list of objects to JSON with custom encoder
- Serialize a class instance to JSON
- Deserialize JSON string into custom Python class
- Validate a JSON structure manually (e.g., required fields)
- Compare two JSON objects and highlight differences
- Module 11: GUI and Automation
- GUI Programming with Tkinter
- Create a basic GUI window with title and size
- Add a label and button to a window
- Display user-entered text using an input field
- Build a simple calculator (add, subtract, multiply, divide)
- Create a login form with username and password fields
- Build a temperature converter (Celsius ↔ Fahrenheit)
- Create a dropdown menu and display selected value
- Add radio buttons for selecting gender
- Add checkboxes and show selected hobbies
- Use frames and grids to organize widgets
- Display list of items and select from it
- File browser: open and read a text file
- Create a to-do list application with add/remove
- Create a feedback form with validation
- Add progress bar and simulate loading
- Create GUI to browse and display images
- Change theme/colors dynamically
- Add menu bar with File/Edit/Help options
- Connect GUI with SQLite to store user data
- Show popup message boxes (info, error, warning)
- Automation with os, shutil, datetime, and schedule
- List all files and folders in a directory
- Create, rename, and delete files/folders using os
- Automatically rename multiple files with a pattern
- Copy/move/delete files using shutil
- Backup a folder to another location
- Get file creation/modification date
- Convert filenames to lowercase in a directory
- Create a daily log file with timestamp
- Schedule a task to run every 5 minutes using schedule
- Delete all .tmp files from a folder
- Check disk usage of a folder
- Record current time and write it into a file every 10 sec
- Take automatic screenshot every 30 seconds
- Send a reminder every hour using notification
- Create a zip backup of a folder
- Script to clean up downloads folder
- Automatically email a log file at midnight
- Archive files older than 7 days
- Generate time-based filenames for saving reports
- Automate system shutdown after a timer
- Automating Web Tasks with pyautogui and selenium
- Automate keyboard typing using pyautogui
- Automate mouse clicks and cursor movements
- Take automatic screenshots every N seconds
- Open a website and search using selenium
- Log in to a website automatically using credentials
- Scrape product prices from an e-commerce site
- Fill and submit a Google form using Selenium
- Download files from a website
- Send automated WhatsApp message via web
- Open and control YouTube (play, pause using hotkeys)
- Automate a web-based calculator
- Click a button by its text or CSS class
- Scroll down a webpage using Selenium
- Capture alert popups and handle them
- Automate form filling on a job portal
- Use headless browser for faster automation
- Wait for page to load before scraping content
- Screenshot a webpage and save
- Fill a captcha and stop at verification
- Build a bot to auto-like latest tweets/posts
- Module 12: Mini Projects
- Beginner Level Projects
- To-Do List App (Console)
- Quiz Game
- Number Guessing Game
- Simple ATM Simulator
- Contact Book
- Calculator with GUI (Tkinter)
- Digital Clock (GUI)
- Dice Roller Simulator
- Password Generator
- Simple Alarm Clock
- Intermediate Projects
- Student Marks Report Generator
- Weather App using API
- Currency Converter (with API or static rates)
- Flashcard App for Learning
- Text File Analyzer
- Typing Speed Tester
- BMI Calculator with GUI
- Age Calculator
- Unit Converter (length, weight, temperature)
- Library Book Management (console or GUI)
- Module 13: Capstone Projects
- Capstone Projects (Intermediate to Advanced)
- Student Result Management System
- E-Library Management System
- Expense Tracker App
- Weather Dashboard (API + GUI)
- Online Quiz Application with Scoreboard
- Portfolio Website Generator (CLI/GUI)
- Job Search Automation Bot
- Inventory and Billing System for a Store
- Python Chatbot (GUI or Terminal)
- Movie Recommendation App (Content-Based)
- School Attendance System with CSV and Visualization
- Budget Planner (Pie Charts + Reports)
- File Organizer Utility (Drag-and-Drop GUI)
- Daily Journal App
- Task Manager App with Notifications
- Currency + Crypto Converter App
- PDF Tools Suite
- Mini Social Media Feed
- Resume Parser and Keyword Matcher
- Data Dashboard using Pandas + Matplotlib + Tkinter
- Automating Web Tasks with pyautogui and selenium
Python Programs
![]() Share with a Friend |
Python Programs - Looping Statements
Print numbers from 1 to 100 - Python Program
Using a Basic For Loop
Example 1 :
A for loop is one of the simplest and most efficient ways to print numbers from 1 to 100. It's straightforward:
# Print numbers from 1 to 100 # Using for loop with range() for num in range(1, 101): print(num, end=" ") print("\nDone printing 1 to 100.")
Output
OUTPUT : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 Done printing 1 to 100.
Explanation
- range(1, 101) generates numbers from 1 to 100 (upper limit excluded).
- end=" " ensures numbers are printed in one line separated by spaces.
- Time complexity: O(n) where n = 100.
print(num)
Using print(num) is used to print numbers from 1 to 100 in vertical form.
print(num, end=" ")
Using end=" " is used to print numbers from 1 to 100 in horizontal form.
Using a While Loop
Example 2 :
A while loop provides another way to achieve the same result. This loop is useful when the condition isn't fixed, providing more control over the iteration process:
# Print numbers from 1 to 100 # Using while loop num = 1 while num <= 100: print(num, end=" ") num += 1 print("\nDone printing 1 to 100.")
Output
OUTPUT : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 Done printing 1 to 100.
Explanation
In while loop, num starts at 1 and increments by 1 in each loop iteration until it exceeds 100. The while loop checks the condition num <= 100 before proceeding with each iteration.
Utilizing List Comprehension
Example 3 :
List comprehension is a concise, Pythonic way to work with lists:
# Print numbers from 1 to 100 # Using List [print(i, end=" ") for i in range(1, 101)]
Output
OUTPUT : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
Recursive Function Approach
Example 4 :
Recursion is an advanced concept, often used for complex problems. However, it can print numbers too:
# Print numbers from 1 to 100 # Using Recursion def print_numbers(n): if n > 100: return print(n, end=" ") print_numbers(n + 1) print_numbers(1)
Output
OUTPUT : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
This function calls itself with incremented values until n exceeds 100. Recursion expresses elegance in solving problems by breaking them into smaller, similar tasks but watch for Python's recursion limit, which can be restrictive with large sequences.
Using Built-in Functions and Itertools
Example 5 :
Python offers powerful built-in libraries. Here\'s how itertools can be used:
# Print numbers from 1 to 100 # Using built-in functions import itertools for i in itertools.islice(itertools.count(1), 100): print(i, end=" ")
Output
OUTPUT : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
itertools showcases Python’s ability to handle sequences creatively. The count function starts at 1, and islice specifies the range. It’s an exploration into Python's advanced capabilities, useful for more complex scenarios beyond simple printing.
