Thursday, 27 February 2025

Read a file line by line and print each line separately.

 


with open("example.txt", "r") as file:

    for line in file:

        print(line.strip())  

#source code --> clcoding.com         


Code Explanation:

Open the File in Read Mode ("r")
open("example.txt", "r") opens the file in read mode.
If the file does not exist, Python will raise a FileNotFoundError.

Read the File Line by Line
for line in file: iterates through each line in the file.

Print Each Line Separately
print(line.strip()) prints the line after using .strip(), which removes extra spaces or newline characters (\n) from the output.

Create a program that writes a list of strings to a file, each on a new line.

 


lines = ["Hello, World!", "Python is great!", "File handling is useful!", "End of file."]


with open("output.txt", "w") as file:

    for line in lines:

        file.write(line + "\n")


print("Data written to output.txt successfully!")

#source code --> clcoding.com  


Code Explanation:

 Create a List of Strings:
We define a list lines that contains multiple strings.

Open the File in Write Mode ("w")
The open("output.txt", "w") statement opens the file in write mode.
If the file does not exist, it will be created.
If the file already exists, it will be overwritten.

Writing to the File:
The for loop iterates through the list of strings.
file.write(line + "\n") writes each string to the file and adds a newline (\n) so that each string appears on a new line.

File Closes Automatically:
The with open(...) statement ensures the file automatically closes after writing.

Print Success Message:
print("Data written to output.txt successfully!") confirms that the process is complete.

Write a program to read the contents of a file and display them on the screen.

 


with open("example.txt", "r") as file:

    content = file.read()


print("File Contents:")

print(content)

#source code --> clcoding.com  


Code explanation:

Opening the File:
We use open("example.txt", "r") to open the file in read mode ("r").
The "r" mode ensures that we are only reading the file, not modifying it.
If the file does not exist, Python will raise a FileNotFoundError.

Using with Statement:
The with open(...) as file: statement ensures the file is closed automatically after the block is executed.

Reading the File:
The read() function reads all the content from the file and stores it in the variable content.

Printing the Contents:
print(content) displays the contents of the file on the screen.


Write a Python program to create a text file named example.txt and write the text "Hello, World!" into it.

 


with open("example.txt", "w") as file:

    file.write("Hello, World!")


print("File created and text written successfully!")

#source code --> clcoding.com  


Code Explanation:

Opening the File:
We use open("example.txt", "w") to open a file named example.txt in write mode ("w").
If the file does not exist, Python creates it automatically.
If the file already exists, its contents will be overwritten.

Using with Statement:
with open(...) as file: is used for better file handling.
It ensures that the file is closed automatically after the block is executed.

Writing to the File:
The write() function writes "Hello, World!" into the file.

Print Confirmation:
The message "File created and text written successfully!" confirms the operation.

Expected Output:
File created and text written successfully!

Write a program to remove duplicates from a list using a set.

 


numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]

unique_numbers = list(set(numbers))

print("List without duplicates:", unique_numbers)

#source code --> clcoding.com  


Code Explanation:

Define a List with Duplicates
numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
This list contains duplicate values like 2, 4, 6, 8.

Convert the List to a Set
unique_numbers = list(set(numbers))
Sets in Python do not allow duplicate values.
Converting the list to a set automatically removes all duplicates.
Converting it back to a list gives us a duplicate-free list.

Print the Unique List
print("List without duplicates:", unique_numbers)
The final list will have only unique values.

Expected Output
List without duplicates: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Write a program to print all keys and values of a dictionary using a loop


 

student = {"name": "John", "age": 20, "grade": "A"}


for key, value in student.items():

    print(f"Key: {key}, Value: {value}")

#source code --> clcoding.com  


Code Explanation:

Define the Dictionary
student = {"name": "John", "age": 20, "grade": "A"}
We create a dictionary named student that contains:

"name" → "John"
"age" → 20
"grade" → "A"

Use a Loop to Iterate Through the Dictionary
for key, value in student.items():
.items() → This method returns pairs of keys and values from the dictionary.
The for loop assigns each key to key and each value to value on every iteration.

Print the Key-Value Pairs
print(f"Key: {key}, Value: {value}")
We use an f-string (f"...") to format and display the key and value.

Expected Output
Key: name, Value: John
Key: age, Value: 20
Key: grade, Value: A

Write a function that checks whether a given key exists in a dictionary.


 def key_exists(dictionary, key):

    if key in dictionary:

        return True

    else:

        return False

student = {"name": "John", "age": 20, "grade": "A"}

key_to_check = "age"


if key_exists(student, key_to_check):

    print(f"The key '{key_to_check}' exists in the dictionary.")

else:

    print(f"The key '{key_to_check}' does not exist in the dictionary.")


#source code --> clcoding.com  


Code Explanation:

Define the Function
def key_exists(dictionary, key):
dictionary → This parameter represents the dictionary we want to check.
key → This is the key we are checking for inside the dictionary.

Check if the Key Exists
if key in dictionary:
    return True
else:
    return False

The in keyword checks if the given key exists inside the dictionary.
If the key is found, the function returns True.
If the key is not found, it returns False.

Example Usage
student = {"name": "John", "age": 20, "grade": "A"}
key_to_check = "age"
We create a dictionary called student.
We store "age" in key_to_check (this is the key we want to check).

Calling the Function
if key_exists(student, key_to_check):
    print(f"The key '{key_to_check}' exists in the dictionary.")
else:
    print(f"The key '{key_to_check}' does not exist in the dictionary.")
The function key_exists(student, key_to_check) is called.
If "age" exists in student, it prints:

The key 'age' exists in the dictionary.
If "age" was not in the dictionary, it would print:

The key 'age' does not exist in the dictionary.

Given a dictionary student = {"name": "John", "age": 20, "grade": "A"}, print the value of "age".

 


student = {"name": "John", "age": 20, "grade": "A"}

print(student["age"])

#source code --> clcoding.com  


Code Explanation:

Creating the Dictionary
student = {"name": "John", "age": 20, "grade": "A"}
A dictionary named student is created using {} (curly brackets).
The dictionary consists of key-value pairs:

"name" → "John" (String)
"age" → 20 (Integer)
"grade" → "A" (String)

Accessing the "age" Value
print(student["age"])
The print() function is used to display output on the screen.
student["age"] retrieves the value associated with the key "age" from the dictionary.
In this case, student["age"] returns 20.

Create a dictionary to store student details like name, age, and grade. Print the dictionary.

 


student = {

    "name": "Alice",

    "age": 20,

    "grade": "A"

}

print("Student Details:", student)

#source code --> clcoding.com  


Code Explanation:

Step 1: Creating a Dictionary
student = {
    "name": "Alice",
    "age": 20,
    "grade": "A"
}

Here, we create a dictionary called student.
It contains three key-value pairs:
"name" → Stores "Alice" (a string).
"age" → Stores 20 (an integer).
"grade" → Stores "A" (a string).

Step 2: Printing the Dictionary
print("Student Details:", student)
The print() function is used to display the dictionary.
It prints the entire dictionary in key-value format.

Expected Output
Student Details: {'name': 'Alice', 'age': 20, 'grade': 'A'}

Write a Python program that takes an integer as input and checks if it is NOT an even number.

 


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

if not (num % 2 == 0):  

    print("The number is NOT even (it is odd).")

else:

    print("The number is even.")

#source code --> clcoding.com 

Code Explanation:

Taking Input from the User
num = int(input("Enter a number: "))
The program asks the user to enter a number.
Since input() always returns a string, we use int() to convert it to an integer and store it in the variable num.

Checking if the Number is NOT Even
if not (num % 2 == 0):
num % 2 == 0 checks if num is even:
If num is even, num % 2 == 0 evaluates to True.
If num is odd, num % 2 == 0 evaluates to False.
not (num % 2 == 0) negates the result:
If num is even (True), not True becomes False.
If num is odd (False), not False becomes True.

Printing the Result
    print("The number is NOT even (it is odd).")
If the condition not (num % 2 == 0) is True, the program prints:
"The number is NOT even (it is odd)."
else:
    print("The number is even.")
If the condition is False (meaning the number is even), the program prints:
"The number is even."


Python Coding Challange - Question With Answer(01270225)

 


Step-by-Step Execution

  1. The outer loop (i) runs from 0 to 1 (i.e., range(0, 2) generates [0, 1]).
  2. Inside the outer loop, the inner loop (j) also runs from 0 to 1 (i.e., range(0, 2) generates [0, 1]).
  3. For each value of i, the inner loop runs completely before moving to the next i.

Execution Flow

Iterationi Valuej ValuePrinted Output
1st000 → 0
2nd011
3rd101 → 0
4th111

Final Output

0
0 1 1 0
1

👉 Key Takeaways:

  • The outer loop (i) controls how many times the inner loop runs.
  • The inner loop (j) executes completely for each value of i.
  • This results in a nested iteration structure where j repeats for every i.

Write a Python program that takes a person's age as input and checks if they are NOT eligible to vote (less than 18 years old).

 


age = int(input("Enter your age: "))


if not (age >= 18):

    print("You are NOT eligible to vote.")

else:

    print("You are eligible to vote.")

#source code --> clcoding.com 


Code Explanation:

Taking Input from the User
age = int(input("Enter your age: "))
The program asks the user to enter their age.
input() returns a string, so we use int() to convert it to an integer and store it in the variable age.

Checking Eligibility with not Operator
if not (age >= 18):
age >= 18 checks if the person is eligible to vote (18 or older).
not (age >= 18) negates the condition:
If age is 18 or more, age >= 18 is True, and not True becomes False.
If age is less than 18, age >= 18 is False, and not False becomes True.

Printing the Result
    print("You are NOT eligible to vote.")
If not (age >= 18) is True (meaning the person is under 18), the program prints:
"You are NOT eligible to vote."
else:
    print("You are eligible to vote.")
If the condition is False (meaning the person is 18 or older), the program prints:

"You are eligible to vote."


Write a Python program that takes a number as input and checks if it is NOT a prime number.

 


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


if num < 2 or any(num % i == 0 for i in range(2, int(num ** 0.5) + 1)):

    print("The number is NOT a prime number.")

else:

    print("The number is a prime number.")

#source code --> clcoding.com 

Code Explanation:

Taking User Input
num = int(input("Enter a number: "))
The user is asked to enter a number.
Since input() returns a string, we convert it to an integer using int().

Checking if the Number is NOT Prime
if num < 2 or any(num % i == 0 for i in range(2, int(num ** 0.5) + 1)):

Step 1: Check if the number is less than 2
Any number less than 2 is NOT prime (e.g., 0 and 1 are not prime).

Step 2: Check if the number is divisible by any number from 2 to √num
We loop from 2 to √num (int(num ** 0.5) + 1) because if a number is divisible by any number in this range, it is NOT prime.
any(num % i == 0 for i in range(2, int(num ** 0.5) + 1)) checks if num is divisible by any i in this range.
Step 3: If either condition is True, print "The number is NOT a prime number."

Printing the Result
    print("The number is NOT a prime number.")
If the number is divisible by any number other than 1 and itself, it is NOT prime.
else:
    print("The number is a prime number.")
If the number passes all conditions, it is prime.


Write a Python program that takes a year as input and checks if it is NOT a leap year.

 


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


if not ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)):

    print("The year is NOT a leap year.")

else:

    print("The year is a leap year.")

#source code --> clcoding.com 


Code Explanation:

Taking User Input

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

The user enters a year, which is stored in the variable year.

Since input() returns a string, we convert it to an integer using int().

Checking if the Year is NOT a Leap Year

if not ((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)):


Step 1: Check if the year is a leap year using two conditions:

(year % 4 == 0 and year % 100 != 0):

The year must be divisible by 4 and NOT divisible by 100 (e.g., 2024).

(year % 400 == 0):

The year must be divisible by 400 (e.g., 2000).


Step 2: Use not to check if the year is NOT a leap year

If the year does NOT satisfy either of the above conditions, then it is NOT a leap year.

Printing the Result

    print("The year is NOT a leap year.")

If the not condition is True, the year is NOT a leap year.

else:

    print("The year is a leap year.")

Otherwise, the year is a leap year.

Write a Python program that takes two numbers as input and checks if the first number is NOT greater than or equal to the second number.

 


num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

if not (num1 >= num2):

    print("The first number is NOT greater than or equal to the second number.")

else:

    print("The first number is greater than or equal to the second number.")

#source code --> clcoding.com 


Code Explanation:

Taking User Input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
The user enters two numbers, stored in num1 and num2.
float() is used to handle decimal numbers as well as integers.

Checking the Condition
if not (num1 >= num2):

Step 1: Condition inside not
The expression num1 >= num2 checks if num1 is greater than or equal to num2.
If num1 is greater than or equal to num2, it returns True.
If num1 is less than num2, it returns False.

Step 2: Using not
not (num1 >= num2) reverses the result.
If num1 is less than num2, the condition becomes True, meaning num1 is NOT greater than or equal to num2.

Printing the Result
    print("The first number is NOT greater than or equal to the second number.")
If the condition is True, it prints that num1 is NOT greater than or equal to num2.
else:
    print("The first number is greater than or equal to the second number.")
Otherwise, it prints that num1 is greater than or equal to num2.

Write a Python program that takes a number as input and prints its multiplication table (up to 10) using a for loop.

 


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


# Print multiplication table

print(f"Multiplication Table of {num}:")

for i in range(1, 11):

    print(f"{num} x {i} = {num * i}")

#source code --> clcoding.com 


Code Explanation:

Take User Input
num = int(input("Enter a number: "))
The input() function prompts the user to enter a number.
int() converts the input (which is a string by default) into an integer.

Print a Header for the Multiplication Table
print(f"Multiplication Table of {num}:")
This prints a message indicating which number’s multiplication table is being displayed.
The f-string (f"") is used for formatting, allowing {num} to be replaced with the actual input number.

Use a for Loop to Generate the Multiplication Table
for i in range(1, 11):
The range(1, 11) function generates numbers from 1 to 10.
The loop iterates through these numbers, storing each in i.

Calculate and Print Each Multiplication Step
print(f"{num} x {i} = {num * i}")
During each iteration, the multiplication (num * i) is calculated.
The result is printed in a formatted way using an f-string, showing the full multiplication equation.

Write a Python program that asks the user for a number n and calculates the sum of all numbers from 1 to n using a while loop.


 n = int(input("Enter a number: "))

sum_numbers = 0

i = 1

while i <= n:

    sum_numbers += i

    i += 1

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

#source code --> clcoding.com 

Code Explanation:

Take User Input:
n = int(input("Enter a number: "))
The program asks the user to enter a number n and converts it to an integer.

Initialize Variables:
sum_numbers = 0
i = 1
sum_numbers will store the total sum.
i is the counter variable, starting from 1.

Use a while Loop to Calculate the Sum:
while i <= n:
    sum_numbers += i
    i += 1
The loop runs as long as i is less than or equal to n.
In each iteration, i is added to sum_numbers, and i is incremented.

Print the Final Sum:
print(f"The sum of numbers from 1 to {n} is {sum_numbers}")
Displays the total sum.


Write a Python program that takes a string as input and prints it in reverse order using a for loop.

 


text = input("Enter a string: ")

reversed_text = ""

for char in text:

    reversed_text = char + reversed_text

print(f"Reversed string: {reversed_text}")

#source code --> clcoding.com 


Code Explanation:

Take User Input:
text = input("Enter a string: ")
The program asks the user to enter a string.

Initialize an Empty String:
reversed_text = ""
This will store the reversed string.

Use a for Loop to Reverse the String:
for char in text:
    reversed_text = char + reversed_text
The loop iterates over each character in text.
Each character is prepended to reversed_text, effectively reversing the order.

Print the Reversed String:
print(f"Reversed string: {reversed_text}")
Displays the reversed string.

.Write a Python program that takes 10 numbers as input from the user (using a for loop) and counts how many are even and how many are odd.



even_count = 0

odd_count = 0


for i in range(10):

    num = int(input(f"Enter number {i+1}: "))

    

    if num % 2 == 0:

        even_count += 1

    else:

        odd_count += 1

print(f"Total even numbers: {even_count}")

print(f"Total odd numbers: {odd_count}")

#source code --> clcoding.com 

Code Explanation:

Initialize Counters:
even_count = 0
odd_count = 0
These variables keep track of the number of even and odd numbers.

Loop to Take 10 Inputs:
for i in range(10):
    num = int(input(f"Enter number {i+1}: "))
The loop runs 10 times, prompting the user to enter a number each time.

Check for Even or Odd:
if num % 2 == 0:
    even_count += 1
else:
    odd_count += 1
If num is divisible by 2, it's even, so even_count is incremented.
Otherwise, it's odd, so odd_count is incremented.

Display the Final Count:
print(f"Total even numbers: {even_count}")
print(f"Total odd numbers: {odd_count}")
This prints the total count of even and odd numbers.


 

Write a Python program that prints all even numbers from 1 to 100 using a for loop.

 


print("Even numbers from 1 to 100:")


for num in range(1, 101):

    if num % 2 == 0:

        if num <= 50:

            print(num, end=" ")  

        else:

            if num == 52:

                print() 

            print(num, end=" ")  


#source code --> clcoding.com 

Code Explanation:

1. Print Header
print("Even numbers from 1 to 100:")
This prints the message "Even numbers from 1 to 100:" before the numbers are displayed.

2. Loop Through Numbers 1 to 100
for num in range(1, 101):
The for loop runs from 1 to 100.

3. Check if the Number is Even
if num % 2 == 0:
If num is divisible by 2 (num % 2 == 0), it's an even number.

4. Print First Half (2 to 50) on First Line
if num <= 50:
    print(num, end=" ")
If the even number is ≤ 50, it gets printed on the first line.

5. Break the Line at 52
if num == 52:
    print()  # Move to a new line
When num reaches 52, the program prints an empty line (print()), which moves the output to the next line.

6. Print Second Half (52 to 100) on Second Line
print(num, end=" ")
Numbers from 52 to 100 are printed on the second line.

Write a function multiply_by_two() that takes a number as input and prints its double.

 

def multiply_by_two(number):

    """This function takes a number and prints its double."""

    result = number * 2  

    print("Double of", number, "is", result)  

multiply_by_two(5)

multiply_by_two(10)


#source code --> clcoding.com 

Code Explanation:

Function Definition

def multiply_by_two(number):

def defines a function in Python.

multiply_by_two is the name of the function.

(number) is the parameter that the function accepts when called.

Function Docstring (Optional but Recommended)

"""This function takes a number and prints its double."""

This is a docstring, used for describing what the function does.

Helps in understanding the function when reading or debugging the code.

 Multiply the Input by 2

result = number * 2

The input number is multiplied by 2 and stored in the variable result.

Example Calculation:

If number = 5, then result = 5 * 2 = 10.

If number = 10, then result = 10 * 2 = 20.

Print the Result

print("Double of", number, "is", result)

This prints the original number and its double.

Example Output:

Double of 5 is 10

Double of 10 is 20

Calling the Function

multiply_by_two(5)

multiply_by_two(10)

multiply_by_two(5) passes 5 as input, prints Double of 5 is 10.

multiply_by_two(10) passes 10 as input, prints Double of 10 is 20.

Write a function calculate_area() that takes length and width as arguments and returns the area of a rectangle.


 

def calculate_area(length, width):

    

    area = length * width  

    return area 


result = calculate_area(5, 3)

print("Area of the rectangle:", result)


#source code --> clcoding.com 


Code Explanation:

Function Definition
def calculate_area(length, width):
def is used to define the function.
calculate_area is the name of the function.
It takes two parameters: length and width.

Calculating the Area
area = length * width
The area of a rectangle is calculated using the formula:
Area=Length×Width
Example calculations:
If length = 5 and width = 3, then:
Area=5×3=15

Returning the Area
return area
The function returns the calculated area so that it can be used later.

Calling the Function
result = calculate_area(5, 3)
Calls calculate_area(5, 3), which calculates:
5 × 3 = 15
The returned value (15) is stored in result.

Printing the Result
print("Area of the rectangle:", result)

Displays the output:
Area of the rectangle: 15

Write a function find_largest() that takes three numbers as arguments and returns the largest number.


 def find_largest(a, b, c):

    """This function takes three numbers as arguments and returns the largest number."""

    return max(a, b, c)  


result = find_largest(10, 25, 8)

print("The largest number is:", result)


#source code --> clcoding.com 


Code Explanation:

Function Definition
def find_largest(a, b, c):
def defines a function.
find_largest is the function name.
It takes three parameters: a, b, c, which represent the three numbers.

Docstring (Optional but Recommended)
"""This function takes three numbers as arguments and returns the largest number."""
Describes what the function does.
Helps in documentation and debugging.

Using max() Function
return max(a, b, c)
max(a, b, c) returns the largest of the three numbers.
Example calculations:
max(10, 25, 8) → 25
max(45, 12, 30) → 45

Calling the Function
result = find_largest(10, 25, 8)
Calls the function with numbers 10, 25, and 8.
Stores the largest number in result.

Printing the Result
print("The largest number is:", result)
Displays:
The largest number is: 25

Write a function print_even_numbers() that prints all even numbers from 1 to 20 using range().

 


def print_even_numbers():

    """This function prints all even numbers from 1 to 20."""

    for num in range(2, 21, 2):  

        print(num, end=" ")  


print_even_numbers()

#source code --> clcoding.com 

Code Explanation:

Function Definition
def print_even_numbers():
def is used to define the function.
print_even_numbers is the function name.
It does not take any parameters, since the range is fixed (1 to 20).

Docstring (Optional but Recommended)
"""This function prints all even numbers from 1 to 20."""
Describes what the function does.
Helps in documentation and debugging.

Using the range() Function
for num in range(2, 21, 2):
range(start, stop, step) generates a sequence of numbers:
2 → Start from 2 (first even number).
21 → Stop before 21 (last number is 20).
2 → Step by 2 (only even numbers).
The loop runs:
2, 4, 6, 8, 10, 12, 14, 16, 18, 20

Printing the Numbers
print(num, end=" ")
Prints each number on the same line with a space (end=" ").
Output:
2 4 6 8 10 12 14 16 18 20

Calling the Function
print_even_numbers()
Calls the function, and it prints:
2 4 6 8 10 12 14 16 18 20

Write a function count_vowels() that takes a string and returns the number of vowels (a, e, i, o, u).

 


def count_vowels(string):

    """This function counts the number of vowels (a, e, i, o, u) in a given string."""

    vowels = "aeiouAEIOU"  

    count = 0  


    for char in string:  

        if char in vowels:  

            count += 1  

    return count  

text = "Hello World"

print("Number of vowels:", count_vowels(text))  


#source code --> clcoding.com 


Code Explanation:

 Function Definition

def count_vowels(string):

def is used to define the function.
count_vowels is the function name.
It takes one parameter, string (the input text).

Defining Vowels
vowels = "aeiouAEIOU"
A string containing all vowel letters (both lowercase and uppercase).
Used to check if a character is a vowel.

Initialize Vowel Count
count = 0
A variable count is set to 0 to store the number of vowels.

Loop Through the String
for char in string:
Loops through each character in the input string.

Check if Character is a Vowel
if char in vowels:
Checks if the character is present in the vowels string.

Increase the Count
count += 1
If the character is a vowel, increase the count by 1.

Return the Count
return count
The function returns the total number of vowels found in the string.


Write a function square_number(n) that returns the square of a number.

 


def square_number(n):
    return n * n 
print(square_number(5))  
print(square_number(10)) 

#source code --> clcoding.com 

Code Explanation:

Define the Function:

def square_number(n): → This defines a function named square_number that takes a single parameter n.

Calculate the Square:
return n * n → This multiplies n by itself and returns the result.

Calling the Function:
square_number(5) → It passes 5 as an argument, which returns 5 * 5 = 25.
square_number(10) → It passes 10, which returns 10 * 10 = 100.

Example Output
25
100


Write a function reverse_string(s) that takes a string and returns the reversed version of it.

 



def reverse_string(s):

    return s[::-1] 

print(reverse_string("hello"))  

print(reverse_string("Python")) 

print(reverse_string("12345"))  


#source code --> clcoding.com 

Code Explanation:

Define the function
def reverse_string(s): → Creates a function reverse_string that takes a string s as input.

Reverse the string using slicing
s[::-1] → Uses negative slicing to reverse the string.
s[start:stop:step]
s[::-1] → Starts from the end (-1 step) and moves backward.

Return the reversed string
return s[::-1] → Returns the reversed version of the input string.

Call the function and print results
reverse_string("hello") → Returns "olleh".
reverse_string("Python") → Returns "nohtyP".

Example Output
olleh
nohtyP
54321

Write a program that converts a given string to uppercase and lowercase using upper() and lower().


 text = input("Enter a string: ")

uppercase_text = text.upper()

lowercase_text = text.lower()

print("Uppercase:", uppercase_text)

print("Lowercase:", lowercase_text)


#source code --> clcoding.com 


Code Explanation:

Take user input
input("Enter a string: ") → The user enters a string, which is stored in text.

Convert the string to uppercase
text.upper() → Converts all letters in text to uppercase.
Example: "hello" → "HELLO"

Convert the string to lowercase
text.lower() → Converts all letters in text to lowercase.
Example: "Hello WORLD" → "hello world"

Print the converted strings
print("Uppercase:", uppercase_text) → Displays the uppercase version.
print("Lowercase:", lowercase_text) → Displays the lowercase version.

Example Output
Input:

Enter a string: Python Programming

Write a function that replaces all spaces in a string with underscores (_).

 


def replace_spaces(s):

    return s.replace(" ", "_")  

print(replace_spaces("Hello World"))       

print(replace_spaces("Python is fun"))     

print(replace_spaces("NoSpacesHere"))      

#source code --> clcoding.com 


Code Explanation:

Define the function
def replace_spaces(s): → Creates a function replace_spaces that takes a string s as input.

Replace spaces using .replace()
s.replace(" ", "_") → Finds all spaces " " in the string and replaces them with underscores "_".

Return the modified string
The function returns the updated string with all spaces replaced.

