Thursday, 27 February 2025

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.

 

Write a Python program that takes two strings as input and checks if they are exactly the same (case-sensitive).


 string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")


if string1 == string2:

    print("The strings are the same.")

else:

    print("The strings are different.")

#source code --> clcoding.com 


Code Explanation:

Taking User Input
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
The program prompts the user to enter two strings.
The input() function is used to take user input as strings.
The values entered by the user are stored in the variables string1 and string2.

Comparing the Two Strings (Case-Sensitive)
if string1 == string2:
The == comparison operator is used to check whether the two strings are identical.
This comparison is case-sensitive, meaning "Hello" and "hello" are considered different because of the uppercase "H".

Printing the Result
    print("The strings are the same.")
else:
    print("The strings are different.")
If the strings are exactly the same, the program prints:
"The strings are the same."

Otherwise, it prints:
"The strings are different."

Tuesday, 25 February 2025

Write a program that asks the user to enter a year and checks if it is a leap year or not.

 


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


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

    print("It's a leap year!")

else:

    print("It's not a leap year.")

#source code --> clcoding.com 

Code Explanation:

Taking Input from the User
year = int(input("Enter a year: "))
The program asks the user to enter a year.
Since input() takes input as a string, we use int() to convert it into an integer.
The value is stored in the variable year.

Checking if the Year is a Leap Year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
A year is a leap year if one of the following conditions is true:

It is divisible by 4 (year % 4 == 0) and NOT divisible by 100 (year % 100 != 0).
OR, it is divisible by 400 (year % 400 == 0).
If the condition is true, the program prints:
It's a leap year!

If the Year is NOT a Leap Year
else:
    print("It's not a leap year.")
If neither of the conditions is met, the year is NOT a leap year.
The program prints:
It's not a leap year.

Write a program that asks the user to enter a single character and checks if it is a vowel or consonant.


 

char = input("Enter a character: ").lower()


if char in 'aeiou':

    print("It's a vowel.")

else:

    print("It's a consonant.")

#source code --> clcoding.com 


Code Explanation:

Taking Input from the User

char = input("Enter a character: ").lower()

The program asks the user to enter a character.

Since input() takes input as a string, it is stored in the variable char.

.lower() is used to convert the input into lowercase so that it works for both uppercase and lowercase letters.


Checking if the Character is a Vowel

if char in 'aeiou':

    print("It's a vowel.")

The if condition checks if the entered character exists in the string 'aeiou'.

If true, it means the character is a vowel, so the program prints:

It's a vowel.

If the Character is NOT a Vowel, It’s a Consonant

else:

    print("It's a consonant.")

If the character is not found in 'aeiou', it means the character is a consonant.

The program prints:

It's a consonant.


Write a program that takes three numbers as input and prints the largest one.


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

b = int(input("Enter second number: "))

c = int(input("Enter third number: "))


if a >= b and a >= c:

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

elif b >= a and b >= c:

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

else:

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

#source code --> clcoding.com 


Code Explanation:

Taking Input from the User
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
The program asks the user to enter three numbers one by one.
Since input() takes values as strings, we use int() to convert them into integers.
The numbers are stored in variables:
a → First number
b → Second number
c → Third number

Checking if a is the Largest Number
if a >= b and a >= c:
    print("The largest number is:", a)
This if condition checks whether a is greater than or equal to both b and c.
If true, a is the largest number, so it prints:
The largest number is: a

Checking if b is the Largest Number
elif b >= a and b >= c:
    print("The largest number is:", b)
If the first condition is false, the program checks if b is greater than or equal to both a and c.
If true, b is the largest number, so it prints:
The largest number is: b

If a and b are NOT the Largest, c Must Be the Largest
else:
    print("The largest number is:", c)
If neither a nor b is the largest, c must be the largest.
The program prints:
The largest number is: c


Write a program that asks the user for a number and checks if it is even or odd.

 


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

if num % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")
#source code --> clcoding.com 

Code Explanation

num = int(input("Enter a number: "))
The program asks the user to enter a number using input().
input() takes user input as a string, so we use int() to convert it into an integer.
The entered number is stored in the variable num.

if num % 2 == 0:
    print("The number is even.")
This if statement checks if the number is divisible by 2 using the modulus operator %.
The modulus operator % returns the remainder after division.
If num % 2 == 0, it means the number is completely divisible by 2, so it is even.
If this condition is true, it prints:
The number is even.

else:
    print("The number is odd.")
If the if condition is false, that means num is not divisible by 2.
This means the number is odd, so it prints:
The number is odd.

