Wednesday, 26 February 2025

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

GeoPython 2025

 


GeoPython 2025 is an upcoming conference dedicated to the intersection of Python programming and geospatial technologies. Scheduled to take place from February 24 to 26, 2025, in Basel, Switzerland, this event serves as a hub for professionals, researchers, and enthusiasts in the geospatial and Python communities.

Event Overview

GeoPython 2025 aims to bring together individuals passionate about geospatial data science, Geographic Information Systems (GIS), remote sensing, and mapping. The conference provides a platform for attendees to share knowledge, discuss advancements, and explore the latest tools and techniques in the field. Participants can look forward to a series of talks, workshops, and networking opportunities designed to foster collaboration and innovation.

Key Dates and Deadlines

  • Conference Dates: February 24–26, 2025
  • Location: Basel, Switzerland

For more detailed information about the event, including registration and program details, visit the official GeoPython 2025 website.

Stay Connected

To stay updated with the latest news and announcements regarding GeoPython 2025, consider following their official social media channels:

These platforms offer insights into past conferences, updates on the upcoming event, and a chance to engage with the GeoPython community.

Conclusion

GeoPython 2025 promises to be a significant event for those interested in the fusion of Python programming and geospatial sciences. Whether you're a seasoned professional or new to the field, the conference offers valuable opportunities to learn, share, and connect. Mark your calendars and prepare to be part of this exciting gathering in Basel.

Python Coding Challange - Question With Answer(01250225)

 


  1. range(1, 10, 3):

    • This generates a sequence of numbers starting from 1, up to (but not including) 10, with a step size of 3.
    • So, it will generate the numbers: 1, 4, 7.
  2. for i in range(1, 10, 3)::
    • This sets up a loop that will iterate through the values 1, 4, and 7 one by one.
  3. print(i):

    • This prints the current value of i during each iteration.
  4. if (i == 4)::

    • This checks if the current value of i is equal to 4.
  5. break:

    • If i equals 4, the break statement will terminate the loop immediately.
    • This means that when i reaches 4, the loop stops, and no further numbers are printed or processed.

What happens during execution:

  • In the first iteration, i = 1, so it prints 1.
  • In the second iteration, i = 4, so it prints 4 and then hits the if condition (i == 4), which triggers the break statement.
  • As a result, the loop stops immediately after i = 4 and does not proceed to the next number (7).

Output:

1
4

The loop breaks before it prints 7.

Write a Python program to find the remainder when 17 is divided by 5.


 a = 17

b = 5

remainder = a % b

print(remainder)

#source code --> clcoding.com


Step-by-Step Explanation:

Assign Values to Variables:

a = 17

b = 5

We store the number 17 in a variable a.

We store the number 5 in a variable b.

Find the Remainder Using % Operator:

remainder = a % b

The % (modulus) operator finds the remainder when one number is divided by another.

Since 17 ÷ 5 gives a quotient of 3 and a remainder of 2, we get:

17 % 5 = 2

The result 2 is stored in the variable remainder.

Print the Result:

print(remainder)

The print() function displays the value of remainder on the screen.

Since remainder = 2, the output will be:

2

Final Output:

2

Write a Python program to divide 18 by 3 and print the result. 5.


 a = 18

b = 3

quotient = a / b

print(quotient)

#source code --> clcoding.com

Step-by-Step Explanation:

Assign Values to Variables:

a = 18

b = 3

We store the number 18 in a variable a.

We store the number 3 in a variable b.

Perform Division:

quotient = a / b

The / operator is used to divide one number by another.

Since a = 18 and b = 3, the division is:

18 / 3 = 6.0

The result 6.0 is stored in the variable quotient.

Print the Result:

print(quotient)

The print() function displays the value of quotient on the screen.

Since quotient = 6.0, the output will be:

6.0

Final Output:

6.0

Write a Python program to multiply 4 by 6 and print the result.

 


a = 4

b = 6

product = a * b

print(product)

#source code --> clcoding.com

Explanation:

Assign Values to Variables:

a = 4

b = 6

Here, we store the number 4 in a variable called a.

We store the number 6 in a variable called b.

Variables help in storing values that we can use later.

Multiply the Two Numbers:

product = a * b

The * operator is used to multiply two numbers.

Since a = 4 and b = 6, the multiplication is:

4 * 6 = 24

The result 24 is stored in a variable called product.

Print the Result:

print(product)

The print() function displays the value of product on the screen.

Since product = 24, the output will be:

24

Final Output:

24

Write a Python program to subtract 15 from 20 and print the result.

 


a = 20

b = 15

difference = a - b

print(difference)  

#source code --> clcoding.com

Explanation:

Assigning Values to Variables:

a = 20

b = 15

The variable a is assigned the value 20.

The variable b is assigned the value 15.

Performing Subtraction:

difference = a - b

The - operator is used to subtract the value of b from a.

difference = 20 - 15, so difference stores the value 5.

Printing the Result:

print(difference)

The print() function outputs the value of difference to the screen.

Since difference = 5, the output will be:

5

Final Output:

5

Write a Python program to add 8 and 5, then print the result.


 a = 8

b = 5

sum_result = a + b

print(sum_result)  

#source code --> clcoding.com


Explanation:

Assigning Values to Variables:

a = 8

b = 5

The variable a is assigned the value 8.

The variable b is assigned the value 5.

Performing Addition:

sum_result = a + b

The + operator is used to add the values of a and b.

sum_result = 8 + 5, so sum_result stores the value 13.

Printing the Result:

print(sum_result)

The print() function outputs the value of sum_result to the screen.

Since sum_result = 13, the output will be:

13

Monday, 24 February 2025

Store "I eat apples" in a variable sentence. Replace "apples" with "bananas" and print the new sentence.


sentence = "I eat apples"  
new_sentence = sentence.replace("apples", "bananas")  
print(new_sentence)
 
#source code --> clcoding.com 

Explanation:

Define the Variable:
sentence = "I eat apples" stores the original sentence in the variable sentence.

Use .replace() to Change the Word:
The .replace("apples", "bananas") method finds the word "apples" and replaces it with "bananas".
The new sentence becomes "I eat bananas".
.replace() does not modify the original string; it creates a new modified string.

Print the Updated Sentence:
print(new_sentence) outputs the modified sentence.

Output:
I eat bananas

Store "Python" in a variable lang. Print the first letter of the string using indexing.

 


lang = "Python" 
first_letter = lang[0] 
print(first_letter) 

#source code --> clcoding.com 

Explanation:

Define the Variable:
lang = "Python" stores the string "Python" in the variable lang.

Use Indexing to Access the First Letter:
In Python, indexing starts from 0.
lang[0] refers to the first character of "Python", which is "P".

Print the Extracted Letter:
print(first_letter) outputs the first letter "P".

Output:
P

Store "hello" in a variable word. Convert it to uppercase and print the result.

 


word = "hello" 

uppercase_word = word.upper()  

print(uppercase_word) 

#source code --> clcoding.com 


Explanation:

Define the Variable:

word = "hello" stores the lowercase string "hello" in the variable word.

Convert to Uppercase:

word.upper() converts all the letters in "hello" to uppercase, resulting in "HELLO".

The .upper() method is a built-in Python function that changes all characters to uppercase.

Print the Uppercase String:

print(uppercase_word) outputs the converted string "HELLO".

Output:

HELLO

Store "Python Programming" in a variable called text and print the length of the string using len().

 


text = "Python Programming"  

length = len(text)

print(length)  

#source code --> clcoding.com 


Explanation:

Define the Variable:

text = "Python Programming" stores the string "Python Programming" in the variable text.

Find the Length:

len(text) calculates the total number of characters in the string, including spaces.

"Python Programming" has 18 characters (including the space between words).

Print the Length:

print(length) outputs the length of the string.

Output:

18

Create a variable greeting and store "Hello, Python!" in it. Then, print the value of greeting.

 

greeting = "Hello, Python!" 

print(greeting) 

#source code --> clcoding.com 


Explanation:

Define the Variable:

greeting = "Hello, Python!" assigns the text "Hello, Python!" to the variable greeting.

A string is a sequence of characters enclosed in double (" ") or single (' ') quotes.


Print the Value:

print(greeting) displays the content stored in the greeting variable on the screen.


Output:

Hello, Python!

Create two float numbers p = 7.5 and q = 12.5. Find their average and print the result.

 


p = 7.5 

q = 12.5 

average = (p + q) / 2  

print(average)  

#source code --> clcoding.com 


Explanation:

Define Variables:

p = 7.5 and q = 12.5 are floating-point numbers.

Calculate Average:

First, we add p and q:

7.5+12.5=20.0

Then, we divide the sum by 2 to get the average:

20.0÷2=10.0

Print the Result:

print(average) displays the calculated average.

Output:

10.0

Store an integer num = 8, convert it into a float, and print the result.

 


num = 8  

num_float = float(num) 

print(num_float)

#source code --> clcoding.com 


Explanation:

Create an Integer Variable:

num = 8: We store the integer value 8 in the variable num.

Convert Integer to Float:

float(num): The float() function converts an integer into a floating-point number.

In this case, 8 is converted to 8.0.

Print the Result:

print(num_float): Displays the converted floating-point number on the screen.

Output:

8.0

Create two float variables x = 4.2 and y = 2.0. Multiply them and print the result.

 

x = 4.2  

y = 2.0  

result = x * y  

print(result)  

#source code --> clcoding.com 


Explanation:

Create Variables:

We define x = 4.2 and y = 2.0.

These are floating-point numbers, meaning they have decimal values (e.g., 4.2, 2.0).

Perform Multiplication:

We multiply x and y using the * operator:

4.2×2.0=8.4

The result (8.4) is stored in the variable result.

Print the Result:

We use print(result) to display the multiplication result.

Output:

8.4

Create two float variables a = 2.5 and b = 3.5. Find their sum and print the result.


 a = 2.5

b = 3.5

sum_result = a + b

print(sum_result)

#source code --> clcoding.com 


Explanation:

Create Variables:

We define a and b as floating-point numbers (2.5 and 3.5).

A floating-point number is a number with a decimal point (e.g., 2.5, 3.5, 10.75).

Perform Addition:

We add a and b together (2.5 + 3.5).

The result of this addition (6.0) is stored in the variable sum_result.

Print the Result:

We use print(sum_result) to display the sum on the screen.

Output:

6.0

Create a variable price and store the value 10.5 in it. Then, print the value of price.


 

price = 10.5  
print(price)  

#source code --> clcoding.com 

Explanation:

price = 10.5: This line creates a variable named price and assigns it the floating-point value 10.5.

print(price): This line prints the value stored in the price variable to the console.

Output:
10.5

Create two integer variables p = 15 and q = 4. Find the remainder when p is divided by q using % and print the result.

 


p = 15  

q = 4  

remainder = p % q  

print(remainder)

#source code --> clcoding.com 

Step-by-Step Explanation 

Step 1: Storing the Numbers

p = 15  

q = 4  

We create two integer variables:

p is assigned the value 15

q is assigned the value 4


Step 2: Using the Modulus Operator (%)

remainder = p % q  

Here, % is the modulus operator, which gives us the remainder when one number is divided by another.

Now, let's divide 15 by 4:

15 ÷ 4 = 3 remainder 3

The quotient is 3 (which means 4 goes into 15 three times).

The remainder is 3 (since 15 - (4 × 3) = 15 - 12 = 3).

So, remainder stores the value 3.

Step 3: Printing the Remainder

print(remainder)

This tells Python: "Show me the remainder when 15 is divided by 4!"

The output on the screen will be:

3

Final Output 

3


Create two integer variables m = 20 and n = 4. Perform division using // (integer division) and print the result.


m = 20  
n = 4  
result = m // n  
print(result)

#source code --> clcoding.com 

Step-by-Step Explanation 

Step 1: Storing the Numbers
m = 20  
n = 4  
We create two integer variables:
m is assigned the value 20
n is assigned the value 4

Step 2: Performing Integer Division
result = m // n  
Here, // is the integer division operator.
It divides m by n, but only keeps the whole number (quotient) and ignores the remainder.
Let's divide 20 by 4:
Normal division: 20 ÷ 4 = 5.0
Integer division (//): 5 (only the whole number, no decimals).
So, result stores the value 5.

Step 3: Printing the Result
print(result)
This tells Python: "Show me the value inside result!"
The output on the screen will be:
5
Final Output 
5

Create two integer variables x = 4 and y = 5. Multiply them and print the result.

 


x = 4  

y = 5  

product = x * y  

print(product)  

#source code --> clcoding.com 

Step-by-Step Breakdown 

Step 1: Storing the Numbers

x = 4  

y = 5  

Here, x is assigned the value 4.

y is assigned the value 5.

Think of x and y as two containers holding numbers.

Step 2: Multiplying the Numbers

product = x * y  

We multiply x and y:

4 × 5 = 20

The result (20) is stored in a new variable called product.

Step 3: Printing the Result

print(product)

This tells Python: "Show me the value inside product!"

Since product holds 20, the output on the screen will be:

20

Final Output: 

When you run the code, Python will print:

20

Create two variables a = 7 and b = 3. Find their sum and print the result.


 a = 7  

b = 3  

sum_result = a + b  

print(sum_result)  

#source code --> clcoding.com 


Explanation:

Variable Assignment:

a = 7 → This assigns the value 7 to the variable a.

b = 3 → This assigns the value 3 to the variable b.

Performing Addition:

sum_result = a + b

a + b → This adds the values stored in a and b (i.e., 7 + 3 = 10).

The result (10) is stored in the variable sum_result.

Printing the Result:

print(sum_result) → Displays the value stored in sum_result on the screen.


Output:

10

Create a variable num and store the number 10 in it. Then, print the value of num.

 


num = 10  
print(num)  

#source code --> clcoding.com 

Explanation:

Variable Assignment (num = 10)
num is the variable name.
= is the assignment operator, which is used to store a value in a variable.
10 is an integer value being assigned to the variable num.
Now, num holds the value 10 in memory.

Printing the Variable (print(num))
print() is a built-in function in Python that displays output on the screen.
num is placed inside print(), so the stored value (10) is printed when the program runs.
Output:
10

Python Coding Challange - Question With Answer(01240225)

 


Step-by-Step Execution:

  1. import numpy as np
    • This imports the NumPy library, which provides efficient array operations.
  2. numbers = np.array([1, 2, 3])
    • This creates a NumPy array:

      numbers = [1, 2, 3] (as a NumPy array)
  3. new_numbers = numbers + 1
    • NumPy allows element-wise operations, so adding 1 increases each element by 1:

      [1+1, 2+1, 3+1][2, 3, 4]
  4. print(new_numbers.tolist())
    • new_numbers.tolist() converts the NumPy array back into a Python list:

      [2, 3, 4]
    • Finally, it prints the result.

Final Output:


[2, 3, 4]

Why use NumPy?

  • Faster operations than standard Python lists.
  • Supports vectorized computations without loops.
  • Memory efficient for large datasets.

Sunday, 23 February 2025

Python Coding challenge - Day 391| What is the output of the following Python Code?

 


Step-by-Step Explanation

1. Importing create_engine

from sqlalchemy import create_engine

create_engine is a function in SQLAlchemy that creates a database engine.

This engine serves as the core interface between Python and the database.


2. Creating an In-Memory SQLite Database

engine = create_engine("sqlite:///:memory:")

"sqlite:///:memory:" tells SQLite to create a temporary, in-memory database.

This means:

The database only exists in RAM.

It disappears once the script stops running.

No .db file is created.


3. Establishing a Connection

conn = engine.connect()

This opens a connection to the SQLite database.

The connection allows you to execute SQL queries.


4. Retrieving Table Names

print(engine.table_names())

Purpose: It attempts to list all tables in the database.

Problem: engine.table_names() is deprecated in SQLAlchemy 1.4+.

Alternative for SQLAlchemy 1.4+

Instead of engine.table_names(), use:

from sqlalchemy import inspect

inspector = inspect(engine)

print(inspector.get_table_names())  # Recommended

This is the correct way to retrieve table names in modern SQLAlchemy versions.

Final Output:

Since we haven't created any tables, the output will be:

[]

Python Coding challenge - Day 390| What is the output of the following Python Code?


 Step-by-Step Explanation

1. Importing List from typing

from typing import List

The typing module provides type hints to improve code readability and maintainability.

List[int] indicates that nums should be a list of integers.

2. Defining the Function

def add_numbers(nums: List[int]) -> int:

Function name: add_numbers

Parameter:

nums: List[int] → A list containing integers.

Return type: int → The function is expected to return an integer.

3. Summing the Numbers

return sum(nums)

sum(nums) calculates the sum of all integers in the list.

4. Calling the Function

print(add_numbers([1, 2, 3]))

[1, 2, 3] is passed to add_numbers.

sum([1, 2, 3]) evaluates to 1 + 2 + 3 = 6.

print(6) outputs:

6

Final Output

6

Python Coding challenge - Day 389| What is the output of the following Python Code?

 


Code Explanation:

1. Understanding Descriptors

A descriptor is a class that defines special methods (__get__, __set__, __delete__) to control attribute access in another class.

Here, Descriptor implements __get__, meaning it controls what happens when its attribute is accessed.


2. Defining the Descriptor Class

class Descriptor:

    def __get__(self, obj, objtype=None): 

        return 42

The __get__ method is triggered whenever an instance of a class accesses an attribute that is a descriptor.

It takes three parameters:

self → The descriptor instance itself.

obj → The instance of the class where the descriptor is being accessed (e.g., t of Test).

objtype → The class type of the instance (i.e., Test).

The method always returns 42, regardless of the object or class.

3. Defining and Using the Test Class

class Test:

    value = Descriptor()

value is an instance of Descriptor, meaning it is a data descriptor for the Test class.

Since value is a class attribute, any access to Test().value triggers Descriptor.__get__.

4. Accessing the Descriptor

t = Test()

print(t.value)

When t.value is accessed, Python does not return a normal instance attribute. Instead:

It detects that value is a descriptor.

Calls Descriptor.__get__(self=Descriptor instance, obj=t, objtype=Test).

The __get__ method returns 42.

Final Output:

42


Python Coding challenge - Day 388| What is the output of the following Python Code?

 


Step-by-step Execution:


Function outer(x) is defined

It takes one parameter x.

Inside outer, another function inner(y) is defined.

inner(y) returns the sum of x (from outer) and y.


Calling outer(10)

x = 10 is passed as an argument.

The function inner(y) is returned as a closure, meaning it "remembers" the value of x = 10.


Assigning f = outer(10)

Now, f is essentially inner(y) but with x = 10 already captured.


Calling f(5)

This is equivalent to calling inner(5), where y = 5.

inner(y) computes 10 + 5 = 15.


Final Output:

15

Heart shape pattern plot using python


 import numpy as np

import matplotlib.pyplot as plt

t=np.linspace(0,2*np.pi,500)

x=16*np.sin(t)**3

y=13*np.cos(t)-5*np.cos(2*t)-2*np.cos(3*t)-np.cos(4*t)

plt.figure(figsize=(6,6))

plt.plot(x,y,color='red',linewidth=8)

plt.title("heartshape pattern plot",fontsize=14)

plt.axis("equal")

plt.axis("off")

plt.show()

#source code --> clcoding.com 

Code Explanation:

Step 1: Importing Required Libraries

import numpy as np

import matplotlib.pyplot as plt

NumPy (np): Used to create numerical arrays and perform mathematical operations efficiently.

Matplotlib (plt): A powerful plotting library that allows visualization of data in various formats.


Step 2: Creating the Parameter t

t = np.linspace(0, 2 * np.pi, 500)

The variable t is an array of 500 evenly spaced values between 0 and 2π.

This range is crucial because it allows the parametric equations to fully define the heart shape. More points would create a smoother curve, while fewer points would make it look more jagged.


Step 3: Defining the Heart Shape Equations

x = 16 * np.sin(t)**3

y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)

