# now give me very very very like 5 year old beginer 100 python basic exercise
# Here’s a list of 100 very basic Python exercises designed for a complete
beginner, akin to what a 5-year-old might grasp. Each exercise includes a simple
task that can help understand fundamental concepts.
# Basic Python Exercises for Beginners
# Print "Hello, World!"
# Write a program that prints Hello, World!.
# Add Two Numbers
# Create a program that adds two numbers and prints the result.
# Subtract Two Numbers
# Write a program that subtracts one number from another.
# Multiply Two Numbers
# Create a program that multiplies two numbers.
# Divide Two Numbers
# Write a program that divides one number by another.
# Find the Remainder
# Create a program that finds the remainder when dividing two numbers.
# Square a Number
# Write a program that squares a number (multiplies it by itself).
# Convert Celsius to Fahrenheit
# Write a program that converts Celsius to Fahrenheit.
# Convert Fahrenheit to Celsius
# Write a program that converts Fahrenheit to Celsius.
# Find the Maximum of Two Numbers
# Write a program that finds the larger of two numbers.
# Find the Minimum of Two Numbers
# Create a program that finds the smaller of two numbers.
# Check Even or Odd
# Write a program that checks if a number is even or odd.
# Count to 10
# Create a program that counts from 1 to 10 and prints each number.
# Count Down from 10
# Write a program that counts down from 10 to 1.
# Create a Simple List
# Create a list of your favorite fruits and print it.
# Print Each Fruit
# Write a program that prints each fruit in your list on a new line.
# Add a Fruit to the List
# Create a program that adds a new fruit to your list.
# Remove a Fruit from the List
# Write a program that removes a fruit from your list.
# Sort the List of Fruits
# Create a program that sorts your list of fruits alphabetically.
# Find the Length of the List
# Write a program that prints the number of fruits in your list.
# Make a Greeting
# Create a program that asks for your name and greets you.
# Ask for Age
# Write a program that asks for your age and prints it.
# Create a Simple Dictionary
# Create a dictionary with your name and age, and print it.
# Print the Dictionary Key-Value Pairs
# Write a program that prints each key-value pair in your dictionary.
# Add a Key-Value Pair to the Dictionary
# Create a program that adds a favorite color to your dictionary.
# Remove a Key from the Dictionary
# Write a program that removes your age from the dictionary.
# Check if Key Exists in the Dictionary
# Create a program that checks if your name is in the dictionary.
# Create a Simple Function
# Write a function that adds two numbers and returns the result.
# Call the Function
# Call your function with two numbers and print the result.
# Create a Function to Greet
# Write a function that greets someone by name.
# Use Default Parameter in Function
# Create a function that greets with a default name.
# Use a Function to Find Square
# Write a function that takes a number and returns its square.
# Print Numbers from 1 to 5 Using a Loop
# Use a loop to print numbers from 1 to 5.
# Print Numbers from 5 to 1 Using a Loop
# Use a loop to count down from 5 to 1.
# Create a List of Numbers
# Create a list of numbers from 1 to 5 and print it.
# Sum All Numbers in a List
# Write a program that sums all the numbers in your list.
# Find Average of Numbers in a List
# Create a program that finds the average of your list of numbers.
# Check if a Number is in a List
# Write a program that checks if a specific number is in your list.
# Print a Pattern Using Loops
# Use loops to print a simple pattern (like stars).
# Use Break in a Loop
# Create a loop that breaks when it reaches 3.
# Use Continue in a Loop
# Write a loop that skips printing the number 2.
# Create a Simple Calculator
# Create a program that performs addition, subtraction, multiplication, and
division.
# Find the Length of a String
# Write a program that finds and prints the length of your name.
# Check if String Contains a Letter
# Create a program that checks if your name contains the letter 'a'.
# Convert String to Uppercase
# Write a program that converts your name to uppercase.
# Convert String to Lowercase
# Create a program that converts your name to lowercase.
# Replace a Letter in a String
# Write a program that replaces 'a' with 'o' in your name.
# Count Vowels in a String
# Create a program that counts the number of vowels in your name.
# Print the First Letter of a String
# Write a program that prints the first letter of your name.
# Print the Last Letter of a String
# Create a program that prints the last letter of your name.
# Create a Simple Loop with Range
# Use range() to print numbers from 1 to 5.
# Print Squares of Numbers from 1 to 5
# Write a program that prints squares of numbers from 1 to 5.
# Create a List of Animals
# Create a list of your favorite animals and print it.
# Print the First Animal from the List
# Write a program that prints the first animal from your list.
# Count Animals in the List
# Create a program that counts how many animals are in your list.
# Check if a Favorite Animal Exists
# Write a program that checks if a specific animal is in your list.
# Create a Simple Tic-Tac-Toe Board
# Create a 3x3 list and print it to represent a Tic-Tac-Toe board.
# Update a Cell in the Tic-Tac-Toe Board
# Write a program that updates a cell in your Tic-Tac-Toe board.
# Print Numbers 1 to 10 with While Loop
# Use a while loop to print numbers from 1 to 10.
# Create a Simple Stopwatch
# Write a program that counts from 1 to 5, pausing for a second between each.
# Simple Text-Based Game
# Create a program where the user has to guess a number from 1 to 5.
# Check if Number is Positive, Negative, or Zero
# Write a program that checks if a number is positive, negative, or zero.
# Create a Simple Clock
# Write a program that prints the current hour, minute, and second.
# Calculate the Area of a Circle
# Create a program that calculates the area of a circle given its radius.
# Find the Perimeter of a Rectangle
# Write a program that calculates the perimeter of a rectangle.
# Simple Countdown Timer
# Write a program that counts down from 5 to 0 and then says "Time's up!"
# Create a Simple Rock-Paper-Scissors Game
# Create a program that allows the user to play rock-paper-scissors against the
computer.
# Simple User Input for Favorite Color
# Ask the user for their favorite color and print it.
# Create a Simple Shopping List
# Write a program that creates a shopping list with a few items and prints it.
# Count Down from 10 to 1 Using a While Loop
# Use a while loop to count down from 10 to 1.
# Create a Simple Quiz
# Write a program that asks a question and checks if the answer is correct.
# Create a Simple Age Checker
# Write a program that asks for age and checks if the user is an adult or a child.
# Check if a String is Empty
# Write a program that checks if a string input by the user is empty or not.
# Concatenate Two Strings
# Create a program that combines two strings and prints the result.
# Create a Simple Password Checker
# Write a program that checks if a password is at least 6 characters long.
# Reverse a String
# Write a program that takes a string and prints it in reverse.
# Create a Simple List of Numbers
# Create a list of numbers and print the list.
# Find the Largest Number in a List
# Write a program that finds and prints the largest number in a list.
# Find the Smallest Number in a List
# Create a program that finds and prints the smallest number in a list.
# Count Down Using a For Loop
# Write a program that counts down from 5 to 1 using a for loop.
# Create a Simple Birthday Reminder
# Write a program that reminds you of your birthday when you input your birth date.
# Ask for Favorite Food
# Create a program that asks for your favorite food and prints it.
# Basic Temperature Converter
# Write a program that converts temperature from Fahrenheit to Celsius.
# Check if Number is Prime
# Write a program that checks if a number is a prime number.
# Count from 1 to 10 in a Loop
# Use a loop to count from 1 to 10.
# Calculate the Sum of Numbers from 1 to 10
# Write a program that sums numbers from 1 to 10.
# Create a Simple To-Do List
# Write a program that lets you add tasks to a to-do list.
# Check if a Year is a Leap Year
# Write a program that checks if a given year is a leap year.
# Print a Simple Square Pattern
# Use loops to print a square pattern of stars.
# Create a Simple Number Guessing Game
# Write a program that asks the user to guess a number between 1 and 10.
# Print the First Five Even Numbers
# Write a program that prints the first five even numbers.
# Create a Simple Counter
# Write a program that counts up from 1 to 5 and prints each number.
# Check if a Word is a Palindrome
# Write a program that checks if a word reads the same forwards and backwards.
# Count the Number of Words in a String
# Write a program that counts and prints the number of words in a string.
# Create a Simple Greeting Function
# Write a function that greets a user by their name.
# Check if a String Starts with a Specific Letter
# Write a program that checks if a string starts with 'A'.
# Find the Average of Five Numbers
# Write a program that calculates the average of five numbers.
# Create a Simple URL Shortener
# Write a program that takes a long URL and prints a shortened version.
# Ask for Two Numbers and Print Their Sum
# Create a program that asks for two numbers and prints their sum.
# Create a Simple Story Generator - Write a program that takes a few words from the
user and creates a silly story.
# These exercises are designed to help beginners get comfortable with basic
programming concepts and Python syntax. They can be done in any order, and some may
require guidance or additional context. Let me know if you need further
explanations for any of them!
# You said:
# more 100
# ChatGPT said:
# ChatGPT
# Sure! Here’s another list of 100 very basic Python exercises for complete
beginners, designed to help them grasp fundamental concepts and enjoy programming:
# More Basic Python Exercises for Beginners
# Create a Simple Age Calculator - Write a program that calculates your age based
on your birth year.
# Find the Sum of a List - Create a program that calculates and prints the sum of a
list of numbers.
# Print All Odd Numbers from 1 to 20 - Write a program that prints all odd numbers
between 1 and 20.
# Create a Simple Countdown Function - Write a function that counts down from a
given number to 0.
# Ask for Two Strings and Concatenate Them - Create a program that asks for two
strings and prints them together.
# Check if a Number is Negative - Write a program that checks if a given number is
negative.
# Print the First 10 Fibonacci Numbers - Write a program that prints the first 10
Fibonacci numbers.
# Create a Simple List of Colors - Write a program that creates a list of colors
and prints it.
# Change a Color in the List - Write a program that changes a color in your color
list.
# Create a Simple Voting Program - Write a program that asks for your favorite
color and counts the votes.
# Count from 1 to 100 by 5s - Write a program that counts from 1 to 100 in steps of
5.
# Create a Simple User Profile - Create a program that stores and prints your name,
age, and favorite color.
# Create a Basic Math Quiz - Write a program that asks a simple math question and
checks the answer.
# Convert Minutes to Seconds - Create a program that converts minutes into seconds.
# Find the Square Root of a Number - Write a program that finds and prints the
square root of a number.
# Create a Simple Library System - Write a program that manages a list of books and
allows adding and removing books.
# Check if a Number is Divisible by 3 - Write a program that checks if a number is
divisible by 3.
# Create a Simple Random Number Generator - Write a program that generates and
prints a random number between 1 and 100.
# Create a Simple Markdown Formatter - Write a program that formats a string to be
bold or italic in Markdown.
# Count Down from a Given Number Using Recursion - Write a recursive function that
counts down from a given number.
# Ask for a Number and Print its Multiplication Table - Write a program that prints
the multiplication table for a given number.
# Create a Simple Weather Report - Write a program that provides a fake weather
report based on the user's location.
# Ask for User Input and Repeat it - Write a program that takes user input and
prints it back.
# Check if Two Strings are Anagrams - Write a program that checks if two strings
are anagrams of each other.
# Calculate the Factorial of a Number - Write a program that calculates the
factorial of a number using a loop.
# Print a Simple Star Triangle - Use loops to print a triangle pattern of stars.
# Find the GCD of Two Numbers - Write a program that finds the greatest common
divisor of two numbers.
# Create a Simple Alarm Clock - Write a program that sets a simple alarm for a
specified time.
# Check if a Year is Odd or Even - Write a program that checks if a given year is
odd or even.
# Create a Simple Text Adventure - Write a program that tells a story and lets the
user choose what happens next.
# Calculate the Area of a Triangle - Write a program that calculates the area of a
triangle given its base and height.
# Generate a Simple Random Password - Create a program that generates a random
password with letters and numbers.
# Check if a String is a Substring - Write a program that checks if one string is a
substring of another.
# Calculate the Total Cost of Shopping Items - Write a program that adds up the
prices of items in a shopping list.
# Create a Simple Currency Converter - Write a program that converts between two
currencies using a fixed exchange rate.
# Ask for a Number and Print its Cube - Write a program that takes a number and
prints its cube.
# Create a Simple Workout Tracker - Write a program that allows users to log their
workouts and print them.
# Check if a String is a Palindrome (Ignoring Case) - Write a program that checks
if a string is a palindrome regardless of case.
# Create a Simple Music Playlist - Write a program that allows adding and removing
songs from a playlist.
# Calculate the Circumference of a Circle - Write a program that calculates the
circumference of a circle given its radius.
# Check if Two Numbers are Equal - Write a program that checks if two numbers
entered by the user are equal.
# Create a Simple Image Viewer (using a URL) - Write a program that takes an image
URL and displays the image (print the URL).
# Create a Simple Grade Calculator - Write a program that calculates the average of
grades and assigns a letter grade.
# Find the Median of a List of Numbers - Write a program that finds and prints the
median of a list of numbers.
# Create a Simple Recipe Manager - Write a program that allows users to add and
view recipes.
# Check if a Number is Prime (Simple Version) - Write a program that checks if a
number is prime using a simple loop.
# Calculate the Area of a Rectangle - Write a program that calculates the area of a
rectangle given its length and width.
# Create a Simple Daily Journal - Write a program that allows users to enter daily
journal entries and print them.
# Ask for a Sentence and Count Vowels - Write a program that counts the number of
vowels in a sentence.
# Create a Simple Greeting Card Generator - Write a program that generates a simple
greeting card message.
# Check if a Character is a Vowel - Write a program that checks if a given
character is a vowel.
# Create a Simple Phone Book - Write a program that allows adding, searching, and
deleting contacts.
# Calculate the Distance Between Two Points - Write a program that calculates the
distance between two points on a plane.
# Create a Simple Stopwatch (using time) - Write a program that simulates a
stopwatch using time delays.
# Ask for a List of Items and Print Them - Write a program that asks for a list of
items and prints each one.
# Check if a String is Numeric - Write a program that checks if a string contains
only numbers.
# Create a Simple Flashcard Quiz - Write a program that tests knowledge with
flashcards (questions and answers).
# Create a Simple Email Validator - Write a program that checks if an email address
is valid based on simple rules.
# Calculate the Total Number of Characters in a String - Write a program that
counts and prints the total number of characters in a string.
# Generate a Simple Random Color Code - Write a program that generates and prints a
random hexadecimal color code.
# Create a Simple Calendar (Month Display) - Write a program that displays the days
of a specified month.
# Count Down by Twos from 10 to 0 - Write a program that counts down from 10 to 0
by twos.
# Create a Simple Math Flashcard App - Write a program that asks simple math
questions and checks the answers.
# Find the LCM of Two Numbers - Write a program that finds the least common
multiple of two numbers.
# Create a Simple Feedback Form - Write a program that collects feedback from users
about a topic.
# Calculate the Sum of Digits in a Number - Write a program that calculates the sum
of the digits in a number.
# Create a Simple Trivia Game - Write a program that asks trivia questions and
keeps score.
# Check if a String Contains Only Alphabets - Write a program that checks if a
string contains only alphabetic characters.
# Create a Simple Travel Budget Calculator - Write a program that helps calculate
the budget for a trip.
# Calculate the Total Cost of a Meal Including Tax - Write a program that
calculates the total cost of a meal including tax.
# Create a Simple Memory Game - Write a program that simulates a simple memory game
with numbers.
# Check if a String Ends with a Specific Letter - Write a program that checks if a
string ends with 'z'.
# Create a Simple Expense Tracker - Write a program that tracks expenses and
calculates the total.
# Calculate the Future Value of an Investment - Write a program that calculates the
future value of an investment based on interest.
# Create a Simple Mood Tracker - Write a program that asks for your mood and logs
it.
# Check if a Number is Odd Using Modulus - Write a program that checks if a number
is odd using the modulus operator.
# Generate a Simple User ID - Write a program that generates a random user ID based
on user input.
# Create a Simple Memory Usage Report - Write a program that displays memory usage
information (mock data).
# Count the Number of Digits in a Number - Write a program that counts and prints
the number of digits in a number.
# Create a Simple Holiday Countdown - Write a program that counts down to a
specified holiday.
# Check if a Number is in a List - Write a program that checks if a given number is
in a predefined list.
# Create a Simple Recipe Suggestion App - Write a program that suggests recipes
based on ingredients entered.
# Calculate the Total Price of Shopping Items - Write a program that calculates the
total price from a list of item prices.
# Generate a Simple Random Quote - Write a program that prints a random
motivational quote from a list.
# Create a Simple Daily Task Organizer - Write a program that helps organize daily
tasks with priority levels.
# Check if a Number is Within a Range - Write a program that checks if a number is
within a specific range.
# Create a Simple Job Application Tracker - Write a program that tracks job
applications and their status.
# Calculate the Volume of a Cylinder - Write a program that calculates the volume
of a cylinder given its radius and height.
# Generate a Simple Random Name - Write a program that generates a random name from
a predefined list.
# Create a Simple Polling App - Write a program that allows users to vote on a
topic and displays results.
# Check if a String Contains a Substring - Write a program that checks if one
string contains another.
# Calculate the Days Until Your Birthday - Write a program that calculates and
prints the number of days until your next birthday.
# Create a Simple Cooking Timer - Write a program that counts down for a specified
cooking time.
# Generate a Simple Random Animal Name - Write a program that randomly selects an
animal name from a list.
# Check if a Number is a Perfect Square - Write a program that checks if a given
number is a perfect square.
# Create a Simple Exercise Log - Write a program that allows users to log exercises
and print them.
# Calculate the Total Distance Traveled - Write a program that calculates the total
distance traveled based on user input.
# Create a Simple Habit Tracker - Write a program that tracks daily habits and
prints a report.
# Check if a Number is a Palindrome - Write a program that checks if a number reads
the same forwards and backwards.
# Generate a Simple Random Password - Write a program that generates a random
password using letters and numbers.
# These exercises are designed to engage beginners with a variety of fun and
practical programming tasks. They can help build confidence and reinforce
foundational concepts in Python. Let me know if you need further explanations or
examples for any specific exercises!
# You said:
# more 100
# ChatGPT said:
# ChatGPT
# Absolutely! Here’s another list of 100 Python exercises for beginners. These
tasks aim to be engaging and build foundational programming skills:
# Even More Basic Python Exercises for Beginners
# Create a Simple Weather Temperature Converter - Write a program that converts
Celsius to Fahrenheit.
# Print the First 20 Odd Numbers - Write a program that prints the first 20 odd
numbers.
# Count the Number of Characters in a String - Write a program that counts and
prints the number of characters in a user-provided string.
# Create a Simple Quiz with Score Tracking - Write a program that asks quiz
questions and tracks the user's score.
# Ask for User's Favorite Movie - Write a program that asks for the user's favorite
movie and prints it.
# Calculate the Sum of the Squares of the First 10 Numbers - Write a program that
calculates the sum of squares from 1 to 10.
# Print a List in Reverse Order - Write a program that prints a list of items in
reverse order.
# Check if a String Contains a Digit - Write a program that checks if a given
string contains any digits.
# Create a Simple Alarm System - Write a program that asks for a time and alerts
you when it's time.
# Calculate the Area of a Trapezoid - Write a program that calculates the area of a
trapezoid given its bases and height.
# Generate a Simple Random Color Name - Write a program that randomly selects a
color name from a list of colors.
# Create a Simple Countdown Timer - Write a program that counts down from a
specified number to zero.
# Check if a Word Contains Only Lowercase Letters - Write a program that checks if
a word contains only lowercase letters.
# Create a Simple Game of Rock, Paper, Scissors - Write a program that lets the
user play rock, paper, scissors against the computer.
# Calculate the Total Cost of a Shopping List - Write a program that takes prices
of items and calculates the total.
# Ask for a Sentence and Count Consonants - Write a program that counts the number
of consonants in a given sentence.
# Generate a Simple Random Fact - Write a program that prints a random fact from a
list of fun facts.
# Create a Simple Task Reminder - Write a program that stores tasks and reminds you
to complete them.
# Check if a Given Character is in a String - Write a program that checks if a
character is present in a string.
# Calculate the Area of a Circle Using a Function - Write a function that
calculates the area of a circle based on the radius.
# Ask for a Number and Print its Factorial - Write a program that takes a number
and prints its factorial.
# Create a Simple Voting System for Favorite Food - Write a program that lets users
vote for their favorite food.
# Count the Number of Spaces in a Sentence - Write a program that counts and prints
the number of spaces in a sentence.
# Generate a Simple Random Username - Write a program that generates a random
username from a list of names.
# Check if a Number is Prime (Advanced) - Write a program that checks if a number
is prime using a more efficient method.
# Create a Simple Interest Calculator - Write a program that calculates simple
interest based on principal, rate, and time.
# Ask for User's Height and Weight - Write a program that asks for and prints the
user's height and weight.
# Count the Number of Uppercase Letters in a String - Write a program that counts
and prints the number of uppercase letters in a string.
# Create a Simple Password Strength Checker - Write a program that checks the
strength of a password based on certain criteria.
# Calculate the Total Days in a Given Year - Write a program that calculates the
total number of days in a given year.
# Ask for a Number and Print its Binary Representation - Write a program that
converts a number to binary and prints it.
# Generate a Simple Random Animal Fact - Write a program that prints a random fact
about an animal.
# Create a Simple Text-Based Calculator - Write a program that performs basic
arithmetic operations based on user input.
# Check if a Number is Perfect - Write a program that checks if a number is a
perfect number (sum of divisors equals the number).
# Ask for a Sentence and Reverse It - Write a program that takes a sentence and
prints it in reverse order.
# Calculate the Average of a List of Numbers - Write a program that calculates and
prints the average of a list of numbers.
# Create a Simple Emoji Translator - Write a program that translates certain words
into emojis.
# Check if a String is a Valid Email Address - Write a program that checks if a
given string is a valid email address format.
# Calculate the Sum of Odd Numbers from 1 to 50 - Write a program that calculates
the sum of all odd numbers from 1 to 50.
# Create a Simple Card Game - Write a program that simulates a simple card game
(like drawing a card).
# Check if a Number is a Narcissistic Number - Write a program that checks if a
number is equal to the sum of its own digits raised to the power of the number of
digits.
# Create a Simple User Profile Editor - Write a program that allows users to create
and edit a profile with name, age, and favorite color.
# Calculate the Total Cost of Items with Discount - Write a program that calculates
the total price after applying a discount.
# Ask for User's Favorite Season - Write a program that asks for and prints the
user's favorite season.
# Check if a Number is a Fibonacci Number - Write a program that checks if a number
is part of the Fibonacci sequence.
# Calculate the Total Distance Travelled by a Car - Write a program that calculates
the total distance based on speed and time.
# Create a Simple Movie Recommendation System - Write a program that recommends
movies based on genres entered by the user.
# Check if a Word is in a Given Sentence - Write a program that checks if a
specific word is present in a sentence.
# Create a Simple Name Reverser - Write a program that takes a name and prints it
in reverse.
# Calculate the Average Price of Products - Write a program that takes a list of
product prices and calculates the average price.
# Ask for User's Favorite Hobby - Write a program that asks for and prints the
user's favorite hobby.
# Check if a Character is a Digit - Write a program that checks if a given
character is a digit.
# Create a Simple Day of the Week Calculator - Write a program that determines the
day of the week for a given date.
# Calculate the Sum of Even Numbers from 1 to 100 - Write a program that calculates
the sum of all even numbers from 1 to 100.
# Ask for a Sentence and Print it in Uppercase - Write a program that takes a
sentence and prints it in uppercase.
# Create a Simple Shopping Cart System - Write a program that allows users to add
items to a cart and view the cart.
# Check if a Number is a Square Number - Write a program that checks if a number is
a square number (perfect square).
# Generate a Simple Random Joke - Write a program that prints a random joke from a
list.
# Create a Simple Interest Compound Calculator - Write a program that calculates
compound interest based on principal, rate, and time.
# Ask for a List of Names and Print Them Alphabetically - Write a program that
takes a list of names and prints them in alphabetical order.
# Calculate the Total Amount of Money Saved - Write a program that calculates total
savings based on monthly contributions.
# Check if a String is a Strong Password - Write a program that checks if a
password meets certain complexity criteria.
# Create a Simple Exercise Recommender - Write a program that recommends exercises
based on user preferences.
# Ask for a Number and Print the Sum of Its Digits - Write a program that takes a
number and prints the sum of its digits.
# Create a Simple Word Counter - Write a program that counts and prints the number
of words in a sentence.
# Check if a Given Date is a Weekend - Write a program that checks if a given date
falls on a weekend.
# Calculate the Total Weight of Items in a List - Write a program that calculates
the total weight from a list of weights.
# Create a Simple Movie Rating System - Write a program that allows users to rate
movies and calculates the average rating.
# Generate a Simple Random Quote Generator - Write a program that randomly selects
a quote from a predefined list.
# Check if a Word is a Compound Word - Write a program that checks if a word can be
formed by combining two smaller words.
# Calculate the Total Time Spent on Activities - Write a program that adds up time
spent on different activities.
# Create a Simple URL Validator - Write a program that checks if a given string is
a valid URL.
# Ask for User's Age and Print it in Months - Write a program that calculates the
user's age in months based on their input.
# Create a Simple Calendar Display - Write a program that displays the current
month and year as a simple calendar.
# Check if a Number is Divisible by Another - Write a program that checks if one
number is divisible by another.
# Calculate the Total Amount Spent on Groceries - Write a program that calculates
the total spent on grocery items.
# Generate a Simple Random Pet Name - Write a program that randomly selects a pet
name from a list.
# Create a Simple Fitness Tracker - Write a program that tracks daily steps and
calculates the total over a week.
# Check if a Number is in a Fibonacci Series - Write a program that checks if a
number is part of the Fibonacci series.
# Create a Simple Time Converter - Write a program that converts hours to minutes
and seconds.
# Calculate the Total Hours Worked in a Week - Write a program that calculates the
total hours worked based on daily input.
# Generate a Simple Random Travel Destination - Write a program that randomly
selects a travel destination from a list.
# Check if a Number is Odd or Even Using Functions - Write a function that checks
if a number is odd or even.
# Ask for User's Favorite Sport - Write a program that asks for and prints the
user's favorite sport.
# Create a Simple Daily Mood Tracker - Write a program that allows users to log
their daily mood.
# Calculate the Total Cost of a Meal Including Tip - Write a program that
calculates the total meal cost with a tip.
# Generate a Simple Random Recipe Suggestion - Write a program that suggests a
recipe randomly from a list.
# Check if a String is a Valid Phone Number - Write a program that checks if a
given string is a valid phone number format.
# Create a Simple Name and Age Sorter - Write a program that sorts names and ages
entered by the user.
# Calculate the Total Savings Over a Period - Write a program that calculates total
savings over a specified number of months.
# Generate a Simple Random Birthday Message - Write a program that prints a random
birthday message from a list.
# Create a Simple User Feedback System - Write a program that allows users to
submit feedback and print it.
# Check if a String is a Valid Date Format - Write a program that checks if a
string matches a valid date format.
# Calculate the Total Distance Traveled Based on Speed - Write a program that
calculates distance based on user input of speed and time.
# Generate a Simple Random Character Name - Write a program that randomly selects a
character name from a list.
# Create a Simple Memory Game (Text-Based) - Write a program that simulates a
simple text-based memory game.
# Check if a Given Number is an Armstrong Number - Write a program that checks if a
number is equal to the sum of its own digits raised to the power of the number of
digits.
# Calculate the Total Time Spent on Hobbies - Write a program that adds up time
spent on different hobbies.
# Generate a Simple Random Nature Fact - Write a program that prints a random fact
about nature.
# Create a Simple User Registration Form - Write a program that collects user
information for registration.
# These exercises should help reinforce basic programming concepts and provide
plenty of opportunities for practice. Let me know if you need any further
assistance or examples!
# Here's a selection of solutions for some of the exercises from 1 to 300, complete
with detailed comments.
# Due to space constraints, I'll provide solutions for the first 20 exercises,
# and you can let me know if you'd like me to continue with more!
# 1. Print "Hello, World!"
# This program prints the famous "Hello, World!" message to the console.
print("Hello, World!")
# 2. Calculate the sum of two numbers
# This program asks the user for two numbers and prints their sum.
# The input() function collects input from the user.
num1 = int(input("Enter first number: ")) # Convert input to integer
num2 = int(input("Enter second number: ")) # Convert input to integer
sum_result = num1 + num2 # Calculate the sum
print("The sum is:", sum_result) # Print the result
# 3. Calculate the area of a rectangle
# This program calculates the area of a rectangle given width and height.
width = float(input("Enter width: ")) # Get width from user
height = float(input("Enter height: ")) # Get height from user
area = width * height # Calculate area
print("The area of the rectangle is:", area) # Print the area
# 4. Find the maximum of two numbers
# This program finds the maximum of two numbers entered by the user.
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second number
max_num = max(num1, num2) # Use max() to find the larger number
print("The maximum number is:", max_num) # Print the maximum number
# 5. Check if a number is even or odd
# This program checks if a number is even or odd using modulus operator.
num = int(input("Enter a number: ")) # Get a number from user
if num % 2 == 0: # Check if the number is divisible by 2
print(num, "is even") # If true, print that it is even
else:
print(num, "is odd") # If false, print that it is odd
# 6. Count the number of vowels in a string
# This program counts the number of vowels in a user-provided string.
sentence = input("Enter a sentence: ") # Get a sentence from user
vowels = "aeiouAEIOU" # Define vowels
count = 0 # Initialize a counter
for char in sentence: # Loop through each character in the string
if char in vowels: # Check if the character is a vowel
count += 1 # Increment the count
print("Number of vowels:", count) # Print the count
# 7. Calculate the factorial of a number
# This program calculates the factorial of a given number using a loop.
num = int(input("Enter a number to find its factorial: ")) # Get input
factorial = 1 # Initialize factorial
for i in range(1, num + 1): # Loop from 1 to num
factorial *= i # Multiply each number
print("Factorial of", num, "is:", factorial) # Print result
# 8. Check if a string is a palindrome
# This program checks if a given string is a palindrome.
word = input("Enter a word: ") # Get a word from user
if word == word[::-1]: # Check if word is the same forwards and backwards
print(word, "is a palindrome") # If true, it is a palindrome
else:
print(word, "is not a palindrome") # If false, it is not a palindrome
# 9. Print the Fibonacci sequence up to n
# This program prints Fibonacci numbers up to n, where n is provided by the user.
n = int(input("Enter the number of terms: ")) # Get number of terms
a, b = 0, 1 # Initialize first two Fibonacci numbers
print("Fibonacci sequence:")
for _ in range(n): # Loop n times
print(a, end=' ') # Print the current number
a, b = b, a + b # Update the numbers
# 10. Calculate the simple interest
# This program calculates simple interest given principal, rate, and time.
principal = float(input("Enter principal amount: ")) # Get principal
rate = float(input("Enter rate of interest: ")) # Get rate
time = float(input("Enter time in years: ")) # Get time
simple_interest = (principal * rate * time) / 100 # Calculate interest
print("Simple Interest is:", simple_interest) # Print result
# 11. Create a list of squares of numbers from 1 to n
# This program generates a list of squares from 1 to n.
n = int(input("Enter a number: ")) # Get n from user
squares = [i ** 2 for i in range(1, n + 1)] # List comprehension for squares
print("Squares from 1 to", n, ":", squares) # Print list of squares
# 12. Count the number of words in a sentence
# This program counts the number of words in a given sentence.
sentence = input("Enter a sentence: ") # Get sentence from user
words = sentence.split() # Split the sentence into words
word_count = len(words) # Count the number of words
print("Number of words:", word_count) # Print the count
# 13. Print the first n prime numbers
# This program prints the first n prime numbers.
def is_prime(num): # Function to check if a number is prime
if num < 2: # Numbers less than 2 are not prime
return False
for i in range(2, int(num**0.5) + 1): # Check for factors
if num % i == 0: # If divisible, not prime
return False
return True
n = int(input("Enter how many prime numbers to print: ")) # Get n
count, num = 0, 2 # Initialize counter and starting number
print("First", n, "prime numbers:")
while count < n: # Loop until count reaches n
if is_prime(num): # Check if num is prime
print(num, end=' ') # Print prime number
count += 1 # Increment count
num += 1 # Move to the next number
# 14. Reverse a given string
# This program reverses the given string and prints it.
string = input("Enter a string: ") # Get string from user
reversed_string = string[::-1] # Reverse the string
print("Reversed string:", reversed_string) # Print reversed string
# 15. Create a simple text-based game
# This program implements a simple text-based guessing game.
import random # Import random module
print("Welcome to the Number Guessing Game!") # Game introduction
number_to_guess = random.randint(1, 100) # Generate a random number between 1 and
100
attempts = 0 # Initialize attempt counter
while True: # Infinite loop until guessed
guess = int(input("Guess a number between 1 and 100: ")) # Get user guess
attempts += 1 # Increment attempts
if guess < number_to_guess: # Guess too low
print("Too low! Try again.")
elif guess > number_to_guess: # Guess too high
print("Too high! Try again.")
else: # Guess is correct
print("Congratulations! You've guessed the number in", attempts,
"attempts.")
break # Exit the loop
# 16. Check if a number is a perfect square
# This program checks if a number is a perfect square.
import math # Import math module for sqrt
num = int(input("Enter a number: ")) # Get number from user
root = math.isqrt(num) # Find the integer square root
if root * root == num: # Check if square of root equals the number
print(num, "is a perfect square.") # If true, it's a perfect square
else:
print(num, "is not a perfect square.") # If false, it's not a perfect square
# 17. Generate a random password
# This program generates a random password using letters and numbers.
import random
import string
length = int(input("Enter the length of the password: ")) # Get desired length
characters = string.ascii_letters + string.digits + string.punctuation # Possible
characters
password = ''.join(random.choice(characters) for i in range(length)) # Generate
password
print("Your random password is:", password) # Print generated password
# 18. Create t a simple calculator
# This program creates a simple calculator for basic operations.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Cannot divide by zero!"
return x / y
print("Select operation:") # Display options
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ") # Get user choice
num1 = float(input("Enter first number: ")) # Get first number
num2 = float(input("Enter second number: ")) # Get second number
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
else:
print("Invalid input") # Handle invalid choices
# 19. Count down from a given number
# This program counts down from a given number to zero.
n = int(input("Enter a number to count down from: ")) # Get starting number
print("Counting down:")
for i in range(n, -1, -1): # Loop from n down to 0
print(i) # Print the current number
# 20. Check if a number is a prime number
# This program checks if a given number is a prime number.
num = int(input("Enter a number: ")) # Get input from user
if num < 2: # Numbers less than 2 are not prime
print(num, "is not a prime number.")
else:
for i in range(2, int(num**0.5) + 1): # Check for factors up to sqrt(num)
if num % i == 0: # If divisible, not prime
print(num, "is not a prime number.")
break
else: # If no divisors found
print(num, "is a prime number.") # Print that it is prime
# 21. Print all prime numbers up to a given number
def is_prime(num):
"""Check if the number is prime."""
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
limit = int(input("Enter a number: ")) # User input for upper limit
print(f"Prime numbers up to {limit}:")
for number in range(2, limit + 1):
if is_prime(number):
print(number, end=' ')
print() # Print newline
# 22. Generate a list of even numbers from 1 to n
n = int(input("Enter a number: ")) # Get upper limit from user
even_numbers = [i for i in range(2, n + 1, 2)] # List comprehension for evens
print("Even numbers from 1 to", n, ":", even_numbers)
# 23. Create a program that reverses a list
input_list = input("Enter elements separated by space: ").split() # Get list from
user
reversed_list = input_list[::-1] # Reverse the list
print("Reversed list:", reversed_list)
# 24. Find the length of a string without using len()
def string_length(s):
"""Calculate the length of a string manually."""
count = 0
for _ in s:
count += 1
return count
input_string = input("Enter a string: ") # Get string from user
length = string_length(input_string) # Calculate length
print("Length of the string is:", length)
# 25. Convert temperature from Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: ")) # Get Celsius input
fahrenheit = (celsius * 9/5) + 32 # Convert to Fahrenheit
print(f"{celsius} Celsius is {fahrenheit} Fahrenheit.")
# 26. Count the number of digits in a number
num = int(input("Enter a number: ")) # Get number from user
digit_count = 0
while num > 0:
num //= 10 # Remove last digit
digit_count += 1 # Increment count
print("Number of digits:", digit_count)
# 27. Check if a year is a leap year
year = int(input("Enter a year: ")) # Get year from user
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
# 28. Calculate the sum of digits of a number
num = input("Enter a number: ") # Get number from user
digit_sum = sum(int(digit) for digit in num) # Calculate sum of digits
print("Sum of digits:", digit_sum)
# 29. Print the multiplication table of a number
number = int(input("Enter a number for multiplication table: ")) # Get input
print(f"Multiplication table for {number}:")
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
# 30. Generate a list of Fibonacci numbers
n = int(input("Enter the number of Fibonacci numbers to generate: ")) # Get n
fibonacci = [0, 1] # Starting values
for i in range(2, n):
next_value = fibonacci[i - 1] + fibonacci[i - 2]
fibonacci.append(next_value) # Add next Fibonacci number
print("Fibonacci series:", fibonacci[:n]) # Print the series
# 31. Create a simple number guessing game
import random
print("Welcome to the Number Guessing Game!")
number_to_guess = random.randint(1, 100) # Generate random number
attempts = 0
while True:
guess = int(input("Guess a number between 1 and 100: ")) # User guess
attempts += 1
if guess < number_to_guess:
print("Too low! Try again.")
elif guess > number_to_guess:
print("Too high! Try again.")
else:
print(f"Congratulations! You've guessed the number in {attempts}
attempts.")
break
# 32. Find the maximum number in a list
input_list = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
max_number = max(input_list) # Use max function
print("Maximum number is:", max_number)
# 33. Calculate the factorial using recursion
def factorial(n):
"""Calculate factorial of n recursively."""
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
num = int(input("Enter a number to calculate its factorial: ")) # Get input
print(f"Factorial of {num} is: {factorial(num)}") # Print factorial
# 34. Find the intersection of two lists
list1 = list(map(int, input("Enter first list of numbers separated by space:
").split()))
list2 = list(map(int, input("Enter second list of numbers separated by space:
").split()))
intersection = list(set(list1) & set(list2)) # Find intersection
print("Intersection of the two lists:", intersection)
# 35. Create a simple text-based game where the player can move around
print("You are in a room. You can move north, south, east, or west.")
while True:
move = input("Which direction do you want to move? ").lower() # Get move
direction
if move in ['north', 'south', 'east', 'west']:
print(f"You moved {move}.") # Confirm move
elif move == 'exit':
print("Exiting the game.")
break
else:
print("Invalid direction. Try again.")
# 36. Calculate the sum of even numbers in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get numbers
even_sum = sum(num for num in numbers if num % 2 == 0) # Calculate sum of evens
print("Sum of even numbers:", even_sum)
# 37. Convert a binary number to decimal
binary = input("Enter a binary number: ") # Get binary input
decimal = int(binary, 2) # Convert binary to decimal
print("Decimal equivalent:", decimal)
# 38. Count the number of occurrences of each character in a string
string = input("Enter a string: ") # Get string from user
char_count = {}
for char in string:
char_count[char] = char_count.get(char, 0) + 1 # Count occurrences
print("Character counts:", char_count)
# 39. Create a program that checks if two strings are anagrams
def are_anagrams(str1, str2):
"""Check if two strings are anagrams."""
return sorted(str1) == sorted(str2)
string1 = input("Enter first string: ") # Get first string
string2 = input("Enter second string: ") # Get second string
if are_anagrams(string1, string2):
print(f"{string1} and {string2} are anagrams.")
else:
print(f"{string1} and {string2} are not anagrams.")
# 40. Calculate the number of vowels in a string
sentence = input("Enter a sentence: ") # Get sentence from user
vowels = "aeiouAEIOU" # Define vowels
vowel_count = sum(1 for char in sentence if char in vowels) # Count vowels
print("Number of vowels:", vowel_count)
# 41. Find the largest and smallest number in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
largest = max(numbers) # Find largest
smallest = min(numbers) # Find smallest
print("Largest number is:", largest)
print("Smallest number is:", smallest)
# 42. Create a program that finds the GCD of two numbers
def gcd(a, b):
"""Calculate the greatest common divisor (GCD) using Euclidean algorithm."""
while b:
a, b = b, a % b
return a
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second number
print("GCD of", num1, "and", num2, "is:", gcd(num1, num2))
# 43. Check if a number is a perfect number
def is_perfect(num):
"""Check if a number is perfect."""
divisors_sum = sum(i for i in range(1, num) if num % i == 0) # Sum divisors
return divisors_sum == num
number = int(input("Enter a number: ")) # Get input
if is_perfect(number):
print(number, "is a perfect number.")
else:
print(number, "is not a perfect number.")
# 44. Count the number of prime numbers in a given range
start = int(input("Enter start of range: ")) # Get start
end = int(input("Enter end of range: ")) # Get end
prime_count = sum(1 for num in range(start, end + 1) if is_prime(num)) # Count
primes
print("Number of prime numbers between", start, "and", end, "is:", prime_count)
# 45. Create a list of unique elements from a list
input_list = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
unique_elements = list(set(input_list)) # Use set to get unique values
print("Unique elements:", unique_elements)
# 46. Check if a string contains only digits
string = input("Enter a string: ") # Get string from user
if string.isdigit():
print("The string contains only digits.")
else:
print("The string does not contain only digits.")
# 47. Create a program that removes duplicates from a list
input_list = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
no_duplicates = list(set(input_list)) # Remove duplicates
print("List without duplicates:", no_duplicates)
# 48. Create a program to find the longest word in a sentence
sentence = input("Enter a sentence: ") # Get sentence from user
words = sentence.split() # Split into words
longest_word = max(words, key=len) # Find longest word
print("The longest word is:", longest_word)
# 49. Create a program that counts down from 10 to 1
for i in range(10, 0, -1): # Loop from 10 to 1
print(i) # Print countdown
print("Blast off!")
# 50. Create a program that generates a random integer
import random
random_number = random.randint(1, 100) # Generate random integer between 1 and 100
print("Random number between 1 and 100 is:", random_number)
# 51. Create a program that finds the second largest number in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
unique_numbers = list(set(numbers)) # Remove duplicates
unique_numbers.sort() # Sort the list
if len(unique_numbers) >= 2: # Check if there are at least two unique numbers
second_largest = unique_numbers[-2] # Get second largest
print("Second largest number is:", second_largest)
else:
print("Not enough unique numbers to find the second largest.")
# 52. Create a program that checks if a string is a palindrome
def is_palindrome(s):
"""Check if the string is a palindrome."""
return s == s[::-1]
input_string = input("Enter a string: ") # Get string from user
if is_palindrome(input_string):
print(input_string, "is a palindrome.")
else:
print(input_string, "is not a palindrome.")
# 53. Find the sum of odd numbers in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
odd_sum = sum(num for num in numbers if num % 2 != 0) # Sum odd numbers
print("Sum of odd numbers:", odd_sum)
# 54. Create a program that converts a string to uppercase
input_string = input("Enter a string: ") # Get string from user
uppercase_string = input_string.upper() # Convert to uppercase
print("Uppercase string:", uppercase_string)
# 55. Create a program that finds the smallest number in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
smallest_number = min(numbers) # Find smallest number
print("Smallest number is:", smallest_number)
# 56. Create a program that counts the number of consonants in a string
sentence = input("Enter a sentence: ") # Get sentence from user
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" # Define consonants
consonant_count = sum(1 for char in sentence if char in consonants) # Count
consonants
print("Number of consonants:", consonant_count)
# 57. Create a program that checks if a string is an anagram of another string
def are_anagrams(str1, str2):
"""Check if two strings are anagrams."""
return sorted(str1) == sorted(str2)
string1 = input("Enter first string: ") # Get first string
string2 = input("Enter second string: ") # Get second string
if are_anagrams(string1, string2):
print(f"{string1} and {string2} are anagrams.")
else:
print(f"{string1} and {string2} are not anagrams.")
# 58. Create a program that counts the number of words in a sentence
sentence = input("Enter a sentence: ") # Get sentence from user
word_count = len(sentence.split()) # Split into words and count
print("Number of words:", word_count)
# 59. Create a program that finds the LCM of two numbers
def lcm(a, b):
"""Calculate the least common multiple (LCM)."""
multiple = max(a, b)
while True:
if multiple % a == 0 and multiple % b == 0:
return multiple
multiple += 1
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second number
print("LCM of", num1, "and", num2, "is:", lcm(num1, num2))
# 60. Create a program that calculates the square root of a number
import math
number = float(input("Enter a number: ")) # Get number from user
sqrt_value = math.sqrt(number) # Calculate square root
print("Square root of", number, "is:", sqrt_value)
# 61. Create a program that generates a random float between 0 and 1
random_float = random.random() # Generate random float
print("Random float between 0 and 1 is:", random_float)
# 62. Create a program that checks if a string is a valid email address
import re
email = input("Enter an email address: ") # Get email from user
if re.match(r"[^@]+@[^@]+\.[^@]+", email):
print("Valid email address.")
else:
print("Invalid email address.")
# 63. Create a program that reverses the words in a sentence
sentence = input("Enter a sentence: ") # Get sentence from user
reversed_sentence = ' '.join(sentence.split()[::-1]) # Reverse words
print("Reversed sentence:", reversed_sentence)
# 64. Create a program that finds the intersection of two sets
set1 = set(map(int, input("Enter first set of numbers separated by space:
").split())) # Get first set
set2 = set(map(int, input("Enter second set of numbers separated by space:
").split())) # Get second set
intersection = set1.intersection(set2) # Find intersection
print("Intersection of the two sets:", intersection)
# 65. Create a program that generates a random color
random_color = "#{:06x}".format(random.randint(0, 0xFFFFFF)) # Generate random hex
color
print("Random color:", random_color)
# 66. Create a program that finds the sum of all the elements in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
total_sum = sum(numbers) # Calculate sum
print("Sum of all elements:", total_sum)
# 67. Create a program that counts the number of uppercase letters in a string
string = input("Enter a string: ") # Get string from user
uppercase_count = sum(1 for char in string if char.isupper()) # Count uppercase
print("Number of uppercase letters:", uppercase_count)
# 68. Create a program that calculates the cube of a number
number = float(input("Enter a number: ")) # Get number from user
cube = number ** 3 # Calculate cube
print("Cube of", number, "is:", cube)
# 69. Create a program that generates a random password
import string
length = int(input("Enter password length: ")) # Get desired length
characters = string.ascii_letters + string.digits + string.punctuation # Possible
characters
password = ''.join(random.choice(characters) for _ in range(length)) # Generate
password
print("Random password:", password)
# 70. Create a program that finds the common elements in two lists
list1 = list(map(int, input("Enter first list of numbers separated by space:
").split())) # Get first list
list2 = list(map(int, input("Enter second list of numbers separated by space:
").split())) # Get second list
common_elements = list(set(list1) & set(list2)) # Find common elements
print("Common elements:", common_elements)
# 71. Create a program that checks if a string is a valid URL
url = input("Enter a URL: ") # Get URL from user
if re.match(r"https?://[^\s]+", url):
print("Valid URL.")
else:
print("Invalid URL.")
# 72. Create a program that finds the first non-repeated character in a string
def first_non_repeated_character(s):
"""Find the first non-repeated character."""
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1 # Count occurrences
for char in s:
if char_count[char] == 1:
return char
return None
input_string = input("Enter a string: ") # Get string from user
non_repeated = first_non_repeated_character(input_string) # Find non-repeated
character
if non_repeated:
print("First non-repeated character is:", non_repeated)
else:
print("No non-repeated character found.")
# 73. Create a program that converts a decimal number to binary
decimal = int(input("Enter a decimal number: ")) # Get decimal input
binary = bin(decimal)[2:] # Convert to binary and remove '0b' prefix
print("Binary equivalent:", binary)
# 74. Create a program that finds the most frequent element in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
most_frequent = max(set(numbers), key=numbers.count) # Find most frequent element
print("Most frequent element is:", most_frequent)
# 75. Create a program that checks if a string contains only alphabetic characters
string = input("Enter a string: ") # Get string from user
if string.isalpha():
print("The string contains only alphabetic characters.")
else:
print("The string does not contain only alphabetic characters.")
# 76. Create a program that finds the sum of squares of a list of numbers
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
sum_of_squares = sum(num ** 2 for num in numbers) # Calculate sum of squares
print("Sum of squares:", sum_of_squares)
# 77. Create a program that converts a string to lowercase
input_string = input("Enter a string: ") # Get string from user
lowercase_string = input_string.lower() # Convert to lowercase
print("Lowercase string:", lowercase_string)
# 78. Create a program that counts the number of spaces in a string
string = input("Enter a string: ") # Get string from user
space_count = string.count(' ') # Count spaces
print("Number of spaces:", space_count)
# 79. Create a program that finds the longest word in a list of words
words = input("Enter words separated by space: ").split() # Get list of words
longest_word = max(words, key=len) # Find longest word
print("The longest word is:", longest_word)
# 80. Create a program that checks if a number is a palindrome
def is_palindrome_number(num):
"""Check if a number is a palindrome."""
return str(num) == str(num)[::-1]
number = int(input("Enter a number: ")) # Get number from user
if is_palindrome_number(number):
print(number, "is a palindrome.")
else:
print(number, "is not a palindrome.")
# 81. Create a program that calculates the average of numbers in a list
numbers = list(map(float, input("Enter numbers separated by space: ").split())) #
Get list
average = sum(numbers) / len(numbers) if numbers else 0 # Calculate average
print("Average of the numbers:", average)
# 82. Create a program that generates a list of random numbers
count = int(input("How many random numbers do you want to generate? ")) # Get
count
random_numbers = [random.randint(1, 100) for _ in range(count)] # Generate random
numbers
print("Random numbers:", random_numbers)
# 83. Create a program that checks if a string starts with a specific substring
string = input("Enter a string: ") # Get string from user
substring = input("Enter substring to check: ") # Get substring
if string.startswith(substring):
print(f"The string starts with '{substring}'.")
else:
print(f"The string does not start with '{substring}'.")
# 84. Create a program that counts the number of unique characters in a string
string = input("Enter a string: ") # Get string from user
unique_char_count = len(set(string)) # Count unique characters
print("Number of unique characters:", unique_char_count)
# 85. Create a program that finds the index of the first occurrence of a character
in a string
string = input("Enter a string: ") # Get string from user
char = input("Enter a character to find: ") # Get character
index = string.find(char) # Find index
if index != -1:
print(f"The first occurrence of '{char}' is at index {index}.")
else:
print(f"The character '{char}' is not found in the string.")
# 86. Create a program that creates a new list containing the squares of elements
from an existing list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
squared_numbers = [num ** 2 for num in numbers] # Square each number
print("Squared numbers:", squared_numbers)
# 87. Create a program that removes all vowels from a string
string = input("Enter a string: ") # Get string from user
vowels = "aeiouAEIOU" # Define vowels
no_vowels = ''.join(char for char in string if char not in vowels) # Remove vowels
print("String without vowels:", no_vowels)
# 88. Create a program that finds the first duplicate element in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
seen = set()
duplicate = None
for num in numbers:
if num in seen:
duplicate = num
break
seen.add(num)
print("First duplicate element is:", duplicate if duplicate else "No duplicates
found.")
# 89. Create a program that checks if a string contains all letters of the alphabet
import string
input_string = input("Enter a string: ") # Get string from user
if set(string.ascii_lowercase).issubset(set(input_string.lower())): # Check for
all letters
print("The string contains all letters of the alphabet.")
else:
print("The string does not contain all letters of the alphabet.")
# 90. Create a program that generates a list of squares of the first n natural
numbers
n = int(input("Enter a number: ")) # Get n
squares = [i ** 2 for i in range(1, n + 1)] # Generate squares
print("Squares of the first", n, "natural numbers:", squares)
# 91. Create a program that checks if a number is a perfect square
import math
number = int(input("Enter a number: ")) # Get number from user
sqrt = int(math.sqrt(number)) # Calculate integer square root
if sqrt * sqrt == number:
print(number, "is a perfect square.")
else:
print(number, "is not a perfect square.")
# 92. Create a program that finds all even numbers in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
even_numbers = [num for num in numbers if num % 2 == 0] # Filter even numbers
print("Even numbers in the list:", even_numbers)
# 93. Create a program that checks if a string contains any digits
string = input("Enter a string: ") # Get string from user
if any(char.isdigit() for char in string): # Check for digits
print("The string contains digits.")
else:
print("The string does not contain digits.")
# 94. Create a program that calculates the sum of all multiples of 3 and 5 up to a
given number
limit = int(input("Enter a number: ")) # Get limit from user
total_sum = sum(num for num in range(1, limit + 1) if num % 3 == 0 or num % 5 == 0)
# Calculate sum
print("Sum of all multiples of 3 and 5 up to", limit, "is:", total_sum)
# 95. Create a program that finds the minimum value in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
minimum = min(numbers) # Find minimum
print("Minimum value in the list is:", minimum)
# 96. Create a program that checks if a string is a valid integer
string = input("Enter a string: ") # Get string from user
if string.lstrip('-').isdigit(): # Check if valid integer
print("The string is a valid integer.")
else:
print("The string is not a valid integer.")
# 97. Create a program that finds all odd numbers in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
odd_numbers = [num for num in numbers if num % 2 != 0] # Filter odd numbers
print("Odd numbers in the list:", odd_numbers)
# 98. Create a program that calculates the total price of items in a shopping list
shopping_list = input("Enter items and their prices (item:price), separated by
commas: ") # Get shopping list
items = shopping_list.split(',')
total_price = sum(float(item.split(':')[1]) for item in items) # Calculate total
price
print("Total price of items:", total_price)
# 99. Create a program that creates a dictionary from two lists
keys = input("Enter keys separated by space: ").split() # Get keys
values = input("Enter values separated by space: ").split() # Get values
dictionary = dict(zip(keys, values)) # Create dictionary
print("Created dictionary:", dictionary)
# 100. Create a program that checks if a string is a valid phone number
phone_number = input("Enter a phone number: ") # Get phone number from user
if re.match(r"^\+?[1-9]\d{1,14}$", phone_number): # Check for valid phone number
print("Valid phone number.")
else:
print("Invalid phone number.")
# 101. Create a program that generates a list of even numbers from 1 to n
n = int(input("Enter a number: ")) # Get the upper limit
even_numbers = [i for i in range(1, n + 1) if i % 2 == 0] # List comprehension to
filter even numbers
print("Even numbers from 1 to", n, ":", even_numbers)
# 102. Create a program that generates a list of odd numbers from 1 to n
odd_numbers = [i for i in range(1, n + 1) if i % 2 != 0] # List comprehension to
filter odd numbers
print("Odd numbers from 1 to", n, ":", odd_numbers)
# 103. Create a program that calculates the factorial of a number
def factorial(num):
"""Calculate the factorial of a number."""
if num == 0 or num == 1:
return 1
return num * factorial(num - 1)
number = int(input("Enter a number: ")) # Get number from user
print("Factorial of", number, "is:", factorial(number)) # Calculate and print
factorial
# 104. Create a program that reverses a string
input_string = input("Enter a string: ") # Get string from user
reversed_string = input_string[::-1] # Reverse the string using slicing
print("Reversed string:", reversed_string)
# 105. Create a program that checks if a number is prime
def is_prime(num):
"""Check if a number is prime."""
if num < 2:
return False
for i in range(2, int(num**0.5) + 1): # Check divisibility up to the square
root of num
if num % i == 0:
return False
return True
number = int(input("Enter a number: ")) # Get number from user
if is_prime(number):
print(number, "is a prime number.")
else:
print(number, "is not a prime number.")
# 106. Create a program that converts Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: ")) # Get Celsius temperature
fahrenheit = (celsius * 9/5) + 32 # Convert to Fahrenheit
print(f"{celsius}°C is equal to {fahrenheit}°F.")
# 107. Create a program that counts the number of vowels in a string
string = input("Enter a string: ") # Get string from user
vowels = "aeiouAEIOU" # Define vowels
vowel_count = sum(1 for char in string if char in vowels) # Count vowels
print("Number of vowels:", vowel_count)
# 108. Create a program that finds the maximum number in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
max_number = max(numbers) # Find maximum
print("Maximum number is:", max_number)
# 109. Create a program that generates the first n Fibonacci numbers
def fibonacci(n):
"""Generate the first n Fibonacci numbers."""
fib_sequence = [0, 1] # Start with the first two Fibonacci numbers
for i in range(2, n):
fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2]) # Add the next
number
return fib_sequence[:n]
n = int(input("Enter the number of Fibonacci numbers to generate: ")) # Get number
from user
print("First", n, "Fibonacci numbers:", fibonacci(n))
# 110. Create a program that checks if a string is a pangram
def is_pangram(s):
"""Check if a string is a pangram."""
alphabet = set('abcdefghijklmnopqrstuvwxyz') # Set of all letters in the
alphabet
return alphabet.issubset(set(s.lower())) # Check if all letters are in the
string
input_string = input("Enter a string: ") # Get string from user
if is_pangram(input_string):
print("The string is a pangram.")
else:
print("The string is not a pangram.")
# 111. Create a program that counts the number of uppercase letters in a string
string = input("Enter a string: ") # Get string from user
uppercase_count = sum(1 for char in string if char.isupper()) # Count uppercase
letters
print("Number of uppercase letters:", uppercase_count)
# 112. Create a program that finds the product of all elements in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
product = 1
for num in numbers:
product *= num # Multiply each number
print("Product of all elements:", product)
# 113. Create a program that checks if a string is a valid IPv4 address
def is_valid_ipv4(address):
"""Check if a string is a valid IPv4 address."""
parts = address.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit() or not (0 <= int(part) <= 255):
return False
return True
ip_address = input("Enter an IPv4 address: ") # Get IP address from user
if is_valid_ipv4(ip_address):
print(ip_address, "is a valid IPv4 address.")
else:
print(ip_address, "is not a valid IPv4 address.")
# 114. Create a program that converts Fahrenheit to Celsius
fahrenheit = float(input("Enter temperature in Fahrenheit: ")) # Get Fahrenheit
temperature
celsius = (fahrenheit - 32) * 5/9 # Convert to Celsius
print(f"{fahrenheit}°F is equal to {celsius}°C.")
# 115. Create a program that removes all whitespace from a string
string = input("Enter a string: ") # Get string from user
no_whitespace = ''.join(string.split()) # Remove all whitespace
print("String without whitespace:", no_whitespace)
# 116. Create a program that checks if a number is a perfect number
def is_perfect_number(num):
"""Check if a number is perfect."""
divisors = [i for i in range(1, num) if num % i == 0] # Find divisors
return sum(divisors) == num # Check if the sum equals the number
number = int(input("Enter a number: ")) # Get number from user
if is_perfect_number(number):
print(number, "is a perfect number.")
else:
print(number, "is not a perfect number.")
# 117. Create a program that finds the common elements in two lists
list1 = list(map(int, input("Enter first list of numbers separated by space:
").split())) # Get first list
list2 = list(map(int, input("Enter second list of numbers separated by space:
").split())) # Get second list
common_elements = list(set(list1) & set(list2)) # Find common elements
print("Common elements:", common_elements)
# 118. Create a program that checks if a string is a valid hexadecimal number
def is_valid_hex(s):
"""Check if a string is a valid hexadecimal number."""
return all(c in '0123456789abcdefABCDEF' for c in s) # Check for valid hex
characters
hex_string = input("Enter a hexadecimal number: ") # Get hex number from user
if is_valid_hex(hex_string):
print(hex_string, "is a valid hexadecimal number.")
else:
print(hex_string, "is not a valid hexadecimal number.")
# 119. Create a program that finds the second smallest number in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list
unique_numbers = list(set(numbers)) # Remove duplicates
unique_numbers.sort() # Sort the list
if len(unique_numbers) >= 2:
second_smallest = unique_numbers[1] # Get second smallest
print("Second smallest number is:", second_smallest)
else:
print("Not enough unique numbers to find the second smallest.")
# 120. Create a program that finds the number of words in a string
string = input("Enter a string: ") # Get string from user
word_count = len(string.split()) # Count words
print("Number of words:", word_count)
# 121. Create a program that calculates the area of a triangle
base = float(input("Enter the base of the triangle: ")) # Get base
height = float(input("Enter the height of the triangle: ")) # Get height
area = 0.5 * base * height # Calculate area
print("Area of the triangle:", area)
# 122. Create a program that checks if a number is a Narcissistic number
def is_narcissistic(num):
"""Check if a number is Narcissistic."""
digits = [int(d) for d in str(num)] # Get digits
power = len(digits) # Number of digits
return sum(d ** power for d in digits) == num # Check the condition
number = int(input("Enter a number: ")) # Get number from user
if is_narcissistic(number):
print(number, "is a Narcissistic number.")
else:
print(number, "is not a Narcissistic number.")
# 123. Create a program that finds the longest substring without repeating
characters
def longest_substring(s):
"""Find the longest substring without repeating characters."""
char_index = {}
start = longest = 0
for i, char in enumerate(s):
if char in char_index and char_index[char] >= start:
start = char_index[char] + 1
char_index[char] = i
longest = max(longest, i - start + 1)
return longest
input_string = input("Enter a string: ") # Get string from user
print("Length of longest substring without repeating characters:",
longest_substring(input_string))
# 124. Create a program that counts the number of lines in a file
filename = input("Enter the filename: ") # Get filename from user
try:
with open(filename, 'r') as file: # Open file for reading
line_count = sum(1 for line in file) # Count lines
print("Number of lines in the file:", line_count)
except FileNotFoundError:
print("File not found.")
# 125. Create a program that finds the square root of a number
import math
number = float(input("Enter a number: ")) # Get number from user
square_root = math.sqrt(number) # Calculate square root
print("Square root of", number, "is:", square_root)
# 126. Create a program that converts a string to a list of characters
string = input("Enter a string: ") # Get string from user
char_list = list(string) # Convert to list of characters
print("List of characters:", char_list)
# 127. Create a program that finds the largest prime factor of a number
def largest_prime_factor(n):
"""Find the largest prime factor of a number."""
prime_factor = None
for i in range(2, int(n**0.5) + 1):
while n % i == 0:
prime_factor = i
n //= i
return prime_factor if n > 1 else prime_factor
number = int(input("Enter a number: ")) # Get number from user
print("Largest prime factor of", number, "is:", largest_prime_factor(number))
# 128. Create a program that checks if two strings are anagrams
def are_anagrams(s1, s2):
"""Check if two strings are anagrams."""
return sorted(s1) == sorted(s2) # Check if sorted characters are the same
string1 = input("Enter first string: ") # Get first string
string2 = input("Enter second string: ") # Get second string
if are_anagrams(string1, string2):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
# 129. Create a program that counts the number of digits in a string
string = input("Enter a string: ") # Get string from user
digit_count = sum(1 for char in string if char.isdigit()) # Count digits
print("Number of digits:", digit_count)
# 130. Create a program that creates a list of squares of even numbers from 1 to n
even_squares = [i**2 for i in range(1, n + 1) if i % 2 == 0] # List comprehension
for even squares
print("Squares of even numbers from 1 to", n, ":", even_squares)
# 131. Create a program that finds the number of occurrences of a substring in a
string
string = input("Enter a string: ") # Get string from user
substring = input("Enter a substring to count: ") # Get substring
occurrences = string.count(substring) # Count occurrences
print(f"The substring '{substring}' occurs {occurrences} times.")
# 132. Create a program that creates a multiplication table for a number
number = int(input("Enter a number for multiplication table: ")) # Get number from
user
for i in range(1, 11):
print(f"{number} x {i} = {number * i}") # Print multiplication table
# 133. Create a program that checks if a string is a valid email address
import re
def is_valid_email(email):
"""Check if a string is a valid email address."""
regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' # Regex for email
validation
return re.match(regex, email) is not None
email = input("Enter an email address: ") # Get email from user
if is_valid_email(email):
print(email, "is a valid email address.")
else:
print(email, "is not a valid email address.")
# 134. Create a program that finds the intersection of two lists
list1 = list(map(int, input("Enter first list of numbers separated by space:
").split())) # Get first list
list2 = list(map(int, input("Enter second list of numbers separated by space:
").split())) # Get second list
intersection = list(set(list1) & set(list2)) # Find intersection
print("Intersection of the two lists:", intersection)
# 135. Create a program that checks if a string is a valid URL
def is_valid_url(url):
"""Check if a string is a valid URL."""
regex = r'^(http|https)://[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,})+' # Regex for URL
validation
return re.match(regex, url) is not None
url = input("Enter a URL: ") # Get URL from user
if is_valid_url(url):
print(url, "is a valid URL.")
else:
print(url, "is not a valid URL.")
# 136. Create a program that counts the frequency of characters in a string
string = input("Enter a string: ") # Get string from user
frequency = {char: string.count(char) for char in set(string)} # Count frequency
of each character
print("Character frequency:", frequency)
# 137. Create a program that generates a random password
import random
import string
length = int(input("Enter desired password length: ")) # Get password length
characters = string.ascii_letters + string.digits + string.punctuation # Define
character set
password = ''.join(random.choice(characters) for _ in range(length)) # Generate
password
print("Generated password:", password)
# 138. Create a program that finds the most common word in a text
text = input("Enter some text: ") # Get text from user
words = text.split() # Split text into words
most_common_word = max(set(words), key=words.count) # Find most common word
print("Most common word is:", most_common_word)
# 139. Create a program that checks if a string contains only digits
string = input("Enter a string: ") # Get string from user
if string.isdigit(): # Check if string is all digits
print("The string contains only digits.")
else:
print("The string does not contain only digits.")
# 140. Create a program that finds the frequency of words in a text
text = input("Enter some text: ") # Get text from user
word_frequency = {word: text.split().count(word) for word in set(text.split())} #
Count frequency of words
print("Word frequency:", word_frequency)
# 141. Create a program that counts the number of sentences in a text
text = input("Enter some text: ") # Get text from user
sentence_count = text.count('.') + text.count('!') + text.count('?') # Count
sentences
print("Number of sentences:", sentence_count)
# 142. Create a program that generates a list of cubes of the first n natural
numbers
n = int(input("Enter a number: ")) # Get n
cubes = [i ** 3 for i in range(1, n + 1)] # Generate cubes
print("Cubes of the first", n, "natural numbers:", cubes)
# 143. Create a program that finds the sum of digits of a number
number = int(input("Enter a number: ")) # Get number from user
sum_of_digits = sum(int(digit) for digit in str(number)) # Calculate sum of digits
print("Sum of digits:", sum_of_digits)
# 144. Create a program that checks if a number is an Armstrong number
def is_armstrong(num):
"""Check if a number is an Armstrong number."""
digits = [int(d) for d in str(num)] # Get digits
power = len(digits) # Number of digits
return sum(d ** power for d in digits) == num # Check the condition
number = int(input("Enter a number: ")) # Get number from user
if is_armstrong(number):
print(number, "is an Armstrong number.")
else:
print(number, "is not an Armstrong number.")
# 145. Create a program that converts a binary number to decimal
binary = input("Enter a binary number: ") # Get binary number from user
decimal = int(binary, 2) # Convert to decimal
print("Decimal equivalent:", decimal)
# 146. Create a program that calculates the distance between two points
import math
x1, y1 = map(float, input("Enter coordinates of first point (x1 y1): ").split()) #
Get first point
x2, y2 = map(float, input("Enter coordinates of second point (x2 y2): ").split())
# Get second point
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) # Calculate distance
print("Distance between the points:", distance)
# 147. Create a program that removes duplicate elements from a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
unique_numbers = list(set(numbers)) # Remove duplicates
print("List without duplicates:", unique_numbers)
# 148. Create a program that finds the average of numbers in a list
numbers = list(map(float, input("Enter numbers separated by space: ").split())) #
Get list of numbers
average = sum(numbers) / len(numbers) # Calculate average
print("Average of the numbers:", average)
# 149. Create a program that sorts a list in ascending order
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
numbers.sort() # Sort the list
print("Sorted list in ascending order:", numbers)
# 150. Create a program that creates a histogram from a list of numbers
import matplotlib.pyplot as plt
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
plt.hist(numbers, bins=10) # Create histogram
plt.title("Histogram of Numbers")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
# 151. Create a program that finds the mode of a list of numbers
from collections import Counter
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
mode_data = Counter(numbers) # Count occurrences
mode = mode_data.most_common(1)[0][0] # Get the most common number
print("Mode of the numbers:", mode)
# 152. Create a program that calculates the GCD of two numbers
def gcd(a, b):
"""Calculate the GCD of two numbers."""
while b:
a, b = b, a % b
return a
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second number
print("GCD of", num1, "and", num2, "is:", gcd(num1, num2))
# 153. Create a program that calculates the LCM of two numbers
def lcm(a, b):
"""Calculate the LCM of two numbers."""
return abs(a * b) // gcd(a, b)
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second number
print("LCM of", num1, "and", num2, "is:", lcm(num1, num2))
# 154. Create a program that checks if a number is a palindrome
def is_palindrome(num):
"""Check if a number is a palindrome."""
return str(num) == str(num)[::-1] # Check if number reads the same backward
number = int(input("Enter a number: ")) # Get number from user
if is_palindrome(number):
print(number, "is a palindrome.")
else:
print(number, "is not a palindrome.")
# 155. Create a program that finds the unique elements of a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
unique_numbers = list(set(numbers)) # Find unique elements
print("Unique elements:", unique_numbers)
# 156. Create a program that checks if a string contains only letters
string = input("Enter a string: ") # Get string from user
if string.isalpha(): # Check if all characters are letters
print("The string contains only letters.")
else:
print("The string does not contain only letters.")
# 157. Create a program that calculates the sum of even numbers from 1 to n
n = int(input("Enter a number: ")) # Get n
sum_even = sum(i for i in range(1, n + 1) if i % 2 == 0) # Calculate sum of even
numbers
print("Sum of even numbers from 1 to", n, "is:", sum_even)
# 158. Create a program that calculates the sum of odd numbers from 1 to n
sum_odd = sum(i for i in range(1, n + 1) if i % 2 != 0) # Calculate sum of odd
numbers
print("Sum of odd numbers from 1 to", n, "is:", sum_odd)
# 159. Create a program that finds the first n prime numbers
def first_n_primes(n):
"""Find the first n prime numbers."""
primes = []
num = 2
while len(primes) < n:
if is_prime(num): # Check if num is prime
primes.append(num)
num += 1
return primes
n = int(input("Enter the number of prime numbers to find: ")) # Get n
print("First", n, "prime numbers:", first_n_primes(n))
# 160. Create a program that converts a decimal number to binary
decimal = int(input("Enter a decimal number: ")) # Get decimal number from user
binary = bin(decimal)[2:] # Convert to binary
print("Binary equivalent:", binary)
# 161. Create a program that converts a decimal number to hexadecimal
hexadecimal = hex(decimal)[2:] # Convert to hexadecimal
print("Hexadecimal equivalent:", hexadecimal)
# 162. Create a program that creates a set from a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
unique_set = set(numbers) # Create a set from the list
print("Set from the list:", unique_set)
# 163. Create a program that calculates the area of a rectangle
length = float(input("Enter the length of the rectangle: ")) # Get length
width = float(input("Enter the width of the rectangle: ")) # Get width
area = length * width # Calculate area
print("Area of the rectangle:", area)
# 164. Create a program that finds the smallest prime number greater than n
def next_prime(n):
"""Find the smallest prime number greater than n."""
num = n + 1
while not is_prime(num): # Keep checking until a prime number is found
num += 1
return num
n = int(input("Enter a number: ")) # Get number from user
print("Smallest prime number greater than", n, "is:", next_prime(n))
# 165. Create a program that calculates the square of a number
number = float(input("Enter a number: ")) # Get number from user
square = number ** 2 # Calculate square
print("Square of", number, "is:", square)
# 166. Create a program that finds the number of unique words in a text
text = input("Enter some text: ") # Get text from user
unique_words = set(text.split()) # Get unique words
print("Number of unique words:", len(unique_words))
# 167. Create a program that counts the number of paragraphs in a text
text = input("Enter some text: ") # Get text from user
paragraph_count = text.count('\n') + 1 # Count paragraphs
print("Number of paragraphs:", paragraph_count)
# 168. Create a program that creates a list of even indexed elements from a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
even_indexed_elements = numbers[::2] # Get elements at even indices
print("Even indexed elements:", even_indexed_elements)
# 169. Create a program that finds the longest word in a string
text = input("Enter some text: ") # Get text from user
longest_word = max(text.split(), key=len) # Find longest word
print("Longest word:", longest_word)
# 170. Create a program that checks if a string is a valid palindrome (ignoring
spaces and punctuation)
def is_valid_palindrome(s):
"""Check if a string is a valid palindrome."""
cleaned = ''.join(c for c in s if c.isalnum()).lower() # Remove non-
alphanumeric characters and convert to lowercase
return cleaned == cleaned[::-1] # Check if the cleaned string is a palindrome
input_string = input("Enter a string: ") # Get string from user
if is_valid_palindrome(input_string):
print("The string is a valid palindrome.")
else:
print("The string is not a valid palindrome.")
# 171. Create a program that generates a list of Fibonacci numbers up to n
def fibonacci_up_to(n):
"""Generate Fibonacci numbers up to n."""
fib_sequence = [0, 1]
while fib_sequence[-1] < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2]) # Add next
Fibonacci number
return fib_sequence[:-1] if fib_sequence[-1] >= n else fib_sequence # Return
numbers up to n
n = int(input("Enter a number: ")) # Get n
print("Fibonacci numbers up to", n, ":", fibonacci_up_to(n))
# 172. Create a program that finds the product of a list of numbers
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
product = 1
for number in numbers: # Calculate product
product *= number
print("Product of the numbers:", product)
# 173. Create a program that finds the maximum value in a list
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
max_value = max(numbers) # Find maximum value
print("Maximum value in the list:", max_value)
# 174. Create a program that finds the minimum value in a list
min_value = min(numbers) # Find minimum value
print("Minimum value in the list:", min_value)
# 175. Create a program that finds the common elements of three lists
list1 = list(map(int, input("Enter first list of numbers separated by space:
").split())) # Get first list
list2 = list(map(int, input("Enter second list of numbers separated by space:
").split())) # Get second list
list3 = list(map(int, input("Enter third list of numbers separated by space:
").split())) # Get third list
common_elements = list(set(list1) & set(list2) & set(list3)) # Find common
elements
print("Common elements of the three lists:", common_elements)
# 176. Create a program that finds the longest palindrome in a string
def longest_palindrome(s):
"""Find the longest palindrome in a string."""
longest = ""
for i in range(len(s)):
for j in range(i, len(s)):
substring = s[i:j + 1] # Get substring
if substring == substring[::-1] and len(substring) > len(longest):
longest = substring # Update longest palindrome
return longest
input_string = input("Enter a string: ") # Get string from user
print("Longest palindrome in the string:", longest_palindrome(input_string))
# 177. Create a program that converts a list to a string
elements = input("Enter elements separated by space: ") # Get elements from user
element_list = elements.split() # Convert to list
result_string = ' '.join(element_list) # Convert to string
print("Converted string:", result_string)
# 178. Create a program that checks if a number is a perfect square
def is_perfect_square(n):
"""Check if a number is a perfect square."""
return int(n**0.5)**2 == n # Check if the square root is an integer
number = int(input("Enter a number: ")) # Get number from user
if is_perfect_square(number):
print(number, "is a perfect square.")
else:
print(number, "is not a perfect square.")
# 179. Create a program that finds the sum of prime numbers in a list
def is_prime(num):
"""Check if a number is prime."""
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
prime_sum = sum(num for num in numbers if is_prime(num)) # Calculate sum of primes
print("Sum of prime numbers in the list:", prime_sum)
# 180. Create a program that checks if a string is a valid IPv4 address
def is_valid_ipv4(ip):
"""Check if a string is a valid IPv4 address."""
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit() or not 0 <= int(part) <= 255:
return False
return True
ip_address = input("Enter an IPv4 address: ") # Get IP address from user
if is_valid_ipv4(ip_address):
print(ip_address, "is a valid IPv4 address.")
else:
print(ip_address, "is not a valid IPv4 address.")
# 181. Create a program that generates a random number between a given range
import random
start = int(input("Enter start of range: ")) # Get start of range
end = int(input("Enter end of range: ")) # Get end of range
random_number = random.randint(start, end) # Generate random number
print("Random number between", start, "and", end, "is:", random_number)
# 182. Create a program that checks if a string is a valid hexadecimal number
def is_valid_hex(hex_string):
"""Check if a string is a valid hexadecimal number."""
regex = r'^[0-9A-Fa-f]+$' # Regex for hexadecimal validation
return re.match(regex, hex_string) is not None
hexadecimal_string = input("Enter a hexadecimal number: ") # Get hexadecimal
number from user
if is_valid_hex(hexadecimal_string):
print(hexadecimal_string, "is a valid hexadecimal number.")
else:
print(hexadecimal_string, "is not a valid hexadecimal number.")
# 183. Create a program that calculates the area of a circle
def area_of_circle(radius):
"""Calculate the area of a circle."""
return math.pi * radius ** 2 # Area formula
radius = float(input("Enter the radius of the circle: ")) # Get radius
print("Area of the circle:", area_of_circle(radius))
# 184. Create a program that checks if a number is an Armstrong number (for n
digits)
def is_armstrong_n_digits(num):
"""Check if a number is an Armstrong number for n digits."""
digits = [int(d) for d in str(num)] # Get digits
power = len(digits) # Number of digits
return sum(d ** power for d in digits) == num # Check the condition
number = int(input("Enter a number: ")) # Get number from user
if is_armstrong_n_digits(number):
print(number, "is an Armstrong number.")
else:
print(number, "is not an Armstrong number.")
# 185. Create a program that finds the longest consecutive sequence of numbers in a
list
def longest_consecutive_sequence(numbers):
"""Find the longest consecutive sequence of numbers in a list."""
if not numbers:
return 0
num_set = set(numbers) # Create a set for O(1) lookups
longest = 0
for num in numbers:
if num - 1 not in num_set: # Check if num is the start of a sequence
current_num = num
current_streak = 1
while current_num + 1 in num_set: # Count consecutive numbers
current_num += 1
current_streak += 1
longest = max(longest, current_streak) # Update longest streak
return longest
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
print("Longest consecutive sequence length:",
longest_consecutive_sequence(numbers))
# 186. Create a program that checks if two strings are rotations of each other
def are_rotations(s1, s2):
"""Check if two strings are rotations of each other."""
if len(s1) != len(s2): # Check if lengths are different
return False
return s1 in s2 + s2 # Check if s1 is in concatenated s2
string1 = input("Enter first string: ") # Get first string
string2 = input("Enter second string: ") # Get second string
if are_rotations(string1, string2):
print("The strings are rotations of each other.")
else:
print("The strings are not rotations of each other.")
# 187. Create a program that finds the maximum product of two numbers in a list
def max_product(numbers):
"""Find the maximum product of two numbers in a list."""
max_product = float('-inf') # Initialize to negative infinity
n = len(numbers)
for i in range(n):
for j in range(i + 1, n):
product = numbers[i] * numbers[j]
max_product = max(max_product, product) # Update max product
return max_product
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
print("Maximum product of two numbers:", max_product(numbers))
# 188. Create a program that finds the second largest number in a list
def second_largest(numbers):
"""Find the second largest number in a list."""
first = second = float('-inf') # Initialize to negative infinity
for num in numbers:
if num > first: # Update first and second
second = first
first = num
elif first > num > second:
second = num
return second
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
print("Second largest number:", second_largest(numbers))
# 189. Create a program that checks if a number is a perfect number
def is_perfect_number(n):
"""Check if a number is a perfect number."""
divisors_sum = sum(i for i in range(1, n) if n % i == 0) # Sum of proper
divisors
return divisors_sum == n # Check if equal to the number
number = int(input("Enter a number: ")) # Get number from user
if is_perfect_number(number):
print(number, "is a perfect number.")
else:
print(number, "is not a perfect number.")
# 190. Create a program that finds all pairs of numbers that sum up to a target
def find_pairs_with_sum(numbers, target):
"""Find all pairs of numbers that sum up to a target."""
pairs = []
seen = set()
for num in numbers:
complement = target - num
if complement in seen: # Check if complement is in seen set
pairs.append((num, complement))
seen.add(num) # Add current number to seen
return pairs
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
target_sum = int(input("Enter the target sum: ")) # Get target sum
print("Pairs that sum up to", target_sum, ":", find_pairs_with_sum(numbers,
target_sum))
# 191. Create a program that generates a multiplication table up to n
n = int(input("Enter a number: ")) # Get number from user
print("Multiplication table up to", n, ":")
for i in range(1, n + 1):
for j in range(1, 11):
print(f"{i} x {j} = {i * j}") # Print multiplication result
# 192. Create a program that checks if a string is a valid anagram of another
string
def are_anagrams(s1, s2):
"""Check if two strings are anagrams of each other."""
return sorted(s1) == sorted(s2) # Compare sorted characters
string1 = input("Enter first string: ") # Get first string
string2 = input("Enter second string: ") # Get second string
if are_anagrams(string1, string2):
print("The strings are anagrams of each other.")
else:
print("The strings are not anagrams of each other.")
# 193. Create a program that finds the first non-repeating character in a string
def first_non_repeating_char(s):
"""Find the first non-repeating character in a string."""
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1 # Count occurrences
for char in s:
if char_count[char] == 1: # Find first non-repeating
return char
return None
input_string = input("Enter a string: ") # Get string from user
result = first_non_repeating_char(input_string)
if result:
print("First non-repeating character:", result)
else:
print("No non-repeating character found.")
# 194. Create a program that calculates the sum of digits of a number
def sum_of_digits(n):
"""Calculate the sum of digits of a number."""
return sum(int(d) for d in str(n)) # Sum digits
number = int(input("Enter a number: ")) # Get number from user
print("Sum of digits of", number, "is:", sum_of_digits(number))
# 195. Create a program that finds the median of a list of numbers
def median(numbers):
"""Find the median of a list of numbers."""
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
mid = n // 2
if n % 2 == 0:
return (sorted_numbers[mid - 1] + sorted_numbers[mid]) / 2 # Average of
two middle values
return sorted_numbers[mid] # Middle value
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list of numbers
print("Median of the numbers:", median(numbers))
# 196. Create a program that counts the frequency of each character in a string
def char_frequency(s):
"""Count the frequency of each character in a string."""
frequency = {}
for char in s:
frequency[char] = frequency.get(char, 0) + 1 # Count occurrences
return frequency
input_string = input("Enter a string: ") # Get string from user
frequency = char_frequency(input_string)
print("Character frequency:", frequency)
# 197. Create a program that checks if a string is a valid palindrome considering
case sensitivity
def is_case_sensitive_palindrome(s):
"""Check if a string is a valid palindrome considering case sensitivity."""
return s == s[::-1] # Check if the string reads the same backward
input_string = input("Enter a string: ") # Get string from user
if is_case_sensitive_palindrome(input_string):
print("The string is a valid case-sensitive palindrome.")
else:
print("The string is not a valid case-sensitive palindrome.")
# 198. Create a program that removes all vowels from a string
def remove_vowels(s):
"""Remove all vowels from a string."""
vowels = 'aeiouAEIOU'
return ''.join(char for char in s if char not in vowels) # Join characters
excluding vowels
input_string = input("Enter a string: ") # Get string from user
print("String without vowels:", remove_vowels(input_string))
# 199. Create a program that finds the square root of a number
import math
number = float(input("Enter a number: ")) # Get number from user
print("Square root of", number, "is:", math.sqrt(number)) # Calculate and print
square root
# 200. Create a program that checks if a number is an automorphic number
def is_automorphic(n):
"""Check if a number is an automorphic number."""
square = n ** 2
return str(square).endswith(str(n)) # Check if square ends with the number
number = int(input("Enter a number: ")) # Get number from user
if is_automorphic(number):
print(number, "is an automorphic number.")
else:
print(number, "is not an automorphic number.")
# 201. Create a program that calculates the factorial of a number
def factorial(n):
"""Calculate the factorial of a number."""
if n == 0: # Base case
return 1
return n * factorial(n - 1) # Recursive call
number = int(input("Enter a number: ")) # Get number from user
print("Factorial of", number, "is:", factorial(number))
# 202. Create a program that checks if a string is a valid URL
import re
def is_valid_url(url):
"""Check if a string is a valid URL."""
regex = r'^(https?://)?(www\.)?([a-z0-9]+(\.[a-z]{2,})+)(:[0-9]{1,5})?(/.*)?$'
return re.match(regex, url) is not None # Check against regex
url = input("Enter a URL: ") # Get URL from user
if is_valid_url(url):
print(url, "is a valid URL.")
else:
print(url, "is not a valid URL.")
# 203. Create a program that finds the GCD of two numbers
def gcd(a, b):
"""Find the greatest common divisor of two numbers."""
while b: # Until b becomes zero
a, b = b, a % b # Swap a and b, b becomes the remainder
return a
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second number
print("GCD of", num1, "and", num2, "is:", gcd(num1, num2))
# 204. Create a program that checks if a string is a valid email address
def is_valid_email(email):
"""Check if a string is a valid email address."""
regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(regex, email) is not None # Check against regex
email = input("Enter an email address: ") # Get email from user
if is_valid_email(email):
print(email, "is a valid email address.")
else:
print(email, "is not a valid email address.")
# 205. Create a program that reverses a string
input_string = input("Enter a string: ") # Get string from user
reversed_string = input_string[::-1] # Reverse the string using slicing
print("Reversed string:", reversed_string)
# 206. Create a program that finds all unique elements in a list
def unique_elements(lst):
"""Find all unique elements in a list."""
return list(set(lst)) # Convert to set to remove duplicates, then back to list
elements = list(map(int, input("Enter elements separated by space: ").split())) #
Get list from user
print("Unique elements:", unique_elements(elements))
# 207. Create a program that merges two dictionaries
dict1 = {'a': 1, 'b': 2} # First dictionary
dict2 = {'b': 3, 'c': 4} # Second dictionary
merged_dict = {**dict1, **dict2} # Merge dictionaries
print("Merged dictionary:", merged_dict)
# 208. Create a program that calculates the area of a triangle
def area_of_triangle(base, height):
"""Calculate the area of a triangle."""
return 0.5 * base * height # Area formula
base = float(input("Enter the base of the triangle: ")) # Get base from user
height = float(input("Enter the height of the triangle: ")) # Get height from user
print("Area of the triangle:", area_of_triangle(base, height))
# 209. Create a program that finds the length of the longest word in a sentence
def longest_word_length(sentence):
"""Find the length of the longest word in a sentence."""
words = sentence.split() # Split sentence into words
return max(len(word) for word in words) # Return the length of the longest
word
sentence = input("Enter a sentence: ") # Get sentence from user
print("Length of the longest word:", longest_word_length(sentence))
# 210. Create a program that counts the number of vowels in a string
def count_vowels(s):
"""Count the number of vowels in a string."""
vowels = 'aeiouAEIOU'
return sum(1 for char in s if char in vowels) # Count vowels
input_string = input("Enter a string: ") # Get string from user
print("Number of vowels in the string:", count_vowels(input_string))
# 211. Create a program that checks if a number is an even number
def is_even(n):
"""Check if a number is even."""
return n % 2 == 0 # Return True if even, False otherwise
number = int(input("Enter a number: ")) # Get number from user
if is_even(number):
print(number, "is an even number.")
else:
print(number, "is an odd number.")
# 212. Create a program that finds the square of a number
number = float(input("Enter a number: ")) # Get number from user
print("Square of", number, "is:", number ** 2) # Calculate and print square
# 213. Create a program that finds the cube of a number
print("Cube of", number, "is:", number ** 3) # Calculate and print cube
# 214. Create a program that finds the number of digits in a number
def count_digits(n):
"""Count the number of digits in a number."""
return len(str(abs(n))) # Convert number to string and count digits
number = int(input("Enter a number: ")) # Get number from user
print("Number of digits in", number, "is:", count_digits(number))
# 215. Create a program that calculates the sum of squares of a list of numbers
def sum_of_squares(numbers):
"""Calculate the sum of squares of a list of numbers."""
return sum(x ** 2 for x in numbers) # Sum of squares
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list from user
print("Sum of squares:", sum_of_squares(numbers))
# 216. Create a program that checks if a number is a prime number
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False # 0 and 1 are not prime
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False # Found a divisor, not prime
return True # No divisors found, prime
number = int(input("Enter a number: ")) # Get number from user
if is_prime(number):
print(number, "is a prime number.")
else:
print(number, "is not a prime number.")
# 217. Create a program that calculates the perimeter of a rectangle
def perimeter_of_rectangle(length, width):
"""Calculate the perimeter of a rectangle."""
return 2 * (length + width) # Perimeter formula
length = float(input("Enter the length of the rectangle: ")) # Get length
width = float(input("Enter the width of the rectangle: ")) # Get width
print("Perimeter of the rectangle:", perimeter_of_rectangle(length, width))
# 218. Create a program that calculates the average of a list of numbers
def average(numbers):
"""Calculate the average of a list of numbers."""
return sum(numbers) / len(numbers) if numbers else 0 # Average formula
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list from user
print("Average of the numbers:", average(numbers))
# 219. Create a program that removes duplicates from a list
def remove_duplicates(lst):
"""Remove duplicates from a list."""
return list(set(lst)) # Convert to set to remove duplicates, then back to list
elements = list(map(int, input("Enter elements separated by space: ").split())) #
Get list from user
print("List without duplicates:", remove_duplicates(elements))
# 220. Create a program that converts a string to uppercase
input_string = input("Enter a string: ") # Get string from user
print("Uppercase string:", input_string.upper()) # Convert to uppercase
# 221. Create a program that converts a string to lowercase
print("Lowercase string:", input_string.lower()) # Convert to lowercase
# 222. Create a program that checks if a number is a narcissistic number
def is_narcissistic(num):
"""Check if a number is a narcissistic number."""
digits = [int(d) for d in str(num)] # Get digits
power = len(digits) # Number of digits
return sum(d ** power for d in digits) == num # Check the condition
number = int(input("Enter a number: ")) # Get number from user
if is_narcissistic(number):
print(number, "is a narcissistic number.")
else:
print(number, "is not a narcissistic number.")
# 223. Create a program that finds the LCM of two numbers
def lcm(a, b):
"""Find the least common multiple of two numbers."""
return abs(a * b) // gcd(a, b) # Using GCD to find LCM
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second number
print("LCM of", num1, "and", num2, "is:", lcm(num1, num2))
# 224. Create a program that counts the number of words in a sentence
def count_words(sentence):
"""Count the number of words in a sentence."""
return len(sentence.split()) # Split sentence into words and count
sentence = input("Enter a sentence: ") # Get sentence from user
print("Number of words in the sentence:", count_words(sentence))
# 225. Create a program that calculates the body mass index (BMI)
def calculate_bmi(weight, height):
"""Calculate the body mass index (BMI)."""
return weight / (height ** 2) # BMI formula
weight = float(input("Enter your weight (kg): ")) # Get weight
height = float(input("Enter your height (m): ")) # Get height
print("Your BMI is:", calculate_bmi(weight, height))
# 226. Create a program that checks if a number is a perfect square
def is_perfect_square(n):
"""Check if a number is a perfect square."""
root = int(n ** 0.5) # Find the integer square root
return root * root == n # Check if square of root is n
number = int(input("Enter a number: ")) # Get number from user
if is_perfect_square(number):
print(number, "is a perfect square.")
else:
print(number, "is not a perfect square.")
# 227. Create a program that finds the sum of the first n natural numbers
def sum_of_natural_numbers(n):
"""Calculate the sum of the first n natural numbers."""
return n * (n + 1) // 2 # Sum formula
n = int(input("Enter a number: ")) # Get number from user
print("Sum of the first", n, "natural numbers is:", sum_of_natural_numbers(n))
# 228. Create a program that checks if a string contains only digits
def is_digit_string(s):
"""Check if a string contains only digits."""
return s.isdigit() # Return True if all characters are digits
input_string = input("Enter a string: ") # Get string from user
if is_digit_string(input_string):
print("The string contains only digits.")
else:
print("The string contains non-digit characters.")
# 229. Create a program that finds the second largest number in a list
def second_largest(numbers):
"""Find the second largest number in a list."""
unique_numbers = list(set(numbers)) # Remove duplicates
unique_numbers.sort() # Sort the list
return unique_numbers[-2] if len(unique_numbers) >= 2 else None # Return
second largest
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list from user
result = second_largest(numbers)
if result is not None:
print("The second largest number is:", result)
else:
print("There is no second largest number.")
# 230. Create a program that calculates the Fibonacci series up to n
def fibonacci(n):
"""Generate Fibonacci series up to n."""
fib_series = []
a, b = 0, 1
while a <= n: # Generate until a exceeds n
fib_series.append(a)
a, b = b, a + b # Update a and b
return fib_series
n = int(input("Enter a number: ")) # Get number from user
print("Fibonacci series up to", n, ":", fibonacci(n))
# 231. Create a program that checks if a string is a pangram
def is_pangram(s):
"""Check if a string is a pangram."""
alphabet = set('abcdefghijklmnopqrstuvwxyz')
return alphabet <= set(s.lower()) # Check if all letters are in string
input_string = input("Enter a string: ") # Get string from user
if is_pangram(input_string):
print("The string is a pangram.")
else:
print("The string is not a pangram.")
# 232. Create a program that calculates the power of a number
def power(base, exponent):
"""Calculate the power of a number."""
return base ** exponent # Power formula
base = float(input("Enter the base: ")) # Get base from user
exponent = int(input("Enter the exponent: ")) # Get exponent from user
print(f"{base} raised to the power of {exponent} is:", power(base, exponent))
# 233. Create a program that generates a random password of specified length
import random
import string
def generate_password(length):
"""Generate a random password of specified length."""
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for _ in range(length)) # Random
selection
length = int(input("Enter the desired password length: ")) # Get length from user
print("Generated password:", generate_password(length))
# 234. Create a program that checks if a string is a valid hexadecimal number
def is_valid_hex(s):
"""Check if a string is a valid hexadecimal number."""
regex = r'^[0-9a-fA-F]+$'
return re.match(regex, s) is not None # Check against regex
hex_string = input("Enter a hexadecimal number: ") # Get hex string from user
if is_valid_hex(hex_string):
print(hex_string, "is a valid hexadecimal number.")
else:
print(hex_string, "is not a valid hexadecimal number.")
# 235. Create a program that counts the number of sentences in a paragraph
def count_sentences(paragraph):
"""Count the number of sentences in a paragraph."""
sentences = re.split(r'[.!?]+', paragraph) # Split by sentence-ending
punctuation
return len([s for s in sentences if s.strip()]) # Count non-empty sentences
paragraph = input("Enter a paragraph: ") # Get paragraph from user
print("Number of sentences in the paragraph:", count_sentences(paragraph))
# 236. Create a program that finds the smallest number in a list
def smallest_number(numbers):
"""Find the smallest number in a list."""
return min(numbers) # Use min function to find the smallest
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list from user
print("Smallest number in the list is:", smallest_number(numbers))
# 237. Create a program that reverses a list
def reverse_list(lst):
"""Reverse a list."""
return lst[::-1] # Reverse using slicing
elements = list(map(int, input("Enter elements separated by space: ").split())) #
Get list from user
print("Reversed list:", reverse_list(elements))
# 238. Create a program that checks if a string contains only alphabetic characters
def is_alpha_string(s):
"""Check if a string contains only alphabetic characters."""
return s.isalpha() # Return True if all characters are alphabetic
input_string = input("Enter a string: ") # Get string from user
if is_alpha_string(input_string):
print("The string contains only alphabetic characters.")
else:
print("The string contains non-alphabetic characters.")
# 239. Create a program that finds the common elements between two lists
def common_elements(list1, list2):
"""Find common elements between two lists."""
return list(set(list1) & set(list2)) # Use set intersection to find common
elements
list1 = list(map(int, input("Enter first list elements separated by space:
").split())) # Get first list
list2 = list(map(int, input("Enter second list elements separated by space:
").split())) # Get second list
print("Common elements:", common_elements(list1, list2))
# 240. Create a program that sorts a list of numbers in ascending order
def sort_list(lst):
"""Sort a list of numbers in ascending order."""
return sorted(lst) # Use sorted function to sort
elements = list(map(int, input("Enter elements separated by space: ").split())) #
Get list from user
print("Sorted list:", sort_list(elements))
# 241. Create a program that finds the maximum value in a list
def maximum_value(numbers):
"""Find the maximum value in a list."""
return max(numbers) # Use max function to find the maximum
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list from user
print("Maximum value in the list is:", maximum_value(numbers))
# 242. Create a program that calculates the sum of even numbers in a list
def sum_of_even_numbers(numbers):
"""Calculate the sum of even numbers in a list."""
return sum(x for x in numbers if x % 2 == 0) # Sum of even numbers
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list from user
print("Sum of even numbers in the list is:", sum_of_even_numbers(numbers))
# 243. Create a program that calculates the sum of odd numbers in a list
def sum_of_odd_numbers(numbers):
"""Calculate the sum of odd numbers in a list."""
return sum(x for x in numbers if x % 2 != 0) # Sum of odd numbers
print("Sum of odd numbers in the list is:", sum_of_odd_numbers(numbers))
# 244. Create a program that calculates the average of even numbers in a list
def average_of_even_numbers(numbers):
"""Calculate the average of even numbers in a list."""
even_numbers = [x for x in numbers if x % 2 == 0] # Filter even numbers
return sum(even_numbers) / len(even_numbers) if even_numbers else 0 # Average
print("Average of even numbers in the list is:", average_of_even_numbers(numbers))
# 245. Create a program that calculates the average of odd numbers in a list
def average_of_odd_numbers(numbers):
"""Calculate the average of odd numbers in a list."""
odd_numbers = [x for x in numbers if x % 2 != 0] # Filter odd numbers
return sum(odd_numbers) / len(odd_numbers) if odd_numbers else 0 # Average
print("Average of odd numbers in the list is:", average_of_odd_numbers(numbers))
# 246. Create a program that finds the intersection of two sets
def intersection(set1, set2):
"""Find the intersection of two sets."""
return set1 & set2 # Set intersection
set1 = set(map(int, input("Enter first set elements separated by space:
").split())) # Get first set
set2 = set(map(int, input("Enter second set elements separated by space:
").split())) # Get second set
print("Intersection of the sets:", intersection(set1, set2))
# 247. Create a program that finds the union of two sets
def union(set1, set2):
"""Find the union of two sets."""
return set1 | set2 # Set union
print("Union of the sets:", union(set1, set2))
# 248. Create a program that checks if a string is a palindrome
def is_palindrome(s):
"""Check if a string is a palindrome."""
return s == s[::-1] # Check if string is equal to its reverse
input_string = input("Enter a string: ") # Get string from user
if is_palindrome(input_string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
# 249. Create a program that finds the largest number in a list
def largest_number(numbers):
"""Find the largest number in a list."""
return max(numbers) # Use max function to find the largest
print("Largest number in the list is:", largest_number(numbers))
# 250. Create a program that counts the number of times a character appears in a
string
def count_character(s, char):
"""Count the number of times a character appears in a string."""
return s.count(char) # Count occurrences of character
char = input("Enter a character: ") # Get character from user
print(f"The character '{char}' appears", count_character(input_string, char),
"times in the string.")
# 251. Create a program that creates a list of squares of numbers from 1 to n
def squares_up_to_n(n):
"""Create a list of squares of numbers from 1 to n."""
return [i ** 2 for i in range(1, n + 1)] # List comprehension for squares
n = int(input("Enter a number: ")) # Get number from user
print("Squares of numbers from 1 to", n, ":", squares_up_to_n(n))
# 252. Create a program that finds the difference between the largest and smallest
numbers in a list
def difference_max_min(numbers):
"""Find the difference between the largest and smallest numbers in a list."""
return max(numbers) - min(numbers) # Difference calculation
print("Difference between largest and smallest in the list is:",
difference_max_min(numbers))
# 253. Create a program that creates a list of Fibonacci numbers up to n
def fibonacci_up_to_n(n):
"""Create a list of Fibonacci numbers up to n."""
fib_series = []
a, b = 0, 1
while a <= n:
fib_series.append(a)
a, b = b, a + b
return fib_series
print("Fibonacci numbers up to", n, ":", fibonacci_up_to_n(n))
# 254. Create a program that counts the number of uppercase and lowercase letters
in a string
def count_upper_lower(s):
"""Count the number of uppercase and lowercase letters in a string."""
upper = sum(1 for char in s if char.isupper()) # Count uppercase
lower = sum(1 for char in s if char.islower()) # Count lowercase
return upper, lower
upper_count, lower_count = count_upper_lower(input_string) # Count uppercase and
lowercase
print(f"Uppercase letters: {upper_count}, Lowercase letters: {lower_count}")
# 255. Create a program that checks if two strings are anagrams
def are_anagrams(s1, s2):
"""Check if two strings are anagrams."""
return sorted(s1) == sorted(s2) # Compare sorted versions
str1 = input("Enter first string: ") # Get first string from user
str2 = input("Enter second string: ") # Get second string from user
if are_anagrams(str1, str2):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")
# 256. Create a program that checks if a string contains all digits
def contains_all_digits(s):
"""Check if a string contains all digits from 0 to 9."""
return set('0123456789') <= set(s) # Check for all digits
input_string = input("Enter a string: ") # Get string from user
if contains_all_digits(input_string):
print("The string contains all digits from 0 to 9.")
else:
print("The string does not contain all digits.")
# 257. Create a program that counts the number of lines in a text file
def count_lines_in_file(filename):
"""Count the number of lines in a text file."""
with open(filename, 'r') as file: # Open file in read mode
return sum(1 for _ in file) # Count lines
filename = input("Enter the filename: ") # Get filename from user
print("Number of lines in the file:", count_lines_in_file(filename))
# 258. Create a program that reads a CSV file and prints its contents
import csv
def read_csv_file(filename):
"""Read a CSV file and print its contents."""
with open(filename, newline='') as csvfile:
reader = csv.reader(csvfile) # Create CSV reader
for row in reader: # Iterate over rows
print(', '.join(row)) # Print each row
filename = input("Enter the CSV filename: ") # Get filename from user
read_csv_file(filename)
# 259. Create a program that converts a list of strings to uppercase
def convert_to_uppercase(strings):
"""Convert a list of strings to uppercase."""
return [s.upper() for s in strings] # List comprehension for uppercase
conversion
strings = input("Enter strings separated by space: ").split() # Get list of
strings
print("Uppercase strings:", convert_to_uppercase(strings))
# 260. Create a program that converts a list of strings to lowercase
def convert_to_lowercase(strings):
"""Convert a list of strings to lowercase."""
return [s.lower() for s in strings] # List comprehension for lowercase
conversion
print("Lowercase strings:", convert_to_lowercase(strings))
# 261. Create a program that generates a list of prime numbers up to n
def generate_primes(n):
"""Generate a list of prime numbers up to n."""
primes = []
for num in range(2, n + 1): # Iterate over numbers
if is_prime(num):
primes.append(num) # Append if prime
return primes
n = int(input("Enter a number: ")) # Get number from user
print("Prime numbers up to", n, ":", generate_primes(n))
# 262. Create a program that checks if a list is sorted in ascending order
def is_sorted(lst):
"""Check if a list is sorted in ascending order."""
return lst == sorted(lst) # Compare with sorted version
elements = list(map(int, input("Enter elements separated by space: ").split())) #
Get list from user
if is_sorted(elements):
print("The list is sorted in ascending order.")
else:
print("The list is not sorted in ascending order.")
# 263. Create a program that calculates the median of a list of numbers
def median(numbers):
"""Calculate the median of a list of numbers."""
sorted_numbers = sorted(numbers) # Sort numbers
mid = len(sorted_numbers) // 2 # Find midpoint
if len(sorted_numbers) % 2 == 0:
return (sorted_numbers[mid - 1] + sorted_numbers[mid]) / 2 # Average of
middle two
return sorted_numbers[mid] # Middle element
numbers = list(map(int, input("Enter numbers separated by space: ").split())) #
Get list from user
print("Median of the numbers:", median(numbers))
# 264. Create a program that creates a list of the cubes of numbers from 1 to n
def cubes_up_to_n(n):
"""Create a list of cubes of numbers from 1 to n."""
return [i ** 3 for i in range(1, n + 1)] # List comprehension for cubes
n = int(input("Enter a number: ")) # Get number from user
print("Cubes of numbers from 1 to", n, ":", cubes_up_to_n(n))
# 265. Create a program that checks if two lists are equal
def are_lists_equal(list1, list2):
"""Check if two lists are equal."""
return list1 == list2 # Direct comparison
list1 = list(map(int, input("Enter first list elements separated by space:
").split())) # Get first list
list2 = list(map(int, input("Enter second list elements separated by space:
").split())) # Get second list
if are_lists_equal(list1, list2):
print("The lists are equal.")
else:
print("The lists are not equal.")
# 266. Create a program that finds the longest word in a sentence
def longest_word(sentence):
"""Find the longest word in a sentence."""
words = sentence.split() # Split sentence into words
return max(words, key=len) # Return longest word
sentence = input("Enter a sentence: ") # Get sentence from user
print("The longest word is:", longest_word(sentence))
# 267. Create a program that counts the frequency of each character in a string
def character_frequency(s):
"""Count the frequency of each character in a string."""
frequency = {}
for char in s:
frequency[char] = frequency.get(char, 0) + 1 # Count occurrences
return frequency
input_string = input("Enter a string: ") # Get string from user
print("Character frequency:", character_frequency(input_string))
# 268. Create a program that calculates the area of a circle given its radius
import math
def area_of_circle(radius):
"""Calculate the area of a circle."""
return math.pi * (radius ** 2) # Area formula
radius = float(input("Enter the radius of the circle: ")) # Get radius from user
print("Area of the circle is:", area_of_circle(radius))
# 269. Create a program that converts a temperature from Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
"""Convert temperature from Celsius to Fahrenheit."""
return (celsius * 9/5) + 32 # Conversion formula
celsius = float(input("Enter temperature in Celsius: ")) # Get Celsius temperature
from user
print(f"Temperature in Fahrenheit is: {celsius_to_fahrenheit(celsius)}")
# 270. Create a program that checks if a number is a prime number
def is_prime(num):
"""Check if a number is prime."""
if num <= 1: # Check for non-prime numbers
return False
for i in range(2, int(num ** 0.5) + 1): # Check divisibility
if num % i == 0:
return False
return True
number = int(input("Enter a number: ")) # Get number from user
if is_prime(number):
print(number, "is a prime number.")
else:
print(number, "is not a prime number.")
# 271. Create a program that finds the common letters in two strings
def common_letters(s1, s2):
"""Find common letters in two strings."""
return set(s1) & set(s2) # Set intersection for letters
str1 = input("Enter first string: ") # Get first string from user
str2 = input("Enter second string: ") # Get second string from user
print("Common letters:", common_letters(str1, str2))
# 272. Create a program that checks if a string is a valid email address
import re
def is_valid_email(email):
"""Check if a string is a valid email address."""
regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(regex, email) is not None # Check against regex
email = input("Enter an email address: ") # Get email from user
if is_valid_email(email):
print(email, "is a valid email address.")
else:
print(email, "is not a valid email address.")
# 273. Create a program that checks if a string is a valid URL
def is_valid_url(url):
"""Check if a string is a valid URL."""
regex = r'^(https?://)?(www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/.*)?$'
return re.match(regex, url) is not None # Check against regex
url = input("Enter a URL: ") # Get URL from user
if is_valid_url(url):
print(url, "is a valid URL.")
else:
print(url, "is not a valid URL.")
# 274. Create a program that counts the number of vowels in a string
def count_vowels(s):
"""Count the number of vowels in a string."""
vowels = "aeiouAEIOU"
return sum(1 for char in s if char in vowels) # Count occurrences of vowels
input_string = input("Enter a string: ") # Get string from user
print("Number of vowels in the string:", count_vowels(input_string))
# 275. Create a program that finds the square of a number
def square(num):
"""Find the square of a number."""
return num ** 2 # Square calculation
number = float(input("Enter a number: ")) # Get number from user
print(f"The square of {number} is:", square(number))
# 276. Create a program that finds the cube of a number
def cube(num):
"""Find the cube of a number."""
return num ** 3 # Cube calculation
print(f"The cube of {number} is:", cube(number))
# 277. Create a program that checks if a list contains a specific element
def contains_element(lst, element):
"""Check if a list contains a specific element."""
return element in lst # Check membership
element = int(input("Enter an element to check: ")) # Get element from user
if contains_element(elements, element):
print(f"The list contains the element {element}.")
else:
print(f"The list does not contain the element {element}.")
# 278. Create a program that counts the number of unique elements in a list
def count_unique_elements(lst):
"""Count the number of unique elements in a list."""
return len(set(lst)) # Use set to find unique elements
print("Number of unique elements in the list:", count_unique_elements(elements))
# 279. Create a program that checks if a number is a perfect number
def is_perfect_number(num):
"""Check if a number is a perfect number."""
divisors = [i for i in range(1, num) if num % i == 0] # Find divisors
return sum(divisors) == num # Check if sum of divisors equals the number
number = int(input("Enter a number: ")) # Get number from user
if is_perfect_number(number):
print(number, "is a perfect number.")
else:
print(number, "is not a perfect number.")
# 280. Create a program that finds the least common multiple (LCM) of two numbers
def lcm(a, b):
"""Find the least common multiple of two numbers."""
return abs(a * b) // gcd(a, b) # Using GCD to find LCM
num1 = int(input("Enter first number: ")) # Get first number
num2 = int(input("Enter second number: ")) # Get second number
print("LCM of", num1, "and", num2, "is:", lcm(num1, num2))
# 281. Create a program that counts the number of words in a sentence
def count_words(sentence):
"""Count the number of words in a sentence."""
return len(sentence.split()) # Split sentence into words and count
sentence = input("Enter a sentence: ") # Get sentence from user
print("Number of words in the sentence:", count_words(sentence))
# 282. Create a program that calculates the body mass index (BMI)
def calculate_bmi(weight, height):
"""Calculate the body mass index (BMI)."""
return weight / (height ** 2) # BMI formula
weight = float(input("Enter your weight (kg): ")) # Get weight
height = float(input("Enter your height (m): ")) # Get height
print("Your BMI is:", calculate_bmi(weight, height))
# 283. Create a program that checks if a number is a perfect square
def is_perfect_square(n):
"""Check if a number is a perfect square."""
root = int(n ** 0.5) # Find the integer square root
return root * root == n # Check if square of root is n
number = int(input("Enter a number: ")) # Get number from user
if is_perfect_square(number):
print(number, "is a perfect square.")
else:
print(number, "is not a perfect square.")
# 284. Create a program that finds the sum of the first n natural numbers
def sum_of_natural_numbers(n):
"""Calculate the sum of the first n natural numbers."""
return n * (n + 1) // 2 # Sum formula
n = int(input("Enter a number: ")) # Get number from user
print("Sum of the first", n, "natural numbers is:", sum_of_natural_numbers(n))
# 285. Create a program that reverses a string
def reverse_string(s):
"""Reverse a string."""
return s[::-1] # Reverse string
input_string = input("Enter a string: ") # Get string from user
print("Reversed string:", reverse_string(input_string))
# 286. Create a program that checks if a string contains only digits
def contains_only_digits(s):
"""Check if a string contains only digits."""
return s.isdigit() # Check if all characters are digits
input_string = input("Enter a string: ") # Get string from user
if contains_only_digits(input_string):
print("The string contains only digits.")
else:
print("The string does not contain only digits.")
# 287. Create a program that finds the second largest number in a list
def second_largest(numbers):
"""Find the second largest number in a list."""
unique_numbers = list(set(numbers)) # Remove duplicates
unique_numbers.sort() # Sort the unique numbers
return unique_numbers[-2] if len(unique_numbers) >= 2 else None # Return
second largest
print("Second largest number in the list is:", second_largest(numbers))
# 288. Create a program that checks if a string is a valid hexadecimal number
def is_valid_hexadecimal(s):
"""Check if a string is a valid hexadecimal number."""
regex = r'^[0-9A-Fa-f]+$'
return re.match(regex, s) is not None # Check against regex
input_string = input("Enter a string: ") # Get string from user
if is_valid_hexadecimal(input_string):
print("The string is a valid hexadecimal number.")
else:
print("The string is not a valid hexadecimal number.")
# 289. Create a program that finds the sum of digits of a number
def sum_of_digits(num):
"""Find the sum of digits of a number."""
return sum(int(digit) for digit in str(num)) # Sum of digits
number = int(input("Enter a number: ")) # Get number from user
print("Sum of the digits of", number, "is:", sum_of_digits(number))
# 290. Create a program that generates random integers within a range
import random
def generate_random_integers(start, end, count):
"""Generate random integers within a specified range."""
return [random.randint(start, end) for _ in range(count)] # List of random
integers
start = int(input("Enter start of range: ")) # Get start of range
end = int(input("Enter end of range: ")) # Get end of range
count = int(input("Enter how many random integers to generate: ")) # Get count
print("Random integers:", generate_random_integers(start, end, count))
# 291. Create a program that finds the smallest prime factor of a number
def smallest_prime_factor(n):
"""Find the smallest prime factor of a number."""
for i in range(2, n + 1):
if n % i == 0 and is_prime(i): # Check for factors and prime status
return i # Return first prime factor
number = int(input("Enter a number: ")) # Get number from user
print("Smallest prime factor of", number, "is:", smallest_prime_factor(number))
# 292. Create a program that checks if a number is a Fibonacci number
def is_fibonacci(n):
"""Check if a number is a Fibonacci number."""
a, b = 0, 1
while a < n:
a, b = b, a + b # Generate Fibonacci numbers
return a == n # Check if number matches
number = int(input("Enter a number: ")) # Get number from user
if is_fibonacci(number):
print(number, "is a Fibonacci number.")
else:
print(number, "is not a Fibonacci number.")
# 293. Create a program that finds the longest common prefix of a list of strings
def longest_common_prefix(strs):
"""Find the longest common prefix among a list of strings."""
if not strs:
return ""
prefix = strs[0] # Start with the first string
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1] # Shorten the prefix
if not prefix:
return ""
return prefix
strings = input("Enter strings separated by space: ").split() # Get list of
strings
print("Longest common prefix:", longest_common_prefix(strings))
# 294. Create a program that counts the number of times a specific word appears in
a sentence
def count_specific_word(sentence, word):
"""Count the number of times a specific word appears in a sentence."""
words = sentence.split() # Split sentence into words
return words.count(word) # Count occurrences of the word
sentence = input("Enter a sentence: ") # Get sentence from user
word = input("Enter the word to count: ") # Get word from user
print(f"The word '{word}' appears", count_specific_word(sentence, word), "times in
the sentence.")
# 295. Create a program that generates a random float number within a range
def generate_random_float(start, end):
"""Generate a random float number within a specified range."""
return random.uniform(start, end) # Generate random float
start = float(input("Enter start of range: ")) # Get start of range
end = float(input("Enter end of range: ")) # Get end of range
print("Random float number:", generate_random_float(start, end))
# 296. Create a program that checks if a string is a valid IP address
def is_valid_ip(ip):
"""Check if a string is a valid IP address."""
regex = r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
return re.match(regex, ip) is not None # Check against regex
ip = input("Enter an IP address: ") # Get IP address from user
if is_valid_ip(ip):
print(ip, "is a valid IP address.")
else:
print(ip, "is not a valid IP address.")
# 297. Create a program that counts the number of consonants in a string
def count_consonants(s):
"""Count the number of consonants in a string."""
vowels = "aeiouAEIOU"
return sum(1 for char in s if char.isalpha() and char not in vowels) # Count
consonants
input_string = input("Enter a string: ") # Get string from user
print("Number of consonants in the string:", count_consonants(input_string))
# 298. Create a program that checks if a string is a valid JSON
import json
def is_valid_json(s):
"""Check if a string is a valid JSON."""
try:
json.loads(s) # Try to parse string as JSON
return True
except ValueError:
return False # Parsing failed
json_string = input("Enter a JSON string: ") # Get JSON string from user
if is_valid_json(json_string):
print("The string is a valid JSON.")
else:
print("The string is not a valid JSON.")
# 299. Create a program that finds the maximum of three numbers
def maximum_of_three(a, b, c):
"""Find the maximum of three numbers."""
return max(a, b, c) # Use max function
a = float(input("Enter first number: ")) # Get first number
b = float(input("Enter second number: ")) # Get second number
c = float(input("Enter third number: ")) # Get third number
print("Maximum of the three numbers is:", maximum_of_three(a, b, c))
# 300. Create a program that calculates the factorial of a number
def factorial(n):
"""Calculate the factorial of a number."""
if n == 0 or n == 1: # Base case for 0! and 1!
return 1
return n * factorial(n - 1) # Recursive call
number = int(input("Enter a number: ")) # Get number from user
print(f"Factorial of {number} is:", factorial(number))
# How to Use the Code
# Run Each Program: Each block of code represents a separate program.
# Copy and paste each program into a Python environment (like Jupyter Notebook,
IDLE, or any Python IDE).
# Input: Follow the prompts to input the required data when each program runs.
# Output: Each program will print the result based on your input.
# Feel free to modify any of the programs or add your own
# as you learn more! If you have any questions about specific programs or concepts,
just let me know!
# Here’s a complete Python script that includes exercises from 1 to 200, formatted
for easy copying.
# Each exercise is commented for clarity.
# Python Exercises from 1 to 200
#### Exercise 1: Hello, World!
print("Hello, World!") # Print greeting
#### Exercise 2: Basic Arithmetic
a = 5
b = 3
print("Addition:", a + b) # Addition
print("Subtraction:", a - b) # Subtraction
print("Multiplication:", a * b) # Multiplication
print("Division:", a / b) # Division
#### Exercise 3: Check Even or Odd
num = int(input("Enter a number: ")) # Input number
if num % 2 == 0:
print(f"{num} is even.") # Even number message
else:
print(f"{num} is odd.") # Odd number message
#### Exercise 4: Simple Function
def greet(name):
return f"Hello, {name}!" # Greeting function
print(greet("Alice")) # Call function
#### Exercise 5: List Operations
my_list = [1, 2, 3, 4, 5]
my_list.append(6) # Append item
print("List after append:", my_list) # Print updated list
#### Exercise 6: Looping through a List
for item in my_list:
print(item) # Print each item in the list
#### Exercise 7: Simple If-Else
number = int(input("Enter a number: ")) # Input number
if number > 0:
print("Positive") # Positive number message
else:
print("Non-positive") # Non-positive message
#### Exercise 8: Simple While Loop
count = 0 # Initialize counter
while count < 5:
print("Count:", count) # Print count
count += 1 # Increment count
#### Exercise 9: String Manipulation
text = "hello"
print(text.upper()) # Convert to uppercase
#### Exercise 10: Simple Calculator
def calculator(a, b, operation):
if operation == 'add':
return a + b
elif operation == 'subtract':
return a - b
elif operation == 'multiply':
return a * b
elif operation == 'divide':
return a / b
result = calculator(10, 5, 'add') # Example usage
print("Calculator Result:", result) # Print result
#### Exercise 11: Check Prime Number
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
num = int(input("Enter a number: ")) # Input number
print(f"{num} is prime: {is_prime(num)}") # Check prime
#### Exercise 12: Simple List Comprehension
squares = [x**2 for x in range(10)] # List comprehension for squares
print("Squares:", squares) # Print squares
#### Exercise 13: Basic Function with Default Parameter
def greet(name="World"):
return f"Hello, {name}!" # Default parameter
print(greet()) # Call without argument
#### Exercise 14: Simple Dictionary Usage
my_dict = {"name": "Alice", "age": 25}
print("Name:", my_dict["name"]) # Access dictionary value
#### Exercise 15: Simple Exception Handling
try:
x = 10 / 0 # Division by zero
except ZeroDivisionError:
print("Cannot divide by zero.") # Error message
#### Exercise 16: Count to 10
for i in range(1, 11):
print(i) # Count from 1 to 10
#### Exercise 17: Find Maximum in a List
numbers = [1, 2, 3, 4, 5]
print("Max:", max(numbers)) # Print maximum
#### Exercise 18: Simple Boolean Logic
a = True
b = False
print("a AND b:", a and b) # AND operation
print("a OR b:", a or b) # OR operation
#### Exercise 19: Simple File Writing
with open("example.txt", "w") as file: # Open file in write mode
file.write("Hello, World!") # Write to file
#### Exercise 20: Simple File Reading
with open("example.txt", "r") as file: # Open file in read mode
content = file.read() # Read file content
print("File Content:", content) # Print content
#### Exercise 21: Fibonacci Sequence
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ') # Print Fibonacci numbers
a, b = b, a + b
print()
fibonacci(10) # Generate Fibonacci sequence
#### Exercise 22: Simple Password Checker
password = input("Enter your password: ") # Input password
if len(password) >= 8:
print("Password is strong.") # Strong password message
else:
print("Password is weak.") # Weak password message
#### Exercise 23: Calculate Factorial
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
num = int(input("Enter a number: ")) # Input number
print("Factorial:", factorial(num)) # Print factorial
#### Exercise 24: Simple Timer
import time
start_time = time.time() # Start timer
time.sleep(2) # Wait for 2 seconds
elapsed_time = time.time() - start_time # Calculate elapsed time
print("Elapsed time:", elapsed_time) # Print elapsed time
#### Exercise 25: Basic Voting System
votes = {"Alice": 0, "Bob": 0} # Initialize votes
while True:
vote = input("Vote for Alice or Bob (or 'exit' to finish): ") # Input vote
if vote == "exit":
break
elif vote in votes:
votes[vote] += 1 # Increment vote
else:
print("Invalid vote.") # Error message
print("Final Votes:", votes) # Print final vote count
#### Exercise 26: Palindrome Checker
def is_palindrome(s):
return s == s[::-1] # Check if string is a palindrome
string = input("Enter a string: ") # Input string
if is_palindrome(string):
print(f"{string} is a palindrome.") # Output result
else:
print(f"{string} is not a palindrome.") # Output result
#### Exercise 27: Count Characters in a String
text = input("Enter a string: ") # Input string
print("Character count:", len(text)) # Print character count
#### Exercise 28: Basic Interest Calculator
principal = float(input("Enter principal amount: ")) # Input principal
rate = float(input("Enter interest rate (in %): ")) / 100 # Input rate
time = float(input("Enter time (in years): ")) # Input time
interest = principal * rate * time # Calculate interest
print("Simple Interest:", interest) # Print interest
#### Exercise 29: Reverse a String
text = input("Enter a string: ") # Input string
print("Reversed string:", text[::-1]) # Print reversed string
#### Exercise 30: Basic Grade Calculator
score = float(input("Enter your score: ")) # Input score
if score >= 90:
print("Grade: A") # Grade A
elif score >= 80:
print("Grade: B") # Grade B
elif score >= 70:
print("Grade: C") # Grade C
elif score >= 60:
print("Grade: D") # Grade D
else:
print("Grade: F") # Grade F
#### Exercise 31: Simple Prime Number Checker
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
num = int(input("Enter a number: ")) # Input number
print(f"{num} is prime: {is_prime(num)}") # Check if prime
#### Exercise 32: Basic Rock-Paper-Scissors Game
import random
def rps_game():
choices = ["rock", "paper", "scissors"]
user_choice = input("Choose rock, paper, or scissors: ") # User choice
computer_choice = random.choice(choices) # Computer choice
print("Computer chose:", computer_choice) # Print computer choice
if user_choice == computer_choice:
print("It's a tie!") # Tie message
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
print("You win!") # Win message
else:
print("You lose!") # Lose message
rps_game() # Play the game
#### Exercise 33: Simple Temperature Converter
def celsius_to_fahrenheit(celsius):
return (celsius * 9 / 5) + 32 # Convert to Fahrenheit
celsius = float(input("Enter temperature in Celsius: ")) # Input Celsius
fahrenheit = celsius_to_fahrenheit(celsius) # Convert
print("Temperature in Fahrenheit:", fahrenheit) # Print result
#### Exercise 34: Simple Countdown Timer
import time
def countdown(seconds):
while seconds:
print(seconds, end='\r') # Print countdown
time.sleep(1) # Wait for a second
seconds -= 1
print("Time's up!") # Timer finished message
countdown(5) # Start countdown
#### Exercise 35: Simple To-Do List
to_do_list = [] # Initialize list
while True:
task = input("Enter a task (or 'exit' to finish): ") # Input task
if task.lower() == 'exit':
break
to_do_list.append(task) # Add task to list
print("Your To-Do List:") # Print final list
for task in to_do_list:
print(task) # Print each task
#### Exercise 36: Simple Number Guessing Game
import random
def number_guessing_game():
number_to_guess = random.randint(1, 10) # Random number to guess
attempts = 3 # Number of attempts
for _ in range(attempts):
guess = int(input("Guess the number (1-10): ")) # User guess
if guess == number_to_guess:
print("Congratulations! You guessed it right.") # Win message
return
else:
print("Try again!") # Try again message
print(f"Sorry, the number was {number_to_guess}.") # Reveal number
number_guessing_game() # Start game
#### Exercise 37: Count Vowels in a String
text = input("Enter a string: ") # Input string
vowels = "aeiouAEIOU" # Vowel characters
count = sum(1 for char in text if char in vowels) # Count vowels
print("Number of vowels:", count) # Print vowel count
#### Exercise 38: Simple Anagram Checker
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2) # Check if anagrams
string1 = input("Enter first string: ") # Input first string
string2 = input("Enter second string: ") # Input second string
print(f"{string1} and {string2} are anagrams: {are_anagrams(string1, string2)}") #
Check anagram
#### Exercise 39: Simple HTML Generator
title = input("Enter the title: ") # Input title
content = input("Enter the content: ") # Input content
html = f"<html>\n<head><title>{title}</title></head>\n<body>\n<p>{content}</p>\n</
body>\n</html>" # Generate HTML
print("Generated HTML:\n", html) # Print generated HTML
#### Exercise 40: Basic Interest Compound Calculator
principal = float(input("Enter principal amount: ")) # Input principal
rate = float(input("Enter interest rate (in %): ")) / 100 # Input rate
time = float(input("Enter time (in years): ")) # Input time
compound_interest = principal * (1 + rate) ** time - principal # Calculate
compound interest
print("Compound Interest:", compound_interest) # Print result
#### Exercise 41: Simple Binary to Decimal Converter
def binary_to_decimal(binary):
return int(binary, 2) # Convert binary to decimal
binary_input = input("Enter a binary number: ") # Input binary number
decimal_output = binary_to_decimal(binary_input) # Convert
print("Decimal value:", decimal_output) # Print decimal value
#### Exercise 42: Simple Decimal to Binary Converter
def decimal_to_binary(decimal):
return bin(decimal)[2:] # Convert decimal to binary
decimal_input = int(input("Enter a decimal number: ")) # Input decimal number
binary_output = decimal_to_binary(decimal_input) # Convert
print("Binary value:", binary_output) # Print binary value
#### Exercise 43: Simple Number Sorting
numbers = [int(x) for x in input("Enter numbers separated by space: ").split()] #
Input numbers
numbers.sort() # Sort numbers
print("Sorted numbers:", numbers) # Print sorted numbers
#### Exercise 44: Simple Matrix Addition
def add_matrices(A, B):
return [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
# Add matrices
A = [[1, 2, 3], [4, 5, 6]] # Matrix A
B = [[7, 8, 9], [10, 11, 12]] # Matrix B
result = add_matrices(A, B) # Add matrices
print("Matrix Addition Result:", result) # Print result
#### Exercise 45: Basic Shopping Cart
cart = [] # Initialize shopping cart
while True:
item = input("Enter an item to add to the cart (or 'exit' to finish): ") #
Input item
if item.lower() == 'exit':
break
cart.append(item) # Add item to cart
print("Your Shopping Cart:") # Print final cart
for item in cart:
print(item) # Print each item
#### Exercise 46: Basic String Formatting
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.") # Formatted string
#### Exercise 47: Simple Voting System (Dictionary)
votes = {"Alice": 0, "Bob": 0} # Initialize votes
while True:
vote = input("Vote for Alice or Bob (or 'exit' to finish): ") # Input vote
if vote == "exit":
break
elif vote in votes:
votes[vote] += 1 # Increment vote
else:
print("Invalid vote.") # Error message
print("Final Votes:", votes) # Print final vote count
#### Exercise 48: Simple Rock-Paper-Scissors Game (With Score)
import random
def rps_game():
choices = ["rock", "paper", "scissors"]
user_score = 0
computer_score = 0
for _ in range(3): # Play three rounds
user_choice = input("Choose rock, paper, or scissors: ") # User choice
computer_choice = random.choice(choices) # Computer choice
print("Computer chose:", computer_choice) # Print computer choice
if user_choice == computer_choice:
print("It's a tie!") # Tie message
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
print("You win!") # Win message
user_score += 1
else:
print("You lose!") # Lose message
computer_score += 1
print(f"Final Score - You: {user_score}, Computer: {computer_score}") # Print
final score
rps_game() # Play the game
#### Exercise 49: Simple Image Viewer (Using PIL)
from PIL import Image
def view_image(image_path):
img = Image.open(image_path) # Open image
img.show() # Display image
image_path = input("Enter image path: ") # Input image path
view_image(image_path) # View image
#### Exercise 50: Basic Currency Converter
def currency_converter(amount, rate):
return amount * rate # Convert currency
amount = float(input("Enter amount in USD: ")) # Input amount
rate = float(input("Enter conversion rate to your currency: ")) # Input rate
converted_amount = currency_converter(amount, rate) # Convert
print("Converted amount:", converted_amount) # Print result
#### Exercise 51: Simple String Reversal Function
def reverse_string(s):
return s[::-1] # Reverse string
string = input("Enter a string: ") # Input string
print("Reversed string:", reverse_string(string)) # Print reversed string
#### Exercise 52: Simple Tic-Tac-Toe Game
def print_board(board):
for row in board:
print("|".join(row)) # Print the game board
def check_winner(board):
for row in board:
if row.count(row[0]) == 3 and row[0] != ' ':
return True # Check rows
for col in range(3):
if all(board[row][col] == board[0][col] and board[0][col] != ' ' for row in
range(3)):
return True # Check columns
if all(board[i][i] == board[0][0] and board[0][0] != ' ' for i in range(3)):
return True # Check diagonal
if all(board[i][2 - i] == board[0][2] and board[0][2] != ' ' for i in
range(3)):
return True # Check other diagonal
return False
board = [[' ' for _ in range(3)] for _ in range(3)] # Initialize board
current_player = 'X'
for turn in range(9):
print_board(board) # Print the board
row = int(input(f"Player {current_player}, enter row (0-2): ")) # Input row
col = int(input(f"Player {current_player}, enter column (0-2): ")) # Input
column
if board[row][col] == ' ':
board[row][col] = current_player # Place mark
if check_winner(board):
print_board(board) # Print the board
print(f"Player {current_player} wins!") # Win message
break
current_player = 'O' if current_player == 'X' else 'X' # Switch players
else:
print("Cell already taken! Try again.") # Error message
else:
print("It's a tie!") # Tie message
#### Exercise 53: Simple Palindrome Checker
def is_palindrome(s):
return s == s[::-1] # Check if string is a palindrome
string = input("Enter a string: ") # Input string
if is_palindrome(string):
print(f"{string} is a palindrome.") # Output result
else:
print(f"{string} is not a palindrome.") # Output result
#### Exercise 54: Basic ATM Simulator
def atm_simulator():
balance = 1000 # Initial balance
while True:
print("1. Check balance\n2. Deposit\n3. Withdraw\n4. Exit")
choice = int(input("Choose an option: ")) # Input choice
if choice == 1:
print("Current balance:", balance) # Show balance
elif choice == 2:
amount = float(input("Enter amount to deposit: ")) # Input deposit
amount
balance += amount # Update balance
print("Deposit successful.") # Deposit success message
elif choice == 3:
amount = float(input("Enter amount to withdraw: ")) # Input withdraw
amount
if amount <= balance:
balance -= amount # Update balance
print("Withdrawal successful.") # Withdrawal success message
else:
print("Insufficient balance.") # Error message
elif choice == 4:
break # Exit
else:
print("Invalid option. Try again.") # Error message
atm_simulator() # Start ATM simulator
#### Exercise 55: Simple Email Validator
import re
def is_valid_email(email):
regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$' # Email regex
return re.match(regex, email) is not None # Check validity
email = input("Enter your email: ") # Input email
if is_valid_email(email):
print("Valid email address.") # Valid email message
else:
print("Invalid email address.") # Invalid email message
#### Exercise 56: Basic Sudoku Validator
def is_valid_sudoku(board):
for i in range(9):
row = set()
col = set()
for j in range(9):
if board[i][j] != 0:
if board[i][j] in row:
return False # Check rows
row.add(board[i][j])
if board[j][i] != 0:
if board[j][i] in col:
return False # Check columns
col.add(board[j][i])
return True
sudoku_board = [[0] * 9 for _ in range(9)] # Initialize board
# Input the Sudoku board here
if is_valid_sudoku(sudoku_board):
print("Valid Sudoku board.") # Valid board message
else:
print("Invalid Sudoku board.") # Invalid board message
#### Exercise 57: Simple Password Strength Checker
def password_strength(password):
if len(password) < 8:
return "Weak" # Weak password
if any(char.isdigit() for char in password) and any(char.islower() for char in
password) and any(char.isupper() for char in password):
return "Strong" # Strong password
return "Moderate" # Moderate password
password = input("Enter a password: ") # Input password
print("Password strength:", password_strength(password)) # Print strength
#### Exercise 58: Basic User Registration
users = [] # Initialize user list
def register_user(username, password):
users.append({"username": username, "password": password}) # Register user
username = input("Enter username: ") # Input username
password = input("Enter password: ") # Input password
register_user(username, password) # Register user
print("User registered successfully.") # Success message
#### Exercise 59: Simple Temperature Conversion (F to C)
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9 # Convert to Celsius
fahrenheit = float(input("Enter temperature in Fahrenheit: ")) # Input Fahrenheit
celsius = fahrenheit_to_celsius(fahrenheit) # Convert
print("Temperature in Celsius:", celsius) # Print result
#### Exercise 60: Basic Word Counter
text = input("Enter a sentence: ") # Input sentence
word_count = len(text.split()) # Count words
print("Word count:", word_count) # Print word count
#### Exercise 61: Simple Command-Line Calculator
def calculator():
print("Simple Calculator")
print("Enter two numbers:")
num1 = float(input("First number: ")) # Input first number
num2 = float(input("Second number: ")) # Input second number
operation = input("Enter operation (+, -, *, /): ") # Input operation
if operation == "+":
result = num1 + num2 # Addition
elif operation == "-":
result = num1 - num2 # Subtraction
elif operation == "*":
result = num1 * num2 # Multiplication
elif operation == "/":
result = num1 / num2 # Division
else:
print("Invalid operation.")
return
print("Result:", result) # Print result
calculator() # Start calculator
#### Exercise 62: Basic Text File Writer
text_to_write = input("Enter text to write to file: ") # Input text
with open("output.txt", "w") as file: # Open file in write mode
file.write(text_to_write) # Write text
print("Text written to output.txt") # Success message
#### Exercise 63: Basic Text File Reader
with open("output.txt", "r") as file: # Open file in read mode
content = file.read() # Read content
print("File content:", content) # Print content
#### Exercise 64: Simple Color Picker
def color_picker():
colors = ['red', 'green', 'blue', 'yellow', 'purple', 'orange']
print("Available colors:", ', '.join(colors)) # List colors
choice = input("Pick a color: ") # User choice
if choice in colors:
print(f"You picked {choice}!") # Success message
else:
print("Color not available.") # Error message
color_picker() # Start color picker
#### Exercise 65: Basic Personal Diary (Using File)
def diary_entry():
entry = input("Write your diary entry: ") # Input diary entry
with open("diary.txt", "a") as file: # Open file in append mode
file.write(entry + "\n") # Write entry
print("Entry added to diary.") # Success message
diary_entry() # Add diary entry
#### Exercise 66: Basic Calculator with Functions
def add(a, b):
return a + b # Addition function
def subtract(a, b):
return a - b # Subtraction function
def multiply(a, b):
return a * b # Multiplication function
def divide(a, b):
if b == 0:
return "Cannot divide by zero." # Division error
return a / b # Division function
num1 = float(input("Enter first number: ")) # Input first number
num2 = float(input("Enter second number: ")) # Input second number
operation = input("Choose operation (+, -, *, /): ") # Input operation
if operation == "+":
print("Result:", add(num1, num2)) # Print addition result
elif operation == "-":
print("Result:", subtract(num1, num2)) # Print subtraction result
elif operation == "*":
print("Result:", multiply(num1, num2)) # Print multiplication result
elif operation == "/":
print("Result:", divide(num1, num2)) # Print division result
else:
print("Invalid operation.") # Error message
#### Exercise 67: Simple Number Pattern
def number_pattern(n):
for i in range(1, n + 1):
print(" ".join(str(x) for x in range(1, i + 1))) # Print pattern
number_pattern(5) # Print number pattern
#### Exercise 68: Simple Name Reversal
name = input("Enter your name: ") # Input name
print("Reversed name:", name[::-1]) # Print reversed name
#### Exercise 69: Basic Unit Converter (Length)
def length_converter(meters):
return meters * 39.3701 # Convert to inches
meters = float(input("Enter length in meters: ")) # Input length
inches = length_converter(meters) # Convert
print("Length in inches:", inches) # Print length
#### Exercise 70: Simple Weather Fetcher (API)
import requests
def get_weather(city):
api_key = 'your_api_key' # Replace with your OpenWeatherMap API key
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = f"{base_url}q={city}&appid={api_key}&units=metric" # API
request
response = requests.get(complete_url) # Fetch data
return response.json() # Return response
city = input("Enter city name: ") # Input city name
weather_data = get_weather(city) # Fetch weather
print(weather_data) # Print weather data
#### Exercise 71: Simple JSON Reader
import json
def read_json(file_path):
with open(file_path, 'r') as file: # Open JSON file
return json.load(file) # Load and return data
json_file = input("Enter JSON file path: ") # Input file path
data = read_json(json_file) # Read JSON
print(data) # Print data
#### Exercise 72: Basic Web Scraper (BeautifulSoup)
import requests
from bs4 import BeautifulSoup
def web_scraper(url):
response = requests.get(url) # Fetch webpage
soup = BeautifulSoup(response.text, 'html.parser') # Parse HTML
return soup.title.string # Return title
url = input("Enter URL: ") # Input URL
title = web_scraper(url) # Scrape title
print("Page Title:", title) # Print title
#### Exercise 73: Basic URL Shortener (Using API)
import requests
def shorten_url(long_url):
api_url = "https://api.shrtcode.com/v2/shorten"
payload = {"url": long_url}
response = requests.post(api_url, json=payload) # API request
return response.json() # Return response
long_url = input("Enter long URL: ") # Input long URL
shortened = shorten_url(long_url) # Shorten URL
print("Shortened URL:", shortened.get("shortenedUrl")) # Print shortened URL
#### Exercise 74: Basic Image Resizer (Using PIL)
from PIL import Image
def resize_image(image_path, output_path, size):
img = Image.open(image_path) # Open image
img = img.resize(size) # Resize image
img.save(output_path) # Save resized image
image_path = input("Enter image path: ") # Input image path
output_path = input("Enter output path: ") # Input output path
size = tuple(map(int, input("Enter new size (width height): ").split())) # Input
new size
resize_image(image_path, output_path, size) # Resize image
print("Image resized and saved.") # Success message
#### Exercise 75: Simple Markdown to HTML Converter
def markdown_to_html(markdown_text):
return markdown_text.replace('# ', '<h1>').replace('\n', '</h1>\
n<p>').replace('**', '<b>').replace('*', '<i>') + '</p>' # Convert markdown to
HTML
markdown_input = input("Enter markdown text: ") # Input markdown text
html_output = markdown_to_html(markdown_input) # Convert
print("Converted HTML:\n", html_output) # Print converted HTML
#### Exercise 76: Simple XML Parser (Using ElementTree)
import xml.etree.ElementTree as ET
def parse_xml(file_path):
tree = ET.parse(file_path) # Parse XML file
return tree.getroot() # Return root element
xml_file = input("Enter XML file path: ") # Input file path
root = parse_xml(xml_file) # Parse XML
print("Root Element:", root.tag) # Print root element tag
#### Exercise 77: Simple Bar Chart (Using Matplotlib)
import matplotlib.pyplot as plt
def plot_bar_chart(data):
plt.bar(data.keys(), data.values()) # Create bar chart
plt.xlabel("Categories") # Label x-axis
plt.ylabel("Values") # Label y-axis
plt.title("Bar Chart") # Title
plt.show() # Show chart
data = {"A": 10, "B": 15, "C": 5} # Sample data
plot_bar_chart(data) # Plot bar chart
#### Exercise 78: Basic Chatbot
def chatbot():
print("Chatbot: Hi! How can I assist you today?")
while True:
user_input = input("You: ")
if user_input.lower() in ['exit', 'quit']:
print("Chatbot: Goodbye!")
break
else:
print("Chatbot: I'm here to help!") # Simple response
chatbot() # Start chatbot
#### Exercise 79: Basic PDF Reader
import PyPDF2
def read_pdf(file_path):
with open(file_path, 'rb') as file: # Open PDF file
reader = PyPDF2.PdfReader(file) # Create PDF reader
for page in reader.pages:
print(page.extract_text()) # Print page text
pdf_file = input("Enter PDF file path: ") # Input file path
read_pdf(pdf_file) # Read PDF
#### Exercise 80: Basic Email Sender (Using smtplib)
import smtplib
def send_email(to_address, subject, body):
with smtplib.SMTP('smtp.gmail.com', 587) as server: # Connect to Gmail server
server.starttls() # Secure the connection
server.login('
[email protected]', 'your_password') # Login
message = f'Subject: {subject}\n\n{body}' # Create message
server.sendmail('
[email protected]', to_address, message) # Send email
to_email = input("Enter recipient email: ") # Input recipient email
email_subject = input("Enter email subject: ") # Input email subject
email_body = input("Enter email body: ") # Input email body
send_email(to_email, email_subject, email_body) # Send email
print("Email sent!") # Success message
#### Exercise 80: Basic Email Sender (Using smtplib)
import smtplib
def send_email(to_address, subject, body):
with smtplib.SMTP('smtp.gmail.com', 587) as server: # Connect to Gmail server
server.starttls() # Secure the connection
server.login('
[email protected]', 'your_password') # Login
message = f'Subject: {subject}\n\n{body}' # Create message
server.sendmail('
[email protected]', to_address, message) # Send email
to_email = input("Enter recipient email: ") # Input recipient email
email_subject = input("Enter email subject: ") # Input email subject
email_body = input("Enter email body: ") # Input email body
send_email(to_email, email_subject, email_body) # Send email
print("Email sent!") # Success message
#### Exercise 81: Simple Number Sorting
def sort_numbers(numbers):
return sorted(numbers) # Return sorted list
numbers = [5, 2, 9, 1, 5, 6] # Example list
print("Sorted numbers:", sort_numbers(numbers)) # Print sorted numbers
#### Exercise 82: Basic Countdown Timer
import time
def countdown(seconds):
while seconds:
mins, secs = divmod(seconds, 60) # Convert seconds to minutes and seconds
timer = '{:02d}:{:02d}'.format(mins, secs) # Format timer
print(timer, end="\r") # Print timer
time.sleep(1) # Wait for a second
seconds -= 1
print("Time's up!")
countdown(10) # Countdown for 10 seconds
#### Exercise 83: Basic HTTP Request (Using requests)
import requests
def get_http_response(url):
response = requests.get(url) # Make HTTP GET request
return response.status_code # Return status code
url = "https://www.example.com" # Example URL
print("HTTP response code:", get_http_response(url)) # Print response code
#### Exercise 84: Simple Text File Writer
text_to_write = input("Enter text to write to file: ") # Input text
with open("output.txt", "w") as file: # Open file in write mode
file.write(text_to_write) # Write text
print("Text written to output.txt") # Success message
#### Exercise 85: Simple Text File Reader
with open("output.txt", "r") as file: # Open file in read mode
content = file.read() # Read content
print("File content:", content) # Print content
#### Exercise 86: Simple Image Downloader
import requests
def download_image(url, filename):
response = requests.get(url) # Download image
with open(filename, 'wb') as file: # Write image to file
file.write(response.content) # Save image
print("Image downloaded as", filename) # Success message
image_url = input("Enter image URL: ") # Input image URL
download_image(image_url, "downloaded_image.jpg") # Download image
#### Exercise 87: Basic Web Scraper (Using BeautifulSoup)
from bs4 import BeautifulSoup
def web_scraper(url):
response = requests.get(url) # Fetch webpage
soup = BeautifulSoup(response.text, 'html.parser') # Parse HTML
return soup.title.string # Return title
url = input("Enter URL: ") # Input URL
title = web_scraper(url) # Scrape title
print("Page Title:", title) # Print title
#### Exercise 88: Simple Rock-Paper-Scissors Game
import random
def rock_paper_scissors(user_choice):
options = ['rock', 'paper', 'scissors']
computer_choice = random.choice(options) # Random choice for computer
print("Computer chose:", computer_choice) # Print computer choice
if user_choice == computer_choice:
return "It's a tie!" # Tie condition
elif (user_choice == 'rock' and computer_choice == 'scissors') or \
(user_choice == 'paper' and computer_choice == 'rock') or \
(user_choice == 'scissors' and computer_choice == 'paper'):
return "You win!" # Win condition
else:
return "You lose!" # Loss condition
user_choice = input("Enter rock, paper, or scissors: ") # User choice
print(rock_paper_scissors(user_choice)) # Play game
#### Exercise 89: Basic Text-Based Adventure Game
def adventure_game():
print("You are in a dark room. There are doors to your left and right.")
choice = input("Do you want to go left or right? ").lower()
if choice == "left":
print("You found a treasure! You win!")
elif choice == "right":
print("You fell into a pit. Game over.")
else:
print("Invalid choice. Game over.")
adventure_game() # Start adventure game
#### Exercise 90: Basic Shape Area Calculator
def calculate_area(shape, **kwargs):
if shape == "rectangle":
return kwargs['width'] * kwargs['height'] # Area of rectangle
elif shape == "circle":
import math
return math.pi * (kwargs['radius'] ** 2) # Area of circle
elif shape == "triangle":
return 0.5 * kwargs['base'] * kwargs['height'] # Area of triangle
print("Area of rectangle:", calculate_area("rectangle", width=5, height=10)) #
Rectangle area
print("Area of circle:", calculate_area("circle", radius=5)) # Circle area
print("Area of triangle:", calculate_area("triangle", base=5, height=10)) #
Triangle area
#### Exercise 91: Simple Prime Number Checker
def is_prime(num):
if num <= 1:
return False # Not prime
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False # Not prime
return True # Is prime
print("Is 11 prime?", is_prime(11)) # Check if number is prime
#### Exercise 92: Basic Currency Converter
def currency_converter(amount, rate):
return amount * rate # Convert currency
amount = float(input("Enter amount in USD: ")) # Input amount
rate = float(input("Enter conversion rate to EUR: ")) # Input rate
print("Amount in EUR:", currency_converter(amount, rate)) # Print converted amount
#### Exercise 93: Simple Random Password Generator
import random
import string
def generate_password(length):
characters = string.ascii_letters + string.digits + string.punctuation #
Possible characters
return ''.join(random.choice(characters) for _ in range(length)) # Generate
password
password_length = int(input("Enter password length: ")) # Input length
print("Generated password:", generate_password(password_length)) # Print generated
password
#### Exercise 94: Basic Contact List Manager
contacts = {}
def add_contact(name, phone):
contacts[name] = phone # Add contact
def display_contacts():
for name, phone in contacts.items():
print(f"{name}: {phone}") # Print contacts
add_contact("Alice", "1234567890") # Add example contact
add_contact("Bob", "0987654321") # Add example contact
display_contacts() # Display contacts
#### Exercise 95: Basic Dice Roller
import random
def roll_dice():
return random.randint(1, 6) # Roll dice
print("You rolled a:", roll_dice()) # Roll and print result
#### Exercise 96: Basic Binary to Decimal Converter
def binary_to_decimal(binary_str):
return int(binary_str, 2) # Convert binary to decimal
binary_number = input("Enter a binary number: ") # Input binary number
print("Decimal value:", binary_to_decimal(binary_number)) # Print decimal value
#### Exercise 97: Simple Hexadecimal to Decimal Converter
def hexadecimal_to_decimal(hex_str):
return int(hex_str, 16) # Convert hexadecimal to decimal
hex_number = input("Enter a hexadecimal number: ") # Input hex number
print("Decimal value:", hexadecimal_to_decimal(hex_number)) # Print decimal value
#### Exercise 98: Basic List Deduplication
def remove_duplicates(lst):
return list(set(lst)) # Remove duplicates
sample_list = [1, 2, 2, 3, 4, 4, 5] # Sample list
print("List without duplicates:", remove_duplicates(sample_list)) # Print
deduplicated list
#### Exercise 99: Simple Markdown to HTML Converter
def markdown_to_html(markdown_text):
html = markdown_text.replace('# ', '<h1>').replace('\n', '</h1>\
n<p>').replace('**', '<b>').replace('*', '<i>') + '</p>' # Simple markdown to HTML
return html
markdown_input = input("Enter markdown text: ") # Input markdown text
print("Converted HTML:\n", markdown_to_html(markdown_input)) # Print converted
HTML
#### Exercise 100: Simple Command-Line Timer
import time
def simple_timer(seconds):
for i in range(seconds, 0, -1):
print(i)
time.sleep(1) # Wait for one second
print("Time's up!")
seconds = int(input("Enter number of seconds: ")) # Input seconds
simple_timer(seconds) # Start timer
#### Exercise 101: Simple Temperature Converter
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32 # Convert Celsius to Fahrenheit
celsius_temp = float(input("Enter temperature in Celsius: ")) # Input temperature
print("Temperature in Fahrenheit:", celsius_to_fahrenheit(celsius_temp)) # Print
converted temperature
#### Exercise 102: Simple Temperature Converter (Fahrenheit to Celsius)
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9 # Convert Fahrenheit to Celsius
fahrenheit_temp = float(input("Enter temperature in Fahrenheit: ")) # Input
temperature
print("Temperature in Celsius:", fahrenheit_to_celsius(fahrenheit_temp)) # Print
converted temperature
#### Exercise 103: Basic File Copying
import shutil
def copy_file(src, dest):
shutil.copy(src, dest) # Copy file
source_file = input("Enter source file path: ") # Input source path
destination_file = input("Enter destination file path: ") # Input destination path
copy_file(source_file, destination_file) # Copy file
print("File copied successfully.") # Success message
#### Exercise 104: Basic Image Viewer (Using PIL)
from PIL import Image
def show_image(image_path):
img = Image.open(image_path) # Open image
img.show() # Show image
image_path = input("Enter image path: ") # Input image path
show_image(image_path) # Show image
#### Exercise 105: Basic JSON Writer
import json
def write_json(data, file_path):
with open(file_path, 'w') as json_file: # Open file in write mode
json.dump(data, json_file) # Write data to JSON
data = {"name": "Alice", "age": 30} # Sample data
write_json(data, 'data.json') # Write data to JSON file
print("Data written to data.json") # Success message
#### Exercise 106: Basic JSON Reader
def read_json(file_path):
with open(file_path, 'r') as json_file: # Open file in read mode
return json.load(json_file) # Read data from JSON
data_read = read_json('data.json') # Read data from JSON file
print("Data read from JSON:", data_read) # Print read data
#### Exercise 107: Simple Word Counter
def count_words(text):
return len(text.split()) # Count words
input_text = input("Enter a text: ") # Input text
print("Word count:", count_words(input_text)) # Print word count
#### Exercise 108: Basic Simple Interest Calculator
def simple_interest(principal, rate, time):
return (principal * rate * time) / 100 # Calculate simple interest
p = float(input("Enter principal amount: ")) # Input principal
r = float(input("Enter rate of interest: ")) # Input rate
t = float(input("Enter time in years: ")) # Input time
print("Simple Interest:", simple_interest(p, r, t)) # Print interest
#### Exercise 109: Basic Compound Interest Calculator
def compound_interest(principal, rate, time):
return principal * ((1 + rate / 100) ** time) # Calculate compound interest
p = float(input("Enter principal amount: ")) # Input principal
r = float(input("Enter rate of interest: ")) # Input rate
t = float(input("Enter time in years: ")) # Input time
print("Compound Interest:", compound_interest(p, r, t)) # Print interest
#### Exercise 110: Simple Random Quote Generator
import random
quotes = [
"The greatest glory in living lies not in never falling, but in rising every
time we fall.",
"The way to get started is to quit talking and begin doing.",
"Life is what happens when you're busy making other plans."
]
print("Random Quote:", random.choice(quotes)) # Print random quote
#### Exercise 111: Basic URL Fetcher
def fetch_url(url):
response = requests.get(url) # Fetch URL
return response.text # Return content
url = input("Enter a URL: ") # Input URL
content = fetch_url(url) # Fetch content
print("Fetched content length:", len(content)) # Print length of content
#### Exercise 112: Simple File Deleter
import os
def delete_file(file_path):
os.remove(file_path) # Delete file
print("File deleted successfully.") # Success message
file_to_delete = input("Enter file path to delete: ") # Input file path
delete_file(file_to_delete) # Delete file
#### Exercise 113: Basic Number Guessing Game
import random
def number_guessing_game():
number_to_guess = random.randint(1, 20) # Random number
attempts = 0
while True:
guess = int(input("Guess a number between 1 and 20: ")) # User guess
attempts += 1
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
else:
print(f"Congratulations! You've guessed the number in {attempts}
attempts.")
break # End game
number_guessing_game() # Start game
#### Exercise 114: Simple Palindrome Checker
def is_palindrome(s):
return s == s[::-1] # Check if string is palindrome
input_string = input("Enter a string: ") # Input string
print(f"Is '{input_string}' a palindrome?", is_palindrome(input_string)) # Check
palindrome
#### Exercise 115: Basic Time Converter (Seconds to Minutes)
def seconds_to_minutes(seconds):
return seconds / 60 # Convert seconds to minutes
seconds_input = int(input("Enter seconds: ")) # Input seconds
print(f"{seconds_input} seconds is {seconds_to_minutes(seconds_input)} minutes.")
# Print conversion
#### Exercise 116: Simple Day of the Week Finder
import datetime
def day_of_week(date_string):
date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d') # Convert
string to date
return date_obj.strftime('%A') # Return day of the week
date_input = input("Enter a date (YYYY-MM-DD): ") # Input date
print("Day of the week:", day_of_week(date_input)) # Print day
#### Exercise 117: Simple Age Calculator
def calculate_age(birth_year):
current_year = datetime.datetime.now().year # Get current year
return current_year - birth_year # Calculate age
birth_year_input = int(input("Enter your birth year: ")) # Input birth year
print("Your age is:", calculate_age(birth_year_input)) # Print age
#### Exercise 118: Basic Sum of Even Numbers
def sum_of_even_numbers(n):
return sum(i for i in range(n + 1) if i % 2 == 0) # Sum even numbers
n_input = int(input("Enter a number: ")) # Input number
print("Sum of even numbers up to", n_input, "is:", sum_of_even_numbers(n_input)) #
Print sum
#### Exercise 119: Basic Sum of Odd Numbers
def sum_of_odd_numbers(n):
return sum(i for i in range(n + 1) if i % 2 != 0) # Sum odd numbers
n_input = int(input("Enter a number: ")) # Input number
print("Sum of odd numbers up to", n_input, "is:", sum_of_odd_numbers(n_input)) #
Print sum
#### Exercise 120: Simple Histogram Plotting
import matplotlib.pyplot as plt
def plot_histogram(data):
plt.hist(data, bins=10) # Plot histogram
plt.xlabel("Values") # Label x-axis
plt.ylabel("Frequency") # Label y-axis
plt.title("Histogram") # Title
plt.show() # Show plot
data_sample = [1, 2, 2, 3, 3, 3, 4, 5] # Sample data
plot_histogram(data_sample) # Plot histogram
#### Exercise 121: Basic Character Frequency Counter
def char_frequency(text):
frequency = {}
for char in text:
frequency[char] = frequency.get(char, 0) + 1 # Count characters
return frequency
input_text = input("Enter a text: ") # Input text
print("Character frequency:", char_frequency(input_text)) # Print frequency
#### Exercise 122: Basic Anagram Checker
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2) # Check if two strings are anagrams
string1 = input("Enter first string: ") # Input first string
string2 = input("Enter second string: ") # Input second string
print(f"Are '{string1}' and '{string2}' anagrams?", are_anagrams(string1, string2))
# Check anagrams
#### Exercise 123: Basic String Compression
def compress_string(s):
compressed = []
count = 1
for i in range(1, len(s)):
if s[i] == s[i - 1]:
count += 1 # Increment count
else:
compressed.append(s[i - 1] + str(count)) # Append compressed part
count = 1
compressed.append(s[-1] + str(count)) # Append last part
return ''.join(compressed)
input_string = input("Enter a string to compress: ") # Input string
print("Compressed string:", compress_string(input_string)) # Print compressed
string
#### Exercise 124: Simple CSV Writer
import csv
def write_csv(data, filename):
with open(filename, 'w', newline='') as csvfile: # Open file in write mode
writer = csv.writer(csvfile) # Create CSV writer
for row in data:
writer.writerow(row) # Write row
data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]] # Sample data
write_csv(data, 'data.csv') # Write data to CSV
print("Data written to data.csv") # Success message
#### Exercise 125: Simple CSV Reader
def read_csv(filename):
with open(filename, 'r') as csvfile: # Open file in read mode
reader = csv.reader(csvfile) # Create CSV reader
return list(reader) # Return list of rows
data_read = read_csv('data.csv') # Read data from CSV
print("Data read from CSV:", data_read) # Print read data
#### Exercise 126: Basic URL Shortener (Using pyshorteners)
import pyshorteners
def shorten_url(url):
s = pyshorteners.Shortener() # Create shortener
return s.tinyurl.short(url) # Shorten URL
url_to_shorten = input("Enter URL to shorten: ") # Input URL
short_url = shorten_url(url_to_shorten) # Shorten URL
print("Shortened URL:", short_url) # Print shortened URL
#### Exercise 127: Simple Phone Number Validator
import re
def is_valid_phone_number(phone):
pattern = re.compile(r'^\+?1?\d{9,15}$') # Define pattern
return bool(pattern.match(phone)) # Validate number
phone_input = input("Enter a phone number: ") # Input phone number
print("Is valid phone number?", is_valid_phone_number(phone_input)) # Validate
#### Exercise 128: Basic Email Validator
def is_valid_email(email):
pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$') #
Define pattern
return bool(pattern.match(email)) # Validate email
email_input = input("Enter an email: ") # Input email
print("Is valid email?", is_valid_email(email_input)) # Validate
#### Exercise 129: Basic File Extension Checker
import os
def check_file_extension(filename, extension):
return filename.endswith(extension) # Check file extension
file_name = input("Enter file name: ") # Input file name
ext = input("Enter file extension (with dot): ") # Input extension
print(f"Does '{file_name}' have the extension '{ext}'?",
check_file_extension(file_name, ext)) # Check
#### Exercise 130: Simple Text Search
def text_search(text, search_term):
return text.count(search_term) # Count occurrences
input_text = input("Enter a text: ") # Input text
search_term = input("Enter search term: ") # Input search term
print(f"'{search_term}' found {text_search(input_text, search_term)} times.") #
Search term occurrences
#### Exercise 131: Basic Currency Exchange Rate Fetcher
import requests
def fetch_exchange_rate(base_currency, target_currency):
response =
requests.get(f'https://api.exchangerate-api.com/v4/latest/{base_currency}') #
Fetch exchange rate
data = response.json() # Parse JSON
return data['rates'].get(target_currency, "Currency not found") # Get rate
base = input("Enter base currency (e.g. USD): ") # Input base currency
target = input("Enter target currency (e.g. EUR): ") # Input target currency
print(f"Exchange rate from {base} to {target}: {fetch_exchange_rate(base,
target)}") # Print rate
#### Exercise 132: Basic URL Query Parameter Builder
from urllib.parse import urlencode
def build_url(base_url, params):
return f"{base_url}?{urlencode(params)}" # Build URL with query parameters
base_url_input = input("Enter base URL: ") # Input base URL
params_input = input("Enter query parameters as key=value pairs (comma separated):
") # Input params
params_dict = dict(pair.split('=') for pair in params_input.split(',')) # Convert
to dict
print("Built URL:", build_url(base_url_input, params_dict)) # Print URL
#### Exercise 133: Basic File Downloader
def download_file(url):
response = requests.get(url) # Fetch file
filename = url.split("/")[-1] # Get file name
with open(filename, 'wb') as file: # Write file
file.write(response.content) # Save content
print("File downloaded:", filename) # Success message
file_url = input("Enter file URL: ") # Input file URL
download_file(file_url) # Download file
#### Exercise 134: Basic Data Merger
def merge_data(data1, data2):
return {**data1, **data2} # Merge dictionaries
data_one = {"name": "Alice", "age": 30} # Sample data
data_two = {"city": "Wonderland", "age": 25} # Sample data
print("Merged data:", merge_data(data_one, data_two)) # Print merged data
#### Exercise 135: Basic Key-Value Store
class KeyValueStore:
def __init__(self):
self.store = {} # Initialize store
def set_value(self, key, value):
self.store[key] = value # Set key-value pair
def get_value(self, key):
return self.store.get(key, "Key not found") # Get value
kv_store = KeyValueStore() # Create key-value store
kv_store.set_value("name", "Alice") # Set value
print("Stored name:", kv_store.get_value("name")) # Get value
#### Exercise 136: Simple To-Do List Manager
class TodoList:
def __init__(self):
self.tasks = [] # Initialize task list
def add_task(self, task):
self.tasks.append(task) # Add task
def show_tasks(self):
return self.tasks # Show tasks
todo_list = TodoList() # Create to-do list
todo_list.add_task("Learn Python") # Add task
print("Tasks:", todo_list.show_tasks()) # Show tasks
#### Exercise 137: Basic Event Logger
class EventLogger:
def __init__(self):
self.events = [] # Initialize event list
def log_event(self, event):
self.events.append(event) # Log event
def show_events(self):
return self.events # Show events
event_logger = EventLogger() # Create event logger
event_logger.log_event("User logged in") # Log event
print("Events:", event_logger.show_events()) # Show events
#### Exercise 138: Basic Recipe Manager
class RecipeManager:
def __init__(self):
self.recipes = {} # Initialize recipe collection
def add_recipe(self, name, ingredients):
self.recipes[name] = ingredients # Add recipe
def get_recipe(self, name):
return self.recipes.get(name, "Recipe not found") # Get recipe
recipe_manager = RecipeManager() # Create recipe manager
recipe_manager.add_recipe("Pancakes", ["Flour", "Eggs", "Milk"]) # Add recipe
print("Pancake recipe:", recipe_manager.get_recipe("Pancakes")) # Get recipe
#### Exercise 139: Simple Reminder System
import time
def reminder_system(reminder, delay):
time.sleep(delay) # Wait for delay
print("Reminder:", reminder) # Print reminder
reminder_text = input("Enter reminder: ") # Input reminder
reminder_time = int(input("Enter delay in seconds: ")) # Input delay
reminder_system(reminder_text, reminder_time) # Set reminder
#### Exercise 140: Basic Quiz Application
class Quiz:
def __init__(self):
self.questions = [] # Initialize question list
def add_question(self, question, answer):
self.questions.append((question, answer)) # Add question
def take_quiz(self):
score = 0
for question, answer in self.questions:
user_answer = input(question + " ")
if user_answer.lower() == answer.lower():
score += 1 # Increment score
print("Your score is:", score) # Print score
quiz_app = Quiz() # Create quiz application
quiz_app.add_question("What is the capital of France?", "Paris") # Add question
quiz_app.take_quiz() # Take quiz
#### Exercise 141: Basic User Registration System
class UserRegistration:
def __init__(self):
self.users = [] # Initialize user list
def register_user(self, username, password):
self.users.append({"username": username, "password": password}) # Register
user
print("User registered:", username) # Success message
user_registration = UserRegistration() # Create user registration system
user_registration.register_user("alice", "password123") # Register user
#### Exercise 142: Basic Shopping Cart
class ShoppingCart:
def __init__(self):
self.items = [] # Initialize cart items
def add_item(self, item):
self.items.append(item) # Add item
def show_cart(self):
return self.items # Show cart items
shopping_cart = ShoppingCart() # Create shopping cart
shopping_cart.add_item("Apple") # Add item
print("Cart items:", shopping_cart.show_cart()) # Show cart items
#### Exercise 143: Basic Student Management System
class Student:
def __init__(self, name, age):
self.name = name # Initialize name
self.age = age # Initialize age
class StudentManagement:
def __init__(self):
self.students = [] # Initialize student list
def add_student(self, student):
self.students.append(student) # Add student
def show_students(self):
return [(student.name, student.age) for student in self.students] # Show
students
student_management = StudentManagement() # Create student management system
student_management.add_student(Student("Alice", 20)) # Add student
print("Students:", student_management.show_students()) # Show students
#### Exercise 144: Basic URL Request Logger
class URLRequestLogger:
def __init__(self):
self.requests = [] # Initialize request log
def log_request(self, url):
self.requests.append(url) # Log URL
def show_requests(self):
return self.requests # Show requests
url_logger = URLRequestLogger() # Create request logger
url_logger.log_request("https://api.example.com/data") # Log URL
print("Logged requests:", url_logger.show_requests()) # Show requests
#### Exercise 145: Basic Music Playlist Manager
class Playlist:
def __init__(self):
self.songs = [] # Initialize song list
def add_song(self, title):
self.songs.append(title) # Add song
def show_playlist(self):
return self.songs # Show playlist
playlist_manager = Playlist() # Create playlist manager
playlist_manager.add_song("Song A") # Add song
print("Playlist:", playlist_manager.show_playlist()) # Show playlist
#### Exercise 146: Basic Product Catalog
class Product:
def __init__(self, name, price):
self.name = name # Initialize name
self.price = price # Initialize price
class ProductCatalog:
def __init__(self):
self.products = [] # Initialize product list
def add_product(self, product):
self.products.append(product) # Add product
def show_catalog(self):
return [(product.name, product.price) for product in self.products] # Show
products
catalog = ProductCatalog() # Create product catalog
catalog.add_product(Product("Laptop", 1000)) # Add product
print("Product Catalog:", catalog.show_catalog()) # Show catalog
#### Exercise 147: Basic Contact Manager
class Contact:
def __init__(self, name, phone):
self.name = name # Initialize name
self.phone = phone # Initialize phone
class ContactManager:
def __init__(self):
self.contacts = [] # Initialize contact list
def add_contact(self, contact):
self.contacts.append(contact) # Add contact
def show_contacts(self):
return [(contact.name, contact.phone) for contact in self.contacts] # Show
contacts
contact_manager = ContactManager() # Create contact manager
contact_manager.add_contact(Contact("Alice", "1234567890")) # Add contact
print("Contacts:", contact_manager.show_contacts()) # Show contacts
#### Exercise 148: Simple Weather Fetcher
def fetch_weather(city):
api_key = 'your_api_key' # Replace with your API key
response = requests.get(f'http://api.openweathermap.org/data/2.5/weather?
q={city}&appid={api_key}&units=metric') # Fetch weather
return response.json() # Return weather data
city_input = input("Enter city name: ") # Input city name
weather_data = fetch_weather(city_input) # Fetch weather
print("Weather data:", weather_data) # Print weather data
#### Exercise 149: Simple Markdown to HTML Converter
import markdown
def convert_markdown_to_html(markdown_text):
return markdown.markdown(markdown_text) # Convert to HTML
markdown_input = input("Enter Markdown text: ") # Input Markdown text
print("HTML output:", convert_markdown_to_html(markdown_input)) # Print HTML
#### Exercise 150: Simple Password Generator
import random
import string
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation #
Character set
return ''.join(random.choice(characters) for _ in range(length)) # Generate
password
password_length = int(input("Enter password length: ")) # Input length
print("Generated password:", generate_password(password_length)) # Print password
#### Exercise 151: Basic Image Resizer (Using PIL)
from PIL import Image
def resize_image(image_path, output_path, size):
img = Image.open(image_path) # Open image
img = img.resize(size) # Resize image
img.save(output_path) # Save resized image
print(f"Image saved as {output_path}") # Success message
input_image_path = input("Enter input image path: ") # Input image path
output_image_path = input("Enter output image path: ") # Input output path
new_size = tuple(map(int, input("Enter new size as width,height: ").split(','))) #
Input new size
resize_image(input_image_path, output_image_path, new_size) # Resize image
#### Exercise 152: Basic PDF Reader (Using PyPDF2)
import PyPDF2
def read_pdf(file_path):
with open(file_path, 'rb') as file: # Open PDF file
reader = PyPDF2.PdfReader(file) # Create PDF reader
for page in reader.pages:
print(page.extract_text()) # Print page text
pdf_file_path = input("Enter PDF file path: ") # Input PDF file path
read_pdf(pdf_file_path) # Read PDF
#### Exercise 153: Basic QR Code Generator (Using qrcode)
import qrcode
def generate_qr_code(data, output_path):
img = qrcode.make(data) # Generate QR code
img.save(output_path) # Save QR code image
print(f"QR code saved as {output_path}") # Success message
data_to_encode = input("Enter data to encode in QR code: ") # Input data
output_qr_path = input("Enter output path for QR code: ") # Input output path
generate_qr_code(data_to_encode, output_qr_path) # Generate QR code
#### Exercise 154: Basic Web Scraper
import requests
from bs4 import BeautifulSoup
def scrape_website(url):
response = requests.get(url) # Fetch URL
soup = BeautifulSoup(response.text, 'html.parser') # Parse HTML
return soup.title.string # Return page title
url_to_scrape = input("Enter URL to scrape: ") # Input URL
print("Page title:", scrape_website(url_to_scrape)) # Print title
#### Exercise 155: Simple Image Downloader
def download_image(url):
response = requests.get(url) # Fetch image
filename = url.split("/")[-1] # Get file name
with open(filename, 'wb') as file: # Write image
file.write(response.content) # Save content
print("Image downloaded:", filename) # Success message
image_url = input("Enter image URL: ") # Input image URL
download_image(image_url) # Download image
#### Exercise 156: Simple Graph Plotter (Using Matplotlib)
import matplotlib.pyplot as plt
def plot_graph(x, y):
plt.plot(x, y) # Plot graph
plt.xlabel("X-axis") # Label x-axis
plt.ylabel("Y-axis") # Label y-axis
plt.title("Simple Graph") # Title
plt.show() # Show plot
x_values = [1, 2, 3, 4, 5] # Sample x values
y_values = [2, 3, 5, 7, 11] # Sample y values
plot_graph(x_values, y_values) # Plot graph
#### Exercise 157: Basic Data Visualizer (Using Seaborn)
import seaborn as sns
import matplotlib.pyplot as plt
def visualize_data(data):
sns.histplot(data, bins=10) # Visualize data
plt.title("Data Visualization") # Title
plt.show() # Show plot
data_sample = [1, 2, 2, 3, 3, 3, 4, 5] # Sample data
visualize_data(data_sample) # Visualize data
#### Exercise 158: Basic Chatbot (Using NLTK)
import nltk
def simple_chatbot(user_input):
if "hello" in user_input.lower():
return "Hello! How can I help you?"
return "I'm not sure how to respond to that."
user_input = input("You: ") # Input user message
print("Chatbot:", simple_chatbot(user_input)) # Chatbot response
#### Exercise 159: Basic Text Summarizer (Using Gensim)
from gensim.summarization import summarize
def summarize_text(text):
return summarize(text) # Summarize text
text_input = input("Enter text to summarize: ") # Input text
print("Summary:", summarize_text(text_input)) # Print summary
#### Exercise 160: Basic News Fetcher (Using News API)
import requests
def fetch_news(api_key, query):
response = requests.get(f'https://newsapi.org/v2/everything?
q={query}&apiKey={api_key}') # Fetch news
return response.json() # Return news data
api_key = 'your_api_key' # Replace with your API key
news_query = input("Enter news topic: ") # Input news topic
print("News data:", fetch_news(api_key, news_query)) # Print news data
#### Exercise 161: Basic File Type Checker
import os
def check_file_type(filename):
return os.path.splitext(filename)[1] # Get file extension
file_name_input = input("Enter file name: ") # Input file name
print("File type:", check_file_type(file_name_input)) # Print file type
#### Exercise 162: Basic Time Calculator
from datetime import datetime, timedelta
def time_calculator(start_time, duration):
start = datetime.strptime(start_time, '%H:%M') # Convert string to datetime
end_time = start + timedelta(minutes=duration) # Calculate end time
return end_time.strftime('%H:%M') # Return end time as string
start_time_input = input("Enter start time (HH:MM): ") # Input start time
duration_input = int(input("Enter duration in minutes: ")) # Input duration
print("End time:", time_calculator(start_time_input, duration_input)) # Print end
time
#### Exercise 163: Basic Fibonacci Sequence Generator
def fibonacci(n):
seq = [0, 1] # Initialize Fibonacci sequence
for i in range(2, n):
seq.append(seq[i - 1] + seq[i - 2]) # Generate next Fibonacci number
return seq[:n] # Return first n Fibonacci numbers
n_terms = int(input("Enter number of terms in Fibonacci sequence: ")) # Input
terms
print("Fibonacci sequence:", fibonacci(n_terms)) # Print sequence
#### Exercise 164: Basic Character Counter
def char_counter(text):
return {char: text.count(char) for char in set(text)} # Count characters
input_text = input("Enter a text: ") # Input text
print("Character count:", char_counter(input_text)) # Print character count
#### Exercise 165: Basic Prime Number Checker
def is_prime(n):
if n <= 1:
return False # Numbers less than or equal to 1 are not prime
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False # Found a divisor, not prime
return True # No divisors found, it is prime
number_to_check = int(input("Enter a number to check if it is prime: ")) # Input
number
print(f"{number_to_check} is prime:", is_prime(number_to_check)) # Check prime
#### Exercise 166: Basic Anagram Checker
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2) # Compare sorted characters
first_string = input("Enter first string: ") # Input first string
second_string = input("Enter second string: ") # Input second string
print("Are anagrams:", are_anagrams(first_string, second_string)) # Check anagrams
#### Exercise 167: Basic Histogram Plotter (Using Matplotlib)
import matplotlib.pyplot as plt
def plot_histogram(data):
plt.hist(data, bins=10) # Create histogram
plt.title("Histogram") # Title
plt.xlabel("Values") # X-axis label
plt.ylabel("Frequency") # Y-axis label
plt.show() # Show plot
data_input = list(map(int, input("Enter numbers separated by space: ").split())) #
Input data
plot_histogram(data_input) # Plot histogram
#### Exercise 168: Basic String Reverser
def reverse_string(s):
return s[::-1] # Reverse string
string_to_reverse = input("Enter a string to reverse: ") # Input string
print("Reversed string:", reverse_string(string_to_reverse)) # Print reversed
string
#### Exercise 169: Basic Palindrome Checker
def is_palindrome(s):
return s == s[::-1] # Check if string is the same forwards and backwards
string_to_check = input("Enter a string to check for palindrome: ") # Input string
print(f"{string_to_check} is a palindrome:", is_palindrome(string_to_check)) #
Check palindrome
#### Exercise 170: Basic Rock, Paper, Scissors Game
import random
def play_rps(user_choice):
options = ["rock", "paper", "scissors"] # Possible choices
computer_choice = random.choice(options) # Computer's choice
if user_choice == computer_choice:
return "It's a tie!"
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
return "You win!"
else:
return "Computer wins!"
user_choice_input = input("Enter rock, paper, or scissors: ") # Input user's
choice
print(play_rps(user_choice_input)) # Play game
#### Exercise 171: Basic Voting System
class VotingSystem:
def __init__(self):
self.candidates = {} # Initialize candidates
def add_candidate(self, name):
self.candidates[name] = 0 # Add candidate with 0 votes
def vote(self, name):
if name in self.candidates:
self.candidates[name] += 1 # Increment vote
else:
print("Candidate not found!") # Handle error
def results(self):
return self.candidates # Return vote counts
voting_system = VotingSystem() # Create voting system
voting_system.add_candidate("Alice") # Add candidate
voting_system.add_candidate("Bob") # Add candidate
voting_system.vote("Alice") # Vote for Alice
voting_system.vote("Bob") # Vote for Bob
voting_system.vote("Alice") # Vote for Alice
print("Voting results:", voting_system.results()) # Print results
#### Exercise 172: Basic URL Checker
import re
def is_valid_url(url):
pattern = re.compile(r'^(http|https)://[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+') # URL
pattern
return bool(pattern.match(url)) # Validate URL
url_input = input("Enter a URL: ") # Input URL
print("Is valid URL?", is_valid_url(url_input)) # Check URL validity
#### Exercise 173: Basic Score Tracker
class ScoreTracker:
def __init__(self):
self.scores = [] # Initialize score list
def add_score(self, score):
self.scores.append(score) # Add score
def average_score(self):
return sum(self.scores) / len(self.scores) if self.scores else 0 #
Calculate average
score_tracker = ScoreTracker() # Create score tracker
score_tracker.add_score(85) # Add score
score_tracker.add_score(90) # Add score
print("Average score:", score_tracker.average_score()) # Print average score
#### Exercise 174: Basic Currency Converter
def currency_converter(amount, rate):
return amount * rate # Convert currency
amount_input = float(input("Enter amount in original currency: ")) # Input amount
conversion_rate = float(input("Enter conversion rate to target currency: ")) #
Input rate
print("Converted amount:", currency_converter(amount_input, conversion_rate)) #
Print converted amount
#### Exercise 175: Basic Text File Writer
def write_to_file(filename, text):
with open(filename, 'w') as file: # Open file in write mode
file.write(text) # Write text to file
print("Text written to file:", filename) # Success message
file_name_to_write = input("Enter filename to write to: ") # Input filename
text_to_write = input("Enter text to write: ") # Input text
write_to_file(file_name_to_write, text_to_write) # Write to file
#### Exercise 176: Basic Text File Reader
def read_from_file(filename):
with open(filename, 'r') as file: # Open file in read mode
return file.read() # Return file content
file_name_to_read = input("Enter filename to read from: ") # Input filename
print("File content:\n", read_from_file(file_name_to_read)) # Print content
#### Exercise 177: Basic Age Calculator
def calculate_age(birth_year):
current_year = 2024 # Current year
return current_year - birth_year # Calculate age
birth_year_input = int(input("Enter your birth year: ")) # Input year
print("Your age is:", calculate_age(birth_year_input)) # Print age
#### Exercise 178: Basic Factorial Calculator
def factorial(n):
if n == 0:
return 1 # 0! is 1
return n * factorial(n - 1) # Recursive calculation
number_to_factorial = int(input("Enter a number to calculate factorial: ")) #
Input number
print(f"Factorial of {number_to_factorial} is:", factorial(number_to_factorial)) #
Print factorial
#### Exercise 179: Basic Number Guessing Game
import random
def guessing_game():
number_to_guess = random.randint(1, 100) # Random number between 1 and 100
attempts = 0
while True:
guess = int(input("Guess a number between 1 and 100: ")) # User's guess
attempts += 1 # Increment attempts
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
else:
print(f"Congratulations! You've guessed the number {number_to_guess} in
{attempts} attempts.") # Success message
break
guessing_game() # Start game
#### Exercise 180: Basic Email Validator
import re
def is_valid_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$' # Email pattern
return re.match(pattern, email) is not None # Validate email
email_input = input("Enter an email address: ") # Input email
print("Is valid email?", is_valid_email(email_input)) # Check validity
#### Exercise 181: Basic Random Password Generator
import random
import string
def generate_random_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation #
Character set
return ''.join(random.choice(characters) for _ in range(length)) # Generate
password
password_length_input = int(input("Enter password length: ")) # Input length
print("Generated password:", generate_random_password(password_length_input)) #
Print password
#### Exercise 182: Basic URL Shortener (Simulated)
def shorten_url(url):
return "short.ly/" + str(hash(url)) # Simulated shortening
url_to_shorten = input("Enter URL to shorten: ") # Input URL
print("Shortened URL:", shorten_url(url_to_shorten)) # Print shortened URL
#### Exercise 183: Basic Stopwatch
import time
def stopwatch():
input("Press Enter to start the stopwatch") # Start prompt
start_time = time.time() # Start time
input("Press Enter to stop the stopwatch") # Stop prompt
elapsed_time = time.time() - start_time # Calculate elapsed time
print(f"Elapsed time: {elapsed_time:.2f} seconds") # Print elapsed time
stopwatch() # Run stopwatch
#### Exercise 184: Basic To-Do List
class TodoList:
def __init__(self):
self.tasks = [] # Initialize task list
def add_task(self, task):
self.tasks.append(task) # Add task
def show_tasks(self):
return self.tasks # Show tasks
todo_list = TodoList() # Create to-do list
todo_list.add_task("Learn Python") # Add task
todo_list.add_task("Build a project") # Add task
print("To-Do List:", todo_list.show_tasks()) # Show tasks
#### Exercise 185: Basic Image Viewer (Simulated)
def view_image(image_path):
print(f"Displaying image from: {image_path}") # Simulated display
image_path_input = input("Enter image path: ") # Input image path
view_image(image_path_input) # View image
#### Exercise 186: Basic Expense Tracker
class ExpenseTracker:
def __init__(self):
self.expenses = [] # Initialize expenses
def add_expense(self, amount):
self.expenses.append(amount) # Add expense
def total_expenses(self):
return sum(self.expenses) # Calculate total
expense_tracker = ExpenseTracker() # Create expense tracker
expense_tracker.add_expense(50) # Add expense
expense_tracker.add_expense(25) # Add expense
print("Total expenses:", expense_tracker.total_expenses()) # Print total expenses
#### Exercise 187: Basic Quiz Application
class Quiz:
def __init__(self):
self.questions = [] # Initialize questions
def add_question(self, question, answer):
self.questions.append((question, answer)) # Add question
def take_quiz(self):
score = 0 # Initialize score
for question, answer in self.questions:
user_answer = input(question + " ") # Ask question
if user_answer.lower() == answer.lower():
score += 1 # Increment score
return score # Return score
quiz_app = Quiz() # Create quiz application
quiz_app.add_question("What is the capital of France?", "Paris") # Add question
quiz_app.add_question("What is 2 + 2?", "4") # Add question
print("Your score:", quiz_app.take_quiz()) # Take quiz
#### Exercise 188: Basic Voting Eligibility Checker
def is_eligible_to_vote(age):
return age >= 18 # Check voting eligibility
age_input = int(input("Enter your age: ")) # Input age
print("Eligible to vote:", is_eligible_to_vote(age_input)) # Check eligibility
#### Exercise 189: Basic Weather App (Simulated)
def get_weather(city):
return f"The weather in {city} is sunny." # Simulated weather data
city_name_input = input("Enter city name: ") # Input city name
print(get_weather(city_name_input)) # Get weather
#### Exercise 190: Basic Math Quiz
class MathQuiz:
def __init__(self):
self.score = 0 # Initialize score
def ask_question(self):
num1, num2 = random.randint(1, 10), random.randint(1, 10) # Random numbers
answer = num1 + num2 # Correct answer
user_answer = int(input(f"What is {num1} + {num2}? ")) # Ask question
if user_answer == answer:
self.score += 1 # Increment score
print("Correct!")
else:
print(f"Wrong! The correct answer is {answer}.")
def get_score(self):
return self.score # Return score
math_quiz = MathQuiz() # Create math quiz
for _ in range(5): # 5 questions
math_quiz.ask_question() # Ask question
print("Your score:", math_quiz.get_score()) # Print score
#### Exercise 191: Basic Password Strength Checker
def check_password_strength(password):
if len(password) < 8:
return "Weak: Password is too short." # Weak password
if not any(char.isdigit() for char in password):
return "Weak: Password should have at least one number." # Weak password
if not any(char.isupper() for char in password):
return "Weak: Password should have at least one uppercase letter." # Weak
password
return "Strong password!" # Strong password
password_input = input("Enter a password to check its strength: ") # Input
password
print(check_password_strength(password_input)) # Check strength
#### Exercise 192: Basic URL Fetcher
import requests
def fetch_url(url):
response = requests.get(url) # Fetch URL
return response.text # Return content
url_to_fetch = input("Enter URL to fetch: ") # Input URL
print("Fetched content:", fetch_url(url_to_fetch)[:100]) # Print first 100
characters
#### Exercise 193: Basic Temperature Converter
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32 # Convert Celsius to Fahrenheit
celsius_input = float(input("Enter temperature in Celsius: ")) # Input Celsius
print("Temperature in Fahrenheit:", celsius_to_fahrenheit(celsius_input)) # Print
Fahrenheit
#### Exercise 194: Basic Character Replacement
def replace_characters(text, old_char, new_char):
return text.replace(old_char, new_char) # Replace characters
text_input = input("Enter text: ") # Input text
old_char_input = input("Enter character to replace: ") # Input character
new_char_input = input("Enter new character: ") # Input new character
print("Modified text:", replace_characters(text_input, old_char_input,
new_char_input)) # Print modified text
#### Exercise 195: Basic Number Sorter
def sort_numbers(numbers):
return sorted(numbers) # Sort numbers
numbers_input = list(map(int, input("Enter numbers separated by space: ").split()))
# Input numbers
print("Sorted numbers:", sort_numbers(numbers_input)) # Print sorted numbers
#### Exercise 196: Basic CSV Writer
import csv
def write_csv(filename, data):
with open(filename, 'w', newline='') as file: # Open file in write mode
writer = csv.writer(file) # Create CSV writer
writer.writerows(data) # Write data
print("Data written to CSV:", filename) # Success message
data_to_write = [["Name", "Age"], ["Alice", 30], ["Bob", 25]] # Sample data
csv_filename = input("Enter filename to write CSV: ") # Input filename
write_csv(csv_filename, data_to_write) # Write CSV
#### Exercise 197: Basic CSV Reader
import csv
def read_csv(filename):
with open(filename, 'r') as file: # Open file in read mode
reader = csv.reader(file) # Create CSV reader
return list(reader) # Return data as list
csv_filename_to_read = input("Enter filename to read CSV: ") # Input filename
print("CSV content:", read_csv(csv_filename_to_read)) # Print content
#### Exercise 198: Basic Email Sender (Simulated)
def send_email(to, subject, body):
print(f"Sending email to {to} with subject '{subject}' and body:\n{body}") #
Simulated send
email_to_input = input("Enter recipient email: ") # Input recipient
email_subject_input = input("Enter email subject: ") # Input subject
email_body_input = input("Enter email body: ") # Input body
send_email(email_to_input, email_subject_input, email_body_input) # Send email
#### Exercise 199: Basic Simple Interest Calculator
def calculate_simple_interest(principal, rate, time):
return (principal * rate * time) / 100 # Calculate interest
principal_input = float(input("Enter principal amount: ")) # Input principal
rate_input = float(input("Enter rate of interest: ")) # Input rate
time_input = float(input("Enter time in years: ")) # Input time
print("Simple Interest:", calculate_simple_interest(principal_input, rate_input,
time_input)) # Print interest
#### Exercise 200: Basic Greeting Card Generator
def greeting_card(name, occasion):
return f"Dear {name},\nWishing you a wonderful {occasion}!" # Generate card
message
recipient_name_input = input("Enter recipient name: ") # Input name
occasion_input = input("Enter occasion: ") # Input occasion
print(greeting_card(recipient_name_input, occasion_input)) # Print greeting card
message
#### Exercise 201: Basic Binary to Decimal Converter
def binary_to_decimal(binary):
return int(binary, 2) # Convert binary to decimal
binary_input = input("Enter a binary number: ") # Input binary
print("Decimal equivalent:", binary_to_decimal(binary_input)) # Print decimal
#### Exercise 202: Basic Decimal to Binary Converter
def decimal_to_binary(decimal):
return bin(decimal)[2:] # Convert decimal to binary
decimal_input = int(input("Enter a decimal number: ")) # Input decimal
print("Binary equivalent:", decimal_to_binary(decimal_input)) # Print binary
#### Exercise 203: Basic Prime Factorization
def prime_factors(n):
factors = [] # Initialize factors list
for i in range(2, n + 1):
while n % i == 0:
factors.append(i) # Append factor
n //= i # Reduce n
return factors # Return factors
number_for_factors = int(input("Enter a number to find its prime factors: ")) #
Input number
print("Prime factors:", prime_factors(number_for_factors)) # Print factors
#### Exercise 204: Basic GCD Calculator
def gcd(a, b):
while b:
a, b = b, a % b # Euclidean algorithm
return a # Return GCD
num1 = int(input("Enter first number: ")) # Input first number
num2 = int(input("Enter second number: ")) # Input second number
print("GCD:", gcd(num1, num2)) # Print GCD
#### Exercise 205: Basic LCM Calculator
def lcm(a, b):
return abs(a * b) // gcd(a, b) # Calculate LCM using GCD
num1_for_lcm = int(input("Enter first number for LCM: ")) # Input first number
num2_for_lcm = int(input("Enter second number for LCM: ")) # Input second number
print("LCM:", lcm(num1_for_lcm, num2_for_lcm)) # Print LCM
#### Exercise 206: Basic String Palindrome Checker
def is_string_palindrome(s):
return s == s[::-1] # Check palindrome
string_for_palindrome = input("Enter a string to check if it's a palindrome: ") #
Input string
print("Is palindrome:", is_string_palindrome(string_for_palindrome)) # Check
palindrome
#### Exercise 207: Basic Unique Element Finder
def unique_elements(lst):
return list(set(lst)) # Return unique elements
list_input = list(map(int, input("Enter numbers separated by space: ").split())) #
Input list
print("Unique elements:", unique_elements(list_input)) # Print unique elements
#### Exercise 208: Basic String Count Vowels
def count_vowels(s):
vowels = "aeiouAEIOU" # Vowel characters
return sum(1 for char in s if char in vowels) # Count vowels
text_input = input("Enter a string: ") # Input string
print("Number of vowels:", count_vowels(text_input)) # Print vowel count
#### Exercise 209: Basic Character Frequency Finder
def char_frequency(s):
return {char: s.count(char) for char in set(s)} # Count frequency of
characters
text_for_frequency = input("Enter a string: ") # Input string
print("Character frequency:", char_frequency(text_for_frequency)) # Print
frequency
#### Exercise 210: Basic Character Removal
def remove_char(s, char_to_remove):
return s.replace(char_to_remove, '') # Remove specified character
string_input = input("Enter a string: ") # Input string
char_to_remove_input = input("Enter character to remove: ") # Input character
print("Modified string:", remove_char(string_input, char_to_remove_input)) # Print
modified string
#### Exercise 211: Basic List Reversal
def reverse_list(lst):
return lst[::-1] # Reverse list
list_to_reverse = list(map(int, input("Enter numbers separated by space:
").split())) # Input list
print("Reversed list:", reverse_list(list_to_reverse)) # Print reversed list
#### Exercise 212: Basic List Sum
def sum_list(lst):
return sum(lst) # Calculate sum
list_for_sum = list(map(int, input("Enter numbers separated by space: ").split()))
# Input list
print("Sum of list:", sum_list(list_for_sum)) # Print sum
#### Exercise 213: Basic List Average
def average_list(lst):
return sum(lst) / len(lst) if lst else 0 # Calculate average
list_for_average = list(map(int, input("Enter numbers separated by space:
").split())) # Input list
print("Average of list:", average_list(list_for_average)) # Print average
#### Exercise 214: Basic List Min and Max
def min_max_list(lst):
return min(lst), max(lst) # Return min and max
list_for_min_max = list(map(int, input("Enter numbers separated by space:
").split())) # Input list
min_val, max_val = min_max_list(list_for_min_max) # Get min and max
print(f"Min: {min_val}, Max: {max_val}") # Print min and max
#### Exercise 215: Basic List Concatenation
def concatenate_lists(lst1, lst2):
return lst1 + lst2 # Concatenate two lists
list1_input = list(map(int, input("Enter first list of numbers separated by space:
").split())) # Input first list
list2_input = list(map(int, input("Enter second list of numbers separated by space:
").split())) # Input second list
print("Concatenated list:", concatenate_lists(list1_input, list2_input)) # Print
concatenated list
#### Exercise 216: Basic Dictionary Merge
def merge_dicts(dict1, dict2):
return {**dict1, **dict2} # Merge two dictionaries
dict1_input = {'a': 1, 'b': 2} # First dictionary
dict2_input = {'b': 3, 'c': 4} # Second dictionary
print("Merged dictionary:", merge_dicts(dict1_input, dict2_input)) # Print merged
dictionary
#### Exercise 217: Basic Dictionary Key Lookup
def lookup_key(dictionary, key):
return dictionary.get(key, "Key not found") # Lookup key
dictionary_input = {'a': 1, 'b': 2, 'c': 3} # Example dictionary
key_to_lookup = input("Enter key to lookup: ") # Input key
print("Value:", lookup_key(dictionary_input, key_to_lookup)) # Print value
#### Exercise 218: Basic List Intersection
def list_intersection(lst1, lst2):
return list(set(lst1) & set(lst2)) # Find intersection
list1_for_intersection = list(map(int, input("Enter first list of numbers separated
by space: ").split())) # Input first list
list2_for_intersection = list(map(int, input("Enter second list of numbers
separated by space: ").split())) # Input second list
print("Intersection:", list_intersection(list1_for_intersection,
list2_for_intersection)) # Print intersection
#### Exercise 219: Basic String Case Toggle
def toggle_case(s):
return s.swapcase() # Toggle case
string_to_toggle = input("Enter a string: ") # Input string
print("Toggled case string:", toggle_case(string_to_toggle)) # Print toggled case
#### Exercise 220: Basic String Splitter
def split_string(s, delimiter=' '):
return s.split(delimiter) # Split string by delimiter
string_to_split = input("Enter a string: ") # Input string
delimiter_input = input("Enter a delimiter (default is space): ") or ' ' # Input
delimiter
print("Split string:", split_string(string_to_split, delimiter_input)) # Print
split string
#### Exercise 221: Basic List Shuffling
import random
def shuffle_list(lst):
random.shuffle(lst) # Shuffle the list in place
return lst # Return shuffled list
list_to_shuffle = list(map(int, input("Enter numbers separated by space:
").split())) # Input list
print("Shuffled list:", shuffle_list(list_to_shuffle)) # Print shuffled list
#### Exercise 222: Basic Find the Second Largest Number
def second_largest(lst):
unique_numbers = list(set(lst)) # Remove duplicates
unique_numbers.sort() # Sort numbers
return unique_numbers[-2] if len(unique_numbers) >= 2 else None # Return
second largest
list_for_second_largest = list(map(int, input("Enter numbers separated by space:
").split())) # Input list
print("Second largest number:", second_largest(list_for_second_largest)) # Print
second largest
#### Exercise 223: Basic Factorial Calculation
def factorial(n):
if n == 0:
return 1 # 0! is 1
result = 1
for i in range(1, n + 1):
result *= i # Calculate factorial
return result # Return factorial
number_for_factorial = int(input("Enter a number to calculate its factorial: ")) #
Input number
print("Factorial:", factorial(number_for_factorial)) # Print factorial
#### Exercise 224: Basic Fibonacci Sequence
def fibonacci(n):
seq = [0, 1] # Initialize sequence
while len(seq) < n:
seq.append(seq[-1] + seq[-2]) # Generate next number
return seq[:n] # Return sequence up to n
length_of_fibonacci = int(input("Enter the length of Fibonacci sequence: ")) #
Input length
print("Fibonacci sequence:", fibonacci(length_of_fibonacci)) # Print sequence
#### Exercise 225: Basic Area of Circle
import math
def area_of_circle(radius):
return math.pi * radius ** 2 # Calculate area
radius_input = float(input("Enter radius of the circle: ")) # Input radius
print("Area of circle:", area_of_circle(radius_input)) # Print area
#### Exercise 226: Basic Temperature Converter (Fahrenheit to Celsius)
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9 # Convert Fahrenheit to Celsius
fahrenheit_input = float(input("Enter temperature in Fahrenheit: ")) # Input
Fahrenheit
print("Temperature in Celsius:", fahrenheit_to_celsius(fahrenheit_input)) # Print
Celsius
#### Exercise 227: Basic Number Guessing Game
import random
def number_guessing_game():
number_to_guess = random.randint(1, 100) # Random number
attempts = 0 # Initialize attempts
while True:
guess = int(input("Guess a number between 1 and 100: ")) # User input
attempts += 1 # Increment attempts
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
else:
print(f"Congratulations! You've guessed the number {number_to_guess} in
{attempts} attempts.") # Success message
break
number_guessing_game() # Start game
#### Exercise 228: Basic Vowel Count Function
def count_vowels(s):
vowels = "aeiouAEIOU" # Vowel characters
return sum(1 for char in s if char in vowels) # Count vowels
text_for_vowel_count = input("Enter a string to count vowels: ") # Input string
print("Number of vowels:", count_vowels(text_for_vowel_count)) # Print vowel count
#### Exercise 229: Basic Reverse a String
def reverse_string(s):
return s[::-1] # Reverse string
string_to_reverse = input("Enter a string to reverse: ") # Input string
print("Reversed string:", reverse_string(string_to_reverse)) # Print reversed
string
#### Exercise 230: Basic List Comprehension
def square_numbers(lst):
return [x ** 2 for x in lst] # Square each number in the list
list_for_squares = list(map(int, input("Enter numbers separated by space:
").split())) # Input list
print("Squared numbers:", square_numbers(list_for_squares)) # Print squared
numbers
#### Exercise 231: Basic Remove Duplicates from List
def remove_duplicates(lst):
return list(set(lst)) # Remove duplicates
list_with_duplicates = list(map(int, input("Enter numbers separated by space (with
duplicates): ").split())) # Input list
print("List without duplicates:", remove_duplicates(list_with_duplicates)) # Print
list
#### Exercise 232: Basic String Joiner
def join_strings(lst, delimiter=' '):
return delimiter.join(lst) # Join strings with delimiter
list_of_strings = input("Enter strings separated by space: ").split() # Input
strings
delimiter_input = input("Enter a delimiter (default is space): ") or ' ' # Input
delimiter
print("Joined string:", join_strings(list_of_strings, delimiter_input)) # Print
joined string
#### Exercise 233: Basic Word Count Function
def count_words(s):
return len(s.split()) # Count words
text_for_word_count = input("Enter a string to count words: ") # Input string
print("Number of words:", count_words(text_for_word_count)) # Print word count
#### Exercise 234: Basic List Rotation
def rotate_list(lst, k):
k = k % len(lst) # Handle rotation greater than length
return lst[-k:] + lst[:-k] # Rotate list
list_to_rotate = list(map(int, input("Enter numbers separated by space:
").split())) # Input list
k_input = int(input("Enter number of positions to rotate: ")) # Input rotation
print("Rotated list:", rotate_list(list_to_rotate, k_input)) # Print rotated list
#### Exercise 235: Basic File Writer
def write_to_file(filename, content):
with open(filename, 'w') as file: # Open file in write mode
file.write(content) # Write content to file
print(f"Content written to {filename}") # Success message
file_name = input("Enter filename to write: ") # Input filename
file_content = input("Enter content to write: ") # Input content
write_to_file(file_name, file_content) # Write to file
#### Exercise 236: Basic File Reader
def read_from_file(filename):
with open(filename, 'r') as file: # Open file in read mode
return file.read() # Read content
file_name_to_read = input("Enter filename to read: ") # Input filename
print("File content:", read_from_file(file_name_to_read)) # Print content
#### Exercise 237: Basic Simple Calculator
def simple_calculator(a, b, operation):
if operation == '+':
return a + b # Addition
elif operation == '-':
return a - b # Subtraction
elif operation == '*':
return a * b # Multiplication
elif operation == '/':
return a / b if b != 0 else "Division by zero!" # Division
else:
return "Invalid operation" # Invalid operation
num1 = float(input("Enter first number: ")) # Input first number
num2 = float(input("Enter second number: ")) # Input second number
operation_input = input("Enter operation (+, -, *, /): ") # Input operation
print("Result:", simple_calculator(num1, num2, operation_input)) # Print result
#### Exercise 238: Basic Prime Number Checker
def is_prime(n):
if n < 2:
return False # Numbers less than 2 are not prime
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False # Found a divisor, not prime
return True # No divisors found, it's prime
number_to_check = int(input("Enter a number to check if it's prime: ")) # Input
number
print("Is prime:", is_prime(number_to_check)) # Check prime
#### Exercise 239: Basic Palindrome Checker
def is_palindrome(s):
return s == s[::-1] # Check if string is the same forwards and backwards
string_to_check = input("Enter a string to check if it's a palindrome: ") # Input
string
print("Is palindrome:", is_palindrome(string_to_check)) # Check palindrome
#### Exercise 240: Basic Count Down Timer
import time
def countdown_timer(seconds):
for i in range(seconds, 0, -1): # Count down
print(i)
time.sleep(1) # Wait for 1 second
print("Time's up!") # End message
seconds_input = int(input("Enter number of seconds for countdown: ")) # Input
seconds
countdown_timer(seconds_input) # Start countdown
# End of exercises
# These exercises add more variety and complexity, covering topics such as file
handling, mathematical calculations, and list manipulations. Feel free to copy and
run them, and let me know if you want additional exercises
# or specific topics!
# # # Exercise 8: Function Definition
# # # Task: Write a function that takes two numbers and returns their product.
# # # product means multiply
# # # This program defines a function to multiply two numbers
# def multiply(num1, num2):
# """Return the product of num1 and num2."""
# return num1 * num2 # Return the product
# # Get input from the user
# num1 = float(input("Enter the first number: ")) # Convert the input to a float
# num2 = float(input("Enter the second number: ")) # Convert the input to a float
# # Call the function and print the result
# result = multiply(num1, num2)
# print("The product is:", result) # Output the product
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# result = display_message("Hello!") # Output: Hello!
# print(result) # Output: None (because nothing is returned)
# def add_item_to_list(lst, item):
# lst.append(item) # Adds the item to the list directly (modifying in place)
# my_list = [1, 2, 3]
# add_item_to_list(my_list, 4) # Calling the function to add an item
# print(my_list) # Output: [1, 2, 3, 4] (the original list has been modified)
# creating our function
def add_user_number_to_orginal_list(list_number, user_number):
list_number.append(user_number) # Adds the item to the list directly
(modifying in place)
orginal_list = [1, 2, 3]
# finiched function now
# Get user input for the item to add, converting it to the appropriate type (int or
str)
user_input = input(" orginal_list = [1, 2, 3], add to the list: ")
# You can choose to convert it to int if you expect integer inputs
# Uncomment the line below to convert to int
user_input = int(user_input)
add_user_number_to_orginal_list(orginal_list, user_input) # Calling the function
to add the user input
print("Updated list:", orginal_list) # Output the modified list
# fix values in your function
def multiply(num1, num2):
"""Return the product of num1 and num2."""
return num1 * num2 # Return the product
# Call the function and print the result
result = multiply(5, 10) # Call the multiply function
print("The product is:", result) # Output the product
# You can modify the code to accept user input for the numbers instead of
# using fixed values like 5 and 10. Here’s how you can do it:
def multiply(num1, num2):
"""Return the product of num1 and num2."""
return num1 * num2 # Return the product
# Get input from the user
num1 = float(input("Enter the first number: ")) # Convert the input to a float
num2 = float(input("Enter the second number: ")) # Convert the input to a float
# Call the function and print the result
result = multiply(num1, num2)
print("The product is:", result) # Output the product
# In this version, the program prompts the user to enter two numbers,
# multiplies them, and then displays the result.
# Share
# You said:
# def multiply(num1, num2):
# """Return the product of num1 and num2."""
# return num1 * num2 # Return the product
# # Call the function and print the result
# result = multiply(5, 10) # Call the multiply function
# print("The product is:", result) # Output the product change it for user
input for he wasted number not 5 and 10 only
# ChatGPT said:
# ChatGPT
# You can modify the code to accept user input for the numbers instead of using
fixed values like 5 and 10. Here’s how you can do it:
# python
# Copy code
# def multiply(num1, num2):
# """Return the product of num1 and num2."""
# return num1 * num2 # Return the product
# # Get input from the user
# num1 = float(input("Enter the first number: ")) # Convert the input to a float
# num2 = float(input("Enter the second number: ")) # Convert the input to a float
# # Call the function and print the result
# result = multiply(num1, num2)
# print("The product is:", result) # Output the product
# In this version, the program prompts the user to enter two numbers, multiplies
them, and then displays the result.
# You said:
# def multiply(num1, num2):
# """Return the product of num1 and num2."""
# return num1 * num2 # Return the product , what goes wrong without return
# ChatGPT said:
# ChatGPT
# In Python, the return statement is crucial when you want a function to give back
a result to the part of the program that called it. If you don't use return, the
function won't output the result to be used elsewhere.
# What happens without return:
# No Output from the Function: If you don't use return, the function won't provide
any result, and instead, it will implicitly return None. This means that when you
call the function, you won't get the expected multiplication result back.
# Example Without return:
# python
# Copy code
# def multiply(num1, num2):
# # Just performs multiplication but doesn't return the result
# num1 * num2
# result = multiply(5, 10) # Call the multiply function
# print("The product is:", result) # Output the product
# Output:
# python
# Copy code
# The product is: None
# Here, since there is no return, the function does the multiplication but doesn't
return the result, so result becomes None.
# Why return is Important:
# It gives back the value (in this case, the product of the two numbers) to
wherever the function was called.
# Without return, you can't access the computed value outside the function.
# So, when you want the result of an operation to be available outside the
function, you must use return.
# You said:
# The product is: None is usefull where
# ChatGPT said:
# ChatGPT
# The result None is useful in specific cases where a function doesn’t need to
return any value. It’s often used for functions that perform an action (like
printing, logging, or modifying data in place) but don’t need to give back a
result.
# Here are a few scenarios where None can be useful:
# 1. Side-Effect Functions (No Return Expected):
# Some functions are designed to perform a task, such as printing or updating a
global state, without returning anything. In these cases, the function implicitly
returns None.
# python
# Copy code
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# result = display_message("Hello!") # Output: Hello!
# print(result) # Output: None (because nothing is returned)
# Since the function's purpose is to display a message, there's no need for a
return value, and None is fine.
# 2. Functions Modifying Data In-Place:
# If a function modifies a data structure (like a list or a dictionary) in place,
it doesn’t need to return anything because the changes are already reflected in the
original structure.
# python
# Copy code
# def add_item_to_list(lst, item):
# lst.append(item) # Modifies the list in place, no return needed
# my_list = [1, 2, 3]
# result = add_item_to_list(my_list, 4)
# print(result) # Output: None
# print(my_list) # Output: [1, 2, 3, 4] (The list was updated)
# The function doesn't return anything, and that’s acceptable because the list was
modified directly.
# 3. Error or Conditional Handling:
# Sometimes a function might return None to signal that no valid result could be
computed, like when an operation isn't possible or valid input isn't provided.
# python
# Copy code
# def divide_numbers(num1, num2):
# if num2 == 0:
# return None # Division by zero, return None
# return num1 / num2
# result = divide_numbers(10, 0)
# if result is None:
# print("Cannot divide by zero!")
# else:
# print("The result is:", result)
# Here, None is used to signal an invalid operation, and the calling code can
handle it appropriately.
# In summary, returning None is useful when:
# A function performs an action but doesn't need to return a value.
# A function modifies data directly.
# A function needs to signal that something went wrong or that no result could be
computed.
# You said:
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# result = display_message("Hello!") # Output: Hello!
# print(result) # Output: None (because nothing is returned) remove none and we
remain with hello only
# ChatGPT said:
# ChatGPT
# To remove the None from being printed in your example, you don't need to assign
the function call to result. Since the display_message function only prints the
message and doesn't return anything, you can simply call the function without
storing the result.
# Here’s how you can modify the code:
# python
# Copy code
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# display_message("Hello!") # This will just print "Hello!" without returning
anything
# Output:
# Copy code
# Hello!
# Why this works:
# By not assigning the function to result, you avoid printing the None value, which
is the default return value of a function that doesn't explicitly return anything.
# You said:
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# result = display_message("Hello!") # Output: Hello!
# print(result) # Output: None (because nothing is returned) i did not
understande
# ChatGPT said:
# ChatGPT
# Let me explain it step by step!
# Here's your original code:
# python
# Copy code
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# result = display_message("Hello!") # Output: Hello!
# print(result) # Output: None (because nothing is returned)
# What’s happening in this code:
# Function Definition:
# python
# Copy code
# def display_message(message):
# print(message)
# The function display_message() takes an argument message and prints it. It does
not return any value (which means it returns None by default).
# Calling the Function:
# python
# Copy code
# result = display_message("Hello!")
# When you call display_message("Hello!"), it prints "Hello!" to the screen.
However, since the function doesn't return anything, Python implicitly returns
None.
# By assigning the result of display_message() to result, you are capturing that
None value in the result variable.
# Printing the Result:
# python
# Copy code
# print(result)
# Since result is None (because the function doesn't return anything), this prints:
# css
# Copy code
# None
# How to Avoid Printing None:
# You can fix this by removing the result = assignment. Just call the function
directly, and it will print the message without returning anything, so you won’t
see None.
# Here’s the modified code:
# python
# Copy code
# def display_message(message):
# print(message) # Prints the message, but doesn't return anything
# # Just call the function, no need to assign its output to a variable
# display_message("Hello!") # This will just print "Hello!"
# Output:
# Copy code
# Hello!
# In this version:
# The function prints "Hello!" directly to the console.
# No None is printed, because you’re not storing the result of the function call in
a variable or printing the function’s return value.
# You said:
# If a function modifies a data structure (like a list or a dictionary) in place,
it doesn’t need to return anything because the changes are already reflected in the
original structure. exmplain well
# ChatGPT said:
# ChatGPT
# When a function modifies a mutable data structure like a list or a dictionary, it
doesn’t need to return anything because the changes happen directly in the original
object. This is called modifying in place.
# Key concepts:
# Mutable vs Immutable:
# Mutable objects: Objects that can be changed after they are created, like lists,
dictionaries, and sets.
# Immutable objects: Objects that cannot be changed after creation, like strings,
tuples, and integers.
# Modifying in place: When a function modifies a mutable object (like a list or a
dictionary) directly, the changes affect the original object outside the function
because the function works with a reference to that object, not a copy.
# Example with a list:
# Here’s an example to explain how this works with a list:
# python
# Copy code
# def add_item_to_list(lst, item):
# lst.append(item) # Adds the item to the list directly (modifying in place)
# my_list = [1, 2, 3]
# add_item_to_list(my_list, 4) # Calling the function to add an item
# print(my_list) # Output: [1, 2, 3, 4] (the original list has been modified)
# What’s happening step-by-step:
# Before function call: my_list contains [1, 2, 3].
# Inside the function:
# The function add_item_to_list is called with my_list and the value 4 as
arguments.
# Inside the function, lst.append(item) adds 4 to the list.
# This modifies the original list (my_list) because lst is a reference to the same
list object.
# After the function call:
# The original list my_list has been changed to [1, 2, 3, 4].
# The function doesn’t need to return anything because the changes are already made
to the original object.
# Example with a dictionary:
# Here’s how it works with a dictionary:
# python
# Copy code
# def update_dict(d, key, value):
# d[key] = value # Modifies the dictionary by adding/updating a key-value pair
# my_dict = {'a': 1, 'b': 2}
# update_dict(my_dict, 'c', 3) # Adds a new key-value pair ('c': 3)
# print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
# What’s happening:
# The function update_dict modifies the original dictionary my_dict by adding the
key-value pair 'c': 3.
# Since dictionaries are mutable, this change directly affects the original
dictionary, even though the function doesn’t return anything.
# Why Functions Don’t Need to Return Anything:
# Since mutable objects (like lists and dictionaries) are passed by reference in
Python, the original object is modified within the function. This means the caller
automatically sees the changes, and there’s no need to return the modified object.
# In contrast, with immutable objects (like strings, integers, and tuples),
functions would need to return the modified value because you cannot change the
original object in place.
# Summary:
# Mutable objects (like lists and dictionaries): When you modify them inside a
function, you are changing the actual object itself, so no return is necessary.
# Immutable objects (like strings and integers): Any changes inside a function
won’t affect the original, so the function must return a new value if changes are
needed.
# You said:
# def add_item_to_list(lst, item):
# lst.append(item) # Adds the item to the list directly (modifying in place)
# my_list = [1, 2, 3]
# add_item_to_list(my_list, 4) # Calling the function to add an item
# print(my_list) # Output: [1, 2, 3, 4] (the original list has been modified)
for user input
# ChatGPT said:
# ChatGPT
# You can modify the code to allow the user to input the item they want to add to
the list. Here’s how you can do that:
# python
# Copy code
# def add_item_to_list(lst, item):
# lst.append(item) # Adds the item to the list directly (modifying in place)
# my_list = [1, 2, 3]
# # Get user input for the item to add, converting it to the appropriate type (int
or str)
# user_input = input("Enter an item to add to the list: ")
# # You can choose to convert it to int if you expect integer inputs
# # Uncomment the line below to convert to int
# # user_input = int(user_input)
# add_item_to_list(my_list, user_input) # Calling the function to add the user
input
# print("Updated list:", my_list) # Output the modified list
# Explanation:
# Function Definition: The add_item_to_list function remains the same; it appends
an item to the list.
# User Input:
# The program prompts the user to enter an item to add to the list using input().
# If you expect the user to input integers, you can convert the input to an integer
by uncommenting the line user_input = int(user_input). If you want to keep the
input as a string (for example, if users might input names), you can leave it as
is.
# Updating the List: The add_item_to_list function is called with my_list and the
user input.
# Output: Finally, the updated list is printed.
# Example Output:
# If the user inputs 4, the output will be:
# css
# Copy code
# Enter an item to add to the list: 4
# Updated list: [1, 2, 3, 4]
# If the user inputs a string, like "apple", the output will be:
# css
# Copy code
# Enter an item to add to the list: apple
# Updated list: [1, 2, 3, 'apple']
# This way, the program allows dynamic input from the user!
# You said:
# Immutable objects (like strings and integers): Any changes inside a function
won’t affect the original, so the function must return a new value if changes are
needed. use those
# ChatGPT said:
# ChatGPT
# To demonstrate how immutable objects (like strings and integers) work in Python,
I'll provide examples where we attempt to modify them inside a function. Since they
are immutable, any modifications made within the function do not affect the
original value outside of it.
# Here’s how you can work with both strings and integers in functions, returning
new values when changes are needed.
# Example with Strings
# In this example, we'll create a function that modifies a string by adding some
text and then returns the new string:
# python
# Copy code
# def append_to_string(original_string, text_to_add):
# # Attempt to modify the original string
# new_string = original_string + text_to_add # Create a new string
# return new_string # Return the new string
# # Original string
# my_string = "Hello"
# # Call the function with user input for what to add
# user_input = input("Enter text to append: ")
# # Get the new string from the function
# updated_string = append_to_string(my_string, user_input)
# # Output both the original and updated strings
# print("Original string:", my_string) # This will remain unchanged
# print("Updated string:", updated_string) # This shows the new string
# Example with Integers
# Similarly, for integers, we can create a function that adds a number to the
original integer and returns the new value:
# python
# Copy code
# def add_to_integer(original_integer, value_to_add):
# # Create a new integer
# new_integer = original_integer + value_to_add # This creates a new integer
# return new_integer # Return the new integer
# # Original integer
# my_integer = 10
# # Get user input for the value to add
# user_input = int(input("Enter a number to add: ")) # Convert input to an integer
# # Get the new integer from the function
# updated_integer = add_to_integer(my_integer, user_input)
# # Output both the original and updated integers
# print("Original integer:", my_integer) # This will remain unchanged
# print("Updated integer:", updated_integer) # This shows the new value
# Summary of What Happens:
# Immutable Nature: In both examples, the original string (my_string) and the
original integer (my_integer) remain unchanged after calling the functions. This is
because strings and integers cannot be modified in place.
# Returning New Values: The functions return new strings or integers that reflect
the desired changes. You need to capture these return values in new variables to
use them.
# User Input: The program collects user input to modify the original values
dynamically.
# Example Outputs:
# For the string example, if the user enters World, the output will be:
# vbnet
# Copy code
# Enter text to append: World
# Original string: Hello
# Updated string: Hello World
# For the integer example, if the user enters 5, the output will be:
# sql
# Copy code
# Enter a number to add: 5
# Original integer: 10
# Updated integer: 15
# This way, you can see how to handle immutable objects in Python functions!
# You said:
# go on
# ChatGPT said:
# ChatGPT
# Let's continue to explore how to work with immutable objects in Python,
particularly focusing on strings and integers. I'll expand on the concepts and
provide more examples, including some additional scenarios that demonstrate the
behavior of these types.
# 1. Strings: More Manipulations
# Strings are often used for various manipulations, such as changing case, slicing,
or formatting. Since they are immutable, each operation results in a new string.
# Example: String Manipulations
# python
# Copy code
# def format_string(original_string):
# # Convert to uppercase and replace spaces with underscores
# new_string = original_string.upper().replace(" ", "_")
# return new_string # Return the new formatted string
# # Original string
# my_string = "Hello World"
# # Format the string
# formatted_string = format_string(my_string)
# # Output both the original and the formatted strings
# print("Original string:", my_string) # Remains unchanged
# print("Formatted string:", formatted_string) # Displays the new string
# Example Output:
# If the user doesn’t provide any input and simply runs the code:
# c
# Copy code
# Original string: Hello World
# Formatted string: HELLO_WORLD
# 2. More Integer Operations
# Integers can be manipulated with various arithmetic operations. Since integers
are also immutable, similar rules apply as with strings.
# Example: Integer Manipulations
# python
# Copy code
# def multiply_integer(original_integer, multiplier):
# # Multiply the integer and return a new value
# new_integer = original_integer * multiplier
# return new_integer # Return the new integer
# # Original integer
# my_integer = 10
# # Call the function with a user input multiplier
# user_input = int(input("Enter a multiplier: ")) # Convert input to an integer
# # Get the new integer from the function
# multiplied_integer = multiply_integer(my_integer, user_input)
# # Output both the original and multiplied integers
# print("Original integer:", my_integer) # This will remain unchanged
# print("Multiplied integer:", multiplied_integer) # This shows the new value
# Example Output:
# If the user enters 3, the output will be:
# yaml
# Copy code
# Enter a multiplier: 3
# Original integer: 10
# Multiplied integer: 30
# 3. Handling User Input and Error Checking
# When working with user input, especially for integers and strings, it's a good
practice to include error handling to ensure the input is valid. Let's enhance the
previous examples with basic error checking.
# Example: String Input with Error Handling
# python
# Copy code
# def safe_format_string(original_string):
# # Check if the input is a string
# if not isinstance(original_string, str):
# return "Invalid input! Please enter a string."
# new_string = original_string.upper().replace(" ", "_")
# return new_string
# user_input = input("Enter a string to format: ")
# formatted_string = safe_format_string(user_input)
# print("Formatted string:", formatted_string)
# Example: Integer Input with Error Handling
# python
# Copy code
# def safe_multiply_integer(original_integer, multiplier):
# # Check if the input is an integer
# if not isinstance(original_integer, int) or not isinstance(multiplier, int):
# return "Invalid input! Please enter integers."
# new_integer = original_integer * multiplier
# return new_integer
# my_integer = 10
# user_input = input("Enter a multiplier (integer): ")
# try:
# user_multiplier = int(user_input) # Convert input to integer
# multiplied_integer = safe_multiply_integer(my_integer, user_multiplier)
# print("Multiplied integer:", multiplied_integer)
# except ValueError:
# print("Invalid input! Please enter a valid integer.")
# 4. Further Examples of String and Integer Manipulations
# Here are more examples showcasing the immutable nature of strings and integers
through different operations.
# Example: Reversing a String
# python
# Copy code
# def reverse_string(original_string):
# # Reverse the string and return a new string
# return original_string[::-1] # Using slicing to reverse
# my_string = "Hello"
# reversed_string = reverse_string(my_string)
# print("Original string:", my_string) # Remains unchanged
# print("Reversed string:", reversed_string) # Displays the new string
# Example Output:
# c
# Copy code
# Original string: Hello
# Reversed string: olleH
# Example: Incrementing an Integer
# python
# Copy code
# def increment_integer(original_integer):
# # Increment the integer and return a new value
# return original_integer + 1
# my_integer = 10
# incremented_integer = increment_integer(my_integer)
# print("Original integer:", my_integer) # Remains unchanged
# print("Incremented integer:", incremented_integer) # Displays the new value
# Example Output:
# bash
# Copy code
# Original integer: 10
# Incremented integer: 11
# Conclusion
# Immutable Objects: Both strings and integers in Python are immutable. This means
that when you try to change them inside a function, you create a new object instead
of modifying the original.
# Returning New Values: Functions need to return new values when dealing with
immutable objects since the original values remain unchanged.
# Error Handling: Implementing error handling for user inputs can help ensure that
your program handles incorrect data gracefully.
# Feel free to ask if you want more examples, explanations, or specific scenarios!
# You said:
# erro
# # creating our function
# def add_user_number_to_orginal_list(list_number, user_number):
# list_number.append(user_number) # Adds the item to the list directly
(modifying in place)
# orginal_list = [1, 2, 3]
# # finiched function now
# # Get user input for the item to add, converting it to the appropriate type (int
or str)
# user_input = input(" orginal_list = [1, 2, 3], add to the list: ")
# # You can choose to convert it to int if you expect integer inputs
# # Uncomment the line below to convert to int
# user_input = int(user_input)
# add_user_number_to_orginal_list(orginal_list, user_input) # Calling the function
to add the user input
# print("Updated list:", orginal_list) # Output the modified list without
return but i got the back the results why
# ChatGPT said:
# ChatGPT
# Your code is functioning correctly because the function
add_user_number_to_orginal_list modifies the original list in place. Let’s break it
down step by step to understand how this works and clarify why you're getting the
updated results without returning anything.
# Explanation of Your Code
# Here's your code again with comments explaining each part:
# python
# Copy code
# # Creating our function
# def add_user_number_to_orginal_list(list_number, user_number):
# list_number.append(user_number) # Adds the item to the list directly
(modifying in place)
# # Original list
# orginal_list = [1, 2, 3]
# # Get user input for the item to add, converting it to the appropriate type (int
or str)
# user_input = input("orginal_list = [1, 2, 3], add to the list: ")
# # Convert input to int if you expect integer inputs
# user_input = int(user_input)
# # Calling the function to add the user input
# add_user_number_to_orginal_list(orginal_list, user_input)
# # Output the modified list
# print("Updated list:", orginal_list) # This will show the updated list
# Why You Get the Updated Results:
# Function Definition:
# The function add_user_number_to_orginal_list takes two parameters: list_number
(the list you want to modify) and user_number (the number to add).
# Inside the function, list_number.append(user_number) modifies the list in place
by adding the user_number to the end of the list.
# Modifying in Place:
# Lists are mutable in Python, which means they can be changed without creating a
new object.
# When you call the function with add_user_number_to_orginal_list(orginal_list,
user_input), you are passing a reference to orginal_list. Therefore, any changes
made inside the function directly affect orginal_list.
# No Need for Return:
# Since you’re modifying the original list directly, there’s no need to return
anything from the function. The changes are reflected in the original list
immediately.
# Output:
# When you print orginal_list after calling the function, it shows the updated list
with the new number added.
# Summary
# No Return Needed: Functions that modify mutable objects (like lists) can change
the object in place without needing to return it. You get to see the updated result
directly in the original variable.
# Mutable vs Immutable: Remember that this behavior applies only to mutable
objects. For immutable objects (like strings or integers), any "modification" will
result in a new object, and you must return that new object if you want to keep the
changes.
# Example Run
# If you run your code and enter 4 when prompted:
# css
# Copy code
# orginal_list = [1, 2, 3], add to the list: 4
# Updated list: [1, 2, 3, 4]
# This confirms that the original list has been successfully modified to include
the new number.
# If you have any further questions or want to explore more examples, feel free to
ask!
# You said:
# now use return
# ChatGPT said:
# ChatGPT
# To incorporate a return statement in your function while still achieving the same
result, you can modify the function to return the updated list after adding the new
number. Here’s how you can do that:
# Updated Code with Return Statement
# python
# Copy code
# # Creating our function
# def add_user_number_to_orginal_list(list_number, user_number):
# list_number.append(user_number) # Adds the item to the list directly
(modifying in place)
# return list_number # Return the modified list
# # Original list
# orginal_list = [1, 2, 3]
# # Get user input for the item to add, converting it to the appropriate type (int)
# user_input = input("orginal_list = [1, 2, 3], add to the list: ")
# user_input = int(user_input) # Convert input to int
# # Calling the function to add the user input and capturing the return value
# updated_list = add_user_number_to_orginal_list(orginal_list, user_input)
# # Output the modified list
# print("Updated list:", updated_list) # This will show the updated list
# Explanation of Changes
# Function Definition:
# The function now includes a return list_number statement at the end. This means
that after the function modifies the list by appending the user_number, it will
return the modified list to the caller.
# Capturing the Return Value:
# When you call the function with updated_list =
add_user_number_to_orginal_list(orginal_list, user_input), you store the returned
list in the variable updated_list. This variable will hold the modified version of
the original list.
# Output:
# When you print updated_list, it shows the updated list with the new number added.
# Example Run
# If you run the updated code and enter 4 when prompted:
# css
# Copy code
# orginal_list = [1, 2, 3], add to the list: 4
# Updated list: [1, 2, 3, 4]
# Summary
# Using Return: The use of return in this context allows you to explicitly return
the modified list, which can be useful if you want to work with the updated list in
a different context or function.
# Original List Still Updated: Since lists are mutable, orginal_list remains
updated even without returning it. However, returning the updated list can make
your code clearer and easier to understand.
# If you have more questions or need further modifications, feel free to ask!
# You said:
# what is difference
# ChatGPT said:
# ChatGPT
# The main difference between modifying a list in place (without returning) and
returning a modified list from a function lies in how the changes are accessed and
whether the original variable is explicitly updated. Let’s break down the
differences:
# 1. In-Place Modification (Without Return)
# When you modify a list in place within a function without using a return
statement, the original list is changed directly, and there's no need to capture a
return value.
# Example:
# python
# Copy code
# def add_user_number_to_orginal_list(list_number, user_number):
# list_number.append(user_number) # Modifies the list in place
# orginal_list = [1, 2, 3]
# user_input = 4 # Example user input
# add_user_number_to_orginal_list(orginal_list, user_input) # Function modifies
the list directly
# print("Updated list:", orginal_list) # Output: Updated list: [1, 2, 3, 4]
# Behavior:
# The function directly modifies orginal_list.
# You don't need to assign the result to another variable; the changes are visible
immediately in orginal_list.
# 2. Modification with Return
# When you modify a list and return it from a function, you create a new flow where
the updated list can be captured in a variable.
# Example:
# python
# Copy code
# def add_user_number_to_orginal_list(list_number, user_number):
# list_number.append(user_number) # Modifies the list in place
# return list_number # Returns the modified list
# orginal_list = [1, 2, 3]
# user_input = 4 # Example user input
# updated_list = add_user_number_to_orginal_list(orginal_list, user_input) #
Capture the return value
# print("Updated list:", updated_list) # Output: Updated list: [1, 2, 3, 4]
# Behavior:
# The function still modifies orginal_list directly, but it also returns the
modified list.
# You capture the returned value in updated_list. This can be useful if you want to
use or pass around the modified list without referring back to the original list.
# Key Differences
# Feature In-Place Modification (No Return) Modification with Return
# Original List Modified directly Modified directly, but also returns the
modified version
# Return Value No return value needed Return value can be captured in a new
variable
# Code Clarity Less explicit about changes More explicit, can make code easier
to understand
# Usage Directly affects the original list Can allow for more flexible code
flow (e.g., chaining operations)
# Impact on Readability May be less clear what the function does Makes the
function's purpose and output clear
# When to Use Each Approach
# Use In-Place Modification:
# When you want to keep the original list updated and don’t need to return a new
list.
# In cases where clarity is not sacrificed, and direct modification is sufficient.
# Use Modification with Return:
# When you want to emphasize the output of a function.
# If you plan to chain function calls or operate on the returned value separately.
# For clearer code when working with multiple functions or when the modified list
might be used elsewhere.
# Conclusion
# Both approaches have their advantages depending on the context of your code.
Using return statements can enhance clarity and flexibility, especially in larger
codebases or more complex logic. In simpler cases, direct modification can keep the
code straightforward. It ultimately depends on your specific use case and coding
style preferences!
# You said:
# give me easiest exmples for both
# ChatGPT said:
# ChatGPT
# Sure! Let’s create the simplest examples for both in-place modification (without
returning) and modification with a return statement. These examples will focus on
adding a number to a list.
# Example 1: In-Place Modification (Without Return)
# In this example, we will create a function that modifies the list directly
without returning anything.
# python
# Copy code
# # Function to add a number to the list in place
# def add_number_to_list(numbers, number_to_add):
# numbers.append(number_to_add) # Modifies the list directly
# # Original list
# my_list = [1, 2, 3]
# # Add a number using the function
# add_number_to_list(my_list, 4) # Adds 4 to my_list
# # Output the modified list
# print("Updated list (in-place):", my_list) # Output: Updated list (in-place):
[1, 2, 3, 4]
# Example 2: Modification with Return
# In this example, we will create a function that adds a number to a list and then
returns the modified list.
# python
# Copy code
# # Function to add a number to the list and return the modified list
# def add_number_and_return(numbers, number_to_add):
# numbers.append(number_to_add) # Modifies the list directly
# return numbers # Returns the modified list
# # Original list
# my_list = [1, 2, 3]
# # Add a number using the function and capture the return value
# updated_list = add_number_and_return(my_list, 4) # Adds 4 and returns the
updated list
# # Output the modified list
# print("Updated list (with return):", updated_list) # Output: Updated list (with
return): [1, 2, 3, 4]
# Summary of Both Examples
# In-Place Modification:
# The function add_number_to_list adds a number directly to the original list and
does not return anything.
# You can see the updated list directly by printing my_list.
# Modification with Return:
# The function add_number_and_return also adds a number directly but additionally
returns the modified list.
# You store the returned value in updated_list, which you can use independently if
needed.
# Example Outputs
# When you run both examples, you will get the following output:
# csharp
# Copy code
# Updated list (in-place): [1, 2, 3, 4]
# Updated list (with return): [1, 2, 3, 4]
# Both methods effectively achieve the same result, but they illustrate different
programming styles regarding how functions interact with lists in Python. If you
have any questions or need further clarification, feel free to ask!
# You said:
# side by side code
# ChatGPT said:
# ChatGPT
# Sure! Here’s a side-by-side comparison of both examples: in-place modification
(without return) and modification with return. This format will help you see the
differences clearly.
# Side-by-Side Code Comparison
# python
# Copy code
# # In-Place Modification (Without Return)
# def add_number_to_list(numbers, number_to_add):
# numbers.append(number_to_add) # Modifies the list directly
# my_list_in_place = [1, 2, 3]
# add_number_to_list(my_list_in_place, 4) # Adds 4 to my_list_in_place
# print("Updated list (in-place):", my_list_in_place) # Output: Updated list (in-
place): [1, 2, 3, 4]
# # Modification with Return
# def add_number_and_return(numbers, number_to_add):
# numbers.append(number_to_add) # Modifies the list directly
# return numbers # Returns the modified list
# my_list_with_return = [1, 2, 3]
# updated_list = add_number_and_return(my_list_with_return, 4) # Adds 4 and
returns the updated list
# print("Updated list (with return):", updated_list) # Output: Updated list (with
return): [1, 2, 3, 4]
# Output
# When you run the above code, the output will be:
# csharp
# Copy code
# Updated list (in-place): [1, 2, 3, 4]
# Updated list (with return): [1, 2, 3, 4]
# Explanation of the Comparison
# Function Names:
# The first function is named add_number_to_list and modifies the list in place
without returning anything.
# The second function is named add_number_and_return and also modifies the list but
returns the modified version.
# List Variables:
# my_list_in_place is used for the in-place modification.
# my_list_with_return is used for the function that returns the modified list.
# Output:
# Both methods ultimately yield the same result, showing how lists can be
manipulated in different ways in Python.
# This side-by-side format allows you to easily compare the two approaches. If you
have any more questions or need further assistance, feel free to ask!