Call the function and print results
replace_spaces("Hello World") → Returns "Hello_World".
replace_spaces("Python is fun") → Returns "Python_is_fun".
replace_spaces("NoSpacesHere") → Returns "NoSpacesHere" (unchanged, as there were no spaces).


Write a program that takes a name and age as input and prints a sentence using an f-string

 


name = input("Enter your name: ")

age = input("Enter your age: ")


print(f"My name is {name} and I am {age} years old.")

      

#source code --> clcoding.com 


Code Explanation:

Take user input for name and age
name = input("Enter your name: ") → Stores the user’s name.
age = input("Enter your age: ") → Stores the user’s age as a string.

Use an f-string for formatted output
f" My name is {name} and I am {age} years old."
The {name} and {age} placeholders are replaced by the actual values entered by the user.

Print the formatted sentence
The program prints a complete sentence with the user's details.

Create a dictionary to store student details like name, age, and grade. Print the dictionary.

 


details = {"name": "Alice", "age": 25, "grade": "A"}

print("Dictionary Example:", details)

#source code --> clcoding.com 


Code Explanation:

Creating a Dictionary:
details = {"name": "Alice", "age": 25, "grade": "A"}
A dictionary named details is created using {} (curly braces).

It consists of key-value pairs:
"name" → "Alice"
"age" → 25
"grade" → "A"

Printing the Dictionary:
print("Dictionary Example:", details)
The print() function is used to display the dictionary.

It outputs:
Dictionary Example: {'name': 'Alice', 'age': 25, 'grade': 'A'}

Given a dictionary student = {"name": "John", "age": 20, "grade": "A"}, print the value of "age".

 


student = {"name": "John", "age": 20, "grade": "A"}

print("Age:", student["age"])


#source code --> clcoding.com 


Code Explanation:

Define the Dictionary:
student = {"name": "John", "age": 20, "grade": "A"}
A dictionary named student is created.
It consists of key-value pairs:
"name" → "John"
"age" → 20
"grade" → "A"
Access the Value of "age":

student["age"]
The key "age" is used inside square brackets [ ] to retrieve its corresponding value, which is 20.

Print the Retrieved Value:
print("Age:", student["age"])

The print() function outputs:
Age: 20

Write a function that checks whether a given key exists in a dictionary.


 def key_exists(dictionary, key):

    if key in dictionary:

        return True

    else:

        return False

student = {"name": "John", "age": 20, "grade": "A"}

key_to_check = "age"

if key_exists(student, key_to_check):

    print(f"The key '{key_to_check}' exists in the dictionary.")

else:

    print(f"The key '{key_to_check}' does not exist in the dictionary.")


Code Explanation:

Define the Function:
def key_exists(dictionary, key):
The function key_exists() takes two parameters:
dictionary: The dictionary in which to search for the key.
key: The key to check for.

Check for Key Presence:
if key in dictionary:
The in keyword is used to check if the key exists in the dictionary.

Return the Result:
return True
If the key exists, the function returns True, otherwise it returns False.

Example Dictionary:
student = {"name": "John", "age": 20, "grade": "A"}
A sample dictionary student is defined.

Specify Key to Check:
key_to_check = "age"
The variable key_to_check is assigned the value "age".

Call the Function and Print Result:
if key_exists(student, key_to_check):
The function is called to check if "age" exists in the student dictionary.
The output will be:
The key 'age' exists in the dictionary.

Write a program to print all keys and values of a dictionary using a loop.

 


student = {"name": "John", "age": 20, "grade": "A"}


for key, value in student.items():

    print(f"{key}: {value}")


#source code --> clcoding.com


Code Explanation: 

Define the Dictionary:
student = {"name": "John", "age": 20, "grade": "A"}
A dictionary named student is created with key-value pairs:
"name" → "John"
"age" → 20
"grade" → "A"

Loop Through the Dictionary:
for key, value in student.items():
The .items() method returns key-value pairs as tuples.
The for loop iterates through each key-value pair.

Print the Key-Value Pairs:
print(f"{key}: {value}")
The print() function formats and prints the key followed by its value.

Output:
name: John
age: 20
grade: A

Write a program to remove duplicates from a list using a set.


 numbers = [1, 2, 3, 4, 5, 3, 2, 1, 6, 7, 8, 5]


unique_numbers = list(set(numbers))


print("List after removing duplicates:", unique_numbers)


#source code --> clcoding.com 


Code Explanation:

Define the List with Duplicates:

numbers = [1, 2, 3, 4, 5, 3, 2, 1, 6, 7, 8, 5]
The list numbers contains duplicate values (1, 2, 3, 5 appear multiple times).

Convert List to Set:
unique_numbers = list(set(numbers))
The set(numbers) converts the list into a set, automatically removing duplicates.
Converting it back to a list ensures the output remains in list format.

Print the Unique List:
print("List after removing duplicates:", unique_numbers)
The final output displays the list without duplicates.

Write a Python program that takes two numbers as input and checks if the first number is completely divisible by the second number

 


num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

if num2 == 0:

    print("Division by zero is not allowed.")

elif num1 % num2 == 0:

    print(f"{num1} is completely divisible by {num2}.")

else:

    print(f"{num1} is NOT completely divisible by {num2}.")

#source code --> clcoding.com 


Code Explanation:

Taking Input from the User
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
The program asks the user to enter two numbers.
int(input()) is used to convert the input into an integer.
The values are stored in num1 and num2.

