├── Al Sweigart
├── 02 Flow Control
│ └── index.py
├── .idea
│ ├── .gitignore
│ ├── vcs.xml
│ ├── inspectionProfiles
│ │ └── profiles_settings.xml
│ ├── misc.xml
│ ├── modules.xml
│ └── Al Sweigart.iml
└── 01 Python Basics
│ ├── python problems
│ ├── test3.py
│ ├── test2.py
│ └── test1.py
│ └── Notes.MD
├── .idea
├── .gitignore
├── vcs.xml
├── misc.xml
├── inspectionProfiles
│ └── profiles_settings.xml
├── modules.xml
└── Learning-Python.iml
├── python programs
├── earth.py
├── Sanduhr.py
├── Nummer(n).py
├── Herztext.py
├── passwort.py
├── raten.py
├── Noten.py
└── Rechner.py
├── practie problems
├── solve_10.py
├── solve_8.py
├── solve_7.py
├── solve_6.py
├── solve_5.py
├── solve_1.py
├── solve_9.py
├── solve_4.py
├── solve_3.py
└── solve_2.py
├── .github
└── workflows
│ ├── black.yml
│ ├── CI.yml
│ ├── auto-reply.yml
│ └── updated-readme.yml
├── README.md
└── My Notes
├── Classes&Objects.MD
├── Intro.MD
└── Index.MD
/Al Sweigart/02 Flow Control/index.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/Al Sweigart/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/Al Sweigart/01 Python Basics/python problems/test3.py:
--------------------------------------------------------------------------------
1 | # Create a “tip calculator”: ask user for bill amount and tip percentage (like “15%”), compute tip and total.
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Al Sweigart/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/python programs/earth.py:
--------------------------------------------------------------------------------
1 | import webbrowser
2 |
3 | # Gib die die URL für Google-earth an
4 | google_earth_url = 'http://earth.google.com/'
5 |
6 | # öffne Google-earth im Standard-Webbrowser
7 | webbrowser.open(google_earth_url)
8 |
9 |
--------------------------------------------------------------------------------
/Al Sweigart/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Al Sweigart/01 Python Basics/python problems/test2.py:
--------------------------------------------------------------------------------
1 | # Modify test1: also ask for their birth month & day, and tell them whether they've had their birthday
2 | # yet this year (relative to today). (Work with date arithmetic manually or use datetime.)
3 |
4 |
--------------------------------------------------------------------------------
/python programs/Sanduhr.py:
--------------------------------------------------------------------------------
1 | def Sanduhr_muster(n):
2 | # Die Reichweite.
3 | for i in range(n, 0, -1):
4 | print(" " * (n - i) + "* " * i)
5 | for i in range(2, n, 1):
6 | print(" " * (n - i) + "* " * i)
7 |
8 |
9 | Sanduhr_muster(5)
--------------------------------------------------------------------------------
/python programs/Nummer(n).py:
--------------------------------------------------------------------------------
1 | ###Practice 6
2 | ##Lies eine Zahl (n) und gib die Reihe(series) aus "1+2+...+n="
3 | n = int(input("Gib die eine Nummer ein: "))
4 |
5 | reihe = " + ".join(str(i) for i in range(1, n + 1))
6 | summe = sum(range(1, n + 1))
7 |
8 | print(f"{reihe} = {summe}")
--------------------------------------------------------------------------------
/python programs/Herztext.py:
--------------------------------------------------------------------------------
1 | print('\n'.join([
2 | ''.join([
3 | (' Pride '[(x - y) % 8] if ((x * 0.05) ** 2 + (y * 0.1) ** 2 - 1) ** 3 - (x * 0.05) ** 2 * (y * 0.1) ** 3 <= 0 else ' ')
4 | for x in range(-30, 30)
5 | ])
6 | for y in range(15, -15, -1)
7 | ]))
8 |
9 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Al Sweigart/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Al Sweigart/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/python programs/passwort.py:
--------------------------------------------------------------------------------
1 | ##### Practice 4
2 | ## Simple Password Checker
3 |
4 | password = input("Passwort eingeben: ")
5 | has_number = any(char.isdigit() for char in password)
6 |
7 | if len(password) > 8 and has_number:
8 | print("starkes Passwort")
9 | else:
10 | print("schwaches Passwort! Versuch es noch einmal...")
11 |
--------------------------------------------------------------------------------
/Al Sweigart/01 Python Basics/python problems/test1.py:
--------------------------------------------------------------------------------
1 | # Write a program that asks the user for their birth year, and prints how old they’ll be in the year 2050.
2 |
3 | ask4BirthYear = int(input("What year were you born? "))
4 | yearConstant = 2050
5 | print("You are going to be " + str(yearConstant - ask4BirthYear) + " years old in the year 2050")
6 |
--------------------------------------------------------------------------------
/.idea/Learning-Python.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Al Sweigart/.idea/Al Sweigart.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/practie problems/solve_10.py:
--------------------------------------------------------------------------------
1 | ##### PROJECT 1 #######
2 | ##Write a program that accepts an input from a user about their birth year
3 | ##Write an output telling the user his/her age depending on the information provided by the user
4 | user_birthYear = int(input("What's your birth year: "))
5 | year_Const = 2025
6 |
7 | print(f"You're {year_Const - user_birthYear} years old.")
--------------------------------------------------------------------------------
/python programs/raten.py:
--------------------------------------------------------------------------------
1 | #####Practice 3
2 | ##Rate Nummer
3 | import random
4 |
5 | Geheim_nummer = random.randint(1, 10)
6 | rate = None
7 |
8 | while rate != Geheim_nummer:
9 | rate = int(input("Errate die Nummer (1-10): "))
10 |
11 | if rate < Geheim_nummer:
12 | print("Zu niedrig!")
13 | elif rate > Geheim_nummer:
14 | print("Zu hoch!")
15 | else:
16 | print("Richtig, die Geheim_nummer war ", Geheim_nummer)
17 |
--------------------------------------------------------------------------------
/python programs/Noten.py:
--------------------------------------------------------------------------------
1 | ###Practice 5
2 | ##Schülernoten
3 |
4 | Schüler_info = {
5 | "Henry": 85,
6 | "Esther": 99,
7 | "Jane": 100,
8 | "Emmanuel": 83,
9 | "Miracle": 91,
10 | "Precious": 79
11 | }
12 |
13 | for schüler, noten in Schüler_info.items():
14 | print(f"{schüler}: {noten}")
15 | Durchschnitt1 = noten / len(Schüler_info)
16 | print(Durchschnitt1)
17 |
18 | durchschnitt = sum(Schüler_info.values()) / len(Schüler_info)
19 | print("Durchschnittliche Note:", durchschnitt)
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.github/workflows/black.yml:
--------------------------------------------------------------------------------
1 | name: 🖤 Black Formatter
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 | branches: [main]
8 |
9 | jobs:
10 | format:
11 | runs-on: ubuntu-latest
12 |
13 | steps:
14 | - name: Checkout code
15 | uses: actions/checkout@v4
16 |
17 | - name: Set up Python
18 | uses: actions/setup-python@v4
19 | with:
20 | python-version: '3.11'
21 |
22 | - name: Install Black
23 | run: pip install black
24 |
25 | - name: Run Black
26 | run: black .
27 |
--------------------------------------------------------------------------------
/practie problems/solve_8.py:
--------------------------------------------------------------------------------
1 | ####### ASSIGNMENT 8 ########
2 | ##Make the list of phones
3 | #--and make a copy of the list of the phones and call it my friend's phones
4 | phones = ["Tecno", "Infinix", "Oppo", "Xiaomi"]
5 | print(phones)
6 |
7 | friends_Phones = phones[:]
8 | print(friends_Phones)
9 |
10 | ##Add a new phone to the original list--also add a new phone to the friend's list
11 | phones.insert(0, "Samsung")
12 |
13 | friends_Phones.append("Iphone")
14 |
15 | ##Prove that you have two separate lists and print a message with the separate lists
16 | print(phones)
17 | print(friends_Phones)
18 |
--------------------------------------------------------------------------------
/.github/workflows/CI.yml:
--------------------------------------------------------------------------------
1 | # https://docs.astral.sh/ruff
2 | name: ci
3 | on:
4 | push:
5 | # branches: [main]
6 | pull_request:
7 | branches: [main]
8 | workflow_dispatch:
9 | jobs:
10 | codespell:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v5
14 | - run: pipx run codespell
15 | ruff_check:
16 | runs-on: ubuntu-latest
17 | steps:
18 | - uses: actions/checkout@v5
19 | - run: pipx run ruff check --output-format=github
20 | ruff_format:
21 | runs-on: ubuntu-latest
22 | steps:
23 | - uses: actions/checkout@v5
24 | - run: pipx run ruff format
25 |
--------------------------------------------------------------------------------
/python programs/Rechner.py:
--------------------------------------------------------------------------------
1 | ###Practice 1
2 | ###Grundrechner
3 | zahl1 = float(input("Gib die erste Zahl ein: "))
4 | operand = input("Operator (+,-,*,/): ")
5 | zahl2 = float(input("Gib die zweite Zahl: "))
6 |
7 | if operand == "+":
8 | ergebnis = zahl1 + zahl2
9 | elif operand == "-":
10 | ergebnis = zahl1 - zahl2
11 | elif operand == "*":
12 | ergebnis = zahl1 * zahl2
13 | elif operand == "/":
14 | if zahl2 != 0:
15 | ergebnis = zahl1 / zahl2
16 | else:
17 | ergebnis = "Teilen durch Null(0) is nicht erlaubt"
18 | else:
19 | ergebnis = "Syntaxfehler!"
20 |
21 | print("Ergebnis:", ergebnis)
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 🐍 Henry’s Python Learning Journey!
2 |
3 | ## 📅 My Progress
4 |
5 | ```diff
6 | [▓▓▓▓▓░░░░░░░░░░░░░░░░░░] 26%
7 | ```
8 |
9 | ##### `print("On a Python Learning Journey, Eyo ✌🏾")`
10 |
11 | Hey there! 👋
12 | Welcome to my mini Python playground — a collection of simple, beginner-level Python programs I’m working on as I learn and grow.
13 | Each one is a small step toward becoming a full-stack developer.
14 |
15 | ---
16 |
17 | ## 📆 Day Counter
18 |
19 | ✨ **Day 11 of Learning Python** ✨
20 |
21 |
22 | 📄 Total lines of code: 328
23 | 🐍 Number of Python files: 22
24 |
25 |
26 |
27 | 🕒 Last updated: 2025-12-21 01:03 UTC
28 |
29 |
--------------------------------------------------------------------------------
/practie problems/solve_7.py:
--------------------------------------------------------------------------------
1 | ############ Assignment 7 #########
2 | ## Think of at least three kinds of your favorite rice, store three rice names in a list,
3 | # and use loop to print the name of each rice.
4 | favorite_Rice = ["foreign rice", "pepper rice", "local rice"]
5 | for rice in favorite_Rice:
6 | print(rice)
7 |
8 | ### Print a sentence using the name of the rice,
9 | ## for each rice you should have one line of output containing a simple statement like;
10 | # "I like pepper rice..."
11 | for tee in favorite_Rice:
12 | print(f"I like {tee.title()} !")
13 |
14 | ###Add a line at the end of your program, outside the for loop,
15 | ##an additional sentence, such as I really love eating rice!
16 | print("\nI like eating rice!!!")
--------------------------------------------------------------------------------
/practie problems/solve_6.py:
--------------------------------------------------------------------------------
1 | ########## ASSIGNMENT 6 ###########
2 | ## Store 7 names of any state in your country in alist
3 | my_States = ["Anambra", "Bauchi", "Cross-river", "Delta", "Edo"]
4 |
5 | ##Print the message; The first three states in the list are...,
6 | # Then use slice to print the first three states
7 | print("The first three states in the list are...")
8 | for i in my_States[0:3]:
9 | print(i)
10 |
11 | ##..also the three states from the middle of the list
12 | #--and also the last three states in the list
13 | print("\nThe three states in the middle of the list are...") #three from the middle
14 | for hey in my_States[1:4]:
15 | print(hey)
16 |
17 | print("\nThe last three states in the list are...") #Last three
18 | for x in my_States[-3:]:
19 | print(x)
20 |
21 |
--------------------------------------------------------------------------------
/practie problems/solve_5.py:
--------------------------------------------------------------------------------
1 | ########### ASSIGNMENT 5 ####################
2 | ## Make a list of your three favorite fruits,
3 | # and then write a series of independent if statements that checks for certain fruits in your list.
4 | # Write five if statement. Each should check whether a certain kind of fruit is in your list.
5 | # If the fruit is in your list, the if block should print a statement, such as "You like Bananas"
6 |
7 | fav_Fruits = ["Orange", "Mango", "Pawpaw"]
8 |
9 | if "Orange" in fav_Fruits:
10 | print("Henry enjoys Oranges")
11 | if "Cucumber" in fav_Fruits:
12 | print("Henry likes Cucumbers")
13 | if "Mango" in fav_Fruits:
14 | print("Henry likes Mangoes")
15 | if "Lemon" in fav_Fruits:
16 | print("Henry like Lemons")
17 | if "Pawpaw" in fav_Fruits:
18 | print("Henry likes Pawpaw")
19 | print("\nAll Done!")
20 |
--------------------------------------------------------------------------------
/practie problems/solve_1.py:
--------------------------------------------------------------------------------
1 | ################## ASSIGNMENT!!!!! ################
2 | ##Store the names of your friends [5] in a list
3 | ##Print a message to them, personalising the messages
4 |
5 | friends = ['Miles', 'Destiny', 'Daniel', 'Esther', 'Peter']
6 | tag = [15, 22, 19, 100, 12]
7 |
8 | to_Miles = f"Hello {friends[0]}, my birthday is on the {tag[0]}th of January!"
9 | print(to_Miles)
10 |
11 | to_Destiny = f"Guten Tag {friends[1]}, kommst du gleich in {tag[1]} Minuten nach Hause?"
12 | print(to_Destiny)
13 |
14 | to_Daniel = f"Happy birthday {friends[2]}!, you're turning {tag[2]} today."
15 | print(to_Daniel)
16 |
17 | to_Esther = f"Hey {friends[3]} please count to {tag[3]} (a hundred)"
18 | print(to_Esther)
19 |
20 | to_Peter = f"Good Morning Mr; {friends[-1]}, the meeting doesn't start until {tag[-1]} o'clock today."
21 | print(to_Peter)
22 |
--------------------------------------------------------------------------------
/practie problems/solve_9.py:
--------------------------------------------------------------------------------
1 | ############ ASSIGNMENT 9 ############
2 | ##Store five countries you want to visit in a list -- make sure its not in alphabetical order, and print it
3 | countries = ["Germany", "South africa", "America (USA)", "Egypt", "Italy"]
4 | print(countries)
5 |
6 | ##Print the list in an alphabetical order
7 | # -- print it in the original form again
8 | for key in sorted(countries):
9 | print(key) #Alphabetical Order
10 | # print(sorted(countries)) #or
11 |
12 | print(countries) #Original Order
13 |
14 | ##Print the list in reverse
15 | # -- print it in the original form again
16 | countries.reverse()
17 | print(countries) #In Reverse
18 |
19 | countries.reverse()
20 | print(countries) #Original Form
21 |
22 | ##Use len() and make a statement
23 | #--indicating the number of countries you would like to visit
24 | country_number = str(len(countries))
25 | print(f"\nI would like to visit {country_number} countries.")
--------------------------------------------------------------------------------
/.github/workflows/auto-reply.yml:
--------------------------------------------------------------------------------
1 | name: 🤖 Auto-Reply to Issues
2 |
3 | on:
4 | issues:
5 | types: [opened]
6 |
7 | permissions:
8 | issues: write
9 |
10 | jobs:
11 | auto-comment:
12 | runs-on: ubuntu-latest
13 |
14 | steps:
15 | - name: Comment on new issue
16 | uses: actions/github-script@v7
17 | with:
18 | github-token: ${{ secrets.GITHUB_TOKEN }}
19 | script: |
20 | const issueNumber = context.issue.number;
21 | const username = context.payload.issue.user.login;
22 | const comment = [
23 | `👋 Hello @${username}, thank you for opening an issue!`,
24 | ``,
25 | `I will get back to you as soon as i can. - 1501henify`,
26 | ``,
27 | `We appreciate your input — Have a great day/night!`
28 | ].join('\n');
29 |
30 | await github.rest.issues.createComment({
31 | owner: context.repo.owner,
32 | repo: context.repo.repo,
33 | issue_number: issueNumber,
34 | body: comment
35 | });
36 |
--------------------------------------------------------------------------------
/practie problems/solve_4.py:
--------------------------------------------------------------------------------
1 | ################# ASSIGNMENT 4 ############
2 | ##Write an if-elif-else chain that determines an Individual's stage of life.
3 | ##Set a value for the variable age
4 | age = 77
5 |
6 | # If the person is less than 2 years old, print a message that the person is a baby.
7 | if age < 2:
8 | print("Aww, a baby")
9 | # If the person is at least 2 years old but less than 4, print a message that the person is a toddler
10 | elif age < 4:
11 | print("Aww, you're a toddler now")
12 | # If the person is at least 4 years old but less than 13, print a message that the person is a kid
13 | elif age < 13:
14 | print("You're a kid!")
15 | # If the person is at least 13 years old but less than 20, print a message that the person is a teenager
16 | elif age < 20:
17 | print("You're now a teenager")
18 | # If the person is at least 20 years but less than 65, print a message that the person is an adult
19 | elif age < 65:
20 | print("You should know better, you're now an adult!")
21 | # If the person is age 65 or older, print a message that the person ia an elder
22 | elif age >= 65:
23 | print("You're now an Elder, Respect")
24 | print("All good ✌") #The End
25 |
--------------------------------------------------------------------------------
/practie problems/solve_3.py:
--------------------------------------------------------------------------------
1 | ################## ASSIGNMENT 3 ########################
2 | #Imagine a soldier that was shot down in a game,
3 | #create a variable called soldier_color and assign it a value of green,yellow or red
4 | soldier_Color = input("Guess soldier's color(Red-Green-Blue): ")
5 | score = 0
6 | ##Write an if-Statement to test whether the soldier's color is green,
7 | # if it is, print a message that the player just earned 5 points
8 | if(soldier_Color == 'Green' or soldier_Color == 'green'):
9 | score += 5
10 | print(f"Winner!, You've Earned {score} Points.")
11 |
12 | ###Choose Another Color, and write the program below using if-else chain
13 | secondSoldier_Color = input("Enter second soldier's color(Red-Green-Blue): ")
14 |
15 | #If the soldier's color is the chosen color, print a statement that the player just earned 10 points.
16 | ##If the soldier's color isn't the color, print a statement that the player just earned 15 points
17 | if(secondSoldier_Color == 'Red' or secondSoldier_Color == 'red'):
18 | score += 10
19 | print(f"Winner!, You've Earned {score} Points.")
20 | else:
21 | score = 0
22 | print(f"Wrong Color!, You've Earned {score} Points")
23 |
24 | print("\nWell-done")
--------------------------------------------------------------------------------
/.github/workflows/updated-readme.yml:
--------------------------------------------------------------------------------
1 | name: 🧠 Update README Stats
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | schedule:
7 | - cron: '0 0 * * *' # Every day at midnight
8 |
9 | jobs:
10 | update-readme:
11 | runs-on: ubuntu-latest
12 |
13 | steps:
14 | - name: Checkout repo
15 | uses: actions/checkout@v3
16 |
17 | - name: Count Python files and lines
18 | run: |
19 | PY_FILES=$(find . -name "*.py" | wc -l)
20 | TOTAL_LINES=$(find . -name "*.py" -exec cat {} + | wc -l)
21 | echo "PY_FILES=$PY_FILES" >> $GITHUB_ENV
22 | echo "TOTAL_LINES=$TOTAL_LINES" >> $GITHUB_ENV
23 |
24 | - name: Update README.md
25 | run: |
26 | STATS="📄 Total lines of code: $TOTAL_LINES\n🐍 Number of Python files: $PY_FILES"
27 | DATE="🕒 Last updated: $(date -u +"%Y-%m-%d %H:%M UTC")"
28 |
29 | sed -i "//,//c\\\n$STATS\n" README.md
30 | sed -i "//,//c\\\n$DATE\n" README.md
31 |
32 | - name: Commit changes
33 | run: |
34 | git config --global user.name "GitHub Actions Bot"
35 | git config --global user.email "actions@github.com"
36 | git add README.md
37 | git commit -m "🧠 Update README stats"
38 | git push
39 |
--------------------------------------------------------------------------------
/practie problems/solve_2.py:
--------------------------------------------------------------------------------
1 | ############ ASSIGNMENT 2 #############
2 | ##You are having a party, make a list of three people you would like to invite
3 | invited_Friends = ["Miles", "Chubby", "Lemar"]
4 | print(invited_Friends)
5 |
6 | ##One of them can't make it, Print a message stating the name of the person that can't
7 | cant_makeIt = invited_Friends.pop(1)
8 | print(f"\nSorry guys!, Unfortunately {cant_makeIt} couldn't make it to the party.")
9 |
10 | ##Replace the name of the one, who can't make it with the one who can make it
11 | invited_Friends.insert(1, "Henry")
12 | print(invited_Friends)
13 |
14 | ##You found a bigger hall!, Print a message informing current guests
15 | gen_Message = "\nHello y'all!"
16 | gen_Message += f"\nSup {invited_Friends[0]}, What's up {invited_Friends[1]}, {invited_Friends[2]}"
17 | gen_Message += "\nThe party will take place at a newly allocated hall, more info's later.\n"
18 | print(gen_Message)
19 |
20 | ##Add three more guests, one at the beginning[0], middle[?], and end of your list
21 | invited_Friends.insert(0, "Maxwell") #Beginning
22 | invited_Friends.insert(2, "Thomas") #Middle
23 | invited_Friends.insert(5, "Joseph") #End
24 | print(invited_Friends)
25 |
26 | ##The event planner failed with getting the bigger hall,
27 | #use pop() method to remove three guests, each time inform him/her of their exclusion
28 |
29 | guest1 = invited_Friends.pop(0) #First Uninvited Guest
30 | print(f"\nDear {guest1}, I was unable to allocate a hall as intended, you've sadly been uninvited.")
31 |
32 | guest2 = invited_Friends.pop(1) #Second Uninvited Guest
33 | print(f"Dear {guest2}, I was unable to allocate a hall as intended, you've sadly been uninvited.")
34 |
35 | guest3 = invited_Friends.pop(3) #Third Uninvited Guest
36 | print(f"Dear {guest3}, I was unable to allocate a hall as intended, you've sadly been uninvited.\n")
37 |
38 | ##Print a message to the remaining three informing them they're still invited
39 | print(invited_Friends)
40 | print(f"\nHey {invited_Friends[0]}, What's up {invited_Friends[1]}, Sup {invited_Friends[2]}, Ok Guys!, Party at my place 🥳🤘🏾")
41 |
42 | ##After the Party use del to remove the last three names so you have an empty list
43 | #del invited_Friends[:] #or
44 | invited_Friends.clear()
45 | print(invited_Friends) ##### DONE 🔥🔥🔥🔥
46 |
--------------------------------------------------------------------------------
/My Notes/Classes&Objects.MD:
--------------------------------------------------------------------------------
1 | ### ✅ Class:
2 |
3 | **A class** in python is a blueprint for creating objects. It groups related data (attributes) and actions (methods) together. Think of a class like a template; where it defines characteristics like color, size, etc...
4 |
5 | ```Python
6 | class Book:
7 | pass
8 | ```
9 |
10 | ### ✅ Object:
11 |
12 | **An object** is an instance of a class in Python. It represents a specific example of the blueprint defined by class. Now with our Dog; If Dog is a class, then variable `my_dog` could be an object representing a specific dog with it's details or functions, like name or age.
13 |
14 | ```Python
15 | class Dog:
16 | def __init__(self, name, age):
17 | self.name = name
18 | self.age = age
19 |
20 | # Object of the Dog class
21 | my_dog = Dog("Schrodinger", 5)
22 | ```
23 |
24 | ### ✅ Inheritance:
25 |
26 | **Inheritance** allows you to create a new class that uses the features of an already existing class without necessarily changing it. This lets you build on existing functionality while keeping the original class intact.
27 |
28 | ```Python
29 | class Animal:
30 | def __init__(self, name):
31 | self.name = name
32 |
33 | def spreche(self):
34 | print(f"{self.name} sagst: Sei zufrienden")
35 |
36 | #Derived class
37 | class Dog(Animal):
38 | def spreche(self):
39 | print(f"{self.name} bellst")
40 | ```
41 |
42 | #### Creating an object for the dog class
43 |
44 | ```Python
45 | my_dog = Dog("Arf")
46 | my_dog.spreche() # Output: Arf bellst
47 | ```
48 |
49 | Dog is a derived class which inherits from Animal class. Overrides `spreche(speak)` method to provide a behavior for parsed in `(Animal)`.
50 | '''
51 |
52 | ### ✅ Encapsulation:
53 |
54 | In Python's **Object-Oriented Programming (OOP)**, we can restrict access to methods and variables to prevent direct modification, especially when dealing with multiple lines of codes all performing various functions. This is referred to as **encapsulation**.
55 |
56 | ```Python
57 | class Person:
58 | def __init__(self, name, age):
59 | self.name = name
60 | self.__age = age #Private attribute
61 |
62 | def get_age(self):
63 | return self.__age #Accessor method
64 |
65 | person = Person("Alice", 30)
66 | print(person.get_age()) #Gives an output of 30
67 | ```
68 |
69 | It's noted from this example that the `the__age` attribute is private, and can only be accessed by calling the `get_age()` method.
70 |
71 | ### ✅ Polymorphism:
72 |
73 | **Polymorphism** really means "more than one forms." In programming _(python🤧)_, polymorphism allows a single entity (like a method, operator, or object) to take on different forms and behave differently in various scenarios, as needed.
74 |
75 | ```Python
76 | class Pferd:
77 | def speak(self):
78 | print("Neigh")
79 |
80 | class Eule:
81 | def speak(self):
82 | print("Hoot")
83 |
84 | def animal_speak(animal):
85 | animal.speak()
86 |
87 | # Using polymorphism
88 | pferd = Pferd()
89 | eule = Eule()
90 |
91 | animal_speak(pferd) # Neigh
92 | animal_speak(eule) # Hoot
93 |
94 | ### Try Area
95 | ```
96 |
97 | #### Basic Functions
98 |
99 | Functions are simple, don't include any parameters or return values, and perform a single task, like so...
100 |
101 | ```Python
102 | def greet_group():
103 | print("Hallo, Leute!")
104 |
105 | def greet_person(name):
106 | print(f"Hallo, {name}")
107 | ```
108 |
109 | #### Functions with Return Values
110 |
111 | functions return values, used instead of printing, allowing caller to use the result, return ends the code and starts outside the function(def).
112 |
113 | ```Python
114 | def add(a, b):
115 | return a + b
116 | result = add(3, 5)
117 | print(result)
118 | ```
119 |
120 | #### Functions with Default Parameters
121 |
122 | : Introducing default parameters makes the function to be more versatile.
123 |
124 | ```Python
125 | def greet(name= "Welt"):
126 | print(f"Hallo, {name}!")
127 | greet()
128 | greet("Henify_") # Replaces name="..." value to Henify_
129 | ```
130 |
131 | #### Functions with Variable Arguments
132 |
133 | Using " **\*args** and **\*\*kwargs** in python lets functions to handle variable number arguments.
134 |
135 | ```Python
136 | def add_all(*args): # With *args
137 | return sum(args)
138 | print(add_all(1, 2, 3, 4, 5))
139 |
140 | def print_info(**kwargs): # With **kwargs
141 | for key, value in kwargs.items():
142 | print(f"{key}: {value}")
143 |
144 | print_info(name= "Henry", age= 17)
145 | ```
146 |
147 | ### Intermediate Functions (Higher_Order_Functions, Lambdas, and Decorators)
148 |
149 | Higher level functions; these functions take other functions as arguments or return them. **Lambdas**; Anonymous, inline functions.
150 | Decorators: Modifies behavior of other functions
151 |
152 | ```Python
153 | def apply_functions(func, value):
154 | return func(value)
155 | print(apply_functions(lambda x: x**2, 5))
156 |
157 | def decorator(func):
158 | def wrapper():
159 | print("Before function call")
160 | func()
161 | print("After function call")
162 | return wrapper()
163 |
164 | @decorator #Decorator
165 | def say_hello():
166 | print("Hallo ✌🏾")
167 | say_hello()
168 | ```
169 |
--------------------------------------------------------------------------------
/Al Sweigart/01 Python Basics/Notes.MD:
--------------------------------------------------------------------------------
1 | # Learning with Al Sweigart - Automate the boring stuff with Python
2 | REPL, explained;
3 | Read Evaluate Print Loop, this lets us run or execute Python instructions one at time and instantly shows it's output.
4 |
5 | Basic Math Operators in Python
6 |
7 | | Operator | Operation | Example |
8 | |:----|:-----------------:|:---------------:|
9 | | ** | Exponent(raised to the power) | 2 ** 3 = 8 |
10 | | % | Modulus/Remainder | 22 % 8 i.e 2 rem 6 = 6 |
11 | | // | Integer division/round up | 22 // 8 = 2.75, 2.75 rounds up to 2|
12 | | / | Division | 22 / 8 = 2.75 |
13 | | * | Multiplication | 3 * 5 = 15 |
14 | | - | Subtraction | 5 - 2 = 3 |
15 | | + | Addition | 5 + 5 = 10 |
16 |
17 | ```py
18 | exponent = 8 ** 4
19 | modulus = 13 % 2
20 | round_up = 93 // 5
21 | divide = 169 / 13
22 | multiply = 12 * 12
23 | subtract = 256 - 13
24 | add = 101 + 102
25 | # print(round_up)
26 | ```
27 |
28 | The order of Operations in python are called **Precedence**, think, **BODMAS** in Python, __i.e__, **PEDMAS**, in that order, the
29 | former taking precedence; The __(**)__ is evaluated first, then __(*)__, __(/)__, __(//)__, __(%)__ operators are evaluated next; from left
30 | to the right. And the __(+)__, __(-)__ operators are evaluated last _(also from left to right)_.
31 |
32 | **Parenthesis ()**, are used to override the order of things, operations in brackets __()__, are treated first,
33 | _also from left to the right_.
34 |
35 | Whitespace in between values do not matter and are ignored in Python **_(except for indentation -starting on a new line)_**,
36 | but a single space is convention and is overlooked.
37 |
38 | ```py
39 | try1= 2 + 2
40 | try1 = 9 + 9
41 | print(try1)
42 | ```
43 |
44 | ### Integer, **Floating-Points _(Floats)_**, and String Data Types
45 | A data type is a category for values, and every value belongs to exactly one datatype.
46 |
47 | ### Common Data Types
48 | **Integers _(int)_** -2, -1, 0, 1, 2, 3, ....
49 | **floating-points _(floats)_** -1.25, -1.0, -0.5, ...
50 | **Strings _(str)_** "a", 'b', "c", 'D' 'Hello!'....
51 |
52 | Strings are always surrounded in single or double quotes __('')__, or __("")__; **_i.e_**,
53 | `'Hello'`, `"Good morning"`, so Python knows where the strings begin and ends, `(' ', or " ")` are called empty strings.
54 |
55 | ```py
56 | greetings = "Hello cruel world"
57 | regards = 'Wish you the very same'
58 | empty = " "
59 | print(empty)
60 | ```
61 |
62 | ### String Concatenation and Replication
63 | __(+)__ sign is a mathematical operator that sums two or more values of integer types;
64 | **However**, **_(+)_** sign is also used for **concatenating** or **joining** strings.
65 |
66 | ```py
67 | friend1 = 'Middleman'
68 | friend2 = "Miles"
69 | friends = friend1 + friend2 # 'Middleman' + "Miles"
70 | print(friends)
71 | ```
72 | The __(*)__ operator, when used on one string value and one integer value, it becomes the string replication operator.
73 |
74 | ```py
75 | friend3 = 'Angel' * 5
76 | print(friend3)
77 | ```
78 |
79 | ### Storing values in variables
80 |
81 | A **variable** is like a _box_, this lets us store a single value.
82 | **Assignments** __(=)__; assigns a value of any known datatype to a variable.
83 |
84 | ```py
85 | light_yrs = 40
86 | print(light_yrs)
87 |
88 | nummer = 2
89 | print(nummer)
90 | print(light_yrs + nummer + light_yrs)
91 |
92 | nummer = nummer + 10
93 | print(nummer)
94 | ```
95 |
96 | A variable is created when a value is stored or assigned to it.
97 | After that, the variable name can be called as their expressions or by name with other variables and values. When a variable is assigned a new value, the old value is forgotten.
98 |
99 | ```py
100 | nummer = 2
101 | print(nummer)
102 | nummer = nummer + 10
103 | print(nummer)
104 | ```
105 |
106 | ### Variable Names
107 |
108 | An ideal Variable name describes the data it contains. One can name a variable
109 | almost anything, under certain rules ofcourse; Python have some restrictions when it
110 | comes to name variables. A good Variable in Python follows these rules;
111 |
112 | __one word no spaces__ (eg; variable name | variableName)
113 | use only letters, numbers and the underscore(_) character no hyphens(-).
114 | variables names can't begin with a number (eg; 15boxes | box15)
115 |
116 | Variable names are _case-sensitive_, in the sense that _box_, **BOX**, `Box`, _`bOX`_, are
117 | different variables. It is a Python convention to start variables with lowercase
118 | letters. __(eg; Find = 'works ✅' but find = "is preferred")__.
119 |
120 | **camelCasing** or **under_score** as variable naming styles are advised.
121 |
122 |
123 | **When there are no more lines of code to execute, the Python program terminates, and stops running.
124 | When a Python file is ran, it starts from the top, working it's way down, executes the inputted commands
125 | until the last line, then the Python program exits.**
126 |
127 | ### Comments
128 | ```py
129 | # This entire area is commented and won't be executed when ran.
130 | ```
131 | Python ignores comments, and can be used to leave notes or to explain what a particular line of code does to others.
132 |
133 | ```py
134 | # (#) for single line comments
135 |
136 | """
137 | for multiple lines
138 | for multiple lines
139 | for multiple lines
140 | """
141 |
142 | ```
143 |
144 | ### Print() Function
145 | The `print()` function displays the string value inside it's parenthesis on the screen when you run the code.
146 |
147 | ```py
148 | print('Hello, treacherous world!')
149 | print('How many fingers am I holding up?') # Then run
150 | ```
151 |
152 | ### Input() Function
153 | The `input()` function waits for the user to type some text on the keyboard and press
154 | **ENTER**. Here the function asks for a particular datatype, Strings **_(str)_** most times; and
155 | you can fill it in directly in the terminal.
156 |
157 | ```py
158 | myOtherName = input("What is your name? ") # Stores value to the variable 'myOtherName
159 | print('Your name is ' + myOtherName)
160 | '''
161 | NOTE!!! input() functions are only available in versions of Python3, may not work if running Python2
162 | '''
163 | ```
164 |
165 | ### Len() Function
166 | The `len()` function, you can pass in a string value **(or a variable containing string)**,
167 | and the function evaluates to the integer value of the total number of characters
168 | **(letters)** in that string.
169 |
170 | ```py
171 | frankOceanSaid = 'I can never make him love me'
172 | print(len(frankOceanSaid))
173 | '''
174 | print() : shows us the output, len(), counts and gives the number of characters
175 | '''
176 | ```
177 |
178 | ### Integer + String concatenation errors
179 |
180 | ```py
181 | # print('I am ' + 29 + 'years old') # 29 is an integer(int), can only concatenate strings(str).
182 | ```
183 |
184 | Python gives an **~~error~~** cuz' the __(+)__ operator can only be used to add two integers
185 | together or concatenate two strings. You can't add an integer to a string, doesn't
186 | follow Pythons grammar rules. One can alter the code to print **_integers(int)_** as
187 | **_stings(str)_**.
188 |
189 | ### The `str()`, `int()`, and `float()` Functions
190 | ___str()___ : this converts to the string version of the integer within
191 | __int()__ : also useful for rounding down a floating-point(floats) number
192 |
193 | ```py
194 | num = 33
195 | print('I am ' + str(num) + 'years old')
196 |
197 | str(-3.14) # Python sees a string, equivalent to 'A', and can't be calculated
198 | str(0)
199 | int('42')
200 | int('-99')
201 | int(7.7) # clearly a float datatype, outputs 7.7 ".7 is > .5", rounds down to 8.
202 | float('3.14')
203 | float(10) # turns to 10.0
204 | ```
205 |
206 | ### Text and number equivalence
207 | An integer can be equal to a floating point number
208 |
209 | 44 == '44' :False, '44', is a string
210 | 44 == 44.0 :True, integers(int) rounds down to 44
211 | 44.0 == 0044.000 :True, ignores the zero's before 44, they are insignificant
212 |
213 | Integers and floats are mathematically numbers.
214 |
215 |
216 | ## FIRST PROGRAM
217 | #### This program says hello and asks for users name.
218 | ```py
219 | print('Hello, cruel world!')
220 | print('What is your name?')
221 |
222 | myName = input()
223 | print('It is good to meet you, ' + myName)
224 |
225 | print('The length of my name has got to be: ')
226 | print(len(myName))
227 |
228 | print('How old are you?')
229 | myAge = input()
230 | print('I will be ' + str(int(myAge) + 1) + ' in a year!')
231 | ```
--------------------------------------------------------------------------------
/My Notes/Intro.MD:
--------------------------------------------------------------------------------
1 | ### Intro to Python
2 |
3 | ```py
4 | print("This is Henry, Henry is speaking")
5 | print('Python is very fun')
6 | ```
7 |
8 | ### Variables and Values
9 |
10 | ```py
11 | our_message = 'Hallo, Ich heise Henry, und du?'
12 | print(our_message)
13 |
14 | a,b,c = 1,2,3
15 | print(a)
16 | print(b)
17 | print(c)
18 | ```
19 |
20 | ### Variable Formatting
21 |
22 | ```py
23 | name = "emmanuel"
24 | print(name.title())
25 | print(name.upper())
26 | print(name.lower())
27 | ```
28 |
29 | ### Striping White Space
30 |
31 | ```py
32 | meiene_Sprache = ' Python'
33 | print(meiene_Sprache)
34 | print(meiene_Sprache.lstrip())
35 | print(meiene_Sprache.rstrip())
36 | print(meiene_Sprache.strip())
37 | ```
38 |
39 | ### Avoiding syntax error with strings
40 |
41 | ```py
42 | # python_message = 'One of Python's strength is it's diverse community.'
43 | # print(python_message) #Error
44 |
45 | python_message = "One of Python's_strength is its_diverse_community._"
46 | print(python_message) correct
47 | ```
48 |
49 | ### Concatenate
50 |
51 | ```py
52 | vorName = "Henry"
53 | nachName = "Okeke"
54 | alt = "18"
55 | vollName = vorName +" "+ nachName
56 |
57 | print("Mein Vorname is " + vorName)
58 | print("Mein Nachname is " + nachName)
59 | print("Meine Alter is " + alt)
60 | print("Mein Name in voll is " + vollName)
61 | ```
62 |
63 | ### Avoiding Type Errors With STR() Function
64 |
65 | ```py
66 | alt = 18
67 | student_Nachrischten = "Glucklishes " + str(alt) + "ste geburstag, Henry"
68 | print(student_Nachrischten)
69 | ```
70 |
71 | ### Lists
72 |
73 | ```py
74 | authors = ['Shakespeare', 'Achebe', 'King Arthur', 'Osamu Dazia']
75 | print(authors)
76 | print(authors[2])
77 | print(authors[-1])
78 |
79 | # Using Individual Values From a list
80 | nachrischten = authors[-1] + "'s No Longer Human, has got to be my favorite book, Ever"
81 | print(nachrischten)
82 | ```
83 |
84 | ### Modifying Elements in a list
85 |
86 | ```py
87 | auto = ["BMW", "camery", "Honda", "Audi"]
88 | print(auto)
89 |
90 | auto[1] = "Lexus"
91 | print(auto)
92 | ```
93 |
94 | ### Adding Elements to lists, List-Appending
95 |
96 | ```py
97 | gods = ["Poseidon", "Aphrodite", "Athens", "Zeus"]
98 | print(gods)
99 |
100 | gods.append("Thor")
101 | print(gods)
102 | ```
103 |
104 | ### Inserting Elements to Lists `.insert([index], "_object")`
105 |
106 | ```py
107 | element = ["Poseidon", "Aphrodite", "Athens", "Zeus"]
108 | print(element)
109 | element.insert(2, "Apollo")
110 | print(element)
111 | ```
112 |
113 | ### Removing from Lists Using Del
114 |
115 | ```py
116 | modules = ["Poseidon", "Aphrodite", "Athens", "Zeus"]
117 | print(modules)
118 | del modules[0]
119 | print(modules)
120 | ```
121 |
122 | ### Removing an Element Using `pop()`
123 |
124 | ```py
125 | titans = ["Poseidon", "Aphrodite", "Athens", "Zeus"]
126 | print(titans)
127 | titans.pop()
128 | print(titans)
129 |
130 | popped_Titans = titans.pop()
131 | print(titans)
132 | print(popped_Titans)
133 |
134 | phones = ["samsung", "motorola", "nubia" "pixel", "xiaomi"]
135 | current_used = phones.pop()
136 | print("My current Phone is a " + current_used.title() + " Redmi note 20 5g")
137 |
138 | first_used = phones.pop(0)
139 | print("My first ever Phone was a " + first_used.title() + " galaxy S10")
140 | ```
141 |
142 | ### Removing an Item by `value(name)`
143 |
144 | ```py
145 | rulers = ["Poseidon", "Aphrodite", "Athens", "Zeus"]
146 | print(rulers)
147 | rulers.remove("Zeus")
148 | print(rulers)
149 |
150 | powerful = "Zeus"
151 | rulers.remove(powerful)
152 | print(rulers)
153 | ```
154 |
155 | ### Conditional Logic `(if-elif-else)` Intro, Indentation & Short Circuiting
156 |
157 | ```py
158 | if(6 > 11):
159 | print("true")
160 | else:
161 | print("false")
162 |
163 | # BOOLEAN
164 | is_licenced = False
165 | good_vision = True
166 |
167 | if is_licenced or good_vision:
168 | print("You can drive!")
169 | else:
170 | print("You can't drive!")
171 |
172 | # IF Statement
173 | alt = 20
174 | if alt >= 18:
175 | print("You can now vote!")
176 | print("Go now to the INEC Office to register")
177 |
178 | # IF-ELSE Statement
179 | age = 17
180 | if age >= 18:
181 | print("You are old enough to vote")
182 | print("Have you been registered?")
183 | else:
184 | print('Sorry, you are too young to vote')
185 | print("Please, register to vote as soon as you turn eighteen (18)")
186 |
187 | print("Thank you.")
188 |
189 |
190 | # IF-ELIF-ELSE Statement
191 | age = 17
192 | if age < 4:
193 | print("You get a free admission to the donations list")
194 | elif age <= 17:
195 | print("Your admission cost is $5")
196 | else:
197 | print("Your admission cost is $10")
198 | ```
199 |
200 | ### TESTING MULTIPLE CONDITIONS
201 |
202 | ```py
203 | requested_toppings = ["mushroom", "pickles", "extra cheese"]
204 |
205 | if 'pickles' in requested_toppings:
206 | print("....adding pickles")
207 | if 'ketchup' in requested_toppings:
208 | print("...adding ketchup")
209 | if 'mushroom' in requested_toppings:
210 | print("...adding mushroom")
211 | print("\n Finished making pizza")
212 | ```
213 |
214 | ### LOOPS
215 |
216 | ```py
217 | cars = ['royce', 'honda', 'BMW']
218 | for i in cars:
219 | print(i)
220 |
221 | for latter in "Apocalypto is awesome!!":
222 | print(latter)
223 |
224 |
225 | # Nested Loops
226 | for crabs in (1,2,3,4,5):
227 | for henry in ['a', 'b', 'c']:
228 | print(crabs, henry)
229 |
230 | # While Loop
231 | i = 0
232 | while i <= 10:
233 | print(i)
234 | i += 1
235 |
236 | while True:
237 | response = input("What's my name: ")
238 | if(response == 'Henry' or response == 'henry'):
239 | print("CORRECT!")
240 | break
241 | elif(response != 'Henry'):
242 | print("INCORRECT!!")
243 | ```
244 |
245 | ### USER INPUT
246 |
247 | ```py
248 | message = input("Tell us your name: ")
249 | print(message)
250 |
251 | name = input("What's your name: ")
252 | print("Hello " + Name + "!")
253 |
254 | customer = "When you shop from us, you get a discount."
255 | customer += "\nWhat's your name? "
256 |
257 | name = input(customer)
258 | print("\nThanks for shopping with us " + name + ", your discount is 50%.")
259 | ```
260 |
261 | ### DATA TYPES
262 |
263 | `#int`
264 | `#float`
265 | `#bool (for boolean)`
266 | `#tuple`
267 | `#dict`
268 | `#str`
269 | `#list`
270 | `#set`
271 |
272 | ### Integers and float
273 |
274 | ```py
275 | paris = 5 - 2
276 | print(paris)
277 |
278 | number = 3 * (3 + 2)
279 | print(number)
280 |
281 | print(type(2 + 2))
282 | print(type(2 / 4))
283 |
284 | print(2 ** 3)
285 | print(10 % 3)
286 | ```
287 |
288 | ### MATH FUNCTIONS
289 |
290 | ```py
291 | #Round
292 | print(round(3.9)) #nearest whole-number
293 | print(abs(-20))
294 |
295 | # Operator Presence (), **, /, *, +, - ...PEDMAS
296 | print(2 + 3 * 4)
297 | print((20 - 3) + 2 ** 3)
298 | ```
299 |
300 | ### EXPRESSION VS STATEMENT
301 |
302 | ```py
303 | denmark = 100 #Expression !_Declaring a value to a variable creates an expression
304 | user = denmark / 5 #Statement !_Performing tasks with known variables creates a statement
305 | print(user)
306 | ```
307 |
308 | ### AUGMENTED ASSIGNMENT OPERATOR
309 |
310 | ```py
311 | super = 20
312 | super = super + 10
313 | super += 10
314 | print(super)
315 |
316 | # STRINGS
317 | #print("Hello, and welcome")
318 |
319 | long = '''
320 | key
321 | car
322 | jaw
323 | mouth
324 | water
325 | cable
326 | fiend
327 | friend
328 | foe
329 | '''
330 | print(long)
331 |
332 | first_name = "Henry "
333 | middle_name = "Ifeanyi "
334 | last_name = "Okeke "
335 | full_name = first_name + middle_name + last_name
336 | print("My names are " + full_name)
337 | print("My names are " + full_name.upper())
338 | print(f"My names are {full_name.upper()}")
339 | ```
340 |
341 | ### WORKING WITH PART OF A STRING\_\_\_slicing
342 |
343 | ```py
344 | amazon_cart = ["Jacket", "tennis", "beanies"]
345 | print(amazon_cart)
346 |
347 | amazon_cart[0] = "Cars"
348 | print(amazon_cart)
349 |
350 | players = ["Natalie", "Jane", "Angel", "Calis", "Crystal"]
351 | print(players[:4])
352 |
353 | players = ["Natalie", "Jane", "Angel", "Calis", "Crystal"]
354 | print(players[1:4])
355 |
356 | players = ["Natalie", "Jane", "Angel", "Calis", "Crystal"]
357 | print(players[2:])
358 |
359 | players = ["Natalie", "Jane", "Angel", "Calis", "Crystal"]
360 | print(players[-3:])
361 | ```
362 |
363 | ### LOOPING THROUGH A SLICE
364 |
365 | ```py
366 | team = ["Natalie", "Jane", "Angel", "Calis", "Crystal"]
367 | print("Here are my first three players;")
368 | for AI in team[0:3]:
369 | print(AI + " You're chosen")
370 | ```
371 |
372 | ### COPYING A LIST
373 |
374 | ```py
375 | my_foods = ['pizza', 'rice', 'noodles']
376 | friends_foods = my_foods[:]
377 |
378 | print("My favorite foods are;")
379 | print(my_foods)
380 |
381 | print("My friends favorite foods are;")
382 | print(friends_foods)
383 |
384 | my_foods.append("Beans")
385 | friends_foods.append("Yam")
386 |
387 | print(my_foods)
388 | print(friends_foods)
389 | ```
390 |
391 | ### ORGANIZING A LIST --- SORTING A LIST
392 |
393 | ```py
394 | cars = ["bmw", "audi", "toyota", "subaru"]
395 | cars.sort()
396 | print(cars)
397 | cars.sort(reverse=False) #either true or false
398 | print(cars)
399 |
400 | # SORTING A LIST TEMPORARILY
401 | cars = ["bmw", "audi", "toyota", "subaru"]
402 | print(sorted(cars))
403 | print(cars)
404 |
405 | cars.reverse()
406 | print(cars)
407 | ```
408 |
409 | ```py
410 | # FINDING LENGTH FROM A LIST
411 | auto = ["bmw", "audi", "toyota", "subaru", "benz", "volkswagen"]
412 | print(len(auto))
413 |
414 | # UNPACKING A LIST
415 | a,b,c,d, *safe, e = [1,2,3,4,5,6,7,8,9]
416 | print(a)
417 | print(b)
418 | print(c)
419 | print(d)
420 | print(safe)
421 | print(e)
422 |
423 |
424 | student_that_paid = ["henry", 'michelle', 'chloe', 'alex', 'chloe']
425 | print('chloe' in student_that_paid)
426 |
427 | # ESCAPE CHARACTER
428 | rain = 'it\'s raining heavily'
429 | print(rain)
430 |
431 | weather = "it's \"almost\" raining."
432 | print(weather)
433 | ```
434 |
--------------------------------------------------------------------------------
/My Notes/Index.MD:
--------------------------------------------------------------------------------
1 | ### Try 1
2 |
3 | ```py
4 | equation = "130 + 145 = 275"
5 | for symbol in equation:
6 | if symbol not in "11":
7 | print(symbol)
8 |
9 | print("Hello", end=" ")
10 | print("World!")
11 | ```
12 |
13 | ### Try 2
14 |
15 | `print("Python", "is", "fun", sep="🔥")`
16 |
17 | ### Try 3
18 |
19 | ```py
20 | #: Use with for file handling to ensure files are closed properly
21 |
22 | # - better ✔
23 | with open("file.txt", "r") as file:
24 | content = file.read()
25 |
26 | # - traditional method 👎🏾
27 | file = open("file.txt", "r")
28 | content = file.read()
29 | file.close()
30 | ```
31 |
32 | ### Try 4
33 |
34 | ```py
35 | #: Use function parameters and return values instead of modifying global state.
36 |
37 | # - better ✔
38 | def add_numbers(a, b):
39 | return a + b
40 |
41 | # - traditional method 👎🏾
42 | total = 0
43 | def add_to_total(num):
44 | global total
45 | total += num
46 | ```
47 |
48 | ### Try 5
49 |
50 | ```py
51 | #: Catch specific exceptions and handle them appropriately
52 |
53 | # - better ✔
54 | try:
55 | result = 10 / x
56 | except ZeroDivisionError:
57 | print("Cannot divide by zero.")
58 |
59 | # - traditional method 👎🏾 __catch's exceptions without handling them properly.
60 | try:
61 | result = 10 / x
62 | except Exception as e:
63 | pass
64 | ```
65 |
66 | ### Try 6
67 |
68 | ```py
69 | #: Inline Expressions
70 |
71 | name = "Henry"
72 | age = 18
73 | print(f"{name} will be {age + 5} years old in 5 years.")
74 | ```
75 |
76 | ### Try 7
77 |
78 | ```py
79 | #: Use loops and functions to eliminate duplication.
80 | users = ["Herr Goethe", "Frau Merkel", "Frau Lines", "Herr Geoff"]
81 |
82 | # - better ✔
83 |
84 | def greet_users(users):
85 | for user in users:
86 | print(f"Hallo, {user}!")
87 |
88 | greet_users(users)
89 |
90 | # - traditional method 👎🏾
91 |
92 | print(f"Hallo, {users[0]}!")
93 | print(f"Hallo, {users[1]}!")
94 | print(f"Hallo, {users[2]}")
95 | print(f"Hallo, {users[3]}!")
96 | ```
97 |
98 | ```py
99 | #: Debugging with `=``
100 |
101 | x = 10
102 | y = 20
103 | print(f"{x = }, {y = }, sum = {x + y}")
104 | ```
105 |
106 | ```py
107 | #: Dictionary Get Method to Avoid KeyErrors
108 |
109 | data = {"name": "Alice"}
110 | print(data.get("age", "Not found"))
111 | ```
112 |
113 | ```py
114 | # Unpacking Multiple Values
115 |
116 | a, *b, c = [1, 2, 3, 4, 5]
117 | print(a, b, c) # great for splitting list dynamically
118 | ```
119 |
120 | ```py
121 | #: Set for Finding Unique Items
122 |
123 | nums = [1, 2, 2, 3, 4, 4]
124 | unique_nums = set(nums) # removes duplicates instantly
125 | print(unique_nums)
126 | ```
127 |
128 | ```py
129 | #: Swap Two Variables Without a Temp Variable
130 |
131 | a, b = 5, 10
132 | a, b = b, a
133 |
134 | print(a)
135 | print(b) # faster and cleaner than using a temporary variable
136 | ```
137 |
138 | ```py
139 | #: Pairing Elements from two lists
140 | #: zip() creates key value pairs(dictionaries)
141 |
142 | names = ["Alice", "Bob", "Charlie"]
143 | scores = [85, 92, 78]
144 |
145 | for name, score in zip(names, scores):
146 | print(f"{name}: {score}")
147 | ```
148 |
149 | ```py
150 | #: Unzipping Data into Separate Lists
151 |
152 | pairs = [("Alice", 85), ("Bob", 91), ("Henry", 78)]
153 | names, scores = zip(*pairs)
154 |
155 | print(names)
156 | print(scores)
157 | ```
158 |
159 | ```py
160 | #: Creating a Dictionary from two lists
161 |
162 | keys = ["name", "age", "city"]
163 | values = ["Alice", 25, "New York"]
164 |
165 | #person = dict(keys, values) #Error!__at most one argument
166 | person = dict(zip(keys, values)) ##Work
167 | print(person)
168 | ```
169 |
170 | ```py
171 | #: Iterating Over Multiple Lists Together
172 |
173 | list1 = [1, 2, 3]
174 | list2 = ["a", "b", "c"]
175 | list3 = ["x", "y", "z"]
176 |
177 | for a, b, c in zip(list1, list2, list3):
178 | print(a, b, c)
179 |
180 | ```
181 |
182 | ```py
183 | #: Transposing a Matrix (Rows - Columns)
184 |
185 | matrix = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
186 | transposed = list(zip(*matrix))
187 |
188 | print(transposed)
189 | ```
190 |
191 | ```py
192 | #: Sorting Multiple Lists Together
193 |
194 | students = ["Alice", "Bob", "Henry"]
195 | marks = [92, 85, 192]
196 |
197 | sorted_data = sorted(zip(marks, students), reverse=True)
198 | print(sorted_data)
199 | ```
200 |
201 | ```py
202 | #: Number Formatting
203 |
204 | pi = 3.1415926535
205 | large_number = 1234567890
206 | print(f"Pi: {pi:3f}, Large Number: {large_number:,}")
207 | ```
208 |
209 | ```py
210 | #: Dynamic Width Alignment
211 |
212 | name = "Bob"
213 | score = 95
214 | print(f"| {name:<10} | {score:^5} |")
215 | ```
216 |
217 | ```py
218 | #: List Comprehensions
219 |
220 | nums = [x**2 for x in range(5)] # more concise than loops
221 | print(nums)
222 | ```
223 |
224 | ```py
225 | #: Join a List Into a String
226 |
227 | words = ["Python", "is", "fun"]
228 | sentence = " ".join(words) # Avoids inefficient string concatenation
229 | print(sentence)
230 | ```
231 |
232 | ```py
233 | #: Use Enumerate Instead of Range(len())
234 |
235 | items = ['apple', 'banana', 'cherry']
236 | for index, item in enumerate(items):
237 | print(index, item)
238 | ```
239 |
240 | ```py
241 | #: Default-dict from collections
242 | #: Default-dict makes it easy to handle missing keys in dictionaries by assigning a default value.
243 |
244 | from collections import defaultdict
245 |
246 | count = defaultdict(int)
247 | words = ['apple', 'banana', 'apple']
248 |
249 | for word in words:
250 | count[word] += 1
251 |
252 | print(count)
253 | ```
254 |
255 | ```py
256 | #: F-Strings
257 | #: Formatted string literals
258 | # {f-strings} make formatting strings easier and more readable than the traditional `format()` method.
259 | name = 'Henry'
260 | age = 18
261 | print(f"My name is {name} and I'm {age} years old.")
262 | ```
263 |
264 | ```py
265 | #: Zip
266 | #: Zip functions allows you to pair elements from multiple
267 | #..iterables into tuples, which is useful for parallel iteration.
268 |
269 | names = ['Alice', 'Emma', 'Jane']
270 | scores = [85, 90, 88]
271 |
272 | for name, score in zip(names, scores):
273 | print(f"{name}: {score}")
274 | ```
275 |
276 | ```py
277 | #: Set Operators
278 | #: Sets are ideal for removing duplicates and performing
279 | #..mathematical equations like Union, Intersection, and difference.
280 |
281 | set1 = {1, 2, 3, 4}
282 | set2 = {3, 4, 5, 6}
283 |
284 | print(set1 & set2) # Intersection - common numbers
285 | print(set1 | set2) # Union - without repetition
286 | ```
287 |
288 | ```py
289 | #: Enumerate
290 | #: Instead of manually tracking indexes when looping, enumerate allows you to
291 | #..access both the index and value of an iterable in a clean way.
292 |
293 | names = ['Alice', 'Bob', 'Henry']
294 | for index, name in enumerate(names, start=1):
295 | print(index, name)
296 | ```
297 |
298 | ```py
299 | #: Unpacking
300 | #: Python's multiple assignment and unpacking features make variables assignments
301 | #..cleaner, especially with tuples and lists.
302 |
303 | a, b = 5, 10
304 | first, *middle, last = [1, 2, 3, 4, 5]
305 | ```
306 |
307 | ```py
308 | #: List Comprehensions
309 | #: List comprehensions offer a concise way to create lists. They're...
310 | #..faster and more readable than traditional loops
311 |
312 | # --Traditional way
313 |
314 | squares = []
315 | for x in range(10):
316 | squares.append(x**2)
317 |
318 | #--List comprehension
319 | squares = [x**2 for x in range(10)]
320 | ```
321 |
322 | ```py
323 | #: Lambda Functions for Short, Anonymous Functions
324 | #: If you need a small function for a quick operation, use a lambda function
325 |
326 | multiply = lambda x, y: x * y
327 | print(multiply(2, 3))
328 | ```
329 |
330 | ```py
331 | #: Use Generators for Large Data Handling
332 | #: When dealing with large datasets, use generators to save money.
333 |
334 | def count_up_to(n):
335 | num = 0
336 | while num < n:
337 | yield num
338 | num += 1
339 | ```
340 |
341 | ```py
342 | #: Use importlib for Dynamic Imports
343 | #: If you need import modules dynamically at runtime, use the importlib module:
344 |
345 | import importlib
346 | my_module = importlib.import_module('module_name')
347 | #..Useful when you don't know which module will be needed until runtime.
348 | ```
349 |
350 | ```py
351 | #: Avoid `from module import *` to Prevent Namespace Pollution
352 | #: Using wildcard imports (*) can cause name conflicts and make your code harder to
353 | #..debug. It's better to explicitly import what you need.
354 |
355 | from math import sqrt
356 | ```
357 |
358 | ```py
359 | #: Selective Imports to Save Memory
360 | #: Instead of importing the entire module, selectively import only what you need to
361 | #..optimize memory usage.
362 |
363 | from math import sqrt, pi
364 | ```
365 |
366 | ```py
367 | #: Use all to Control Wildcard Imports
368 | #: If you use module import *, you can specify which objects should be
369 | #..imported using all in your module:
370 |
371 | _all_ = ['function1', 'Class2']
372 | ```
373 |
374 | ```py
375 | #: Lazy Imports Inside Functions
376 | #: To prevent unnecessary imports or resolve circular dependencies, import modules
377 | #..inside functions.
378 |
379 | def my_function():
380 | import datetime
381 | return datetime.datetime.now()
382 | ```
383 |
384 | ```py
385 | #: Import Multiple Modules in One Line
386 | #: For small scripts or to keep imports tidy, import multiple modules on a single line.
387 |
388 | import os, sys, json
389 | ```
390 |
391 | ```py
392 | #: Relative Imports for Better Package Management
393 | #: In large projects, use relative imports to make code modular and avoid name clashes.
394 |
395 | from .subpackage import module
396 | #..This is especially useful when you have well organized packages.
397 | ```
398 |
399 | ```py
400 | #: Use Aliases to Shorten Module Names
401 | #: When dealing with long module names, use aliases to shorten them for clearer code
402 |
403 | import numpy as np
404 | import pandas as pd
405 | #..This reduces repetitive typing and keeps your code more readable
406 | ```
407 |
408 | ```py
409 | #: Secure Random Choice from a List
410 | #: This program securely chooses a random item from a list
411 |
412 | import secrets
413 |
414 | # List of items
415 | items = ['apple', 'banana', 'cherry', 'date']
416 |
417 | # Securely choose a random item
418 | random_item = secrets.choice(items)
419 | print(f"Random Chosen Item: {random_item}")
420 | ```
421 |
422 | ```py
423 | #: ...secure random integer
424 | #: This program generate a secure random integer between two numbers.
425 |
426 | import secrets
427 |
428 | # Generate a secure random integer between 1 and 100
429 | random_init = secrets.randbelow(100) + 1
430 | print(f"Secure Random Integer: {random_init}")
431 | ```
432 |
433 | ```py
434 | #: ...Generate a Secure URL-safe Token
435 | #: This program generates a secure URL-safe token, which is useful for
436 | #..generating things like secure reset links
437 |
438 | import secrets
439 |
440 | # Generate a secure URL-safe token
441 | url_safe_token = secrets.token_urlsafe(16)
442 | print(f"URL-safe Token: {url_safe_token}")
443 | ```
444 |
445 | ```py
446 | #: Generate a Secure Token
447 | #: This program generates a secure random token.
448 |
449 | import secrets
450 |
451 | # Generate a secure random token
452 | token = secrets.token_hex(16)
453 | print(f"Secure Token: {token}")
454 | ```
455 |
--------------------------------------------------------------------------------