Write a Python program that asks the user to enter a number and then prints whether the number is positive, negative, or zero.

 


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


if num > 0:

    print("The number is positive.")

elif num < 0:

    print("The number is negative.")

else:

    print("The number is zero.")

#source code --> clcoding.com 


Step-by-Step Explanation

Taking Input from the User

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

The program asks the user to enter a number using input().

The input() function takes input as a string, so we use int() to convert it into an integer.

Now, the number is stored in the variable num.

Example Inputs & Stored Values:

If the user enters 5, then num = 5

If the user enters -3, then num = -3

If the user enters 0, then num = 0


Checking the Number using if Statement

if num > 0:

    print("The number is positive.")

The if statement checks if num is greater than 0.

If true, it prints:

The number is positive.

Otherwise, it moves to the next condition.

Example:

If the user enters 8, num > 0 is True, so the program prints:

The number is positive.


Checking the Number using elif Statement

elif num < 0:

    print("The number is negative.")

If the first condition (if num > 0) is False, Python checks this condition.

The elif statement checks if num is less than 0.

If true, it prints:

The number is negative.

Example:

If the user enters -5, num < 0 is True, so the program prints:

The number is negative.


Handling the Case where the Number is Zero (else Statement)

else:

    print("The number is zero.")

If num is not greater than 0 and not less than 0, that means it must be zero.

So, the program prints:

The number is zero.



PyCon APAC 2025

 

The Python community in the Asia-Pacific region is gearing up for an exciting event: PyCon APAC 2025. Scheduled for March 1-2, 2025, this two-day in-person conference will be hosted at the prestigious Ateneo de Manila University in Quezon City, Philippines.

What is PyCon APAC?

PyCon APAC is an annual, volunteer-driven, not-for-profit conference that serves as a hub for Python enthusiasts, developers, and industry leaders across the Asia-Pacific region. The conference aims to provide a platform for exploring, discussing, and practicing Python and its associated technologies. Each year, a different country in the region hosts the event, with past locations including Singapore, Japan, Taiwan, South Korea, Malaysia, Thailand, and Indonesia. This year, the Philippines has the honor of hosting, following the success of PyCon PH 2024.

What to Expect at PyCon APAC 2025

The conference promises a rich and diverse program designed to cater to Python enthusiasts of all levels. Attendees can look forward to:

  • Talks: Engage with insightful presentations from experts covering a wide array of Python-related topics.

  • Workshops: Participate in hands-on sessions to deepen your practical understanding of Python.

  • Panel Discussions: Join conversations on current trends, challenges, and the future of Python in various industries.

  • Lightning Talks: Experience quick, engaging presentations that provide a snapshot of innovative ideas and projects.

  • Poster Sessions: Explore visual presentations of projects and research, offering a chance for one-on-one discussions.

  • PyLadies Lunch: A special gathering aimed at supporting and celebrating women in the Python community.

  • Open Spaces: Informal meetups where attendees can discuss topics of interest in a relaxed setting.

  • Group Lunches: Opportunities to network and share ideas over a meal with fellow Python enthusiasts.

Additionally, March 3, 2025, is dedicated to Sprints. This day offers a welcoming environment for everyone—whether you're an experienced open-source contributor or a newcomer eager to learn—to collaborate on projects and contribute to the Python ecosystem.

Keynote Speakers

The conference boasts an impressive lineup of keynote speakers, including:

  • Jeremi Joslin: Renowned for his contributions to open-source projects and the Python community.

  • Edwin N. Gonzales: A data science expert with extensive experience in machine learning and AI.

  • Cheuk Ting Ho: An advocate for diversity in tech and a prominent figure in the global Python community.

  • Clark Urzo: A software engineer known for his innovative work in web development using Python.

Tickets and Participation

Tickets for PyCon APAC 2025 are now available. Given the in-person nature of the event, early registration is encouraged to secure your spot. Whether you're a seasoned developer, a beginner, or simply passionate about Python, this conference offers something for everyone.

Venue

The event will take place at the Ateneo de Manila University, a prestigious institution known for its commitment to excellence and innovation. Located in Quezon City, the university provides a conducive environment for learning and collaboration.

Join the Conversation

Stay updated and connect with fellow attendees through the official PyCon APAC 2025 channels. Engage in discussions, share your excitement, and be part of the vibrant Python community in the Asia-Pacific region.

Don't miss this opportunity to learn, network, and contribute to the Python ecosystem. Mark your calendars for March 1-2, 2025, and we'll see you in Quezon City!

Ticket : https://pycon-apac.python.ph

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)