Checking for Division by Zero
if num2 == 0:
    print("Division by zero is not allowed.")
Since dividing by zero is mathematically undefined, we first check if num2 is zero.
If num2 == 0, the program prints an error message and does not proceed further.

Checking for Complete Divisibility
elif num1 % num2 == 0:
    print(f"{num1} is completely divisible by {num2}.")
The modulus operator (%) is used to check divisibility.
If num1 % num2 == 0, it means num1 is completely divisible by num2, so the program prints a confirmation message.

Handling Cases Where num1 is Not Divisible by num2
else:
    print(f"{num1} is NOT completely divisible by {num2}.")
If the remainder is not zero, it means num1 is not completely divisible by num2, so the program prints a negative response.


Write a program that takes a string as input and prints the first and last character of the string

 



text = input("Enter a string: ")

if len(text) > 0:

    print("First character:", text[0])  

    print("Last character:", text[-1])  

else:

    print("The string is empty!")


#source code --> clcoding.com 


Code Explanation:

Take user input
input("Enter a string: ") → Asks the user to enter a string.

Check if the string is not empty
if len(text) > 0: → Ensures the input is not empty before accessing characters.

Print the first character
text[0] → Index 0 gives the first character of the string.

Print the last character
text[-1] → Index -1 gives the last character of the string.

Handle empty string cases
If the user enters an empty string, the program prints "The string is empty!" instead of throwing an error.

Write a function factorial(n) that returns the factorial of a number.


 

def factorial(n):

    if n == 0 or n == 1:

        return 1 

    result = 1

    for i in range(2, n + 1):  

        result *= i  

    return result

print(factorial(5))  

print(factorial(3))  

print(factorial(0))  

#source code --> clcoding.com 


Code Explanation:

Define the Function:
def factorial(n): → Defines the function, which takes n as input.

Handle Base Case (0 and 1):
if n == 0 or n == 1: return 1 → Since 0! = 1! = 1, return 1.

Initialize result to 1
result = 1 → This variable will store the factorial value.

Loop from 2 to n:
for i in range(2, n + 1): → Iterates through numbers from 2 to n.
result *= i → Multiplies result by i in each step.

Return the Final Result:
return result → Returns the computed factorial.

Example Output
120
6
1

Write a function sum_of_list(lst) that returns the sum of all elements in a list

 


def sum_of_list(lst):

    return sum(lst)  

print(sum_of_list([1, 2, 3, 4, 5]))

print(sum_of_list([10, 20, 30])) 

print(sum_of_list([-5, 5, 10])) 


#source code --> clcoding.com 


Code Explanation:

Define the Function:
def sum_of_list(lst): → Defines a function named sum_of_list that takes a list lst as input.

Calculate the Sum:
return sum(lst) → Uses the built-in sum() function to calculate the total of all numbers in the list.

Calling the Function:
sum_of_list([1, 2, 3, 4, 5]) → Returns 1 + 2 + 3 + 4 + 5 = 15.
sum_of_list([10, 20, 30]) → Returns 10 + 20 + 30 = 60.
sum_of_list([-5, 5, 10]) → Returns -5 + 5 + 10 = 10.

Example Output
15
60
10

Write a function reverse_string(s) that returns the reversed string.

 


def reverse_string(s):

    return s[::-1] 

print(reverse_string("hello"))  

print(reverse_string("Python"))  

print(reverse_string("12345")) 


#source code --> clcoding.com 


Code Explanation:

Define the Function:
def reverse_string(s): → Defines a function named reverse_string that takes a string s as input.

Reverse the String:
return s[::-1] → Uses Python slicing to reverse the string.
s[start:stop:step] → Here, [::-1] means:
Start from the end (-1 step)
Move backward one character at a time
Continue until the beginning is reached

Calling the Function:
reverse_string("hello") → Returns "olleh".
reverse_string("Python") → Returns "nohtyP".
reverse_string("12345") → Returns "54321".

Example Output
olleh
nohtyP
54321

Write a function is_even(n) that returns True if a number is even, otherwise False.


 def is_even(n):

    return n % 2 == 0  

print(is_even(8))  

print(is_even(7)) 

print(is_even(0))  


#source code --> clcoding.com 

Code Explanation:

Define the Function:
def is_even(n): → This defines a function named is_even that takes a single parameter n.

Check if the Number is Even:
return n % 2 == 0 →
% is the modulus operator, which gives the remainder when n is divided by 2.
If n % 2 == 0, it means n is even, so the function returns True.
Otherwise, it returns False.

Calling the Function:
is_even(8) → Since 8 % 2 == 0, it returns True.
is_even(7) → Since 7 % 2 == 1, it returns False.
is_even(0) → Since 0 % 2 == 0, it returns True.

Example Output
True
False
True

Wednesday, 26 February 2025

Write a Python program that takes two words as input and compares their lengths.


word1 = input("Enter the first word: ")

word2 = input("Enter the second word: ")

len1 = len(word1)

len2 = len(word2)

if len1 > len2:

    print(f'"{word1}" is longer than "{word2}".')

elif len1 < len2:

    print(f'"{word2}" is longer than "{word1}".')

else:

    print(f'"{word1}" and "{word2}" are of the same length.')

#source code --> clcoding.com 


Code Explanation:

