Monday, 23 December 2024
How to install Jupyter Notebook (Python)
Python Coding December 23, 2024 Python No comments
Step 1: Install Python
- Download Python: Go to Python.org and download the latest version.
- Install Python:
- During installation, ensure you check the box "Add Python to PATH".
- Complete the installation process.
Step 2: Install Jupyter Notebook
You can install Jupyter Notebook using pip (Python's package manager).
- Open a terminal (Command Prompt, PowerShell, or any shell).
- Run the following command:pip install notebook
Step 3: Verify Installation
- Check if Jupyter is installed by typing:
If it shows the version, the installation was successful.jupyter --version
Step 4: Start Jupyter Notebook
- To start Jupyter Notebook, type:jupyter notebook
- This will open Jupyter in your default web browser.
- You can now create and run .ipynb files (notebooks).
Optional: Install Jupyter via Anaconda
If you want an all-in-one solution with additional tools:
- Download Anaconda from anaconda.com.
- Install it and Jupyter Notebook will be included.
Step 5: Create a Notebook
- After starting Jupyter Notebook, it will open in your web browser showing the home directory.
- Click on "New" (on the right side) and select Python 3 (or any other kernel you have installed).
- A new notebook will open where you can write and run Python code.
Step 6: Running Code in Jupyter Notebook
- Write your Python code in a cell.
- Press Shift + Enter to execute the code and move to the next cell.
Step 7: Stop Jupyter Notebook
- To stop Jupyter Notebook, go to the terminal where it’s running and press Ctrl + C.
- Confirm by typing y and pressing Enter.
Tips for Beginners
- Save your work: Use File → Save and Checkpoint.
- Add Markdown: Switch the cell type to Markdown to write text and format it.
You're all set to explore and use Jupyter Notebook!
Day 54: Python Program to Find Sum of Series 1/1!+1/2!+1/3!....1/N!
Python Developer December 23, 2024 100 Python Programs for Beginner No comments
import math
def sum_of_series(n):
"""
Calculates the sum of the series 1/1! + 1/2! + 1/3! + ... + 1/N!
:param n: The number of terms in the series
:return: The sum of the series
"""
if n <= 0:
return "N should be a positive integer."
total_sum = 0
for i in range(1, n + 1):
total_sum += 1 / math.factorial(i)
return total_sum
try:
N = int(input("Enter a positive integer N: "))
if N <= 0:
print("Please enter a positive integer.")
else:
result = sum_of_series(N)
print(f"The sum of the series for N={N} is: {result:.6f}")
except ValueError:
print("Invalid input! Please enter a positive integer.")
#source code --> clcoding.com
Code Explanation:
1. Importing the math module:
import math
The math module provides access to mathematical functions, including math.factorial() used in this program.
2. Function Definition:
def sum_of_series(n):
"""
Calculates the sum of the series 1/1! + 1/2! + 1/3! + ... + 1/N!
:param n: The number of terms in the series
:return: The sum of the series
"""
This function calculates the sum of the series up to 𝑁 terms.
3. Input Validation:
if n <= 0:
return "N should be a positive integer."
Ensures that N is a positive integer. If N≤0, an error message is returned.
4. Series Calculation:
total_sum = 0
for i in range(1, n + 1):
total_sum += 1 / math.factorial(i)
total_sum: Accumulates the sum of the series. Initially set to 0.
for i in range(1, n + 1): Loops through integers from 1 to 𝑁
math.factorial(i): Computes i!, the factorial of 𝑖
1 / math.factorial(i): Adds the term 1/𝑖! to the total sum.
5. Returning the Result:
return total_sum
Returns the computed sum of the series.
6. User Input Handling:
try:
N = int(input("Enter a positive integer N: "))
if N <= 0:
print("Please enter a positive integer.")
else:
result = sum_of_series(N)
print(f"The sum of the series for N={N} is: {result:.6f}")
except ValueError:
print("Invalid input! Please enter a positive integer.")
try block:
Prompts the user for an integer input for 𝑁.
If the user enters a valid positive integer:
Checks if
N>0. If not, prints an error message.
Otherwise, calls sum_of_series(N) to compute the sum and prints the result with six decimal places.
except block:
Handles invalid inputs (e.g., entering a string or decimal) and displays an error message.
Python Coding Challange - Question With Answer(01231224)
Python Coding December 23, 2024 Python Quiz No comments
What will be the output of the following code?
import numpy as np
arr = np.arange(1, 10).reshape(3, 3)
result = arr.sum(axis=0) - arr.sum(axis=1)
print(result)
[0, 0, 0]
[1, -1, 1]
[3, -3, 3]
[2, 2, -2]
Step 1: Create the array with np.arange(1, 10)
The function np.arange(1, 10) creates a 1D NumPy array containing integers from 1 to 9 (inclusive of 1 but exclusive of 10).
np.arange(1, 10) = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Step 2: Reshape the array to 3x3
The method .reshape(3, 3) converts the 1D array into a 2D array with 3 rows and 3 columns:
arr = [[1, 2, 3], [4, 5, 6],
[7, 8, 9]]
Step 3: Compute arr.sum(axis=0)
The parameter axis=0 means sum along columns (vertically).
For each column, we add the elements from the top to the bottom:
- First column: 1+4+7=12
- Second column: 2+5+8=15
- Third column: 3+6+9=18
Result of arr.sum(axis=0):
[12, 15, 18]
Step 4: Compute arr.sum(axis=1)
The parameter axis=1 means sum along rows (horizontally).
For each row, we add the elements from left to right:
- First row: 1+2+3=6
- Second row: 4+5+6=15
- Third row: 7+8+9=24
Result of arr.sum(axis=1):
[6, 15, 24]
Step 5: Perform element-wise subtraction
The subtraction operation is element-wise, meaning corresponding elements of the two arrays are subtracted.
- 12−6=6
- 15−15=0
- 18−24=−6
Result of arr.sum(axis=0) - arr.sum(axis=1):
[6, 0, -6]
Step 6: Print the result
Finally, the result is printed:
[6, 0, -6]
Key Points:
- axis=0 computes the sum along columns (vertically).
- axis=1 computes the sum along rows (horizontally).
- Subtraction is performed element-wise between the two resulting arrays.
Sunday, 22 December 2024
Day 53: Python Program to Find Sum of Series 1+1/2+1/3...+1/N
Python Developer December 22, 2024 100 Python Programs for Beginner No comments
def sum_of_series(n):
if n <= 0:
return "N should be a positive integer."
total_sum = 0
for i in range(1, n + 1):
total_sum += 1 / i
return total_sum
try:
N = int(input("Enter a positive integer N: "))
if N <= 0:
print("Please enter a positive integer.")
else:
result = sum_of_series(N)
print(f"The sum of the series for N={N} is: {result:.6f}")
except ValueError:
print("Invalid input! Please enter a positive integer.")
#source code --> clcoding.com
Code Explanation:
Day 52: Python Program to Print an Identity Matrix
Python Developer December 22, 2024 100 Python Programs for Beginner No comments
def print_identity_matrix(n):
"""
Prints an identity matrix of size n x n.
:param n: Size of the identity matrix
"""
if n <= 0:
print("Please enter a positive integer for the size of the matrix.")
return
for i in range(n):
for j in range(n):
if i == j:
print(1, end=" ")
else:
print(0, end=" ")
print()
try:
size = int(input("Enter the size of the identity matrix: "))
print_identity_matrix(size)
except ValueError:
print("Invalid input! Please enter a valid integer.")
#source code --> clcoding.com
Code Explanation:
Saturday, 21 December 2024
Day 51: Python Program to Form an Integer that has Number of Digits at 10’s LSD at 1’s Place
Python Developer December 21, 2024 100 Python Programs for Beginner No comments
def form_integer(number):
if number < 0:
print("Please provide a non-negative integer.")
return None
num_str = str(number)
num_digits = len(num_str)
last_digit = int(num_str[-1])
result = num_digits * 10 + last_digit
return result
number = int(input("Enter a positive integer: "))
new_integer = form_integer(number)
if new_integer is not None:
print(f"The newly formed integer is: {new_integer}")
#source code --> clcoding.com
Code Explanation:
Day 50 : Python Program to Find Gravitational Force Between the Two Object
Python Developer December 21, 2024 100 Python Programs for Beginner No comments
import math
def calculate_gravitational_force(m1, m2, r):
"""Calculates the gravitational force between two objects."""
G = 6.67430e-11
force = G * (m1 * m2) / (r ** 2)
return force
def main():
print("Gravitational Force Calculator")
try:
mass1 = float(input("Enter the mass of the first object (kg): "))
mass2 = float(input("Enter the mass of the second object (kg): "))
distance = float(input("Enter the distance between the objects (m): "))
if mass1 <= 0 or mass2 <= 0 or distance <= 0:
print("Masses and distance must be positive values.")
return
force = calculate_gravitational_force(mass1, mass2, distance)
print(f"The gravitational force between the objects is {force:.2e} N.")
except ValueError:
print("Invalid input. Please enter numeric values.")
if __name__ == "__main__":
main()
#source code --> clcoding.com
Code Explanation:
Python Bitwise Operators: A Comprehensive Guide
Python Coding December 21, 2024 Python No comments
Bitwise operators in Python allow you to perform operations at the bit level. These operators are essential for tasks such as low-level programming, cryptography, and working with hardware. In this guide, we will explore all Python bitwise operators with clear examples to help you master their usage.
1. What Are Bitwise Operators?
Bitwise operators work on binary representations of numbers (bits). These operators directly manipulate the bits and return results based on bitwise operations. Python provides the following bitwise operators:
Operator | Name | Description | |||
---|---|---|---|---|---|
& | Bitwise AND | Sets each bit to 1 if both bits are 1 | |||
| | Bitwise OR |
| |||
^ | Bitwise XOR | Sets each bit to 1 if only one bit is 1 | |||
~ | Bitwise NOT | Inverts all the bits | |||
<< | Left Shift | Shifts bits to the left | |||
>> | Right Shift | Shifts bits to the right |
2. Understanding Binary Representation
Before diving into examples, it is crucial to understand how numbers are represented in binary.
For example:
5
in binary is0101
3
in binary is0011
3. **Bitwise AND (&
)
The &
operator compares each bit of two numbers. A bit is set to 1
if both corresponding bits are 1
.
Syntax:
result = a & b
Example:
a = 5 # Binary: 0101
b = 3 # Binary: 0011
result = a & b # Binary: 0001
print(result) # Output: 1
Truth Table:
Bit 1 | Bit 2 | Result |
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
4. **Bitwise OR (|
)
The |
operator compares each bit of two numbers. A bit is set to 1
if at least one of the corresponding bits is 1
.
Syntax:
result = a | b
Example:
a = 5 # Binary: 0101
b = 3 # Binary: 0011
result = a | b # Binary: 0111
print(result) # Output: 7
Truth Table:
Bit 1 | Bit 2 | Result |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
5. **Bitwise XOR (^
)
The ^
operator compares each bit of two numbers. A bit is set to 1
if the corresponding bits are different.
Syntax:
result = a ^ b
Example:
a = 5 # Binary: 0101
b = 3 # Binary: 0011
result = a ^ b # Binary: 0110
print(result) # Output: 6
Truth Table:
Bit 1 | Bit 2 | Result |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
6. **Bitwise NOT (~
)
The ~
operator inverts all the bits of a number. For positive numbers, it returns the negative value of the number minus one.
Syntax:
result = ~a
Example:
a = 5 # Binary: 0101
result = ~a # Binary: -0110
print(result) # Output: -6
Explanation:
In binary, ~5
flips all bits of 0101
to 1010
. In two's complement representation, this corresponds to -6
.
7. **Left Shift (<<
)
The <<
operator shifts the bits of a number to the left by the specified number of positions. Each left shift doubles the number.
Syntax:
result = a << n
Example:
a = 5 # Binary: 0101
result = a << 2 # Binary: 10100
print(result) # Output: 20
Explanation:
Shifting 0101
two places to the left gives 10100
, which is 20
in decimal.
8. **Right Shift (>>
)
The >>
operator shifts the bits of a number to the right by the specified number of positions. Each right shift divides the number by two (ignoring the remainder).
Syntax:
result = a >> n
Example:
a = 5 # Binary: 0101
result = a >> 2 # Binary: 0001
print(result) # Output: 1
Explanation:
Shifting 0101
two places to the right gives 0001
, which is 1
in decimal.
9. Combining Bitwise Operators
You can combine bitwise operators to perform complex bit-level operations.
Example:
a = 5 # Binary: 0101
b = 3 # Binary: 0011
# Combining operators
result = (a & b) | (~a)
print(result) # Output: -2
10. Practical Applications of Bitwise Operators
1. Setting and Clearing Bits
# Setting a bit
number = 0b1010
position = 1
number |= (1 << position)
print(bin(number)) # Output: 0b1011
# Clearing a bit
number &= ~(1 << position)
print(bin(number)) # Output: 0b1010
2. Checking if a Bit is Set
number = 0b1010
position = 2
is_set = (number & (1 << position)) != 0
print(is_set) # Output: True
3. Swapping Two Numbers Without a Temporary Variable
a = 5
b = 3
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b) # Output: 3, 5
11. Common Mistakes with Bitwise Operators
Mistake 1: Confusing Bitwise Operators with Logical Operators
a = 5
b = 3
# Incorrect: Using 'and' instead of '&'
result = a and b # Logical AND, not Bitwise AND
print(result) # Output: 3
Mistake 2: Ignoring Operator Precedence
result = ~a & b # Not the same as ~(a & b)
Use parentheses to make the precedence clear.
Conclusion
Bitwise operators are powerful tools in Python for performing low-level operations. They are invaluable in fields like cryptography, network programming, and embedded systems. By mastering these operators, you can write more efficient and optimized code.
Python Logical Operators: A Comprehensive Guide
Python Coding December 21, 2024 Python No comments
Logical operators in Python are essential tools for combining and manipulating conditional statements. They allow you to evaluate multiple conditions and return a boolean result (‘True’ or ‘False’). In this guide, we will delve deep into Python's logical operators: and
, or
, and not
, along with practical examples.
1. What are Logical Operators?
Logical operators are used to combine conditional expressions. The result of a logical operation depends on the truth values (‘True’ or ‘False’) of the individual expressions involved. Python provides three logical operators:
- 1. and
- 2. or
- 3. not
2. The and Operator
The and operator returns True
if both conditions are True
. If either condition is False
, the result is False
.
Syntax:
condition1 and condition2Truth Table:
Condition 1 | Condition 2 | Result |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Example:
age = 25
is_employed = True
# Check if the person is above 18 and employed
if age > 18 and is_employed:
print("Eligible for the job.")
else:
print("Not eligible for the job.")
Output:
Eligible for the job.
3. The or
Operator
The or
operator returns True
if at least one of the conditions is True
. It only returns False
if both conditions are False
.
Syntax:
condition1 or condition2
Truth Table:
Condition 1 | Condition 2 | Result |
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Example:
age = 16
has_permission = True
# Check if the person is above 18 or has permission
if age > 18 or has_permission:
print("Access granted.")
else:
print("Access denied.")
Output:
Access granted.
4. The not
Operator
The not operator is a unary operator that reverses the truth value of the condition. If the condition is True, it returns False, and vice versa.Syntax:
not conditionTruth Table:
Condition | Result |
True | False |
False | True |
Example:
is_raining = False# Check if it is not raining
if not is_raining:
print("You can go for a walk.")
else:
print("Better stay indoors.")
Output:
You can go for a walk.5. Combining Logical Operators
Logical operators can be combined to evaluate complex conditions. Python evaluates them based on operator precedence:
not
(highest precedence)and
or
(lowest precedence)
You can use parentheses ()
to control the order of evaluation.
Example:
age = 20
has_permission = False
is_employed = True
# Complex condition
if (age > 18 and is_employed) or has_permission:
print("Eligible for the program.")
else:
print("Not eligible for the program.")
Output:
Eligible for the program.
6. Practical Use Cases of Logical Operators
Case 1: Login Authentication
username = "admin"
password = "1234"
# Check if username and password match
if username == "admin" and password == "1234":
print("Login successful.")
else:
print("Invalid credentials.")
Case 2: Traffic Signal
light_color = "green"
car_stopped = True
# Check if it is safe to cross the road
if light_color == "green" and car_stopped:
print("You can cross the road.")
else:
print("Wait until it is safe.")
Case 3: Discount Eligibility
age = 65
is_member = True
# Check if eligible for a discount
if age > 60 or is_member:
print("Eligible for a discount.")
else:
print("Not eligible for a discount.")
7. Common Pitfalls with Logical Operators
Mistake 1: Forgetting Operator Precedence
x = True
y = False
z = True
# Misunderstanding precedence
result = x or y and z # Evaluates as x or (y and z)
print(result) # Output: True
Mistake 2: Using =
Instead of ==
x = 10
# Incorrect condition
if x = 10: # This will throw a SyntaxError
print("x is 10")
Conclusion
Logical operators are powerful tools in Python for building complex conditional statements. Understanding how to use and
, or
, and not
, along with their precedence rules, will enable you to write efficient and clear code. Practice combining logical operators with real-world scenarios to master their usage!
Python Operators: A Comprehensive Guide
Python Coding December 21, 2024 Python No comments
Python Operators: A Comprehensive Guide
Operators are fundamental building blocks of programming, and Python provides a rich set of operators to perform various operations on variables and values. This guide will walk you through the different types of operators available in Python, complete with examples to help you understand how they work.
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.
Operator | Description | Example |
---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 5 - 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division | 5 / 2 = 2.5 |
% | Modulus | 5 % 2 = 1 |
** | Exponentiation | 5 ** 2 = 25 |
// | Floor Division | 5 // 2 = 2 |
Example:
x = 102. Comparison Operators
Comparison operators are used to compare two values and return a boolean result (‘True’ or ‘False’).
Operator | Description | Example |
== | Equal to | 5 == 3 (False) |
!= | Not equal to | 5 != 3 (True) |
> | Greater than | 5 > 3 (True) |
< | Less than | 5 < 3 (False) |
>= | Greater than or equal to | 5 >= 3 (True) |
<= | Less than or equal to | 5 <= 3 (False) |
Example:
a = 7b = 4
print("Equal to:", a == b)
print("Not equal to:", a != b) print("Greater than:", a > b)
print("Less than:", a < b)
print("Greater than or equal to:", a >= b) print("Less than or equal to:", a <= b)
3. Logical Operators
Logical operators are used to combine conditional statements.
Operator | Description | Example |
and | Returns True if both statements are True | (5 > 3 and 7 > 4) |
or | Returns True if one of the statements is True | (5 > 3 or 7 < 4) |
not | Reverses the result | not(5 > 3) |
Example:
x = Truey = False
print("AND Operator:", x and y)
print("OR Operator:", x or y)
print("NOT Operator:", not x)
4. Assignment Operators
Assignment operators are used to assign values to variables.
Operator | Description | Example |
= | Assign | x = 5 |
+= | Add and assign | x += 3 (x=x+3) |
-= | Subtract and assign | x -= 3 (x=x-3) |
*= | Multiply and assign | x *= 3 (x=x*3) |
/= | Divide and assign | x /= 3 (x=x/3) |
%= | Modulus and assign | x %= 3 (x=x%3) |
//= | Floor divide and assign | x //= 3 |
**= | Exponentiate and assign | x **= 3 |
Example:
x = 10x += 5
print("Add and assign:", x)
x *= 2
print("Multiply and assign:", x)
5. Bitwise Operators
Bitwise operators work on bits and perform operations bit by bit.
Operator | Description | Example | ||
& | AND | 5 & 3 | ||
` | ` | OR | `5 | 3` |
^ | XOR | 5 ^ 3 | ||
~ | NOT | ~5 | ||
<< | Left shift | 5 << 1 | ||
>> | Right shift | 5 >> 1 |
Example:
a = 5b = 3
print("Bitwise AND:", a & b)
print("Bitwise OR:", a | b)
print("Bitwise XOR:", a ^ b)
print("Bitwise NOT:", ~a)
print("Left shift:", a << 1)
print("Right shift:", a >> 1)
6. Membership Operators
Membership operators are used to test if a sequence contains a specified value.
Operator | Description | Example |
in | Returns True if a value is found in a sequence | 'a' in 'apple' |
not in | Returns True if a value is not found in a sequence | 'b' not in 'apple' |
Example:
string = "hello"
print("'h' in string:", 'h' in string)
print("'z' not in string:", 'z' not in string)
7. Identity Operators
Identity operators are used to compare the memory location of two objects.
Operator | Description | Example |
is | Returns True if both variables are the same object | x is y |
is not | Returns True if both variables are not the same object | x is not y |
Example:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print("a is b:", a is b)
print("a is not c:", a is not c)
8. Special Operators: Operator Precedence
Operator precedence determines the order in which operations are performed. For example, multiplication has a higher precedence than addition.
Example:
result = 5 + 3 * 2
print("Result:", result) # Output: 11 (Multiplication first, then addition)
You can use parentheses ()
to override the precedence.
Example:
result = (5 + 3) * 2
print("Result:", result) # Output: 16
Conclusion
Understanding Python operators is essential for writing efficient and readable code. This guide covered arithmetic, comparison, logical, assignment, bitwise, membership, and identity operators with examples. By mastering these operators, you can manipulate data effectively and create more complex programs.
Day 48: Python Program To Clear Rightmost Set Bit of a Number
Python Developer December 21, 2024 100 Python Programs for Beginner No comments
Code Explanation:
Day 49 : Python Program to Test Collatz Conjecture for a Given Number
Python Developer December 21, 2024 100 Python Programs for Beginner No comments
def collatz_conjecture(n):
if n <= 0:
print("Please enter a positive integer.")
return
print(f"Starting number: {n}")
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print(n, end=" ")
print("\nReached 1!")
try:
number = int(input("Enter a positive integer to test the Collatz conjecture: "))
collatz_conjecture(number)
except ValueError:
print("Invalid input! Please enter a valid integer.")
#source code --> clcoding.com
Code Explanation:
Python Coding challenge - Day 16 | What is the output of the following Python Code?
Python Developer December 21, 2024 Python Coding Challenge No comments
Explanation:
The .istitle() method:
This method checks whether a string follows title case formatting.
A string is considered title case if:
The first character of each word is uppercase.
All other characters in each word are lowercase.
Words are separated by non-alphanumeric characters (like spaces, punctuation, or special symbols).
Breaking down the input string:
'Hello!2@#World' is split into words at non-alphanumeric boundaries.
The "words" identified in this string are:
'Hello' (first character uppercase, rest lowercase → valid title case).
'World' (first character uppercase, rest lowercase → valid title case).
Special characters and numbers:
Special characters (!2@#) are ignored in determining title case.
As long as the alphanumeric words follow the title case rules, .istitle() will return True.
Why the result is True:
The string 'Hello!2@#World' meets the criteria for title case:
The two words (Hello and World) follow title case rules.
Non-alphanumeric characters and numbers do not break the title case structure.
Final Output:
Python Coding challenge - Day 15 | What is the output of the following Python Code?
Python Developer December 21, 2024 Python Coding Challenge No comments
Code Explanation:
The copy method:
a.copy() creates a shallow copy of the list a.
A shallow copy means that a new list object is created, but the elements inside the list (if mutable) are not deeply copied.
The is operator:
is checks for object identity, i.e., whether two variables refer to the same object in memory.
What happens here:
a and b are two distinct list objects in memory because a.copy() created a new list.
Even though the contents of the two lists are the same, they are not the same object.
Verification:
print(a == b) would return True because == checks for value equality, and both lists contain the same elements.
print(a is b) returns False because they are two different objects in memory.
Final Output:
Friday, 20 December 2024
Tic Tac Toe Game using Gui
Python Coding December 20, 2024 No comments
import tkinter as tk
from tkinter import messagebox
def check_winner():
"""Checks if there is a winner or if the game is a draw."""
for row in board:
if row[0]["text"] == row[1]["text"] == row[2]["text"] != "":
return row[0]["text"]
for col in range(3):
if board[0][col]["text"] == board[1][col]["text"] == board[2][col]["text"] != "":
return board[0][col]["text"]
if board[0][0]["text"] == board[1][1]["text"] == board[2][2]["text"] != "":
return board[0][0]["text"]
if board[0][2]["text"] == board[1][1]["text"] == board[2][0]["text"] != "":
return board[0][2]["text"]
if all(board[row][col]["text"] != "" for row in range(3) for col in range(3)):
return "Draw"
return None
def on_click(row, col):
"""Handles button click events."""
global current_player
if board[row][col]["text"] == "":
board[row][col]["text"] = current_player
winner = check_winner()
if winner:
if winner == "Draw":
messagebox.showinfo("Game Over", "It's a draw!")
else:
messagebox.showinfo("Game Over", f"Player {winner} wins!")
reset_board()
else:
current_player = "O" if current_player == "X" else "X"
def reset_board():
"""Resets the game board for a new game."""
global current_player
current_player = "X"
for row in range(3):
for col in range(3):
board[row][col]["text"] = ""
# Create the main window
root = tk.Tk()
root.title("Tic-Tac-Toe")
# Initialize variables
current_player = "X"
board = [[None for _ in range(3)] for _ in range(3)]
# Create the game board (3x3 buttons)
for row in range(3):
for col in range(3):
button = tk.Button(
root, text="", font=("Helvetica", 20), height=2, width=5,
command=lambda r=row, c=col: on_click(r, c)
)
button.grid(row=row, column=col)
board[row][col] = button
# Run the application
root.mainloop()
Thursday, 19 December 2024
Python Coding challenge - Day 14| What is the output of the following Python Code?
Python Developer December 19, 2024 Python Coding Challenge No comments
Explanation:
Python Coding challenge - Day 13| What is the output of the following Python Code?
Python Developer December 19, 2024 Python Coding Challenge No comments
Code Explanation:
Day 47: Python Program to Set Bit of an Integer
Python Developer December 19, 2024 100 Python Programs for Beginner No comments
def count_set_bits(n):
count=0
while n > 0:
count += n & 1
n >>= 1
return count
num=int(input("Enter an integer"))
print(f"The number of set bits in {num}is{count_set_bits(num)}.")
#source code --> clcoding.com
Code Explanation:
Day 46: Python Program to Swap Two Numbers Without Using The Third Variable
Python Developer December 19, 2024 100 Python Programs for Beginner No comments
def swap_numbers(a, b):
a = a + b
b = a - b
a = a - b
return a, b
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
a, b = swap_numbers(a, b)
print(f"After swapping: First number = {a} and Second number = {b}")
#source code --> clcoding.com
Code Explanation:
Popular Posts
-
100 Data Structure and Algorithm Problems to Crack Coding Interviews Unlock your potential to ace coding interviews with this comprehensiv...
-
Financial Machine Learning surveys the nascent literature on machine learning in the study of financial markets. The authors highlight th...
-
Step-by-Step Breakdown 1. Lists a and b are defined: a = [ 1 , 2 ] b = [3, 4] a is a list containing [1, 2]. b is a list containing [3, ...
-
Step 1: Define the lists a and b a = [1, 2]: A list containing integers 1 and 2. b = [3, 4]: A list containing integers 3 and 4. Step 2:...
-
Through a recent series of breakthroughs, deep learning has boosted the entire field of machine learning. Now, even programmers who know c...
-
This textbook grew out of notes for the ECE143 Programming for Data Analysis class that the author has been teaching at University of Cali...
-
Explanation: Input List: The input list is numbers = [1, 2, 3, 4]. Lambda Function: The lambda x: x * 2 function takes each element x from...
-
import turtle # Set up the turtle t = turtle.Turtle() t.speed( 2 ) t.penup() # Define scaling factor scale_factor = 3.5 # Draw the kite t...
-
Code Explanation: Lists keys and values: keys = ['a', 'b', 'c'] is a list of strings that will serve as the keys f...
-
Explanation: Creating Lists: a = [1, 2, 3]: This is a list of integers. b = [4, 5, 6]: This is another list of integers. Using zip: zip(a,...