Skip to content

Commit d2f098a

Browse files
exceptions, data structures
1 parent 7cab94b commit d2f098a

12 files changed

+193
-0
lines changed

basic/fibinocci.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def fib(n): # write Fibonacci series up to n
2+
"""Print a Fibonacci series up to n."""
3+
a, b = 0, 1
4+
while a < n:
5+
print(a, end=' ')
6+
a, b = b, a+b
7+
print()
8+
9+
# Now call the function we just defined:
10+
fib(10)

control_structures/match_color.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
from enum import Enum
3+
4+
class Color(Enum):
5+
RED = 'red'
6+
GREEN = 'green'
7+
BLUE = 'blue'
8+
9+
color = Color(input("Enter your choice of 'red', 'blue' or 'green': "))
10+
11+
match color:
12+
case Color.RED:
13+
print("I see red!")
14+
case Color.GREEN:
15+
print("Grass is green")
16+
case Color.BLUE:
17+
print("I'm feeling the blues :(")
18+

control_structures/match_statement.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def http_error(status):
2+
match status:
3+
case 400:
4+
return "Bad request"
5+
case 404:
6+
return "Not found"
7+
case 418:
8+
return "I'm a teapot"
9+
case 401 | 403 | 404:
10+
return "Not allowed as a error"
11+
case _:
12+
return "Something's wrong with the internet"
13+
14+
result = http_error(400)
15+
print(result)
16+
17+
result = http_error(401)
18+
print(result)
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Basic list comprehension
2+
squares = [x ** 2 for x in range(10)]
3+
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4+
5+
# Conditional comprehension
6+
evens = [x for x in range(10) if x % 2 == 0]
7+
print(evens) # Output: [0, 2, 4, 6, 8]
8+
9+
10+
# advance level
11+
12+
def filter_even_numbers(data):
13+
return [x for x in data if x % 2 == 0]
14+
15+
my_data = [1, 2, 3, 4, 5, 6]
16+
print(filter_even_numbers(my_data)) # Output: [2, 4, 6]

data_structures/list_functions.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
2+
3+
print(fruits.count('apple'))
4+
5+
print(fruits.count('tangerine'))
6+
7+
print(fruits.index('banana'))
8+
9+
print(fruits.index('banana', 4)) # Find next banana starting at position 4
10+
11+
fruits.reverse()
12+
13+
print(fruits)
14+
15+
fruits.append('grape')
16+
print(fruits)
17+
18+
fruits.sort()
19+
print(fruits)
20+
21+
print(fruits.pop())

data_structures/list_slicing.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
2+
# Basic slicing
3+
my_list = [1, 2, 3, 4, 5]
4+
print(my_list[1:4]) # Output: [2, 3, 4]
5+
6+
# Advanced slicing with step
7+
print(my_list[::2]) # Output: [1, 3, 5]
8+
9+
# real time scenario
10+
11+
def get_middle_elements(data):
12+
return data[1:-1] # Excludes the first and last elements
13+
14+
my_data = [10, 20, 30, 40, 50]
15+
print(get_middle_elements(my_data)) # Output: [20, 30, 40]

data_structures/list_stack.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
stack = [3, 4, 5]
2+
stack.append(6)
3+
stack.append(7)
4+
5+
print(stack)
6+
7+
stack.pop()
8+
9+
print(stack)
10+
11+
stack.pop()
12+
13+
stack.pop()
14+
print(stack)

data_structures/tuples.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
my_tuple = (1, 2, 3)
2+
3+
try:
4+
print(my_tuple[3]) # Output: 2
5+
except IndexError as e:
6+
print("error occured:",e)
7+
8+
9+
# advance level
10+
11+
def get_min_max(data):
12+
return (min(data), max(data))
13+
14+
try:
15+
my_data = [10, 20, 30, 40, 50,-7]
16+
print(get_min_max(my_data)) # Output: (10, 50)
17+
except ValueError as e:
18+
print("Error occured:",e)
19+
20+

exceptions/custom_exceptions.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class CustomError(Exception):
2+
def __init__(self, message):
3+
self.message = message
4+
5+
try:
6+
raise CustomError("This is a custom error.")
7+
except CustomError as e:
8+
print("Caught a custom error:", e.message)

exceptions/file_operations.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
try:
2+
file = open("example1.txt", "r")
3+
content = file.read()
4+
except FileNotFoundError:
5+
print("File not found.")
6+
else:
7+
print("File content:", content)
8+
finally:
9+
if 'file' in locals():
10+
file.close()
11+
print("File operation completed.")

exceptions/multiple_exceptions.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
try:
2+
result = 10 / 0
3+
print(result)
4+
except (ZeroDivisionError, ValueError) as e:
5+
print("Error occurred:", e)
6+
7+
8+
# another example
9+
10+
def get_positive_number(number):
11+
if number <= 0:
12+
raise ValueError("The number must be positive.")
13+
return number
14+
15+
try:
16+
number = get_positive_number("uyu")
17+
print(number)
18+
except (ValueError, TypeError) as e:
19+
print("Caught an error:", e)
20+
21+
22+
# another example
23+
try:
24+
value = int("abc") # This will raise a ValueError because "abc" is not a valid integer.
25+
except TypeError as e:
26+
print("Caught an error:", e)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class ValidationError(Exception):
2+
def __init__(self, message):
3+
self.message = message
4+
5+
def validate_age(age):
6+
if age < 0:
7+
raise ValidationError("Age cannot be negative.")
8+
elif age == 0:
9+
raise ValidationError("Age cannot be zero")
10+
else:
11+
print("Valid age:", age)
12+
13+
try:
14+
validate_age(20)
15+
except ValidationError as e:
16+
print("Validation error:", e.message)

0 commit comments

Comments
 (0)