These equations define the x and y coordinates of the heart shape.


Explanation of the x Equation:

x = 16 * np.sin(t)**3

np.sin(t) generates a sine wave between -1 and 1.

Cubing it (**3) amplifies the curvature and ensures the heart shape is symmetric.

The factor 16 scales the shape horizontally.


Explanation of the y Equation:

y = 13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)

The primary component is 13 * np.cos(t), which determines the general height and shape.

The additional cosine terms (cos(2t), cos(3t), cos(4t)) refine the shape, adding the necessary dips and curves to resemble a heart.

The coefficients (13, -5, -2, -1) adjust the proportions of the lobes and the bottom curve.


Step 4: Plotting the Heart

plt.figure(figsize=(6, 6))

plt.plot(x, y, color='red', linewidth=8)  

plt.figure(figsize=(6,6)): Creates a square figure (6x6 inches) to ensure the heart doesn’t look distorted.

plt.plot(x, y, color='red', linewidth=8):

Plots the heart shape using the x and y coordinates.

The color is set to red to resemble a traditional heart.

The linewidth is set to 8, making the heart bold and thick.


Step 5: Customizing the Display

plt.title("Heart shape pattern plot", fontsize=16)

plt.axis("equal")

plt.axis("off")

plt.title("Heart shape pattern plot", fontsize=16): Adds a title to the plot with a larger font size for visibility.

plt.axis("equal"): Ensures the aspect ratio remains 1:1, preventing distortion.

plt.axis("off"): Hides the axes, making the heart the only focus.


Step 6: Displaying the Heart

plt.show()

This renders the heart shape and displays it on the screen.



Butterfly pattern plot using python


import numpy as np
import matplotlib.pyplot as plt
t=np.linspace(0,2*np.pi,300)

x = np.sin(t)*(np.exp(np.cos(t))-2*np.cos(4*t))  
y = np.cos(t)*(np.exp(np.cos(t))-2*np.cos(4*t))  

plt.plot(x,y,color='purple',linewidth=2)
plt.plot(-x,y,color='orange',linewidth=2)

plt.title("Beautiful butterfly pattern plot",fontsize=14)
plt.axis("off")
plt.axis("equal")
plt.show()
#source code --> clcoding.com 

Code Explanation:

Importing Necessary Libraries

import numpy as np

import matplotlib.pyplot as plt

numpy: Used to generate an array of numbers (t) and perform mathematical operations.

matplotlib.pyplot: Used to plot the butterfly pattern.

Generating Values for the Plot

t = np.linspace(0, 2*np.pi, 300)

t is a NumPy array containing 300 values evenly spaced between 0 and 2π.

These values act as the parameter for our equations.


Defining the X and Y Coordinates

x = np.sin(t) * (np.exp(np.cos(t)) - 2*np.cos(4*t))  

y = np.cos(t) * (np.exp(np.cos(t)) - 2*np.cos(4*t))  

np.sin(t) and np.cos(t) create a symmetrical shape.

These equations define a butterfly-like pattern.


Creating the Plot

plt.figure(figsize=(6, 6))

This sets the figure size to 6x6 inches.

It ensures that the butterfly shape is not stretched.


Plotting the Butterfly Wings

plt.plot(x, y, color='purple', linewidth=2)   

plt.plot(-x, y, color='orange', linewidth=2)  

The first plot plt.plot(x, y, ...) creates one wing.

The second plot plt.plot(-x, y, ...) mirrors the first wing.

Colors:

Purple for one side

Orange for the mirrored side


Adding Aesthetics

plt.title("Beautiful Butterfly Pattern ", fontsize=14)

plt.axis("equal")  # Keeps the proportions equal

plt.axis("off")    # Hides the axes for a clean look

Title makes the plot more readable.

Equal aspect ratio prevents stretching or distortion.

Axis removal ensures focus on the butterfly.


Displaying the Plot

plt.show()

This renders the butterfly pattern.


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)