rows = int(input("Enter the number of rows: "))
for i in range(rows, 0, -1):
print("*" * i)
#source code --> clcoding.com
Python Developer December 14, 2024 100 Python Programs for Beginner No comments
rows = int(input("Enter the number of rows: "))
for i in range(rows, 0, -1):
print("*" * i)
#source code --> clcoding.com
Python Developer December 14, 2024 100 Python Programs for Beginner No comments
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print(f"The area of the triangle is: {area:.2f}")
#source code --> clcoding.com
Python Developer December 14, 2024 100 Python Programs for Beginner No comments
def binary_to_gray(binary_str):
"""
Function to convert a binary number to its corresponding Gray Code.
:param binary_str: The input binary string.
:return: The converted Gray Code string.
"""
gray_code = binary_str[0]
for i in range(1, len(binary_str)):
gray_bit = str(int(binary_str[i - 1]) ^ int(binary_str[i]))
gray_code += gray_bit
return gray_code
binary_input = input("Enter a binary number to convert into Gray Code: ")
if all(bit in '01' for bit in binary_input):
result = binary_to_gray(binary_input)
print(f"Binary number: {binary_input}")
print(f"Corresponding Gray Code: {result}")
else:
print("Invalid input. Please enter a valid binary number consisting only of 0's and 1's.")
#source code --> clcoding.com
Python Developer December 14, 2024 100 Python Programs for Beginner No comments
def binary_equivalent(number):
if number == 0:
return ""
return binary_equivalent(number // 2) + str(number % 2)
number = int(input("Enter an integer: "))
if number == 0:
print("The binary equivalent of 0 is 0.")
elif number > 0:
print(f"The binary equivalent of {number} is {binary_equivalent(number)}.")
else:
print(f"The binary equivalent of {number} is -{binary_equivalent(abs(number))}.")
#source code --> clcoding.com
Python Developer December 14, 2024 100 Python Programs for Beginner No comments
num = int(input("Enter a number to find its factorial: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is: {factorial}")
#source code --> clcoding.com
Python Developer December 14, 2024 100 Python Programs for Beginner No comments
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is {factorial(num)}.")
#source code --> clcoding.com
Python Developer December 14, 2024 100 Python Programs for Beginner No comments
def fibonacci_series(n):
a, b = 0, 1
series = []
for _ in range(n):
series.append(a)
a, b = b, a + b
return series
num_terms = int(input("Enter the number of terms: "))
if num_terms <= 0:
print("Please enter a positive integer.")
else:
print("Fibonacci series:")
print(fibonacci_series(num_terms))
#source code --> clcoding.com
1. Function Definition: fibonacci_series(n)
The function takes a single parameter, n, which represents the number of terms in the Fibonacci sequence to generate.
Inside the function:
a, b = 0, 1: Initializes the first two numbers of the Fibonacci sequence, where a starts at 0 and b at 1.
series = []: Creates an empty list to store the Fibonacci sequence.
2. Generating Fibonacci Terms
for _ in range(n)::
Iterates n times to generate the sequence.
The loop variable _ is used when the variable itself is not needed.
series.append(a):
Adds the current value of a (the current Fibonacci number) to the series list.
a, b = b, a + b:
Updates a to the value of b (the next Fibonacci number).
Updates b to the sum of a and b (the next-next Fibonacci number).
This update effectively shifts the series forward.
3. Returning the Result
After the loop ends, the complete Fibonacci sequence is stored in series.
The function returns the series list.
Main Program
4. Input from User
num_terms = int(input("Enter the number of terms: ")):
Prompts the user to input the number of terms they want in the Fibonacci sequence.
Converts the input to an integer and stores it in num_terms.
5. Input Validation
if num_terms <= 0::
Checks if the input is less than or equal to 0 (invalid input).
If invalid, prints a message: "Please enter a positive integer.".
else::
If the input is valid (a positive integer), proceeds to generate the Fibonacci sequence.
6. Generating and Printing the Sequence
print("Fibonacci series:"):
Outputs a message indicating that the Fibonacci sequence will follow.
print(fibonacci_series(num_terms)):
Calls the fibonacci_series function with the user-specified number of terms and prints the returned list.
Python Developer December 13, 2024 Python Coding Challenge No comments
Python Developer December 13, 2024 Python Coding Challenge No comments
Importing NumPy:
import numpy as np imports the NumPy library for numerical computations.
Creating a 2D Array:
arr = np.array([[1, 2], [3, 4]]) creates a 2-dimensional NumPy array:
[[1, 2],
[3, 4]]
The array has 2 rows and 2 columns.
Printing the Shape:
arr.shape returns a tuple representing the dimensions of the array.
In this case, the array has:
2 rows
2 columns
So, arr.shape will return (2, 2).
(2, 2)
Python Developer December 13, 2024 Python Coding Challenge No comments
Python Developer December 13, 2024 Python Coding Challenge No comments
range(5):
The range(5) generates numbers from 0 to 4 (not including 5).
The loop iterates through these numbers one by one (i takes values 0, 1, 2, 3, 4).
The if Condition:
Inside the loop, the statement if i == 3 checks if the current value of i equals 3.
If this condition is True, the break statement is executed, which exits the loop immediately, stopping further iteration.
print(i):
The print(i) statement executes for every value of i before the loop encounters the break.
If i equals 3, the loop terminates, and print(i) is not executed for that value or any values after it.
Python Developer December 13, 2024 Python Coding Challenge No comments
Importing NumPy:
The statement import numpy as np imports the NumPy library, which is a popular Python library for numerical computations.
Creating an Array:
arr = np.array([1, 2, 3, 4]) creates a NumPy array with the elements [1, 2, 3, 4].
NumPy arrays are similar to Python lists but optimized for numerical operations.
Adding a Scalar to an Array:
arr + 2 adds the scalar value 2 to each element of the array. This operation is called broadcasting in NumPy.
Broadcasting automatically applies the operation to each element of the array without requiring a loop.
Printing the Result:
print(arr + 2) outputs the result of the broadcasting operation.
Final Output:
[3 4 5 6]
Python Developer December 12, 2024 Python Coding Challenge No comments
Function Definition with a Default Argument:
def func(x=[]):
The function func is defined with a default parameter x, which is initialized to an empty list [] if no argument is passed during the function call.
Important behavior: Default arguments are evaluated once when the function is defined, not each time the function is called. This means if you use a mutable default argument (like a list), it will persist across multiple function calls.
Appending to the List:
x.append(1)
Inside the function, the code x.append(1) adds the value 1 to the list x.
Since x is initialized to an empty list [], 1 will be appended to it on the first call.
Return the List:
return x
After appending 1, the list x is returned.
First Function Call:
print(func())
When func() is called the first time, the default list x is an empty list [].
1 is appended to this list, making it [1], and this list is returned and printed.
Second Function Call:
print(func())
When func() is called the second time, the same list is used (because of the default argument behavior).
The list from the previous call already contains [1].
1 is appended again, so the list becomes [1, 1], and this list is returned and printed.
[1]
[1, 1]
Python Developer December 12, 2024 Python Coding Challenge No comments
Define the Function:
def mystery(a, b, c):
A function named mystery is defined with three parameters: a, b, and c.
Use of Ternary Conditional Operator:
return a if a > b else c
This is a ternary conditional statement in Python.
It evaluates the condition a > b:
If a > b is True, the function returns a.
If a > b is False, the function returns c.
Call the Function:
result = mystery(5, 3, 10)
The function mystery is called with arguments 5, 3, and 10, i.e., a = 5, b = 3, and c = 10.
Evaluate the Conditional Statement:
The condition a > b is evaluated:
a = 5 and b = 3, so 5 > 3 is True.
Since the condition is true, the function returns a, which is 5.
Print the Result:
print(result)
The value returned by the function (5) is stored in the variable result and printed.
Final Output:
5
Python Developer December 12, 2024 Python Coding Challenge No comments
Create a Dictionary Using a Dictionary Comprehension:
x = {i: i ** 2 for i in range(3)}
This creates a dictionary x where:
The keys are numbers generated by range(3) (i.e., 0, 1, and 2).
The values are the squares of the keys.
The resulting dictionary is:
x = {0: 0, 1: 1, 2: 4}
Access the Dictionary Keys:
y = x.keys()
x.keys() returns a dictionary view object that dynamically reflects the keys of the dictionary x.
At this point, y contains the keys of x: {0, 1, 2}.
Modify the Dictionary:
x[3] = 9
A new key-value pair is added to the dictionary x.
The dictionary now becomes:
x = {0: 0, 1: 1, 2: 4, 3: 9}
Convert the Keys to a List:
print(list(y))
Since y is a dictionary view object, it dynamically reflects the keys of the dictionary x.
Even though y was assigned before modifying x, it still reflects the updated dictionary x.
The keys of x at this point are [0, 1, 2, 3].
[0, 1, 2, 3]
Purpose of the Code:
The function func(nums) is designed to compute the product of all elements in the input list nums.
Multiplication is achieved using a loop that iterates through each element of nums and multiplies it with a variable (result) initialized to 1.
Initialization:
result = 1
The variable result is initialized with the value 1.
Starting with 1 is crucial because 1 is the identity value for multiplication (multiplying any number by 1 leaves the number unchanged).
Iteration and Multiplication:
for n in nums:
result *= n
The for loop iterates over each element n in the list nums.
In each iteration:
result *= n is equivalent to result = result * n.
The current value of n is multiplied with result, and the updated value is stored back in result.
Return the Result:
return result
After all elements in nums have been processed by the loop, the accumulated product (stored in result) is returned as the output.
Python Developer December 12, 2024 Python Coding Challenge No comments
Define a Recursive Function:
def recursive_sum(n):
A function named recursive_sum is defined.
This function takes a single parameter n, which represents the number up to which the sum is calculated.
Base Case:
if n == 0:
return 0
This is the base case of the recursion.
If n is 0, the function stops recursing and returns 0.
The base case is essential to prevent infinite recursion.
Recursive Case:
return n + recursive_sum(n - 1)
If n is not 0, the function returns n added to the result of recursive_sum(n - 1).
This means the function calls itself with the argument n - 1 and continues reducing n until the base case is reached.
Print the Result:
print(recursive_sum(5))
The function is called with n = 5.
The function recursively calculates the sum of numbers from 5 to 1.
Recursive Flow:
When recursive_sum(5) is called:
5 + recursive_sum(4)
4 + recursive_sum(3)
3 + recursive_sum(2)
2 + recursive_sum(1)
1 + recursive_sum(0)
Base case reached, returns 0.
Returns 1 + 0 = 1.
Returns 2 + 1 = 3.
Returns 3 + 3 = 6.
Returns 4 + 6 = 10.
Returns 5 + 10 = 15.
15
Python Developer December 12, 2024 Python Coding Challenge No comments
Python Coding December 12, 2024 Python Quiz No comments
Shallow Copy (copy()):
Slice Assignment:
List Expansion/Contraction:
| Step | List a | List b |
|---|---|---|
| Initial state | [1, 2, 3] | [1, 2, 3] |
| After copy | [1, 2, 3] | [1, 2, 3] |
| After assignment | [1, 4, 5, 3] | [1, 2, 3] |
Python Coding December 12, 2024 Python Quiz No comments
Shallow Copy:
In-place Modification:
Python Developer December 11, 2024 100 Python Programs for Beginner No comments
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is {factorial(num)}.")
#source code --> clcoding.com
Python Developer December 11, 2024 100 Python Programs for Beginner No comments
n = input("Enter a number: ")
result = int(n) + int(n*2) + int(n*3)
print("Result:", result)
1. Taking User Input:
#source code --> clcoding.com
Python Developer December 11, 2024 100 Python Programs for Beginner No comments
def reverse_a_number(number):
reversed_a_number = int(str(number)[::-1])
return reversed_a_number
number = int(input("Enter a number:"))
reversed_a_num = reverse_a_number(number)
print(f"The reverse of {number} is {reversed_a_num}.")
#source code --> clcoding.com
Python Coding December 11, 2024 Python Quiz No comments
Python Developer December 11, 2024 Python Coding Challenge No comments
1. Class Definition
class MyClass:
A class named MyClass is defined. Classes in Python are blueprints for creating objects, but they can also contain methods that can be called without creating an instance of the class.
2. @classmethod Decorator
@classmethod
def hello(cls):
The @classmethod decorator makes the method hello a class method.
Class methods:
Take the class itself as the first argument, which is conventionally named cls.
Can be called directly on the class without requiring an instance.
Here, cls refers to the class MyClass.
3. The Method Implementation
print(f"Hello from {cls.__name__}")
Inside the hello method:
The cls parameter gives access to the class object.
cls.__name__ retrieves the name of the class (MyClass in this case).
The print statement outputs a message using the class name.
MyClass.hello()
The class method hello is called directly on the class MyClass, without creating an instance.
The cls parameter inside the method refers to MyClass.
Hello from MyClass
Python Developer December 11, 2024 Python Coding Challenge No comments
1. List Definition
x = [1, 2, 3]
A list x is defined with three elements: [1, 2, 3].
List indexing in Python starts at 0. So:
x[0] is 1
x[1] is 2
x[2] is 3
2. Using the pop() Method
y = x.pop(1)
The pop() method removes and returns an element from the list at the specified index.
Here, 1 is passed as the argument, meaning the element at index 1 (the second element, 2) is removed from the list x.
After x.pop(1), the following happens:
The value 2 is removed from the list.
The updated list becomes [1, 3].
The removed value (2) is returned by pop() and assigned to the variable y.
3. Printing the Result
print(y)
The value of y (which is 2) is printed to the console.
2
Python Developer December 11, 2024 Python Coding Challenge No comments
1. The for Loop
for i in range(3):
The range(3) function generates a sequence of numbers starting from 0 up to, but not including, 3. The sequence is: [0, 1, 2].
The for loop iterates over each number in this sequence:
On the first iteration, i is 0.
On the second iteration, i is 1.
On the third iteration, i is 2.
2. The print() Function with end Parameter
print(i, end=", ")
The print() function is used to display output.
Normally, print() adds a newline (\n) after each call. However, the end parameter allows you to specify a custom string to append instead of the default newline.
Here, end=", " means a comma followed by a space (", ") is appended to the output instead of moving to the next line.
3. Output Construction
The loop executes print(i, end=", ") for each value of i:
On the first iteration: i = 0, so 0, is printed.
On the second iteration: i = 1, so 1, is appended.
On the third iteration: i = 2, so 2, is appended.
0, 1, 2,
Python Developer December 11, 2024 Python Coding Challenge No comments
def multiply(x, y=2):
return x * y
print(multiply(3))
Explanation:
1. Function Definition with a Default Argument
def multiply(x, y=2):
return x * y
The function multiply is defined with two parameters:
x: This is a required parameter that must be provided when the function is called.
y: This is an optional parameter with a default value of 2. If no value is provided for y during the function call, it defaults to 2.
The function returns the product of x and y.
2. Function Call
print(multiply(3))
Here, the function multiply is called with only one argument: 3. This value is assigned to x.
Since no value is provided for y, it uses its default value of 2.
The calculation inside the function becomes:
3 * 2 = 6
3. Output
The function returns 6, which is passed to the print function.
6
Python Developer December 11, 2024 Python Coding Challenge No comments
1. Defining the Function
def square(n):
return n ** 2
A function named square is defined. It takes one argument, n.
The function returns the square of n (i.e., n ** 2).
2. Using map()
result = map(square, [1, 2, 3])
The map() function applies a given function (here, square) to each item in an iterable (here, the list [1, 2, 3]).
The square function is called for each element in the list:
For 1: square(1) → 1 ** 2 → 1
For 2: square(2) → 2 ** 2 → 4
For 3: square(3) → 3 ** 2 → 9
The map() function returns a map object, which is an iterator that contains the results (1, 4, 9).
3. Converting to a List
print(list(result))
The map object is converted into a list using list(result), which materializes the results of the map() operation.
[1, 4, 9]
Python Developer December 11, 2024 Python Coding Challenge No comments
Step 1: Defining the Function
The function subtract(a, b) takes two arguments, a and b, and returns the result of a - b.
Step 2: Understanding the Nested Function Call
The key to understanding this code is evaluating the inner function call first.
Inner Function Call:
subtract(4, 2)
Here, a = 4 and b = 2.
The function returns:
4 - 2 = 2
Outer Function Call:
Now substitute the result of the inner call (2) into the outer function call:
subtract(7, 2)
Here, a = 7 and b = 2.
The function returns:
7 - 2 = 5
Step 3: Storing and Printing the Result
The result of the entire expression, 5, is stored in the variable result:
result = 5
Output: 5
Python Developer December 11, 2024 Python Coding Challenge No comments
1. Creating the Set my_set
my_set = {1, 2, 3} creates a set with the elements {1, 2, 3}.
A set in Python is a collection of unique, unordered elements. Duplicate elements are not allowed.
2. Using the union Method
my_set.union({3, 4, 5}) combines all the unique elements from my_set and the set {3, 4, 5} into a new set.
The union() method does not modify the original set (my_set) but returns a new set containing the combined unique elements.
3. Combining Sets
my_set contains {1, 2, 3}.
The input to union is {3, 4, 5}.
The union of these two sets includes all unique elements:
{1, 2, 3, 4, 5}
Notice that 3 is present in both sets, but since sets do not allow duplicates, it appears only once.
4. Printing the Result
print(result) outputs:
{1, 2, 3, 4, 5}
The order of elements in the printed result may vary because sets in Python are unordered.
Python Coding December 10, 2024 Python Coding Challenge No comments
Variable a:
Variable b:
The - (unary minus) operator negates the value of a.Variable c:
c = ~a:
The ~ (bitwise NOT) operator inverts all the bits of the number in its binary representation.
So, ~5 = -(5 + 1) = -6.
Python Developer December 10, 2024 Python Coding Challenge No comments
Function Definition:
def square(n):
return n ** 2
A function named square is defined.
It takes one parameter, n.
The function returns the square of n (n ** 2).
Using map:
result = map(square, [1, 2, 3])
The map() function applies a specified function (square in this case) to each item in an iterable ([1, 2, 3]).
The result of map() is an iterator, which lazily applies the square function to each element in the list.
Execution of map(square, [1, 2, 3]):
Resulting iterator contains the values: 1, 4, 9.
Converting the Iterator to a List:
print(list(result))
The list() function is used to convert the iterator returned by map() into a list.
The resulting list: [1, 4, 9].
The print() function then outputs this list.
[1, 4, 9]
Python Developer December 10, 2024 Python Coding Challenge No comments
Purpose of try and except:
Python uses try and except blocks to handle exceptions (runtime errors) gracefully.
When code inside the try block raises an exception, the program's execution jumps to the corresponding except block to handle it.
This prevents the program from crashing and allows it to handle errors in a controlled way.
Division by Zero:
x = 5 / 0
Inside the try block, the code attempts to divide 5 by 0.
Division by zero is not allowed in Python, so it raises a ZeroDivisionError exception.
Handling the Exception:
except ZeroDivisionError:
print("Cannot divide by zero!")
When the ZeroDivisionError is raised, the program execution jumps to the except block.
Inside the except block, a message is printed: "Cannot divide by zero!".
Program Flow:
The program does not crash because the exception is handled.
Once the except block is executed, the program continues (if there are additional statements after this block).
Cannot divide by zero!
Python Developer December 10, 2024 Python Coding Challenge No comments
List Definition:
nums = [1, 2, 3, 4, 5]
A list named nums is defined containing integers from 1 to 5.
List Comprehension:
result = [n for n in nums if n % 2 == 0]
This is a list comprehension that creates a new list based on a condition.
Syntax: [expression for item in iterable if condition]
In this case:
n is each element in the list nums.
The condition n % 2 == 0 checks if n is divisible by 2 (i.e., if n is an even number).
Only elements in nums that satisfy this condition are included in the new list result.
Execution:
1 % 2 == 0 → False → Not included.
2 % 2 == 0 → True → Included.
3 % 2 == 0 → False → Not included.
4 % 2 == 0 → True → Included.
5 % 2 == 0 → False → Not included.
Resulting list: [2, 4].
Print Statement:
print(result)
The print() function outputs the value of result.
[2, 4]
Python Developer December 10, 2024 Python Coding Challenge No comments
Dictionary Creation:
my_dict = {'a': 1, 'b': 2, 'c': 3}
A dictionary named my_dict is created.
It contains three key-value pairs:
'a': 1
'b': 2
'c': 3
Using get() Method:
my_dict.get('d', 'Not Found')
The get() method is used to retrieve the value associated with a specified key from the dictionary.
It takes two arguments:
The key to look for ('d' in this case).
A default value to return if the key does not exist in the dictionary ('Not Found').
In this code:
The key 'd' is not present in the dictionary.
The get() method returns the default value 'Not Found'.
Print Statement:
print(my_dict.get('d', 'Not Found'))
The print() function outputs the result returned by the get() method.
Not Found
Python Coding December 10, 2024 Python Quiz No comments
Python Developer December 10, 2024 Python Coding Challenge No comments
Function Definition:
def func(a, b=2, c=3):
return a + b + c
A function named func is defined.
It takes three parameters:
a (required parameter).
b (optional parameter with a default value of 2).
c (optional parameter with a default value of 3).
The function returns the sum of a, b, and c.
Function Call:
print(func(5, c=10))
The function func is called with two arguments:
5 for the first parameter a.
10 for the parameter c.
The parameter b is not provided in the function call, so it uses its default value of 2.
The function call can be understood as:
func(a=5, b=2, c=10)
Execution of the Function: Inside the function, the expression a + b + c is evaluated:
a = 5
b = 2
c = 10
The calculation: 5 + 2 + 10 = 17.
Output: The function returns 17, and the print statement displays it on the console.
17
Python Developer December 10, 2024 Python Coding Challenge No comments
Python Coding December 10, 2024 Python Coding Challenge No comments
Calculate the modulus:
x % y = 55 % 7 = 6
(This gives the remainder when 55 is divided by 7.)
Calculate the floor division:
x // y = 55 // 7 = 7
(This gives the quotient when 55 is divided by 7, ignoring the remainder.)
Multiply the quotient by z:
(x // y) * z = 7 * 6 = 42
Add the modulus to the result:
(x % y) + ((x // y) * z) = 6 + 42 = 48
48
Free Books Python Programming for Beginnershttps://t.co/uzyTwE2B9O
— Python Coding (@clcoding) September 11, 2023
Top 10 Python Data Science book
— Python Coding (@clcoding) July 9, 2023
๐งต:
Top 4 free Mathematics course for Data Science ! pic.twitter.com/s5qYPLm2lY
— Python Coding (@clcoding) April 26, 2024
Web Development using Python
— Python Coding (@clcoding) December 2, 2023
๐งต: