๐ Python Concepts with Demo Programs
This blog covers important Python basics with simple code examples. Each demo has syntax highlighting and a copy button — perfect for learning or sharing!
1️⃣ Base Types and Operations
# Base Types
int_val = 78
float_val = 3.14
bool_val = True
str_val = "Hello Python"
print(f"Integer: {int_val}, Type: {type(int_val)}")
print(f"Float: {float_val}, Type: {type(float_val)}")
print(f"Boolean: {bool_val}, Type: {type(bool_val)}")
print(f"String: {str_val}, Type: {type(str_val)}")
# Conversions
str_to_int = int("15")
int_to_float = float(int_val)
print(f"\nString '15' to Int: {str_to_int}")
print(f"Int {int_val} to Float: {int_to_float}")
# Math Operations
result_add = 5 + 3.6
result_div = 10 / 3
result_floor_div = 10 // 3
result_round = round(5.7)
print(f"\n5 + 3.6 = {result_add}")
print(f"10 / 3 = {result_div}")
print(f"10 // 3 = {result_floor_div}")
print(f"Round(5.7) = {result_round}")
2️⃣ Variable Assignment
a = 10
b = 20
print(f"a: {a}, b: {b}")
c, d = 30, 40
print(f"c: {c}, d: {d}")
e = f = g = 50
print(f"e: {e}, f: {f}, g: {g}")
x, y = 100, 200
print(f"\nBefore swap: x={x}, y={y}")
x, y = y, x
print(f"After swap: x={x}, y={y}")
3️⃣ Sequence Containers
# List
my_list = [10, 20, 30, 40, 50]
print(f"\nOriginal List: {my_list}")
print(f"Second item: {my_list[1]}")
print(f"Slice [1:4]: {my_list[1:4]}")
my_list[1] = 25
print(f"Modified List: {my_list}")
# Tuple
my_tuple = (1, 'two', 3.0)
print(f"\nTuple: {my_tuple}")
print(f"First item: {my_tuple[0]}")
# Dictionary
my_dict = {'name': 'Alice', 'age': 30, 'city': 'NY'}
my_dict['age'] = 31
my_dict['job'] = 'Engineer'
print(f"Updated Dict: {my_dict}")
4️⃣ Boolean Logic & Conditionals
a, b, c = 10, 20, 10
print(a == c)
print((a == c) and (a > b))
print((a == c) or (a > b))
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C or lower")
status = "Active" if score >= 80 else "Inactive"
print(status)
5️⃣ Modules, Math, Random
import math, random
print(f"Cos(0): {math.cos(0):.4f}")
print(f"Pi: {math.pi}")
print(f"Sqrt(25): {math.sqrt(25)}")
print(f"Random int: {random.randint(1,100)}")
print(f"Random float: {random.random():.4f}")
6️⃣ Loops & Iteration
data = ['apple', 'banana', 'cherry']
for item in data:
print(item)
for i in range(5):
print(f"Count: {i}")
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue
if count == 7:
print(f"Found {count}!")
break
print(f"Odd number: {count}")
7️⃣ Exception Handling
def safe_division(a, b):
try:
print(a / b)
except ZeroDivisionError:
print("Error: Divide by zero!")
except TypeError:
print("Error: Invalid type!")
finally:
print("Done.\n")
safe_division(10, 2)
safe_division(10, 0)
safe_division(10, "two")
8️⃣ String Operations
s = "HelloPython"
print(s[1:5])
print(s[-5:])
words = ['data', 'science', 'is', 'fun']
joined = " ".join(words)
print(joined)
print(joined.split(" "))
pi = 3.14159
print(f"Pi = {pi:.2f}")
9️⃣ Boolean & Identity Checks
a = [1,2,3]
b = [1,2,3]
print(a == b)
print(a is b)
c = a
print(a is c)
๐ Sets & Dictionaries
nums = [1,2,2,3,4,4]
my_set = set(nums)
print(my_set)
user = {'id': 1, 'name': 'Chris', 'admin': True}
for k, v in user.items():
print(f"{k}: {v}")
11️⃣ Bytes & Bytearray
b = b"Python Data"
print(b)
ba = bytearray(b)
ba[0] = 65
print(ba)
print(ba.decode())
12️⃣ Else Block in Loops
nums = [1,3,5,7]
target = 6
for n in nums:
if n == target:
break
else:
print("Target not found!")
13️⃣ Data Analysis Example
def analyze(scores):
if not scores:
print("No scores!")
return
mean = sum(scores) / len(scores)
print(f"Mean: {mean:.2f}")
for s in scores:
print("Pass" if s >= 70 else "Fail")
scores = [85, 62, 78, 91, 55, 70, 88]
analyze(scores)
14️⃣ Functions with Defaults
def say_hello(name, greeting="Hello"):
print(f"{greeting}, {name}!")
say_hello("Alice")
say_hello("Bob", "Good Morning")
say_hello(name="Charlie", greeting="Hey there")
✅ Final Thoughts
This collection covers all key Python topics — data types, control flow, functions, and error handling. Perfect for students, beginners, and content creators on YouTube.
No comments:
Post a Comment