Taking Input from the User
word1 = input("Enter the first word: ")
word2 = input("Enter the second word: ")
The program asks the user to enter two words.
The input is stored in the variables word1 and word2.

Calculating the Lengths of the Words
len1 = len(word1)
len2 = len(word2)
The len() function is used to determine the length of each word.
len1 stores the length of word1, and len2 stores the length of word2.

Comparing the Lengths
if len1 > len2:
    print(f'"{word1}" is longer than "{word2}".')
elif len1 < len2:
    print(f'"{word2}" is longer than "{word1}".')
else:
    print(f'"{word1}" and "{word2}" are of the same length.')
If len1 is greater than len2, the program prints that word1 is longer.
If len1 is less than len2, the program prints that word2 is longer.
If both words have the same length, the program prints that they are of equal length.

 

Top 5 Skills You Must Know Before You Learn Python

 


Introduction

Python is one of the most beginner-friendly programming languages, but having some foundational skills before diving in can make your learning journey smoother and more effective. Whether you're a complete beginner or transitioning from another language, these five essential skills will help you grasp Python concepts more easily.


1. Basic Computer Literacy

Before learning Python, ensure you are comfortable with:

  • Using a computer efficiently
  • Navigating files and folders
  • Installing and using software
  • Basic troubleshooting skills

These will help you set up your Python environment without unnecessary roadblocks.


2. Logical Thinking and Problem-Solving

Programming is all about breaking down problems into smaller steps. Strengthen your logical thinking skills by:

  • Practicing puzzles and brain teasers
  • Learning the basics of algorithms
  • Thinking in a structured way to solve problems

This mindset will help you write efficient Python code.


3. Understanding Basic Math Concepts

Python often involves mathematical operations, so having a grasp of:

  • Arithmetic (addition, subtraction, multiplication, division)
  • Basic algebra (variables, expressions)
  • Understanding of how numbers work in computing

While advanced math isn't required, comfort with numbers is a plus.


4. Familiarity with English and Syntax

Since most programming languages, including Python, use English-based syntax, it helps to:

  • Understand basic English vocabulary and structure
  • Read and follow instructions carefully
  • Get comfortable with writing structured statements

This will make reading and writing Python code much easier.


5. Introduction to Algorithmic Thinking

Even without coding experience, understanding how instructions work in a sequence will be beneficial. Learn about:

  • Flowcharts and pseudocode
  • Conditional statements (if-else logic)
  • Loops and repetitive tasks

This will prepare you for Python’s logical flow and syntax.


Conclusion

You don’t need to be an expert in these areas before learning Python, but having a basic understanding will accelerate your progress. With these foundational skills, you’ll find Python much easier to grasp and enjoy the learning experience even more!

Write a Python program that takes a number as input and checks if it is between 50 and 100


 num = float(input("Enter a number: "))


if 50 <= num <= 100:

    print("The number is between 50 and 100.")

else:

    print("The number is NOT between 50 and 100.")

#source code --> clcoding.com 


Code Explanation:

Taking User Input
num = float(input("Enter a number: "))
The program asks the user to enter a number.
float(input()) is used to allow both integers and decimal values.

Checking if the Number is Between 50 and 100
if 50 <= num <= 100:
This condition checks if the number is greater than or equal to 50 AND less than or equal to 100.
The chained comparison (50 <= num <= 100) is a concise way to check a range.

Printing the Result
    print("The number is between 50 and 100.")
else:
    print("The number is NOT between 50 and 100.")
If the condition is True, the program prints that the number is in the range.
Otherwise, it prints that the number is NOT in the range.


Python Program to Find the Smallest of Three Numbers Using Comparison Operators

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

num3 = float(input("Enter the third number: "))

if num1 <= num2 and num1 <= num3:

    print("The smallest number is:", num1)

elif num2 <= num1 and num2 <= num3:

    print("The smallest number is:", num2)

else:

    print("The smallest number is:", num3)

#source code --> clcoding.com 


Code Explanation:

Taking Input from the User
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
The program asks the user to enter three numbers.
input() is used to take input, and float() is used to convert the input into a decimal number (to handle both integers and floating-point numbers).
The values are stored in num1, num2, and num3.

Finding the Smallest Number Using Comparison Operators
if num1 <= num2 and num1 <= num3:
    print("The smallest number is:", num1)
This first condition checks if num1 is less than or equal to both num2 and num3.
If True, it means num1 is the smallest, and the program prints its value.

Checking the Second Number
elif num2 <= num1 and num2 <= num3:
    print("The smallest number is:", num2)
If num1 is not the smallest, the program checks if num2 is less than or equal to both num1 and num3.
If True, it means num2 is the smallest, and the program prints its value.

If Neither num1 nor num2 is the Smallest
else:
    print("The smallest number is:", num3)
If both conditions above fail, it means num3 must be the smallest number.
The program prints num3.

 

Popular Posts

Categories

100 Python Programs for Beginner (96) AI (38) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (188) C (77) C# (12) C++ (83) Course (67) Coursera (247) Cybersecurity (25) Data Analysis (1) Data Analytics (2) data management (11) Data Science (142) Data Strucures (8) Deep Learning (21) Django (16) Downloads (3) edx (2) Engineering (14) Euron (29) Events (6) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (9) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (76) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (1011) Python Coding Challenge (452) Python Quiz (90) Python Tips (5) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses

Python Coding for Kids ( Free Demo for Everyone)