diff --git a/01_Day_Introduction/helloworld.py b/01_Day_Introduction/helloworld.py index d8007868f..0f7dd1538 100644 --- a/01_Day_Introduction/helloworld.py +++ b/01_Day_Introduction/helloworld.py @@ -1,25 +1,30 @@ -# Introduction -# Day 1 - 30DaysOfPython Challenge +# ===================================== +# Day 1 - 30 Days of Python Challenge +# Introduction to Python +# ===================================== -print("Hello World!") # print hello world +# Printing a simple message +print("Hello, World!") -print(2 + 3) # addition(+) -print(3 - 1) # subtraction(-) -print(2 * 3) # multiplication(*) -print(3 + 2) # addition(+) -print(3 - 2) # subtraction(-) -print(3 * 2) # multiplication(*) -print(3 / 2) # division(/) -print(3 ** 2) # exponential(**) -print(3 % 2) # modulus(%) -print(3 // 2) # Floor division operator(//) +print("\n--- Basic Arithmetic Operations ---") -# Checking data types +a = 3 +b = 2 -print(type(10)) # Int -print(type(3.14)) # Float -print(type(1 + 3j)) # Complex -print(type('Asabeneh')) # String -print(type([1, 2, 3])) # List -print(type({'name': 'Asabeneh'})) # Dictionary -print(type({9.8, 3.14, 2.7})) # Tuple +print(f"Addition: {a} + {b} = {a + b}") +print(f"Subtraction: {a} - {b} = {a - b}") +print(f"Multiplication: {a} * {b} = {a * b}") +print(f"Division: {a} / {b} = {a / b}") +print(f"Exponentiation: {a} ** {b} = {a ** b}") +print(f"Modulus: {a} % {b} = {a % b}") +print(f"Floor Division: {a} // {b} = {a // b}") + +print("\n--- Checking Data Types ---") + +print(type(10)) # Integer +print(type(3.14)) # Float +print(type(1 + 3j)) # Complex +print(type("Asabeneh")) # String +print(type([1, 2, 3])) # List +print(type({"name": "Asabeneh"})) # Dictionary +print(type((9.8, 3.14, 2.7))) # Tuple diff --git a/02_Day_Variables_builtin_functions/variables.py b/02_Day_Variables_builtin_functions/variables.py index bb5c28037..444139588 100644 --- a/02_Day_Variables_builtin_functions/variables.py +++ b/02_Day_Variables_builtin_functions/variables.py @@ -1,19 +1,24 @@ # Variables in Python -first_name = 'Asabeneh' -last_name = 'Yetayeh' -country = 'Finland' -city = 'Helsinki' -age = 250 -is_married = True -skills = ['HTML', 'CSS', 'JS', 'React', 'Python'] +first_name = 'MAX' #string +last_name = 'VERSTAPPEN' #string +continent = 'Europe' #string +country = 'Netherlands' #string +city = 'Amsterdam' #string + +age = 69 #integer + +is_married = True #bool + +skills = ['HTML', 'CSS', 'JS', 'React', 'Python','Rust'] #list of string + person_info = { - 'firstname': 'Asabeneh', - 'lastname': 'Yetayeh', - 'country': 'Finland', - 'city': 'Helsinki' -} + 'firstname': 'MAX', + 'lastname': 'VERSTAPPEN', + 'country': 'Netherlands', + 'city': 'Amsterdam' +} #dictionary # Printing the values stored in the variables @@ -21,6 +26,7 @@ print('First name length:', len(first_name)) print('Last name: ', last_name) print('Last name length: ', len(last_name)) +print('Continent: ', cotinent) print('Country: ', country) print('City: ', city) print('Age: ', age) @@ -30,7 +36,7 @@ # Declaring multiple variables in one line -first_name, last_name, country, age, is_married = 'Asabeneh', 'Yetayeh', 'Helsink', 250, True +first_name, last_name, country, age, is_married = 'MAX', 'VERSTAPPEN', 'Netherlands', 69, True print(first_name, last_name, country, age, is_married) print('First name:', first_name) diff --git a/05_Day_Lists/day_5.py b/05_Day_Lists/day_5.py index 6b9c2a1f7..40b265a0c 100644 --- a/05_Day_Lists/day_5.py +++ b/05_Day_Lists/day_5.py @@ -2,14 +2,15 @@ print(len(empty_list)) # 0 # list of fruits -fruits = ['banana', 'orange', 'mango', 'lemon'] +fruits = ['banana', 'orange', 'mango', 'lemon'] #list of fruits vegetables = ['Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot'] # list of vegetables animal_products = ['milk', 'meat', 'butter', 'yoghurt'] # list of animal products web_techs = ['HTML', 'CSS', 'JS', 'React', 'Redux', 'Node', 'MongDB'] # list of web technologies -countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] +countries = ['Finland', 'Estonia', 'Denmark', 'Sweden', 'Norway'] #list of countries +liquors = ['Whiskey' , 'Beer' , 'Cognac' , 'Gin' , 'Scotch' , 'Vodka' , 'Rum'] #list of liquors # Print the lists and it length print('Fruits:', fruits) @@ -23,7 +24,6 @@ print('Number of countries:', len(countries)) # Modifying list - fruits = ['banana', 'orange', 'mango', 'lemon'] first_fruit = fruits[0] # we are accessing the first item using its index print(first_fruit) # banana @@ -75,19 +75,20 @@ # Append fruits = ['banana', 'orange', 'mango', 'lemon'] -fruits.append('apple') +fruits.append('apple') #adding apple in the end of the list print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple'] -# ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime] fruits.append('lime') -print(fruits) +print(fruits) # ['banana', 'orange', 'mango', 'lemon', 'apple', 'lime'] + + # insert fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.insert(2, 'apple') # insert apple between orange and mango -print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon'] -# ['banana', 'orange', 'apple', 'mango', 'lime','lemon',] +print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lemon'] fruits.list(3, 'lime') -print(fruits) +print(fruits) # ['banana', 'orange', 'apple', 'mango', 'lime','lemon',] + # remove fruits = ['banana', 'orange', 'mango', 'lemon'] @@ -164,6 +165,7 @@ print(fruits.index('orange')) # 1 ages = [22, 19, 24, 25, 26, 24, 25, 24] print(ages.index(24)) + # Reverse fruits = ['banana', 'orange', 'mango', 'lemon'] fruits.reverse() diff --git a/06_Day_Tuples/day_06.py b/06_Day_Tuples/day_06.py new file mode 100644 index 000000000..907c11241 --- /dev/null +++ b/06_Day_Tuples/day_06.py @@ -0,0 +1,201 @@ +# ===================================================== +# 30 Days Of Python - Day 6: Tuples (Full Practice Code) +# ===================================================== + +print("===== DAY 6: TUPLES =====\n") + +# ----------------------------------------------------- +# 1. Creating Tuples +# ----------------------------------------------------- + +# Empty tuple +empty_tuple_1 = () +empty_tuple_2 = tuple() + +print("Empty tuples:") +print(empty_tuple_1) +print(empty_tuple_2) +print() + +# Tuple with initial values +fruits = ('banana', 'orange', 'mango', 'lemon') +print("Fruits tuple:", fruits) +print() + +# ----------------------------------------------------- +# 2. Tuple Length +# ----------------------------------------------------- + +print("Length of fruits tuple:", len(fruits)) +print() + +# ----------------------------------------------------- +# 3. Accessing Tuple Items +# ----------------------------------------------------- + +# Positive indexing +first_fruit = fruits[0] +second_fruit = fruits[1] +last_fruit = fruits[len(fruits) - 1] + +print("Positive indexing:") +print("First fruit:", first_fruit) +print("Second fruit:", second_fruit) +print("Last fruit:", last_fruit) +print() + +# Negative indexing +print("Negative indexing:") +print("First fruit:", fruits[-4]) +print("Second fruit:", fruits[-3]) +print("Last fruit:", fruits[-1]) +print() + +# ----------------------------------------------------- +# 4. Slicing Tuples +# ----------------------------------------------------- + +# Positive slicing +print("Positive slicing:") +print("All fruits:", fruits[0:]) +print("Middle fruits:", fruits[1:3]) +print("From index 1 to end:", fruits[1:]) +print() + +# Negative slicing +print("Negative slicing:") +print("All fruits:", fruits[-4:]) +print("Middle fruits:", fruits[-3:-1]) +print("From -3 to end:", fruits[-3:]) +print() + +# ----------------------------------------------------- +# 5. Changing Tuples to Lists +# ----------------------------------------------------- + +print("Changing tuple to list to modify it:") + +fruits_list = list(fruits) +fruits_list[0] = 'apple' +print("Modified list:", fruits_list) + +fruits = tuple(fruits_list) +print("Converted back to tuple:", fruits) +print() + +# ----------------------------------------------------- +# 6. Checking an Item in a Tuple +# ----------------------------------------------------- + +print("Checking items in tuple:") +print("'orange' in fruits:", 'orange' in fruits) +print("'banana' in fruits:", 'banana' in fruits) +print("'grape' in fruits:", 'grape' in fruits) +print() + +# ----------------------------------------------------- +# 7. Joining Tuples +# ----------------------------------------------------- + +vegetables = ('Tomato', 'Potato', 'Cabbage', 'Onion', 'Carrot') +fruits_and_vegetables = fruits + vegetables + +print("Joined tuples:") +print(fruits_and_vegetables) +print() + +# ----------------------------------------------------- +# 8. Deleting Tuples +# ----------------------------------------------------- + +temp_tuple = ('item1', 'item2', 'item3') +del temp_tuple +print("Tuple deleted successfully\n") + +# ===================================================== +# EXERCISES - LEVEL 1 +# ===================================================== + +print("===== EXERCISES: LEVEL 1 =====\n") + +# 1. Create an empty tuple +empty_tuple = () +print("1. Empty tuple:", empty_tuple) + +# 2. Create sisters and brothers tuples +sisters = ('Anna', 'Beth') +brothers = ('John', 'Mike') + +print("2. Sisters:", sisters) +print(" Brothers:", brothers) + +# 3. Join siblings +siblings = sisters + brothers +print("3. Siblings:", siblings) + +# 4. Number of siblings +print("4. Number of siblings:", len(siblings)) + +# 5. Add parents to family_members +family_members = siblings + ('Father', 'Mother') +print("5. Family members:", family_members) +print() + +# ===================================================== +# EXERCISES - LEVEL 2 +# ===================================================== + +print("===== EXERCISES: LEVEL 2 =====\n") + +# 1. Unpack siblings and parents +*siblings_only, father, mother = family_members + +print("1. Unpacked:") +print(" Siblings:", siblings_only) +print(" Father:", father) +print(" Mother:", mother) +print() + +# 2. Create food tuples +fruits_tp = ('banana', 'orange', 'mango') +vegetables_tp = ('carrot', 'potato', 'onion') +animal_products_tp = ('milk', 'meat', 'butter') + +food_stuff_tp = fruits_tp + vegetables_tp + animal_products_tp +print("2. Food stuff tuple:", food_stuff_tp) +print() + +# 3. Convert tuple to list +food_stuff_lt = list(food_stuff_tp) +print("3. Food stuff list:", food_stuff_lt) +print() + +# 4. Slice middle item(s) +middle_index = len(food_stuff_lt) // 2 + +if len(food_stuff_lt) % 2 == 0: + middle_items = food_stuff_lt[middle_index - 1: middle_index + 1] +else: + middle_items = food_stuff_lt[middle_index] + +print("4. Middle item(s):", middle_items) +print() + +# 5. Slice first three and last three items +print("5. First three items:", food_stuff_lt[:3]) +print(" Last three items:", food_stuff_lt[-3:]) +print() + +# 6. Delete food_stuff_tp +del food_stuff_tp +print("6. food_stuff_tp tuple deleted") +print() + +# 7. Check nordic countries +nordic_countries = ('Denmark', 'Finland', 'Iceland', 'Norway', 'Sweden') + +print("7. Nordic country checks:") +print(" Is 'Estonia' a nordic country?", 'Estonia' in nordic_countries) +print(" Is 'Iceland' a nordic country?", 'Iceland' in nordic_countries) + +print("\n===== END OF DAY 6 =====") \ No newline at end of file diff --git a/07_Day_Sets/day_07.py b/07_Day_Sets/day_07.py new file mode 100644 index 000000000..ac0757b08 --- /dev/null +++ b/07_Day_Sets/day_07.py @@ -0,0 +1,253 @@ +# ===================================================== +# 30 Days Of Python - Day 7: Sets (Full Practice Code) +# ===================================================== + +print("===== DAY 7: SETS =====\n") + +# ----------------------------------------------------- +# 1. Creating Sets +# ----------------------------------------------------- + +# Empty set +empty_set = set() +print("Empty set:", empty_set) + +# Set with initial values +fruits = {'banana', 'orange', 'mango', 'lemon'} +print("Fruits set:", fruits) +print() + +# ----------------------------------------------------- +# 2. Getting Set Length +# ----------------------------------------------------- + +print("Length of fruits set:", len(fruits)) +print() + +# ----------------------------------------------------- +# 3. Checking Items in a Set +# ----------------------------------------------------- + +print("Checking items:") +print("Is 'mango' in fruits?", 'mango' in fruits) +print("Is 'apple' in fruits?", 'apple' in fruits) +print() + +# ----------------------------------------------------- +# 4. Adding Items to a Set +# ----------------------------------------------------- + +# Add one item +fruits.add('lime') +print("After adding lime:", fruits) + +# Add multiple items +vegetables = ('tomato', 'potato', 'cabbage', 'onion', 'carrot') +fruits.update(vegetables) +print("After updating with vegetables:", fruits) +print() + +# ----------------------------------------------------- +# 5. Removing Items from a Set +# ----------------------------------------------------- + +# Remove an item +fruits.remove('banana') +print("After removing banana:", fruits) + +# Discard (no error if item doesn't exist) +fruits.discard('grape') +print("After discarding grape (no error):", fruits) + +# Pop random item +removed_item = fruits.pop() +print("Randomly removed item:", removed_item) +print("Set after pop:", fruits) +print() + +# ----------------------------------------------------- +# 6. Clearing and Deleting Sets +# ----------------------------------------------------- + +temp_set = {'a', 'b', 'c'} +temp_set.clear() +print("Cleared set:", temp_set) + +temp_set2 = {'x', 'y', 'z'} +del temp_set2 +print("temp_set2 deleted\n") + +# ----------------------------------------------------- +# 7. Converting List to Set +# ----------------------------------------------------- + +fruit_list = ['banana', 'orange', 'mango', 'lemon', 'orange', 'banana'] +fruit_set = set(fruit_list) +print("List:", fruit_list) +print("Converted to set (unique items):", fruit_set) +print() + +# ----------------------------------------------------- +# 8. Joining Sets (Union & Update) +# ----------------------------------------------------- + +set_a = {1, 2, 3} +set_b = {4, 5, 6} + +union_set = set_a.union(set_b) +print("Union using union():", union_set) +print("Union using | :", set_a | set_b) + +set_a.update(set_b) +print("After update:", set_a) +print() + +# ----------------------------------------------------- +# 9. Intersection +# ----------------------------------------------------- + +whole_numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +even_numbers = {0, 2, 4, 6, 8, 10} + +print("Intersection:", whole_numbers.intersection(even_numbers)) +print("Intersection using &:", whole_numbers & even_numbers) +print() + +# ----------------------------------------------------- +# 10. Subset and Superset +# ----------------------------------------------------- + +print("Is even_numbers subset of whole_numbers?", + even_numbers.issubset(whole_numbers)) + +print("Is whole_numbers superset of even_numbers?", + whole_numbers.issuperset(even_numbers)) +print() + +# ----------------------------------------------------- +# 11. Difference +# ----------------------------------------------------- + +print("Difference (whole - even):", + whole_numbers.difference(even_numbers)) + +python = {'p', 'y', 't', 'o', 'n'} +dragon = {'d', 'r', 'a', 'g', 'o', 'n'} + +print("Python - Dragon:", python - dragon) +print("Dragon - Python:", dragon - python) +print() + +# ----------------------------------------------------- +# 12. Symmetric Difference +# ----------------------------------------------------- + +print("Symmetric difference:", + python.symmetric_difference(dragon)) +print("Using ^ :", python ^ dragon) +print() + +# ----------------------------------------------------- +# 13. Disjoint Sets +# ----------------------------------------------------- + +even = {0, 2, 4, 6, 8} +odd = {1, 3, 5, 7, 9} + +print("Are even and odd disjoint?", even.isdisjoint(odd)) +print("Are python and dragon disjoint?", python.isdisjoint(dragon)) +print() + +# ===================================================== +# EXERCISES - LEVEL 1 +# ===================================================== + +print("===== EXERCISES: LEVEL 1 =====\n") + +it_companies = {'Facebook', 'Google', 'Microsoft', + 'Apple', 'IBM', 'Oracle', 'Amazon'} + +# 1. Length +print("1. Number of IT companies:", len(it_companies)) + +# 2. Add Twitter +it_companies.add('Twitter') +print("2. After adding Twitter:", it_companies) + +# 3. Add multiple companies +it_companies.update(['Tesla', 'Intel', 'Netflix']) +print("3. After adding multiple companies:", it_companies) + +# 4. Remove one company +it_companies.remove('IBM') +print("4. After removing IBM:", it_companies) + +# 5. Difference between remove and discard +print("\n5. Difference between remove and discard:") +print("- remove(): raises error if item not found") +print("- discard(): does NOT raise error\n") + +# ===================================================== +# EXERCISES - LEVEL 2 +# ===================================================== + +print("===== EXERCISES: LEVEL 2 =====\n") + +A = {19, 22, 24, 20, 25, 26} +B = {19, 22, 20, 25, 26, 24, 28, 27} + +# 1. Join A and B +print("1. A union B:", A.union(B)) + +# 2. Intersection +print("2. A intersection B:", A.intersection(B)) + +# 3. Subset +print("3. Is A subset of B?", A.issubset(B)) + +# 4. Disjoint +print("4. Are A and B disjoint?", A.isdisjoint(B)) + +# 5. Join A with B and B with A +print("5. A | B:", A | B) +print(" B | A:", B | A) + +# 6. Symmetric difference +print("6. Symmetric difference:", A.symmetric_difference(B)) + +# 7. Delete sets +del A +del B +print("7. Sets A and B deleted\n") + +# ===================================================== +# EXERCISES - LEVEL 3 +# ===================================================== + +print("===== EXERCISES: LEVEL 3 =====\n") + +age = [22, 19, 24, 25, 26, 24, 25, 24] +age_set = set(age) + +# 1. Compare list and set length +print("1. Age list length:", len(age)) +print(" Age set length:", len(age_set)) +print(" List is bigger because it contains duplicates\n") + +# 2. Data type explanation +print("2. Data types explanation:") +print("- String: ordered, immutable, text data") +print("- List: ordered, mutable, allows duplicates") +print("- Tuple: ordered, immutable, allows duplicates") +print("- Set: unordered, mutable, unique items only\n") + +# 3. Unique words in sentence +sentence = "I am a teacher and I love to inspire and teach people" +words = sentence.split() +unique_words = set(words) + +print("3. Sentence:", sentence) +print(" Unique words:", unique_words) +print(" Number of unique words:", len(unique_words)) + +print("\n===== END OF DAY 7 =====") \ No newline at end of file diff --git a/08_Day_Dictionaries/day_08.py b/08_Day_Dictionaries/day_08.py new file mode 100644 index 000000000..00a845966 --- /dev/null +++ b/08_Day_Dictionaries/day_08.py @@ -0,0 +1,203 @@ +# ===================================================== +# 30 Days Of Python - Day 8: Dictionaries (Full Code) +# ===================================================== + +print("===== DAY 8: DICTIONARIES =====\n") + +# ----------------------------------------------------- +# 1. Creating Dictionaries +# ----------------------------------------------------- + +# Empty dictionary +empty_dict = {} +print("Empty dictionary:", empty_dict) + +# Dictionary with data +person = { + 'first_name': 'Asabeneh', + 'last_name': 'Yetayeh', + 'age': 250, + 'country': 'Finland', + 'is_married': True, + 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address': { + 'street': 'Space street', + 'zipcode': '02210' + } +} + +print("Person dictionary:", person) +print() + +# ----------------------------------------------------- +# 2. Dictionary Length +# ----------------------------------------------------- + +print("Length of person dictionary:", len(person)) +print() + +# ----------------------------------------------------- +# 3. Accessing Dictionary Items +# ----------------------------------------------------- + +print("Accessing items:") +print("First name:", person['first_name']) +print("Country:", person['country']) +print("Skills:", person['skills']) +print("First skill:", person['skills'][0]) +print("Street:", person['address']['street']) +print() + +# Using get() method +print("Using get():") +print("City:", person.get('city')) # None (no error) +print() + +# ----------------------------------------------------- +# 4. Adding Items to a Dictionary +# ----------------------------------------------------- + +person['job_title'] = 'Instructor' +person['skills'].append('HTML') + +print("After adding job_title and skill:", person) +print() + +# ----------------------------------------------------- +# 5. Modifying Items in a Dictionary +# ----------------------------------------------------- + +person['first_name'] = 'Eyob' +person['age'] = 252 + +print("After modifying name and age:", person) +print() + +# ----------------------------------------------------- +# 6. Checking Keys in a Dictionary +# ----------------------------------------------------- + +print("Checking keys:") +print("'first_name' in person?", 'first_name' in person) +print("'salary' in person?", 'salary' in person) +print() + +# ----------------------------------------------------- +# 7. Removing Items from a Dictionary +# ----------------------------------------------------- + +# pop(key) +person.pop('job_title') +print("After pop('job_title'):", person) + +# popitem() - removes last item +person.popitem() +print("After popitem():", person) + +# del keyword +del person['is_married'] +print("After deleting is_married:", person) +print() + +# ----------------------------------------------------- +# 8. Changing Dictionary to List of Items +# ----------------------------------------------------- + +items_list = person.items() +print("Dictionary items:", items_list) +print() + +# ----------------------------------------------------- +# 9. Clearing a Dictionary +# ----------------------------------------------------- + +temp_dict = {'a': 1, 'b': 2} +temp_dict.clear() +print("Cleared dictionary:", temp_dict) +print() + +# ----------------------------------------------------- +# 10. Copying a Dictionary +# ----------------------------------------------------- + +person_copy = person.copy() +print("Copied dictionary:", person_copy) +print() + +# ----------------------------------------------------- +# 11. Getting Keys and Values +# ----------------------------------------------------- + +print("Keys:", person.keys()) +print("Values:", person.values()) +print() + +# ===================================================== +# EXERCISES - DAY 8 +# ===================================================== + +print("===== EXERCISES: DAY 8 =====\n") + +# 1. Create an empty dictionary called dog +dog = {} +print("1. Dog dictionary:", dog) + +# 2. Add name, color, breed, legs, age +dog['name'] = 'Buddy' +dog['color'] = 'Brown' +dog['breed'] = 'Labrador' +dog['legs'] = 4 +dog['age'] = 5 +print("2. Dog after adding properties:", dog) + +# 3. Create student dictionary +student = { + 'first_name': 'John', + 'last_name': 'Doe', + 'gender': 'Male', + 'age': 22, + 'marital_status': 'Single', + 'skills': ['Python', 'JavaScript'], + 'country': 'Finland', + 'city': 'Helsinki', + 'address': { + 'street': 'Main street', + 'zipcode': '00100' + } +} +print("\n3. Student dictionary:", student) + +# 4. Length of student dictionary +print("\n4. Length of student dictionary:", len(student)) + +# 5. Get skills value and check data type +skills = student['skills'] +print("\n5. Skills:", skills) +print(" Data type of skills:", type(skills)) + +# 6. Modify skills +student['skills'].append('React') +student['skills'].append('Django') +print("\n6. Modified skills:", student['skills']) + +# 7. Get dictionary keys as a list +keys_list = list(student.keys()) +print("\n7. Keys list:", keys_list) + +# 8. Get dictionary values as a list +values_list = list(student.values()) +print("\n8. Values list:", values_list) + +# 9. Change dictionary to list of tuples +items_tuples = list(student.items()) +print("\n9. Dictionary as list of tuples:", items_tuples) + +# 10. Delete one item +del student['marital_status'] +print("\n10. After deleting marital_status:", student) + +# 11. Delete one dictionary +del dog +print("\n11. Dog dictionary deleted") + +print("\n===== END OF DAY 8 =====") \ No newline at end of file diff --git a/09_Day_Conditionals/day_09.py b/09_Day_Conditionals/day_09.py new file mode 100644 index 000000000..84e1e5b93 --- /dev/null +++ b/09_Day_Conditionals/day_09.py @@ -0,0 +1,237 @@ +# ===================================================== +# 30 Days Of Python - Day 9: Conditionals (Full Code) +# ===================================================== + +print("===== DAY 9: CONDITIONALS =====\n") + +# ----------------------------------------------------- +# 1. IF CONDITION +# ----------------------------------------------------- + +a = 3 +if a > 0: + print("A is a positive number") +print() + +# ----------------------------------------------------- +# 2. IF ELSE +# ----------------------------------------------------- + +a = -2 +if a < 0: + print("A is a negative number") +else: + print("A is a positive number") +print() + +# ----------------------------------------------------- +# 3. IF ELIF ELSE +# ----------------------------------------------------- + +a = 0 +if a > 0: + print("A is a positive number") +elif a < 0: + print("A is a negative number") +else: + print("A is zero") +print() + +# ----------------------------------------------------- +# 4. SHORT HAND (TERNARY) +# ----------------------------------------------------- + +a = 3 +print("A is positive") if a > 0 else print("A is negative") +print() + +# ----------------------------------------------------- +# 5. NESTED CONDITIONS +# ----------------------------------------------------- + +a = 4 +if a > 0: + if a % 2 == 0: + print("A is a positive and even number") + else: + print("A is a positive and odd number") +elif a == 0: + print("A is zero") +else: + print("A is a negative number") +print() + +# ----------------------------------------------------- +# 6. IF WITH AND LOGICAL OPERATOR +# ----------------------------------------------------- + +a = -3 +if a > 0 and a % 2 == 0: + print("A is an even and positive integer") +elif a > 0 and a % 2 != 0: + print("A is a positive integer") +elif a == 0: + print("A is zero") +else: + print("A is a negative number") +print() + +# ----------------------------------------------------- +# 7. IF WITH OR LOGICAL OPERATOR +# ----------------------------------------------------- + +user = 'James' +access_level = 3 + +if user == 'admin' or access_level >= 4: + print("Access granted!") +else: + print("Access denied!") +print() + +# ===================================================== +# EXERCISES: LEVEL 1 +# ===================================================== + +print("===== EXERCISES: LEVEL 1 =====\n") + +# 1. Driving age check +age = int(input("Enter your age: ")) + +if age >= 18: + print("You are old enough to learn to drive.") +else: + years_left = 18 - age + print(f"You need {years_left} more year(s) to learn to drive.") +print() + +# 2. Compare ages +my_age = 25 +your_age = int(input("Enter your age: ")) + +difference = abs(my_age - your_age) + +if your_age > my_age: + if difference == 1: + print("You are 1 year older than me.") + else: + print(f"You are {difference} years older than me.") +elif your_age < my_age: + if difference == 1: + print("You are 1 year younger than me.") + else: + print(f"You are {difference} years younger than me.") +else: + print("We are the same age.") +print() + +# 3. Compare two numbers +a = int(input("Enter number one: ")) +b = int(input("Enter number two: ")) + +if a > b: + print(f"{a} is greater than {b}") +elif a < b: + print(f"{a} is smaller than {b}") +else: + print(f"{a} is equal to {b}") +print() + +# ===================================================== +# EXERCISES: LEVEL 2 +# ===================================================== + +print("===== EXERCISES: LEVEL 2 =====\n") + +# 1. Grade system +score = int(input("Enter your score: ")) + +if 90 <= score <= 100: + print("Grade: A") +elif 80 <= score <= 89: + print("Grade: B") +elif 70 <= score <= 79: + print("Grade: C") +elif 60 <= score <= 69: + print("Grade: D") +elif 0 <= score <= 59: + print("Grade: F") +else: + print("Invalid score") +print() + +# 2. Season checker +month = input("Enter a month: ").capitalize() + +if month in ['September', 'October', 'November']: + print("Season: Autumn") +elif month in ['December', 'January', 'February']: + print("Season: Winter") +elif month in ['March', 'April', 'May']: + print("Season: Spring") +elif month in ['June', 'July', 'August']: + print("Season: Summer") +else: + print("Invalid month") +print() + +# 3. Fruit checker +fruits = ['banana', 'orange', 'mango', 'lemon'] +fruit = input("Enter a fruit: ").lower() + +if fruit in fruits: + print("That fruit already exist in the list") +else: + fruits.append(fruit) + print("Updated fruits list:", fruits) +print() + +# ===================================================== +# EXERCISES: LEVEL 3 +# ===================================================== + +print("===== EXERCISES: LEVEL 3 =====\n") + +person = { + 'first_name': 'Asabeneh', + 'last_name': 'Yetayeh', + 'age': 250, + 'country': 'Finland', + 'is_married': True, + 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'], + 'address': { + 'street': 'Space street', + 'zipcode': '02210' + } +} + +# 1. Middle skill +if 'skills' in person: + skills = person['skills'] + middle_index = len(skills) // 2 + print("Middle skill:", skills[middle_index]) +print() + +# 2. Check Python skill +if 'skills' in person: + print("Has Python skill?", 'Python' in person['skills']) +print() + +# 3. Developer role check +skills = set(person['skills']) + +if {'JavaScript', 'React'}.issubset(skills) and len(skills) == 2: + print("He is a front end developer") +elif {'Node', 'Python', 'MongoDB'}.issubset(skills) and 'React' not in skills: + print("He is a backend developer") +elif {'React', 'Node', 'MongoDB'}.issubset(skills): + print("He is a fullstack developer") +else: + print("Unknown title") +print() + +# 4. Marital & country info +if person['is_married'] and person['country'] == 'Finland': + print(f"{person['first_name']} {person['last_name']} lives in Finland. He is married.") + +print("\n===== END OF DAY 9 =====") \ No newline at end of file diff --git a/10_Day_Loops/day_10.py b/10_Day_Loops/day_10.py new file mode 100644 index 000000000..ff776e59f --- /dev/null +++ b/10_Day_Loops/day_10.py @@ -0,0 +1,300 @@ +# ===================================================== +# 30 Days Of Python - Day 10: Loops (FULL SOLUTION) +# ===================================================== + +print("===== DAY 10: LOOPS =====\n") + +# ===================================================== +# WHILE LOOP +# ===================================================== + +print("While loop: 0 to 4") +count = 0 +while count < 5: + print(count) + count += 1 +print() + +# While loop with else +print("While loop with else:") +count = 0 +while count < 5: + print(count) + count += 1 +else: + print("Loop finished at:", count) +print() + +# ===================================================== +# BREAK AND CONTINUE (WHILE) +# ===================================================== + +print("Break example (stop at 3):") +count = 0 +while count < 5: + print(count) + count += 1 + if count == 3: + break +print() + +print("Continue example (skip 3):") +count = 0 +while count < 5: + if count == 3: + count += 1 + continue + print(count) + count += 1 +print() + +# ===================================================== +# FOR LOOP EXAMPLES +# ===================================================== + +print("For loop with list:") +numbers = [0, 1, 2, 3, 4, 5] +for number in numbers: + print(number) +print() + +print("For loop with string:") +language = "Python" +for letter in language: + print(letter) +print() + +print("For loop with tuple:") +numbers = (0, 1, 2, 3, 4, 5) +for number in numbers: + print(number) +print() + +print("For loop with dictionary:") +person = { + 'first_name': 'Asabeneh', + 'last_name': 'Yetayeh', + 'age': 250, + 'country': 'Finland' +} + +for key, value in person.items(): + print(key, ":", value) +print() + +print("For loop with set:") +it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple'} +for company in it_companies: + print(company) +print() + +# ===================================================== +# BREAK AND CONTINUE (FOR) +# ===================================================== + +print("Break in for loop:") +for number in range(6): + print(number) + if number == 3: + break +print() + +print("Continue in for loop:") +for number in range(6): + if number == 3: + continue + print(number) +print() + +# ===================================================== +# RANGE FUNCTION +# ===================================================== + +print("Range examples:") +print(list(range(11))) +print(list(range(0, 11, 2))) +print(list(range(10, -1, -1))) +print() + +# ===================================================== +# NESTED FOR LOOP +# ===================================================== + +print("Nested loop (skills):") +person = { + 'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'] +} + +for skill in person['skills']: + print(skill) +print() + +# ===================================================== +# FOR ELSE +# ===================================================== + +print("For-else example:") +for number in range(5): + print(number) +else: + print("Loop ended successfully") +print() + +# ===================================================== +# PASS +# ===================================================== + +print("Pass example:") +for _ in range(3): + pass +print("Pass executed without errors\n") + +# ===================================================== +# EXERCISES: LEVEL 1 +# ===================================================== + +print("===== EXERCISES: LEVEL 1 =====\n") + +# 1. 0 to 10 (for & while) +print("0 to 10 using for loop:") +for i in range(11): + print(i) + +print("\n0 to 10 using while loop:") +i = 0 +while i <= 10: + print(i) + i += 1 +print() + +# 2. 10 to 0 (for & while) +print("10 to 0 using for loop:") +for i in range(10, -1, -1): + print(i) + +print("\n10 to 0 using while loop:") +i = 10 +while i >= 0: + print(i) + i -= 1 +print() + +# 3. Triangle pattern +print("Triangle pattern:") +for i in range(1, 8): + print("#" * i) +print() + +# 4. 8x8 grid +print("8x8 grid:") +for i in range(8): + for j in range(8): + print("#", end=" ") + print() +print() + +# 5. Multiplication pattern +print("Square numbers:") +for i in range(11): + print(f"{i} x {i} = {i*i}") +print() + +# 6. Iterate list +languages = ['Python', 'Numpy', 'Pandas', 'Django', 'Flask'] +for lang in languages: + print(lang) +print() + +# 7. Even numbers 0–100 +print("Even numbers:") +for i in range(0, 101): + if i % 2 == 0: + print(i) +print() + +# 8. Odd numbers 0–100 +print("Odd numbers:") +for i in range(0, 101): + if i % 2 != 0: + print(i) +print() + +# ===================================================== +# EXERCISES: LEVEL 2 +# ===================================================== + +print("===== EXERCISES: LEVEL 2 =====\n") + +# 1. Sum of all numbers +total = 0 +for i in range(101): + total += i +print("The sum of all numbers is", total) +print() + +# 2. Sum of evens and odds +even_sum = 0 +odd_sum = 0 + +for i in range(101): + if i % 2 == 0: + even_sum += i + else: + odd_sum += i + +print(f"The sum of all evens is {even_sum}. And the sum of all odds is {odd_sum}.") +print() + +# ===================================================== +# EXERCISES: LEVEL 3 +# ===================================================== + +print("===== EXERCISES: LEVEL 3 =====\n") + +# 1. Countries containing 'land' +countries = [ + 'Finland', 'Iceland', 'Thailand', 'Poland', + 'Switzerland', 'Canada', 'Ireland' +] + +print("Countries containing 'land':") +for country in countries: + if 'land' in country.lower(): + print(country) +print() + +# 2. Reverse fruits using loop +fruits = ['banana', 'orange', 'mango', 'lemon'] +reversed_fruits = [] + +for i in range(len(fruits)-1, -1, -1): + reversed_fruits.append(fruits[i]) + +print("Reversed fruits:", reversed_fruits) +print() + +# 3. Countries data (simplified version) +countries_data = [ + {'name': 'China', 'population': 1444216107, 'languages': ['Chinese']}, + {'name': 'India', 'population': 1393409038, 'languages': ['Hindi', 'English']}, + {'name': 'USA', 'population': 331893745, 'languages': ['English']}, + {'name': 'Indonesia', 'population': 276361783, 'languages': ['Indonesian']}, + {'name': 'Pakistan', 'population': 225199937, 'languages': ['Urdu', 'English']} +] + +# Total number of languages +languages = set() +for country in countries_data: + for lang in country['languages']: + languages.add(lang) + +print("Total number of languages:", len(languages)) + +# 10 most populated countries (here limited sample) +countries_data.sort(key=lambda x: x['population'], reverse=True) + +print("\nMost populated countries:") +for country in countries_data[:10]: + print(country['name'], "-", country['population']) + +print("\n===== END OF DAY 10 =====") \ No newline at end of file diff --git a/11_Day_Functions/day_11.py b/11_Day_Functions/day_11.py new file mode 100644 index 000000000..5c90d8847 --- /dev/null +++ b/11_Day_Functions/day_11.py @@ -0,0 +1,259 @@ +# ===================================================== +# 30 Days Of Python - Day 11: Functions (FULL SOLUTION) +# ===================================================== + +import math +import keyword + +print("===== DAY 11: FUNCTIONS =====\n") + +# ===================================================== +# BASIC FUNCTION DECLARATIONS +# ===================================================== + +def add_two_numbers(a, b): + return a + b + +print("Add two numbers:", add_two_numbers(3, 7)) + + +def area_of_circle(r): + return math.pi * r * r + +print("Area of circle:", area_of_circle(10)) + + +def add_all_nums(*nums): + total = 0 + for num in nums: + if not isinstance(num, (int, float)): + return "All arguments must be numbers" + total += num + return total + +print("Sum all numbers:", add_all_nums(1, 2, 3, 4)) + + +def convert_celsius_to_fahrenheit(c): + return (c * 9/5) + 32 + +print("C to F:", convert_celsius_to_fahrenheit(25)) + + +def check_season(month): + month = month.capitalize() + if month in ['September', 'October', 'November']: + return 'Autumn' + elif month in ['December', 'January', 'February']: + return 'Winter' + elif month in ['March', 'April', 'May']: + return 'Spring' + elif month in ['June', 'July', 'August']: + return 'Summer' + else: + return 'Invalid month' + +print("Season:", check_season("October")) + + +def calculate_slope(x1=0, y1=0, x2=1, y2=1): + if x2 - x1 == 0: + return "Undefined slope" + return (y2 - y1) / (x2 - x1) + +print("Slope:", calculate_slope()) + + +def solve_quadratic_eqn(a, b, c): + d = b**2 - 4*a*c + if d < 0: + return "No real roots" + x1 = (-b + math.sqrt(d)) / (2*a) + x2 = (-b - math.sqrt(d)) / (2*a) + return x1, x2 + +print("Quadratic:", solve_quadratic_eqn(1, -3, 2)) + + +def print_list(lst): + for item in lst: + print(item) + +print_list([1, 2, 3]) + + +def reverse_list(arr): + reversed_arr = [] + for i in range(len(arr)-1, -1, -1): + reversed_arr.append(arr[i]) + return reversed_arr + +print(reverse_list([1, 2, 3, 4, 5])) +print(reverse_list(["A", "B", "C"])) + + +def capitalize_list_items(lst): + return [item.upper() for item in lst] + +print(capitalize_list_items(['python', 'java'])) + + +def add_item(lst, item): + lst.append(item) + return lst + +print(add_item(['Potato', 'Tomato'], 'Meat')) + + +def remove_item(lst, item): + if item in lst: + lst.remove(item) + return lst + +print(remove_item(['Potato', 'Tomato', 'Mango'], 'Mango')) + + +def sum_of_numbers(n): + return sum(range(n+1)) + +print(sum_of_numbers(100)) + + +def sum_of_odds(n): + return sum(i for i in range(n+1) if i % 2 != 0) + +print("Sum odds:", sum_of_odds(10)) + + +def sum_of_even(n): + return sum(i for i in range(n+1) if i % 2 == 0) + +print("Sum evens:", sum_of_even(10)) + + +# ===================================================== +# LEVEL 2 +# ===================================================== + +def evens_and_odds(n): + evens = sum(1 for i in range(n+1) if i % 2 == 0) + odds = sum(1 for i in range(n+1) if i % 2 != 0) + return f"The number of odds are {odds}. The number of evens are {evens}." + +print(evens_and_odds(100)) + + +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:", factorial(5)) + + +def is_empty(value): + return not bool(value) + +print("Is empty:", is_empty("")) + + +def calculate_mean(lst): + return sum(lst) / len(lst) + + +def calculate_median(lst): + lst = sorted(lst) + n = len(lst) + mid = n // 2 + return (lst[mid] if n % 2 != 0 else (lst[mid-1] + lst[mid]) / 2) + + +def calculate_mode(lst): + return max(set(lst), key=lst.count) + + +def calculate_range(lst): + return max(lst) - min(lst) + + +def calculate_variance(lst): + mean = calculate_mean(lst) + return sum((x - mean) ** 2 for x in lst) / len(lst) + + +def calculate_std(lst): + return math.sqrt(calculate_variance(lst)) + + +numbers = [1, 2, 2, 3, 4, 5] +print("Mean:", calculate_mean(numbers)) +print("Median:", calculate_median(numbers)) +print("Mode:", calculate_mode(numbers)) +print("Range:", calculate_range(numbers)) +print("Variance:", calculate_variance(numbers)) +print("Std Dev:", calculate_std(numbers)) + + +def greet(name="Guest"): + return f"Hello, {name}!" + +print(greet()) +print(greet("Alice")) + + +def show_args(**kwargs): + for k, v in kwargs.items(): + print(f"{k}: {v}") + +show_args(name="Alice", age=30) + + +# ===================================================== +# LEVEL 3 +# ===================================================== + +def is_prime(n): + if n <= 1: + return False + for i in range(2, int(math.sqrt(n)) + 1): + if n % i == 0: + return False + return True + +print("Is prime:", is_prime(29)) + + +def all_unique(lst): + return len(lst) == len(set(lst)) + +print("All unique:", all_unique([1, 2, 3])) + + +def same_data_type(lst): + return all(type(item) == type(lst[0]) for item in lst) + +print("Same type:", same_data_type([1, 2, 3])) + + +def is_valid_variable(var): + return var.isidentifier() and not keyword.iskeyword(var) + +print("Valid variable:", is_valid_variable("my_var")) + + +def most_spoken_languages(data, n=10): + languages = {} + for country in data: + for lang in country['languages']: + languages[lang] = languages.get(lang, 0) + 1 + return sorted(languages.items(), key=lambda x: x[1], reverse=True)[:n] + + +def most_populated_countries(data, n=10): + return sorted(data, key=lambda x: x['population'], reverse=True)[:n] + + +print("\n===== END OF DAY 11 =====") \ No newline at end of file diff --git a/13_Day_List_comprehension/day_13.py b/13_Day_List_comprehension/day_13.py new file mode 100644 index 000000000..fb3a610c7 --- /dev/null +++ b/13_Day_List_comprehension/day_13.py @@ -0,0 +1,179 @@ +# ===================================================== +# 30 Days Of Python - Day 13: List Comprehension +# ===================================================== + +print("===== DAY 13: LIST COMPREHENSION =====\n") + +# ----------------------------------------------------- +# 1. List Comprehension Basics +# ----------------------------------------------------- + +language = 'Python' + +# Converting string to list (normal way) +lst = list(language) +print("List using list():", lst) + +# Using list comprehension +lst = [i for i in language] +print("List using list comprehension:", lst) +print() + +# ----------------------------------------------------- +# 2. Generating Numbers with List Comprehension +# ----------------------------------------------------- + +numbers = [i for i in range(11)] +print("Numbers from 0 to 10:", numbers) + +# Squares +squares = [i * i for i in range(11)] +print("Squares:", squares) + +# List of tuples (number, square) +number_tuples = [(i, i * i) for i in range(11)] +print("Tuples (number, square):", number_tuples) +print() + +# ----------------------------------------------------- +# 3. List Comprehension with Condition +# ----------------------------------------------------- + +# Even numbers +even_numbers = [i for i in range(21) if i % 2 == 0] +print("Even numbers:", even_numbers) + +# Odd numbers +odd_numbers = [i for i in range(21) if i % 2 != 0] +print("Odd numbers:", odd_numbers) + +# Filtering positive even numbers +numbers = [-8, -7, -3, -1, 0, 1, 3, 4, 5, 7, 6, 8, 10] +positive_even_numbers = [i for i in numbers if i % 2 == 0 and i > 0] +print("Positive even numbers:", positive_even_numbers) +print() + +# ----------------------------------------------------- +# 4. Flattening a 2D List +# ----------------------------------------------------- + +list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +flattened_list = [number for row in list_of_lists for number in row] +print("Flattened list:", flattened_list) +print() + +# ===================================================== +# LAMBDA FUNCTIONS +# ===================================================== + +print("===== LAMBDA FUNCTIONS =====\n") + +# Named function +def add_two_nums(a, b): + return a + b + +print("Named function:", add_two_nums(2, 3)) + +# Lambda version +add_two_nums = lambda a, b: a + b +print("Lambda function:", add_two_nums(2, 3)) + +# Self-invoking lambda +print("Self-invoking lambda:", (lambda a, b: a + b)(2, 3)) + +# Square and cube +square = lambda x: x ** 2 +cube = lambda x: x ** 3 + +print("Square of 3:", square(3)) +print("Cube of 3:", cube(3)) + +# Multiple variables +multiple_variable = lambda a, b, c: a ** 2 - 3 * b + 4 * c +print("Multiple variable lambda:", multiple_variable(5, 5, 3)) +print() + +# ----------------------------------------------------- +# Lambda Inside Another Function +# ----------------------------------------------------- + +def power(x): + return lambda n: x ** n + +cube = power(2)(3) +print("2 power of 3:", cube) + +two_power_of_five = power(2)(5) +print("2 power of 5:", two_power_of_five) +print() + +# ===================================================== +# EXERCISES - DAY 13 +# ===================================================== + +print("===== EXERCISES: DAY 13 =====\n") + +# 1. Filter only negative and zero +numbers = [-4, -3, -2, -1, 0, 2, 4, 6] +negative_and_zero = [i for i in numbers if i <= 0] +print("1. Negative and zero:", negative_and_zero) + +# 2. Flatten list of lists +list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] +flattened = [num for row in list_of_lists for num in row] +print("\n2. Flattened list:", flattened) + +# 3. Create list of tuples +tuple_list = [ + (i, 1, i, i**2, i**3, i**4, i**5) + for i in range(11) +] +print("\n3. List of tuples:") +for item in tuple_list: + print(item) + +# 4. Flatten countries list and format +countries = [[('Finland', 'Helsinki')], + [('Sweden', 'Stockholm')], + [('Norway', 'Oslo')]] + +formatted_countries = [ + [country.upper(), country[:3].upper(), city.upper()] + for row in countries + for country, city in row +] + +print("\n4. Formatted countries:", formatted_countries) + +# 5. Convert to list of dictionaries +countries_dict = [ + {'country': country.upper(), 'city': city.upper()} + for row in countries + for country, city in row +] + +print("\n5. Countries as dictionaries:", countries_dict) + +# 6. Concatenate names +names = [[('Asabeneh', 'Yetayeh')], + [('David', 'Smith')], + [('Donald', 'Trump')], + [('Bill', 'Gates')]] + +full_names = [ + f"{first} {last}" + for row in names + for first, last in row +] + +print("\n6. Full names:", full_names) + +# 7. Lambda for slope and y-intercept +# y = mx + b +slope = lambda x1, y1, x2, y2: (y2 - y1) / (x2 - x1) +y_intercept = lambda m, x, y: y - m * x + +print("\n7. Slope:", slope(1, 2, 3, 6)) +print(" Y-intercept:", y_intercept(2, 1, 4)) + +print("\n===== END OF DAY 13 =====") \ No newline at end of file diff --git a/14_Day_Higher_order_functions/day_14.py b/14_Day_Higher_order_functions/day_14.py new file mode 100644 index 000000000..53c451e1a --- /dev/null +++ b/14_Day_Higher_order_functions/day_14.py @@ -0,0 +1,214 @@ +# ===================================================== +# 30 Days Of Python - Day 14: Higher Order Functions +# ===================================================== + +from functools import reduce + +print("===== DAY 14: HIGHER ORDER FUNCTIONS =====\n") + +# ----------------------------------------------------- +# FUNCTION AS A PARAMETER +# ----------------------------------------------------- + +def sum_numbers(nums): + return sum(nums) + +def higher_order_function(func, lst): + return func(lst) + +result = higher_order_function(sum_numbers, [1, 2, 3, 4, 5]) +print("Sum using function as parameter:", result) +print() + +# ----------------------------------------------------- +# FUNCTION AS A RETURN VALUE +# ----------------------------------------------------- + +def square(x): + return x ** 2 + +def cube(x): + return x ** 3 + +def absolute(x): + return x if x >= 0 else -x + +def higher_order_function_returner(func_type): + if func_type == 'square': + return square + elif func_type == 'cube': + return cube + elif func_type == 'absolute': + return absolute + +print("Square:", higher_order_function_returner('square')(3)) +print("Cube:", higher_order_function_returner('cube')(3)) +print("Absolute:", higher_order_function_returner('absolute')(-3)) +print() + +# ----------------------------------------------------- +# PYTHON CLOSURES +# ----------------------------------------------------- + +def add_ten(): + ten = 10 + def add(num): + return num + ten + return add + +closure_func = add_ten() +print("Closure result 5:", closure_func(5)) +print("Closure result 10:", closure_func(10)) +print() + +# ----------------------------------------------------- +# PYTHON DECORATORS +# ----------------------------------------------------- + +def uppercase_decorator(function): + def wrapper(): + return function().upper() + return wrapper + +@uppercase_decorator +def greeting(): + return 'Welcome to Python' + +print("Decorator result:", greeting()) +print() + +# ----------------------------------------------------- +# MULTIPLE DECORATORS +# ----------------------------------------------------- + +def split_string_decorator(function): + def wrapper(): + return function().split() + return wrapper + +@split_string_decorator +@uppercase_decorator +def greeting(): + return 'Welcome to Python' + +print("Multiple decorators:", greeting()) +print() + +# ----------------------------------------------------- +# DECORATOR WITH PARAMETERS +# ----------------------------------------------------- + +def decorator_with_parameters(function): + def wrapper(first_name, last_name, country): + function(first_name, last_name, country) + print(f"I live in {country}") + return wrapper + +@decorator_with_parameters +def print_full_name(first_name, last_name, country): + print(f"I am {first_name} {last_name}. I love to teach.") + +print_full_name("Asabeneh", "Yetayeh", "Finland") +print() + +# ===================================================== +# BUILT-IN HIGHER ORDER FUNCTIONS +# ===================================================== + +countries = ['Estonia', 'Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland'] +names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham'] +numbers = list(range(1, 11)) + +# ----------------------------------------------------- +# MAP +# ----------------------------------------------------- + +countries_upper = list(map(str.upper, countries)) +print("Map uppercase countries:", countries_upper) + +numbers_squared = list(map(lambda x: x ** 2, numbers)) +print("Map square numbers:", numbers_squared) + +names_upper = list(map(str.upper, names)) +print("Map uppercase names:", names_upper) +print() + +# ----------------------------------------------------- +# FILTER +# ----------------------------------------------------- + +countries_with_land = list(filter(lambda c: 'land' in c.lower(), countries)) +print("Countries with 'land':", countries_with_land) + +six_char_countries = list(filter(lambda c: len(c) == 6, countries)) +print("Countries with 6 letters:", six_char_countries) + +six_or_more = list(filter(lambda c: len(c) >= 6, countries)) +print("Countries with >= 6 letters:", six_or_more) + +countries_starting_E = list(filter(lambda c: c.startswith('E'), countries)) +print("Countries starting with E:", countries_starting_E) +print() + +# ----------------------------------------------------- +# REDUCE +# ----------------------------------------------------- + +sum_numbers = reduce(lambda x, y: x + y, numbers) +print("Sum using reduce:", sum_numbers) + +sentence = reduce( + lambda x, y: f"{x}, {y}", + countries[:-1] +) + f", and {countries[-1]} are north European countries" + +print(sentence) +print() + +# ----------------------------------------------------- +# CHAINING MAP + FILTER + REDUCE +# ----------------------------------------------------- + +chained = reduce( + lambda x, y: x + y, + map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)) +) +print("Chained result:", chained) +print() + +# ----------------------------------------------------- +# FUNCTIONS FOR EXERCISES +# ----------------------------------------------------- + +def get_string_lists(lst): + return list(filter(lambda x: isinstance(x, str), lst)) + +print("String only list:", get_string_lists([1, 'hello', 3, 'world'])) +print() + +def categorize_countries(pattern): + return list(filter(lambda c: pattern.lower() in c.lower(), countries)) + +print("Countries with 'land':", categorize_countries('land')) +print() + +def count_countries_by_letter(country_list): + result = {} + for country in country_list: + first_letter = country[0] + result[first_letter] = result.get(first_letter, 0) + 1 + return result + +print("Country count by letter:", count_countries_by_letter(countries)) +print() + +def get_first_ten_countries(country_list): + return country_list[:10] + +def get_last_ten_countries(country_list): + return country_list[-10:] + +print("First ten countries:", get_first_ten_countries(countries)) +print("Last ten countries:", get_last_ten_countries(countries)) + +print("\n===== END OF DAY 14 =====") \ No newline at end of file diff --git a/15_Day_Python_type_errors/day_15.py b/15_Day_Python_type_errors/day_15.py new file mode 100644 index 000000000..6de6a6b7d --- /dev/null +++ b/15_Day_Python_type_errors/day_15.py @@ -0,0 +1,110 @@ +# ===================================================== +# 30 Days Of Python - Day 15: Python Type Errors +# ===================================================== + +print("===== DAY 15: PYTHON TYPE ERRORS =====\n") + +# ----------------------------------------------------- +# SYNTAX ERROR (cannot be caught at runtime) +# ----------------------------------------------------- +print("SyntaxError example (shown as comment):") +print("print 'hello world' # Missing parentheses\n") + +# ----------------------------------------------------- +# NAME ERROR +# ----------------------------------------------------- +try: + print(age) +except NameError as e: + print("NameError:", e) + age = 25 + print("Fixed -> age =", age) +print() + +# ----------------------------------------------------- +# INDEX ERROR +# ----------------------------------------------------- +numbers = [1, 2, 3, 4, 5] +try: + print(numbers[5]) +except IndexError as e: + print("IndexError:", e) + print("Valid indexes are 0 to", len(numbers) - 1) +print() + +# ----------------------------------------------------- +# MODULE NOT FOUND ERROR +# ----------------------------------------------------- +try: + import maths +except ModuleNotFoundError as e: + print("ModuleNotFoundError:", e) + import math + print("Fixed -> math module imported") +print() + +# ----------------------------------------------------- +# ATTRIBUTE ERROR +# ----------------------------------------------------- +import math +try: + print(math.PI) +except AttributeError as e: + print("AttributeError:", e) + print("Fixed -> math.pi =", math.pi) +print() + +# ----------------------------------------------------- +# KEY ERROR +# ----------------------------------------------------- +user = {'name': 'Asab', 'age': 250, 'country': 'Finland'} +try: + print(user['county']) +except KeyError as e: + print("KeyError:", e) + print("Fixed -> country =", user['country']) +print() + +# ----------------------------------------------------- +# TYPE ERROR +# ----------------------------------------------------- +try: + print(4 + '3') +except TypeError as e: + print("TypeError:", e) + print("Fixed -> 4 + int('3') =", 4 + int('3')) + print("Alternative -> '4' + '3' =", str(4) + '3') +print() + +# ----------------------------------------------------- +# IMPORT ERROR +# ----------------------------------------------------- +try: + from math import power +except ImportError as e: + print("ImportError:", e) + from math import pow + print("Fixed -> pow(2, 3) =", pow(2, 3)) +print() + +# ----------------------------------------------------- +# VALUE ERROR +# ----------------------------------------------------- +try: + print(int('12a')) +except ValueError as e: + print("ValueError:", e) + print("Fixed -> int('12') =", int('12')) +print() + +# ----------------------------------------------------- +# ZERO DIVISION ERROR +# ----------------------------------------------------- +try: + print(1 / 0) +except ZeroDivisionError as e: + print("ZeroDivisionError:", e) + print("Fix -> check denominator before division") +print() + +print("===== END OF DAY 15 =====") \ No newline at end of file diff --git a/16_Day_Python_date_time/day_16.py b/16_Day_Python_date_time/day_16.py new file mode 100644 index 000000000..090db018d --- /dev/null +++ b/16_Day_Python_date_time/day_16.py @@ -0,0 +1,71 @@ +from datetime import datetime, date + +print("===== DAY 16: PYTHON DATE & TIME EXERCISES =====\n") + +# -------------------------------------------------- +# 1. Get current day, month, year, hour, minute, timestamp +# -------------------------------------------------- +now = datetime.now() + +print("1) Current date and time info") +print("Day:", now.day) +print("Month:", now.month) +print("Year:", now.year) +print("Hour:", now.hour) +print("Minute:", now.minute) +print("Timestamp:", now.timestamp()) +print() + +# -------------------------------------------------- +# 2. Format current date +# Format: "%m/%d/%Y, %H:%M:%S" +# -------------------------------------------------- +formatted_date = now.strftime("%m/%d/%Y, %H:%M:%S") +print("2) Formatted current date:") +print(formatted_date) +print() + +# -------------------------------------------------- +# 3. Convert string to time +# Today is "5 December, 2019" +# -------------------------------------------------- +date_string = "5 December, 2019" +date_object = datetime.strptime(date_string, "%d %B, %Y") + +print("3) String to datetime") +print("Original string:", date_string) +print("Converted datetime:", date_object) +print() + +# -------------------------------------------------- +# 4. Time difference between now and New Year +# -------------------------------------------------- +current_time = datetime.now() +new_year = datetime(year=current_time.year + 1, month=1, day=1) + +time_left = new_year - current_time +print("4) Time left until New Year:") +print(time_left) +print() + +# -------------------------------------------------- +# 5. Time difference between 1 January 1970 and now +# -------------------------------------------------- +epoch = datetime(1970, 1, 1) +time_since_epoch = current_time - epoch + +print("5) Time since 1 January 1970:") +print(time_since_epoch) +print() + +# -------------------------------------------------- +# 6. Uses of datetime module +# -------------------------------------------------- +print("6) Uses of datetime module:") +print("- Time series analysis") +print("- Logging user activity timestamps") +print("- Scheduling tasks") +print("- Blog post timestamps") +print("- Measuring execution time") + +print("\n===== END OF DAY 16 =====") \ No newline at end of file diff --git a/17_Day_Exception_handling/day_17.py b/17_Day_Exception_handling/day_17.py new file mode 100644 index 000000000..1360fb15b --- /dev/null +++ b/17_Day_Exception_handling/day_17.py @@ -0,0 +1,13 @@ +names = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland', 'Estonia', 'Russia'] + +# Unpacking +*nordic_countries, es, ru = names + +print("Nordic countries:", nordic_countries) +print("Estonia:", es) +print("Russia:", ru) + +#output:- +# Nordic countries: ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland'] +# Estonia: Estonia +# Russia: Russia \ No newline at end of file diff --git a/18_Day_Regular_expressions/day_18.py b/18_Day_Regular_expressions/day_18.py new file mode 100644 index 000000000..3e492360c --- /dev/null +++ b/18_Day_Regular_expressions/day_18.py @@ -0,0 +1,82 @@ +import re +from collections import Counter + +print("===== DAY 18: REGULAR EXPRESSIONS =====\n") + +# -------------------------------------------------- +# EXERCISES: LEVEL 1 +# -------------------------------------------------- + +# 1. Most frequent word in a paragraph +paragraph = '''I love teaching. If you do not love teaching what else can you love. +I love Python if you do not love something which can give you all the capabilities +to develop an application what else can you love.''' + +# extract words (ignore punctuation, case-insensitive) +words = re.findall(r'\b[a-zA-Z]+\b', paragraph) +word_counts = Counter(words) + +most_common_words = word_counts.most_common() +print("LEVEL 1 - Exercise 1:") +print(most_common_words) +print() + +# -------------------------------------------------- + +# 2. Extract numbers and find distance +text = 'The position of some particles on the horizontal x-axis are -12, -4, -3 and -1 in the negative direction, 0 at origin, 4 and 8 in the positive direction.' + +numbers = re.findall(r'-?\d+', text) +numbers = list(map(int, numbers)) + +distance = max(numbers) - min(numbers) + +print("LEVEL 1 - Exercise 2:") +print("Extracted numbers:", numbers) +print("Distance between furthest particles:", distance) +print() + +# -------------------------------------------------- +# EXERCISES: LEVEL 2 +# -------------------------------------------------- + +# Valid Python variable checker +def is_valid_variable(name): + pattern = r'^[a-zA-Z_][a-zA-Z0-9_]*$' + return bool(re.match(pattern, name)) + +print("LEVEL 2:") +print(is_valid_variable('first_name')) # True +print(is_valid_variable('first-name')) # False +print(is_valid_variable('1first_name')) # False +print(is_valid_variable('firstname')) # True +print() + +# -------------------------------------------------- +# EXERCISES: LEVEL 3 +# -------------------------------------------------- + +sentence = '''%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%; +There $is nothing; &as& mo@re rewarding as educa@ting &and& +@emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting +tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?''' + +# Clean text +def clean_text(text): + return re.sub(r'[^a-zA-Z\s]', '', text) + +cleaned_text = clean_text(sentence) +print("LEVEL 3 - Cleaned Text:") +print(cleaned_text) +print() + +# Find most frequent words +def most_frequent_words(text, n=3): + words = re.findall(r'\b[a-zA-Z]+\b', text) + counts = Counter(words) + return counts.most_common(n) + +print("LEVEL 3 - Most Frequent Words:") +print(most_frequent_words(cleaned_text)) + +print("\n===== END OF DAY 18 =====") \ No newline at end of file