with open("example.txt", "r") as file:
for line in file:
print(line.strip())
#source code --> clcoding.com
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
#source code --> clcoding.com
lines = ["Hello, World!", "Python is great!", "File handling is useful!", "End of file."]
with open("output.txt", "w") as file:
for line in lines:
file.write(line + "\n")
print("Data written to output.txt successfully!")
#source code --> clcoding.com
with open("example.txt", "r") as file:
content = file.read()
print("File Contents:")
print(content)
#source code --> clcoding.com
with open("example.txt", "w") as file:
file.write("Hello, World!")
print("File created and text written successfully!")
#source code --> clcoding.com
numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
unique_numbers = list(set(numbers))
print("List without duplicates:", unique_numbers)
#source code --> clcoding.com
student = {"name": "John", "age": 20, "grade": "A"}
for key, value in student.items():
print(f"Key: {key}, Value: {value}")
#source code --> clcoding.com
if key in dictionary:
return True
else:
return False
student = {"name": "John", "age": 20, "grade": "A"}
key_to_check = "age"
if key_exists(student, key_to_check):
print(f"The key '{key_to_check}' exists in the dictionary.")
else:
print(f"The key '{key_to_check}' does not exist in the dictionary.")
#source code --> clcoding.com
student = {"name": "John", "age": 20, "grade": "A"}
print(student["age"])
#source code --> clcoding.com
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
print("Student Details:", student)
#source code --> clcoding.com
num = int(input("Enter a number: "))
if not (num % 2 == 0):
print("The number is NOT even (it is odd).")
else:
print("The number is even.")
#source code --> clcoding.com
Python Coding February 27, 2025 Python Quiz No comments
Iteration | i Value | j Value | Printed Output |
---|---|---|---|
1st | 0 | 0 | 0 → 0 |
2nd | 0 | 1 | 1 |
3rd | 1 | 0 | 1 → 0 |
4th | 1 | 1 | 1 |
001
1
0
1
👉 Key Takeaways:
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
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
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
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.
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
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
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
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
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
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
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
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.
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
"""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
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
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
Function Definition
def count_vowels(string):
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
print(reverse_string("Python"))
print(reverse_string("12345"))
#source code --> clcoding.com
uppercase_text = text.upper()
lowercase_text = text.lower()
print("Uppercase:", uppercase_text)
print("Lowercase:", lowercase_text)
#source code --> clcoding.com
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
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
details = {"name": "Alice", "age": 25, "grade": "A"}
print("Dictionary Example:", details)
#source code --> clcoding.com
student = {"name": "John", "age": 20, "grade": "A"}
print("Age:", student["age"])
#source code --> clcoding.com
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.")
student = {"name": "John", "age": 20, "grade": "A"}
for key, value in student.items():
print(f"{key}: {value}")
#source code --> clcoding.com
unique_numbers = list(set(numbers))
print("List after removing duplicates:", unique_numbers)
#source code --> clcoding.com
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
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
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
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
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
print(reverse_string("Python"))
print(reverse_string("12345"))
#source code --> clcoding.com
return n % 2 == 0
print(is_even(8))
print(is_even(7))
print(is_even(0))
#source code --> clcoding.com
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
Python Coding February 26, 2025 Python No comments
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.
Before learning Python, ensure you are comfortable with:
These will help you set up your Python environment without unnecessary roadblocks.
Programming is all about breaking down problems into smaller steps. Strengthen your logical thinking skills by:
This mindset will help you write efficient Python code.
Python often involves mathematical operations, so having a grasp of:
While advanced math isn't required, comfort with numbers is a plus.
Since most programming languages, including Python, use English-based syntax, it helps to:
This will make reading and writing Python code much easier.
Even without coding experience, understanding how instructions work in a sequence will be beneficial. Learn about:
This will prepare you for Python’s logical flow and syntax.
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!
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
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
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
🧵: