Test Your Brain Tips For Py
Test Your Brain Tips For Py
# 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.
# Create a program that adds two numbers and prints the result.
# Subtract Two Numbers
# Create a program that finds the remainder when dividing two numbers.
# Square a Number
# Write a program that prints each fruit in your list on a new line.
# Add a Fruit to the List
# 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 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 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 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 counts from 1 to 5, pausing for a second between each.
# Simple Text-Based Game
# 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 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
# 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 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 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 asks the user to guess a number between 1 and 10.
# Print the First Five Even Numbers
# 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 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:
# 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.
# 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.
# Create a Simple Random Number Generator - Write a program that generates and
prints a random number between 1 and 100.
# 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.
# 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.
# 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.
# Create a Simple Music Playlist - Write a program that allows adding and removing
songs from a playlist.
# 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.
# 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.
# 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.
# Ask for a List of Items and Print Them - Write a program that asks for a list of
items and prints each one.
# 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.
# 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.
# 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 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.
# Create a Simple Daily Task Organizer - Write a program that helps organize daily
tasks with priority levels.
# 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.
# 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.
# 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.
# 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:
# 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.
# 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.
# 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.
# 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.
# 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.
# 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).
# 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.
# Calculate the Total Distance Travelled by a Car - Write a program that calculates
the total distance based on speed and time.
# 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.
# 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.
# Generate a Simple Random Joke - Write a program that prints a random joke from a
list.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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.
# 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!
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
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
# 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.")
# 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.")
# 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)
# 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)
# 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)
# 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)
# 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)
# 89. Create a program that checks if a string contains all letters of the alphabet
import string
# 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)
# 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)
# 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)
# 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)
# 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)
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.")
# 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
# 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
# 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)
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
# 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)
# 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)
# 146. Create a program that calculates the distance between two points
import math
# 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)
# 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
# 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)
# 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)
# 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
# 181. Create a program that generates a random number between a given range
import random
# 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
# 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
# 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
# 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
# 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
# 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
# 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
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
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
# 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
# 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
# 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
# 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
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))
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.")
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
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.")
# 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
# 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)
# 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
# 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
# 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))
# 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))
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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
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.")
# Here’s a complete Python script that includes exercises from 1 to 200, formatted
for easy copying.
# Each exercise is commented for clarity.
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
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
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
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
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
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
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
def rps_game():
choices = ["rock", "paper", "scissors"]
user_score = 0
computer_score = 0
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
def view_image(image_path):
img = Image.open(image_path) # Open image
img.show() # Display image
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
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
if is_valid_sudoku(sudoku_board):
print("Valid Sudoku board.") # Valid board message
else:
print("Invalid Sudoku board.") # Invalid board message
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
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
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
def read_json(file_path):
with open(file_path, 'r') as file: # Open JSON file
return json.load(file) # Load and return data
def web_scraper(url):
response = requests.get(url) # Fetch webpage
soup = BeautifulSoup(response.text, 'html.parser') # Parse HTML
return soup.title.string # Return title
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
def parse_xml(file_path):
tree = ET.parse(file_path) # Parse XML file
return tree.getroot() # Return root element
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
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
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
def get_http_response(url):
response = requests.get(url) # Make HTTP GET request
return response.status_code # Return status code
def web_scraper(url):
response = requests.get(url) # Fetch webpage
soup = BeautifulSoup(response.text, 'html.parser') # Parse HTML
return soup.title.string # Return title
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
def display_contacts():
for name, phone in contacts.items():
print(f"{name}: {phone}") # Print contacts
def roll_dice():
return random.randint(1, 6) # Roll dice
def simple_timer(seconds):
for i in range(seconds, 0, -1):
print(i)
time.sleep(1) # Wait for one second
print("Time's up!")
def show_image(image_path):
img = Image.open(image_path) # Open image
img.show() # Show image
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."
]
def delete_file(file_path):
os.remove(file_path) # Delete file
print("File deleted successfully.") # Success message
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
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
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
def shorten_url(url):
s = pyshorteners.Shortener() # Create shortener
return s.tinyurl.short(url) # Shorten URL
def is_valid_phone_number(phone):
pattern = re.compile(r'^\+?1?\d{9,15}$') # Define pattern
return bool(pattern.match(phone)) # Validate number
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
def show_tasks(self):
return self.tasks # Show tasks
def show_events(self):
return self.events # Show events
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
def show_cart(self):
return self.items # Show cart items
class StudentManagement:
def __init__(self):
self.students = [] # Initialize student list
def show_students(self):
return [(student.name, student.age) for student in self.students] # Show
students
def show_requests(self):
return self.requests # Show requests
class ProductCatalog:
def __init__(self):
self.products = [] # Initialize product list
def show_catalog(self):
return [(product.name, product.price) for product in self.products] # Show
products
class ContactManager:
def __init__(self):
self.contacts = [] # Initialize contact list
def show_contacts(self):
return [(contact.name, contact.phone) for contact in self.contacts] # Show
contacts
def convert_markdown_to_html(markdown_text):
return markdown.markdown(markdown_text) # Convert to HTML
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
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
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
def visualize_data(data):
sns.histplot(data, bins=10) # Visualize data
plt.title("Data Visualization") # Title
plt.show() # Show plot
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."
def summarize_text(text):
return summarize(text) # Summarize text
def check_file_type(filename):
return os.path.splitext(filename)[1] # Get file extension
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
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!"
def results(self):
return self.candidates # Return vote counts
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
def average_score(self):
return sum(self.scores) / len(self.scores) if self.scores else 0 #
Calculate average
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
def is_valid_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$' # Email pattern
return re.match(pattern, email) is not None # Validate email
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
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
def show_tasks(self):
return self.tasks # Show tasks
def total_expenses(self):
return sum(self.expenses) # Calculate total
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
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
def fetch_url(url):
response = requests.get(url) # Fetch URL
return response.text # Return content
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
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
def shuffle_list(lst):
random.shuffle(lst) # Shuffle the list in place
return lst # Return shuffled list
def area_of_circle(radius):
return math.pi * radius ** 2 # Calculate area
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
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
# 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!
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# 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)
# 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 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
# Share
# You said:
# def multiply(num1, num2):
# """Return the product of num1 and num2."""
# return num1 * num2 # Return the product
# 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
# 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.
# python
# Copy code
# def multiply(num1, num2):
# # Just performs multiplication but doesn't return the result
# num1 * num2
# 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.
# 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.
# python
# Copy code
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# 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.
# 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.
# You said:
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# python
# Copy code
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# 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
# python
# Copy code
# def display_message(message):
# print(message) # Prints a message but doesn't return anything
# 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).
# 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.
# 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.
# python
# Copy code
# def display_message(message):
# print(message) # Prints the message, but doesn't return anything
# Copy code
# Hello!
# In this version:
# 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.
# 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
# python
# Copy code
# def update_dict(d, key, value):
# d[key] = value # Modifies the dictionary by adding/updating a key-value pair
# 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
# 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: ")
# 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.
# 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.
# 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: ")
# 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
# 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.
# # Original string
# my_string = "Hello World"
# # Format the string
# formatted_string = format_string(my_string)
# 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.
# # 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
# 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.
# 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.
# my_string = "Hello"
# reversed_string = reverse_string(my_string)
# my_integer = 10
# incremented_integer = increment_integer(my_integer)
# You said:
# erro
# # 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: ")
# 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)
# 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:
# # 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)
# 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 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:
# 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:
# 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.
# 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]
# 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
# 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:
# 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]
# 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:
# 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!