├── using-modules ├── image.jpg ├── calculator.py ├── creating-modules.py ├── importing-modules.py ├── using-virtual-environments.py └── installing-with-pip.py ├── .github ├── ISSUE_TEMPLATE │ ├── ask-a-question.md │ ├── bug-report.md │ ├── add-a-tutorial.md │ └── feature-request.md ├── pull_request_template.md └── workflows │ ├── first-greetings-bot2.yml │ ├── first-greetings-bot.yml │ ├── run-modified-python.sh │ ├── python-flake8-linter-run.yml │ └── execute-modified-python-file.yml ├── getting-started ├── hello-world.py └── commenting.py ├── databases └── mongodb.py ├── common-built-in-functions ├── input.py ├── join.py ├── len.py ├── replace.py ├── enumerate.py └── range.py ├── variables ├── creating-variables.py ├── strings.py ├── booleans.py ├── integers.py └── floats.py ├── functions ├── recursive_func.py ├── using-functions.py └── lambda-functions.py ├── exceptions └── handling-exceptions.py ├── LICENSE ├── file-handling ├── deleting-files.py ├── reading-files.py ├── scanning-files.py └── writing-to-files.py ├── loops ├── while-loops.py ├── using-pass.py ├── using-break.py ├── for-loops.py └── using-continue.py ├── decorators └── timer.py ├── sets ├── modify-sets.py ├── creating-sets.py └── remove-set-elements.py ├── lists ├── declaring-lists.py ├── dataframe.py ├── list-comprehension.py ├── indexing-lists.py └── altering-lists.py ├── operators ├── arithmetic.py ├── comparison.py └── assigning.py ├── string-formatting ├── fstrings.py └── string-reversal.py ├── conditions └── if-else.py ├── tuples └── tuples-basic.py ├── dictionaries ├── using-dictionaries-basic.py ├── iterating-over-dictionaries.py └── using-dictionaries-advanced.py ├── CONTRIBUTING.md └── README.md /using-modules/image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/inspirezonetech/TeachMePythonLikeIm5/HEAD/using-modules/image.jpg -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/ask-a-question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Ask a question 3 | about: Ask a question about anything you're not sure about 4 | title: "Your title" 5 | labels: question 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Your query** 11 | ... 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report a bug or problem with repo 4 | title: "Your title" 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **About Bug or problem** 11 | ... 12 | 13 | **Steps to reproduce** 14 | ... 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/add-a-tutorial.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Tutorial 3 | about: Add or suggest a tutorial 4 | title: "[tutorial] Your title" 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Description of the tutorial** 11 | ... 12 | 13 | **Do you want to be assigned to work on this?** 14 | (mark [x]) 15 | - [ ] YES 16 | - [ ] NO 17 | 18 | **Optional: Any additional info you want to add** 19 | ... 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this repo 4 | title: "Your title" 5 | labels: 'feature request' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Description** 11 | ... 12 | 13 | **Do you want to be assigned to work on this?** 14 | (mark [x]) 15 | - [ ] YES 16 | - [ ] NO 17 | 18 | **Optional: Any additional info you want to add** 19 | ... 20 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | ## Please fill in this pull request template before submitting 3 | 4 | ### 1. This pull request resolves #??? 5 | (^Fill in the issue number after #) 6 | 7 | ### 2. Description 8 | (Write description of your changes here) 9 | 10 | ### 3. Fill in checklist by marking [x] 11 | 12 | - [ ] I've read the CONTRIBUTING.md 13 | - [ ] I was assigned to this issue 14 | - [ ] My code is formatted using required linting 15 | - [ ] I've run my code locally and checked it works 16 | -------------------------------------------------------------------------------- /.github/workflows/first-greetings-bot2.yml: -------------------------------------------------------------------------------- 1 | name: greeter 2 | 3 | on: [pull_request] 4 | 5 | jobs: 6 | job-greeter: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: "Greeter" 10 | uses: JJ/pr-greeting-action@releases/v0 11 | with: 12 | repo-token: ${{ secrets.GITHUB_TOKEN }} 13 | pr-message: "Well done @${{ github.actor }} on creating your first pull request on this repo! Our maintainers will review this soon. In the mean time don't forget to give us a star :star:" 14 | -------------------------------------------------------------------------------- /getting-started/hello-world.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: using the print statement 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Print is used to output to the console 6 | print("hello world") 7 | 8 | # ------------------------------------------------------------------------------------ 9 | # Challenge: 1. print "hello universe" to the console 10 | # ------------------------------------------------------------------------------------ 11 | -------------------------------------------------------------------------------- /databases/mongodb.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: brief description of tutorial content 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Code here explaining concept with comments to guide 6 | 7 | # ------------------------------------------------------------------------------------ 8 | # Challenge: list challenges to be completed here. minimum of one challenge per tutorial 9 | # ------------------------------------------------------------------------------------ 10 | -------------------------------------------------------------------------------- /.github/workflows/first-greetings-bot.yml: -------------------------------------------------------------------------------- 1 | name: greeting 2 | 3 | on: [pull_request, issues] 4 | 5 | jobs: 6 | job-greeting: 7 | runs-on: ubuntu-latest 8 | steps: 9 | 10 | - uses: actions/first-interaction@v1 11 | with: 12 | repo-token: ${{ secrets.GITHUB_TOKEN }} 13 | pr-message: "Well done @${{ github.actor }} on creating your first pull request on this repo! Our maintainers will review this soon. In the mean time, don't forget to give us a star :star:" 14 | issue-message: 'Thank you @${{ github.actor }} for creating your first issue on this repo! Our maintainers will get to this soon.' 15 | -------------------------------------------------------------------------------- /common-built-in-functions/input.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: using the input built in function 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # input is used to allow a user to input text into a variable. 6 | test = input("You can also put text to be printed in the brackets.") 7 | 8 | # ------------------------------------------------------------------------------------ 9 | # Challenge: 1. create a program that asks for someones name, then prints it. 10 | # ------------------------------------------------------------------------------------ 11 | -------------------------------------------------------------------------------- /getting-started/commenting.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: using comments in you code 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # # is used to add comments to you code. The text in the comment will be ignored by the program itself but can be used to make notes or explain what your code does. 6 | 7 | # This is a comment. Yay! 8 | 9 | # ------------------------------------------------------------------------------------ 10 | # Challenge: 1. using comments make this code say "Hello": print("Hello") + ("World") 11 | # ------------------------------------------------------------------------------------ 12 | -------------------------------------------------------------------------------- /.github/workflows/run-modified-python.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo "run-sh: Inside run-modified-python.sh" 4 | 5 | #read json file and store in variable 6 | a=$(cat /home/runner/files_modified.json) 7 | echo "run-sh: Content of files_modified.json: $a" 8 | 9 | #parse json to get file path and name 10 | #cut " from string 11 | b=$(echo "$a" | cut -d '"' -f 2) 12 | #cut [ from string 13 | b=$(echo "$b" | cut -d '[' -f 2) 14 | #cut ] from string 15 | b=$(echo "$b" | cut -d ']' -f 2) 16 | 17 | echo "run-sh: After parsing, file to execute: $b" 18 | 19 | #check if this is a .py file 20 | if [[ $b == *".py"* ]]; then 21 | echo "run-sh: This is a .py file, executing" 22 | python3 $b 23 | else 24 | echo "run-sh: File modified is not a python file! Will not execute" 25 | fi 26 | -------------------------------------------------------------------------------- /common-built-in-functions/join.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: how to use join() function 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # join is a built-in-function. It means you don't have to define it before using it 6 | # join is used to connect a list of string 7 | stringList = ["I", "love", "Python"] 8 | 9 | # join can have an optional separation string 10 | a = "-separationString-".join(stringList) 11 | 12 | # the result can be print as follow 13 | print(a) 14 | 15 | 16 | # ------------------------------------------------------------------------------------ 17 | # Challenge: use join function to join a list of characters. 18 | # the list should be combined to show your name. 19 | # ------------------------------------------------------------------------------------ 20 | -------------------------------------------------------------------------------- /variables/creating-variables.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: using variables in python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # there's no need to declare variables in python. simply use them 6 | 7 | # integers 8 | a = 1 9 | b = 2 10 | print(a + b) 11 | 12 | # strings 13 | c = 'hello' 14 | d = 'world' 15 | print(c + d) 16 | 17 | # bonus: you can check the type of a variable using the type() function 18 | print(type(a)) 19 | print(type(c)) 20 | 21 | # ------------------------------------------------------------------------------------ 22 | # Challenge: 1. create an integer holding the number 7 and print the integer 23 | # 2. create a string holding the sentence "I'm learning python" and print the string 24 | # ------------------------------------------------------------------------------------- 25 | -------------------------------------------------------------------------------- /.github/workflows/python-flake8-linter-run.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a single version of Python 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: python-flake8-linter-run 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | job-python-linter: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | 18 | - name: Set up Python 3.8 19 | uses: actions/setup-python@v2 20 | with: 21 | python-version: 3.8 22 | 23 | - name: Install dependencies 24 | run: | 25 | python -m pip install --upgrade pip 26 | pip install flake8 27 | 28 | # run linter on python file 29 | - name: Run Lint with flake8! 30 | run: flake8 . --ignore E302,E305,E501 --isolated --count --max-complexity=10 --statistics --show-source 31 | 32 | 33 | -------------------------------------------------------------------------------- /common-built-in-functions/len.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: using the len built in function 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # len is used to find the amount of items in an object (ie an array) 6 | array = ["1", "2", "3"] 7 | # the len can be printed 8 | print("The length of the array is: ", len(array)) 9 | 10 | # len can also be used to find the amount of characters in a string. 11 | text = "text" 12 | # the len can also be stored in a variable 13 | textlen = len(text) 14 | print("The amount of characters in the variable text is: ", textlen) 15 | 16 | # ------------------------------------------------------------------------------------ 17 | # Challenge: 1. create an array with your own data and get the length of it. 18 | # 2. create a program that checks the length of the string "Hello World!". 19 | # ------------------------------------------------------------------------------------ 20 | -------------------------------------------------------------------------------- /functions/recursive_func.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: How to make a recursive function 3 | # A recursive function is a function that calls itself 4 | # ------------------------------------------------------------------------------------ 5 | 6 | # find the factorial of a user entered number 7 | # the 'def' keyword is used to declare a function. the structure of a function is: 8 | mul = 1 9 | def fact(num): 10 | if num == 1: 11 | return num 12 | else: 13 | return num * fact(num - 1) 14 | 15 | num = int(input('Enter a number to get the factorial of it: ')) 16 | if num == 0: 17 | print("Factorial of 0: 1") 18 | else: 19 | print("Factorial of ", num, ":", fact(num)) 20 | 21 | # ----------------------------------------------------------------------------------- 22 | # Challenge: create a recursive function that makes a countdown from a user entered number till zero 23 | # ------------------------------------------------------------------------------------ 24 | -------------------------------------------------------------------------------- /exceptions/handling-exceptions.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Handling exceptions in python 3 | 4 | # ------------------------------------------------------------------------------------ 5 | 6 | # You can handle exceptions in a try / except blocks 7 | # The program executes the code in the try block, 8 | # if something goes wrong an exception is raised 9 | # It will be handled by the except block, 10 | # if not the except section will be ignored. 11 | 12 | 13 | try: 14 | a = 2 15 | a = a - 1 16 | print("Working!!") 17 | if a == 0: 18 | # Here a custom exception is raised if a is equal to 0 19 | raise ValueError("a cannot be 0") 20 | except ValueError: 21 | print('Something went wrong') 22 | raise 23 | 24 | # ------------------------------------------------------------------------------------ 25 | # Challenge: Create a try / except block and raise a custom exception when the value received is not a number 26 | # ------------------------------------------------------------------------------------ 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 inspirezonetech 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/execute-modified-python-file.yml: -------------------------------------------------------------------------------- 1 | name: execute-modified-python-file 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | job-execute-python: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | 15 | # checkout repo 16 | - uses: actions/checkout@v2 17 | 18 | # setup python 19 | - name: Set up Python 3.8 20 | uses: actions/setup-python@v2 21 | with: 22 | python-version: 3.8 23 | 24 | # install requirements.txt if it exists 25 | - name: Install dependencies 26 | run: | 27 | python -m pip install --upgrade pip 28 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 29 | 30 | #use action to get file that changed 31 | - uses: lots0logs/gh-action-get-changed-files@2.1.4 32 | with: 33 | token: ${{ secrets.GITHUB_TOKEN }} 34 | 35 | # test if modified file will run 36 | - name: Execute file! 37 | run: | 38 | echo "job: running script to execute modified file:" 39 | ./.github/workflows/run-modified-python.sh 40 | echo "job: Done" 41 | -------------------------------------------------------------------------------- /using-modules/calculator.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Importing Modules in Python 3 | # This file is the calculator module created for the "creating-modules.py" tutorial 4 | # ------------------------------------------------------------------------------------ 5 | 6 | # Creating a module with functions inside, in this case 7 | # A calculator module to sum and multiply 8 | 9 | def sum_two_numbers(a, b): 10 | result = a + b 11 | return f'result of sum {a} + {b} = {result}' 12 | 13 | 14 | def multiply_two_numbers(a, b): 15 | result = a * b 16 | return f'result of multiply {a} X {b} = {result}' 17 | 18 | # ------------------------------------------------------------------------------------ 19 | # Challenge: (Part of the challenge with "creating-modules.py") 20 | # Add two more functions to this module: divide_two_numbers, subtract_two_numbers. 21 | # Then call the functions from "creating-modules.py" 22 | # ------------------------------------------------------------------------------------ 23 | 24 | # Here define function called divide_two_numbers 25 | 26 | 27 | # Here define function called subtract_two_numbers 28 | -------------------------------------------------------------------------------- /file-handling/deleting-files.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Receives a file name from a user and deletes it 3 | # ------------------------------------------------------------------------------------ 4 | 5 | import os 6 | 7 | def delete_file(filename): 8 | try: 9 | os.remove(filename) # deletes filename 10 | print(f'{filename} has been deleted') # prints out success message 11 | except OSError: 12 | print('No such file in directory!') # prints error message when file not found 13 | 14 | def main(): 15 | filename = None 16 | try: 17 | # get the filename from the user 18 | filename = input('Please enter name (with type) of the file you would like to remove: ') 19 | except EOFError: 20 | return filename 21 | 22 | # call delete function from above and pass in the filename 23 | delete_file(filename) 24 | 25 | if __name__ == '__main__': 26 | main() 27 | 28 | 29 | # ------------------------------------------------------------------------------------ 30 | # Challenge: Delete a specific file in directory 31 | # ------------------------------------------------------------------------------------ 32 | -------------------------------------------------------------------------------- /loops/while-loops.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: While Loops in Python 3 | # ------------------------------------------------------------------------------------ 4 | # Here we will look into how to use one of the loops - while loop to generate desired outputs with certain condition 5 | # Syntax: After while we pass the condition to be checked 6 | 7 | t = 0 8 | while t < 10: 9 | t = t + 2 10 | print(t) 11 | 12 | # Also we can use an |else| stance with the while loop as if the condition don't satisfy and we need a last statement to be executed after the while loop is finished: 13 | 14 | t = 0 15 | while t < 10: 16 | t = t + 2 17 | print(t) 18 | else: 19 | print("loop finished") 20 | 21 | # So above loop will work till the specified condition is satisfied hence will run about 5 times in this case 22 | 23 | 24 | # ------------------------------------------------------------------------------------ 25 | # Challenge: Take a user input n and find and print the reverse of the number. Also you don't have to print trailing zeroes while reversing. 26 | # Example: 1.) Input - 2345 , Output - 5432 27 | # 2.) Input - 2480 , Output - 842 28 | # ------------------------------------------------------------------------------------ 29 | -------------------------------------------------------------------------------- /decorators/timer.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Implementation of decorator in Python. 3 | # ------------------------------------------------------------------------------------ 4 | 5 | import time 6 | 7 | # defining the decorator timer 8 | def timer(func): 9 | # wrapper function taking arbitary arguments 10 | def wrapper(*args, **kwargs): 11 | # storing the current time. 12 | start_time = time.time() 13 | # calling func passed in the timer function. 14 | func(*args, **kwargs) 15 | # displaying the time it takes to completely run the func. 16 | print("Function took : ", time.time() - start_time, "seconds.") 17 | # returning the wrapper function. 18 | return wrapper 19 | 20 | # using decorator timer 21 | @timer 22 | # defining a function to decorate with timer. 23 | def run(): 24 | for i in range(10): 25 | print(i) 26 | 27 | # calling the function which is decorated with timer. 28 | run() 29 | 30 | # ------------------------------------------------------------------------------------ 31 | # Challenge: Create a decorator to wrap a function and print "START" before the function call and print "END" after the function executes successfully. 32 | # ------------------------------------------------------------------------------------ 33 | -------------------------------------------------------------------------------- /common-built-in-functions/replace.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: The replace method replaces a specified string with another specified string. 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Example 1. 6 | # Replace all occurences of "dog" with "cat" 7 | 8 | dog_txt = "I always wanted a dog! My dog is awsome :) My dog\'s name is Taco" 9 | cat_txt = dog_txt.replace("dog", "cat") 10 | 11 | print("\nExample 1. - Replace all occurences of \"dog\" with \"cat\"") 12 | print(f'Old String: {dog_txt}') 13 | print(f'New String: {cat_txt}') 14 | 15 | 16 | # Example 2. 17 | # Replace the two first occurences of "dog" with "cat" 18 | 19 | dog_txt = "I always wanted a dog! My dog is awsome :) My dog\'s name is Taco" 20 | cat_txt = dog_txt.replace("dog", "cat", 2) 21 | 22 | print("\nExample 2. - Replace first two occurences of \"dog\" with \"cat\"") 23 | print(f'Old String: {dog_txt}') 24 | print(f'New String: {cat_txt}\n') 25 | 26 | # ------------------------------------------------------------------------------------ 27 | # Challenge: 28 | # 1. From the string "Teach me Python like Im 5" produce the string "Teach me Java like Im 10". 29 | # 2. From the string "Im 10 years old" produce the string "How old are you?". 30 | # ------------------------------------------------------------------------------------ 31 | -------------------------------------------------------------------------------- /sets/modify-sets.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Set Modification in Python 3 | # Sets are mutable. However, since they are unordered, indexing has no meaning. 4 | # We cannot access or change an element of a set using indexing or slicing. Set data type does not support it. 5 | # ------------------------------------------------------------------------------------ 6 | 7 | # We can add a single element using the add() method, and multiple elements using the update() method. 8 | # The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided. 9 | 10 | # initialize a 11 | a = {1, 3} 12 | print(a) 13 | 14 | # a[0] 15 | # if you uncomment the above line 16 | # you will get an error 17 | # TypeError: 'set' object does not support indexing 18 | 19 | # add an element 20 | # Output: {1, 2, 3} 21 | a.add(2) 22 | print(a) 23 | 24 | # add multiple elements 25 | # Output: {1, 2, 3, 4} 26 | a.update([2, 3, 4]) 27 | print(a) 28 | 29 | # add list and set 30 | # Output: {1, 2, 3, 4, 5, 6, 8} 31 | a.update([4, 5], {2, 6, 8}) 32 | print(a) 33 | 34 | # ------------------------------------------------------------------------------------ 35 | # Challenge: Create a new set b and Update the set a to include the elements of set b. 36 | # ------------------------------------------------------------------------------------ 37 | -------------------------------------------------------------------------------- /loops/using-pass.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: How to use pass statement within loops. 3 | # ------------------------------------------------------------------------------------ 4 | 5 | 6 | # Nothing actually happens when pass is executed in python. It just passes control to next line that automatically happens but 7 | # sometimes it comes handy, especially in production codes. As we can't leave the body of if, else, for, while, etc undefined or 8 | # it'll throw error so sometimes we use pass with these statements to not get any error. 9 | 10 | # So, it's used sometimes where we need to define a syntactically empty block. 11 | # It is much like a comment but python interpreter executes it while comments get ignored completely. 12 | 13 | 14 | for i in [1, 2, 3]: 15 | pass 16 | i = 0 17 | my_list = [1, 2, 3] 18 | while i < len(my_list): 19 | print(my_list[i]) 20 | i += 1 21 | 22 | # In above example we won't get any error as we are using pass but if we don't use pass and just use 23 | # for loop without body then we'll get error. 24 | 25 | 26 | # ------------------------------------------------------------------------------------ 27 | # Challenge: Create a loop with fruits and number, if it's a fruit print it, and if it's a number pass it. 28 | # note : use typeof to make the condition 29 | # ------------------------------------------------------------------------------------ 30 | -------------------------------------------------------------------------------- /lists/declaring-lists.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # LIST 3 | # List is a collection which is ordered and changeable. 4 | # ------------------------------------------------------------------------------------ 5 | # Code here explaining concept with comments to guide 6 | # Syntax: 7 | # empty list 8 | lst = [] 9 | # list of integer 10 | lst = [1, 2, 3, 4, 5] 11 | # list with various data type 12 | lst = [1, "hello", 3.55] 13 | # nested list 14 | lst = [1, [8, 3, 4, 5], "hello"] 15 | # retrieval of elements using list index 16 | print(lst[0]) # this will print first element of the list that is [1] 17 | # negative index 18 | print(lst[-1]) # output: ["hello"] 19 | # there are some in-built function available in the python for the list, like 20 | # lst.sort() # this will arrange the element in the ascending order. 21 | lst.append(9) # this will add element in the end of the list. 22 | lst.remove(9) # this will remove the element 9 from the list. 23 | lst.insert(1, 9) # this will add insert the element 9 at index place 1. 24 | del lst[0:2] # this will delete the element in the range 0-2. 25 | lst.count(9) # this will return the no of argument passes. 26 | # ------------------------------------------------------------------------------------ 27 | # Challenge: list challenges to be completed here. minimum of one challenge per tutorial 28 | # 1. Take input from the user into the empty list using input() function. 29 | # ------------------------------------------------------------------------------------ 30 | -------------------------------------------------------------------------------- /using-modules/creating-modules.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Importing Modules in Python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # The file "calculator.py" which is located in the same directory as this file is an example of a module 6 | 7 | # In this line you import the module, 8 | # With the keyword import and the name of your module 9 | import calculator 10 | 11 | a = 2 12 | b = 4 13 | 14 | # Here we are calling the function inside the module to get the result 15 | # Of the sum of number a and b 16 | result_sum = calculator.sum_two_numbers(a, b) 17 | 18 | # Here we are calling the function inside the module to get the result 19 | # Of the multiplication of number a and b 20 | result_multiplication = calculator.multiply_two_numbers(a, b) 21 | 22 | print(result_sum) 23 | 24 | print(result_multiplication) 25 | 26 | # ------------------------------------------------------------------------------------ 27 | # Challenge: (Edits needed to "calculator.py" which is located in the same directory as this file) 28 | # Add to the "calculator.py" module two more functions: divide_two_numbers, subtract_two_numbers. 29 | # Then call the new functions, Passing in two integers and print the result 30 | # ------------------------------------------------------------------------------------ 31 | 32 | # Here call the divide_two_numbers function you created in "calculator.py" 33 | 34 | 35 | # Here call the subtract_two_numbers function you created in "calculator.py" 36 | -------------------------------------------------------------------------------- /operators/arithmetic.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: What are arithmetic operators and how to use them. 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Arithmetic operators all you to perform mathematical calculations in Python. 6 | a = 5 7 | b = 3 8 | 9 | a + b # addition - adds two operands together 10 | a - b # subtraction - subtracts the right operand from the left 11 | a * b # multiplication - multiplies two operands 12 | a / b # division - divides left operand from right 13 | a % b # modulus - remainder of the division of left operand by the right 14 | a ** b # exponential - left operand raised to the power of the right 15 | a // b # floor division - division that results in whole number adjusted to the left in the number line 16 | 17 | # When doing more complicated arithmetic, brackets are useful to seperate calculations. 18 | c = 10 19 | d = 12 20 | 21 | (((a + b) / c) * d) # (a + b) will be performed first 22 | 23 | # ------------------------------------------------------------------------------------ 24 | # Challenge: list challenges to be completed here. minimum of one challenge per tutorial 25 | # ------------------------------------------------------------------------------------ 26 | # 1. Ask a user to input two numbers. Print these two numbers and show: 27 | # (a) the sum of the numbers 28 | # (b) the divison of the numbers (both a / b and b / a) 29 | # (c) the modulus of the numbers (both a % b and b % a) 30 | -------------------------------------------------------------------------------- /loops/using-break.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: How to use break statements within loops. 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Break statements are useful to use with loops in Python. They allow for a loop to be 6 | # 'broken out of' or 'escaped'. Break is mainly used when a condition is met, and we 7 | # want to immediately exit a loop 8 | 9 | for letter in 'Python': 10 | print(letter) 11 | if letter == 't': 12 | break # if the letter 't' was found, then the break will stop the for loop 13 | 14 | # If nested loops are being used, the break statement will exit the innermost 15 | # enclosing loop. 16 | 17 | for y in range(2, 10): 18 | for x in range(2, y): 19 | if y % x == 0: 20 | print('{} equals {} * {}'.format(y, x, y / x)) 21 | break # the if statement is exited, but the for loops are still active 22 | else: 23 | print(y, 'is a prime number') 24 | 25 | # ------------------------------------------------------------------------------------ 26 | # Challenge: list challenges to be completed here. minimum of one challenge per tutorial 27 | # ------------------------------------------------------------------------------------ 28 | # 1. Search for a letter in a string & break out of loop when it has been found. 29 | # 2. Create a while loop that 30 | # (a) opens a file 31 | # (b) writes a number to the file 32 | # (c) closes the file. 33 | # When the file has 100 lines, break out of the loop and print the content of the file. 34 | -------------------------------------------------------------------------------- /loops/for-loops.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: For-loops in Python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # We use for loops when we have to access elements in a DS or while working within a range of numbers. 6 | # One of the loops which helps us to iterate through a particular DS. 7 | 8 | anime = ['Luffy', 'Naruto', 'Zoro', 'Midoriya', 'Lelouch', 'Levi', 'Natsu', 'Sanji', 'Shanks', 'Kakashi', 'Kageyama'] 9 | 10 | # What we have to do is print each of these names in list anime 11 | 12 | for name in anime: 13 | print(name) 14 | 15 | # This will help you to access and print each of the names in the list. 16 | 17 | # Alternate 18 | 19 | length = len(anime) 20 | 21 | for i in range(length): 22 | print(anime[i]) 23 | 24 | # Also there is an |else| stance for each of the loops so here it is for for-loop: 25 | 26 | 27 | for name in anime: 28 | print(name) 29 | else: 30 | print('Loop has finished') 31 | 32 | # It gives us a message when the loop is finished. 33 | 34 | # Practice with the below challenge 35 | # ------------------------------------------------------------------------------------ 36 | # Challenge: You have given a list of numbers and you have to output how many of the numbers are even and how many are odd. 37 | # list = [ 3, 21, 4, 56, 34, 69, 45, 63, 99 ] 38 | 39 | # Example : list = [ 2, 4, 5, 8, 34, 21 ] 40 | # Output:- Odd : 2, Even : 4 41 | # 42 | # ------------------------------------------------------------------------------------ 43 | -------------------------------------------------------------------------------- /string-formatting/fstrings.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial on f-strings 3 | # Using f-strings is a simple and fast method for String formatting 4 | 5 | # ------------------------------------------------------------------------------------ 6 | 7 | # # Syntax of f-strings: 8 | # We start the string with the keyword f, followed by our string in double quotes and {} is used as a placeholder for the values involved in the formatting. 9 | 10 | 11 | # The following example makes it clearer: 12 | name = "John" 13 | age = 17 14 | print(f"I am {name} and I am {age} years old") 15 | 16 | # Output- I am John and I am 17 years old 17 | 18 | # Note that F(in capitals) also works 19 | 20 | 21 | # Using multi-line f-strings: 22 | name = 'John' 23 | age = 32 24 | occupation = 'Web developer' 25 | 26 | msg = ( 27 | f'Name: {name}\n' 28 | f'Age: {age}\n' 29 | f'Occupation: {occupation}' 30 | ) 31 | print(msg) 32 | 33 | 34 | # You can also write a multi-lines f-string with double quotes like docstrings: 35 | msg_two = f""" 36 | Name: {name} 37 | Age: {age} 38 | Occupation: {occupation} 39 | """ 40 | print(msg_two) 41 | 42 | # Output: 43 | # Name: John 44 | # Age: 32 45 | # Occupation: Web developer 46 | 47 | # ------------------------------------------------------------------------------------ 48 | # Challenge: 49 | # Using f-strings print the following: 50 | # Hi, I am , my hobby is , and I'm from 51 | # name, hobby and location will be inputs from the user 52 | # Do the same for a multi-line output. 53 | # ------------------------------------------------------------------------------------ 54 | -------------------------------------------------------------------------------- /using-modules/importing-modules.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: importing modules 3 | # ------------------------------------------------------------------------------------ 4 | # What is a module ? 5 | # A module is a file which ends by .py. Very simple, you can even create 6 | # yourself a module. The name of the module takes automatically the name of the file. 7 | # It can contain many things (functions, variable ...) you can use everywhere on your project. 8 | # To use a module, you have to import it. We use the keyword "import" + module name. 9 | 10 | # Example for one import : 11 | # import os 12 | 13 | # But Python have standard so let's do it well... 14 | # Multiple imports, not in the same line : 15 | # import sys 16 | # import warnings 17 | 18 | # Specific thing imported from a module we use the keyword "from" : 19 | # from datetime import date 20 | # but we can write that like we see above : 21 | # import datetime.date 22 | 23 | # the path is really important, it means date is in the file datetime.py 24 | # Note that all imports must be at the top of the file 25 | 26 | # ------------------------------------------------------------------------------------ 27 | # Challenge: use the random import 28 | # ------------------------------------------------------------------------------------ 29 | # Python has the module random, import it and uncomment the code below to show a 30 | # random number and set your favorite number to show a nice message if it's the 31 | # right number when you execute this file 32 | 33 | # favorite_number = 1 34 | # number = random.randint(0, 6) 35 | # if number == favorite_number: 36 | # print("Yeah, it's your number! Lucky you!") 37 | # else: 38 | # print('Nope, try again') 39 | -------------------------------------------------------------------------------- /conditions/if-else.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Lets learn how to use if else 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # For this example we are programming a game that uses lives, 6 | # if a user runs out of lives the program will display a game 7 | # over message. 8 | 9 | lives = 0 10 | 11 | if lives == 0: # the variable lives is equal to 0. 12 | print("Game Over.") 13 | elif lives != 0: # the variable lives is not equal to 0. 14 | print("Ha Ha Ha, Staying Alive.") 15 | 16 | # For example if we want play a game that is rated 12 years and up 17 | # Lets write a program to check if you can play that game. 18 | 19 | age = 13 20 | 21 | if age >= 12: 22 | print("Yes, you can play that game.") 23 | else: 24 | print("Lets find a better game for you.") 25 | 26 | 27 | # We can also use elif do a chain of conditions 28 | # like this: 29 | 30 | if age < 18: 31 | print("Can't join army") 32 | elif age > 35: 33 | print("Can't join army") 34 | else: 35 | print("Can join army!") 36 | 37 | # ------------------------------------------------------------------------------------ 38 | # Challenge: Using your knowledge of operators, write two conditions where it 39 | # says "replace-me", to check if your car is going below speed limit and above 40 | # the minimum speed for the street. 41 | # ------------------------------------------------------------------------------------ 42 | 43 | street_max_speed = 100 44 | street_min_speed = 50 45 | car_speed = 70 46 | 47 | if "replace_me": 48 | print("Lower your speed or you will be penalized") 49 | elif "replace_me": 50 | print("You should get a higher speed") 51 | else: 52 | print("Ok, you are in a good speed to travel") 53 | -------------------------------------------------------------------------------- /variables/strings.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: brief description of tutorial content 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # In Python, strings are defined by enclosing charaters in either single quotation 6 | # marks or double quotation marks 7 | 8 | string1 = 'This is a string' 9 | string2 = "This is also a string" 10 | 11 | # Printing a string is the same as printing any variable 12 | print(string1) # This will print 'This is a string' 13 | 14 | # Strings can be concatinated with a simple + sign 15 | print(string1 + string2) # This will print 'This is a stringThis is also a string' 16 | 17 | # A string in Python is like an array of characters in C 18 | print(string1[6]) # This will print 's' 19 | print(string2[8:11]) # This will print 'als' 20 | 21 | # If you wish to print a string with other variables amoung it, simply use a formatter 22 | a = 5 23 | b = 10 24 | print('This is how we print the vaiable a = {} and b = {} with ease'.format(a, b)) 25 | 26 | # There are many tricks to you can do with strings and other operators when you get 27 | # more comfortable with them! 28 | 29 | # ------------------------------------------------------------------------------------ 30 | # Challenge: list challenges to be completed here. minimum of one challenge per tutorial 31 | # ------------------------------------------------------------------------------------ 32 | # 1. Create a string & print out each character individually. 33 | # 2. Create a string & find the length of it. 34 | # 3. Print a string with different predefined variables in it. 35 | # 4. Write a program that adds 'ing' to every string. 36 | # 5. Write a program that replaces every 's' in a string with a '$' 37 | -------------------------------------------------------------------------------- /lists/dataframe.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: creating a dataframe from lists 3 | # ------------------------------------------------------------------------------------ 4 | # Think of a dataframe as an excel spreadsheet. All it is is a two-dimensional structure consisting of rows and columns. 5 | # Here I'll show you how to create a datframe with three columns using a list of lists. 6 | # Remember a list is created using square brackets []. So list of lists is different lists all wraped in a square bracket i.e. [['Sophie'], ['Jade']] 7 | # PS: anywhere you see a step, remove the hashtag before the code and remove everything in the bracket (). This does not include step 2! 8 | # e.g. in your practice, copy only "import pandas as pd" not "# import pandas as pd (step 2)" 9 | 10 | # Firstly, pip install pandas then import pandas as pd 11 | # pip install pandas (step 1) 12 | # import pandas as pd (step 2) 13 | # Creating a list of lists with two strings and an integer each 14 | list = [['Purple Hibiscus', 'Chimamanda', 2001], ['Things Fall Apart', 'Chinua', 1980]] # Step 3 15 | 16 | # Storing the transformation from list to dataframe in a variable 17 | # df means dataframe but you can call your variable anything 18 | # df = pd.DataFrame(list, columns=['BookTitle', 'AuthorFirstName', 'YearPublished']) (Step 4) 19 | # df (step 5) 20 | 21 | # There are different ways to create a dataframe from lists. This was just one of them! 22 | 23 | # ------------------------------------------------------------------------------------ 24 | # Challenge: get the right answer ! 25 | # 1. Make your own list of lists 26 | # 2. Store it in another variable that is not called df 27 | # 3. Create a dataframe from it 28 | # ------------------------------------------------------------------------------------ 29 | -------------------------------------------------------------------------------- /file-handling/reading-files.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------------------- 2 | # Tutorial: Receives a file name from the user, reads and then displays the contents to the console 3 | # ------------------------------------------------------------------------------------------------- 4 | 5 | # Taking the file we would like to read (Similar to selecting a book you want to read) 6 | # Make sure you give the full path in case the file is not present in the same location as the program 7 | filename = "" # Give your file name here 8 | # filename = input("Enter the file name you would like to read: ") # uncomment if you want to give the file name while running 9 | 10 | try: 11 | # Since we know which file to read let's open it first (We have to open the book first so that we can read) 12 | fread = open(filename, mode="r") # Here the r specifies we want to read the file 13 | 14 | # Now since we have the file open we can read it (Once our book is open we can start reading from the book) 15 | fcontents = fread.read() # Reads and saves all the contents into the variable fcontents 16 | 17 | # As we have read from the file we check out what's present in the file 18 | print(fcontents) 19 | 20 | # It's always a good practice to close the file after we finish reading from the file 21 | fread.close() 22 | 23 | except (EOFError, FileNotFoundError): 24 | print("File not found! Please check if the file exists in the same folder or provide the full path.") 25 | 26 | # --------------------------------------------------------------------------------------------------------------------- 27 | # Challenge: Create a file and add some content into the file. Change the filename in the program and verify the output 28 | # --------------------------------------------------------------------------------------------------------------------- 29 | -------------------------------------------------------------------------------- /common-built-in-functions/enumerate.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: brief description of tutorial content 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Enums are set of symbolic names bound to unique constant values. 6 | # Example, we can have Month enumeration with 12 months 7 | 8 | from enum import Enum 9 | 10 | class Month(Enum): 11 | JAN = 1 12 | FEB = 2 13 | MAR = 3 14 | APR = 4 15 | MAY = 5 16 | JUN = 6 17 | JUL = 7 18 | AUG = 8 19 | SEP = 9 20 | OCT = 10 21 | NOV = 11 22 | DEC = 12 23 | 24 | # Access via Name 25 | 26 | feb_elem = Month.FEB 27 | 28 | print("Number for Month {name} is {value}".format(name=feb_elem.name, 29 | value=feb_elem.value)) 30 | 31 | # Access via Value 32 | 33 | feb_elem = Month(2) 34 | 35 | print("Number for Month {name} is {value}".format(name=feb_elem.name, 36 | value=feb_elem.value)) 37 | 38 | 39 | # ------------------------------------------------------------------------------------ 40 | # Challenge: list challenges to be completed here. minimum of one challenge per tutorial 41 | # ------------------------------------------------------------------------------------ 42 | 43 | # # Challenge 1: Create Enum which store Day of week and Color as value for each day 44 | # # Replace the question(?) with logic 45 | 46 | # class ColorWeek(?): 47 | # MONDAY = 'RED' 48 | # TUESDAY = 'GREEN' 49 | # WEDNESDAY = 'BLUE' 50 | # THURSDAY = 'CYAN' 51 | # FRIDAY = 'YELLOW' 52 | # SATURDAY = 'WHITE' 53 | # SUNDAY = 'BLUE' 54 | 55 | # if ColorWeek.MONDAY.value == ?: 56 | # print("Color for Monday is RED") 57 | 58 | # # Print the day when color is GREEN 59 | # print("Day with color GREEN is: ") 60 | # print(?) 61 | -------------------------------------------------------------------------------- /common-built-in-functions/range.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Range() built-in function in Python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Code here explaining concept with comments to guide 6 | 7 | 8 | # Range func is inbuilt function having arguments passed to it below: 9 | # if we use just a single argument range(n) - it takes 0 by default as starting point and follows for n values i.e. ending at n-1 10 | # range(n) = range(0,n) as exclusive of its upper limit. 11 | # range(start,stop,step) {start is inclusive and stop is exclusive and step is the value of increament or decreament in each iteration of numbers 12 | # { By default, if we do not state the third argument it is taken as +1 } 13 | 14 | # Syntax: 15 | 16 | n = 5 17 | 18 | x = range(0, n, 1) # goes from 0 to n-1 with step size of 1 equal to range(n) 19 | 20 | y = range(n, 0, -2) # goes from n to 1 with step size of -2 21 | 22 | # Here I will set up an example for you all to clarify any more doubts about range() 23 | 24 | # Example: 25 | 26 | t = range(1, 11) 27 | for number in t: 28 | if number % 2 == 0: 29 | print(number) 30 | 31 | 32 | # The above example gets us all the even numbers within the range [1,10]. 33 | 34 | # So range deals with both increament as well as decreament hence very useful while calling for loops. 35 | # Also range() returns a sequence of numbers included in | range(start,stop,step) | 36 | 37 | # ------------------------------------------------------------------------------------ 38 | # Challenge: Take user based input n and then compute the sum of first n natural numbers(1,2,3,4....,n) and print the sum. Use the range function only and not the direct formula. 39 | # Example: Input - 5 40 | # Output - 15 41 | # ------------------------------------------------------------------------------------ 42 | -------------------------------------------------------------------------------- /sets/creating-sets.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Set Creation in Python 3 | # A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed). 4 | # Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc. 5 | # ------------------------------------------------------------------------------------ 6 | 7 | # A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using the built-in set() function. 8 | # It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements. 9 | 10 | # Different types of sets in Python 11 | # set of integers 12 | my_set = {1, 2, 3} 13 | print(my_set) 14 | 15 | # set of mixed datatypes 16 | my_set = {1.0, "Hello World", (1, 2, 3)} 17 | print(my_set) 18 | 19 | # set cannot have mutable items 20 | # here [3, 4] is a mutable list 21 | # this will cause an error. 22 | # my_set = {1, 2, [3, 4]} # uncomment this line to see the error 23 | 24 | # Distinguish set and dictionary while creating empty set 25 | # initialize a with {} 26 | a = {} 27 | 28 | # check data type of a 29 | print(type(a)) 30 | 31 | # initialize a with set() 32 | a = set() 33 | 34 | # check data type of a 35 | print(type(a)) 36 | 37 | # we can make set from a list 38 | my_set = set(["ice-cream", "burgar", "french-fries", "burgar"]) 39 | print(my_set) 40 | 41 | # ------------------------------------------------------------------------------------ 42 | # Challenge: 43 | # 1. Create a set of numbers from 1 to 10 and print it. 44 | # 2. Set cannot have duplicates - Create a set with duplicate values and print it. Observe the difference in output. 45 | # ------------------------------------------------------------------------------------ 46 | -------------------------------------------------------------------------------- /sets/remove-set-elements.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Removing Elements in a Set 3 | # A particular item can be removed from a set using the methods discard() and remove(). 4 | # ------------------------------------------------------------------------------------ 5 | 6 | # The only difference between the two is that the discard() function leaves a set unchanged if the element is not present in the set. 7 | # On the other hand, the remove() function will raise an error in such a condition (if element is not present in the set). 8 | 9 | # Difference between discard() and remove() 10 | 11 | # initialize my_set 12 | my_set = {1, 3, 4, 5, 6} 13 | print(my_set) 14 | 15 | # discard an element 16 | # Output: {1, 3, 5, 6} 17 | my_set.discard(4) 18 | print(my_set) 19 | 20 | # remove an element 21 | # Output: {1, 3, 5} 22 | my_set.remove(6) 23 | print(my_set) 24 | 25 | # discard an element 26 | # not present in my_set 27 | # Output: {1, 3, 5} 28 | my_set.discard(2) 29 | print(my_set) 30 | 31 | # Similarly, we can remove and return an item using the pop() method. 32 | # Since set is an unordered data type, there is no way of determining which item will be popped. It is completely arbitrary. 33 | # We can also remove all the items from a set using the clear() method. 34 | 35 | # initialize my_set 36 | # Output: set of unique elements 37 | my_set = set("HelloWorld") 38 | print(my_set) 39 | 40 | # pop an element 41 | # Output: random element 42 | print(my_set.pop()) 43 | 44 | # pop another element 45 | my_set.pop() 46 | print(my_set) 47 | 48 | # clear my_set 49 | # Output: set() 50 | my_set.clear() 51 | print(my_set) 52 | 53 | # ------------------------------------------------------------------------------------ 54 | # Challenge: Remove an element which is not present in my_set and print the set. Observe the output. Check which type of error it is and why it occurs. 55 | # ------------------------------------------------------------------------------------ 56 | -------------------------------------------------------------------------------- /tuples/tuples-basic.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Tuple basics 3 | # ------------------------------------------------------------------------------------ 4 | # A tuple is just like a list. But one difference is that items are enclosed with 5 | # (parentheses), instead of [brackets]. 6 | my_tuple = ("Tuple", "is", "fun") 7 | 8 | # It can also store variables of different types: 9 | my_tuple2 = (123, 1.0, "Hello", "World!", True) 10 | 11 | # Another notable difference is that tuple items are immutable. 12 | # Immutable means the items cannot be updated or changed. 13 | # Although you can still index an item like this: 14 | last_item = my_tuple2[-1] 15 | 16 | # This won't work (Commented out, otherwise it'll cause an error): 17 | # my_tuple2 = False 18 | 19 | # To initialize an empty tuple, you can just write empty parentheses. 20 | empty_tuple = () 21 | # But interestingly, to define a tuple that consists of one item, 22 | # you don't write parentheses. Instead, you just add a trailing comma. 23 | tuple_with_one_item = "one", 24 | 25 | # Just like a list, you can count how many items a tuple has by using len(): 26 | print(len(my_tuple)) 27 | # Output: 3 28 | 29 | # When you unpack multiple items to one variable, Python actually creates a tuple 30 | # behind-the-scenes. 31 | t = 101010, True, "Neon" 32 | print(t) 33 | # Output: (101010, True, 'Neon') 34 | # You can also do the reverse operation: 35 | x, y, z = t 36 | print(x, y, z) 37 | # Output: 101010 True Neon 38 | 39 | # ------------------------------------------------------------------------------------ 40 | # Challenge: Create a tuple that stores each word in your name as strings. 41 | # Then, unpack the tuple into multiple variables. You can call the variables whatever 42 | # you want. (One example: first_name, middle_name, last_name) 43 | # ------------------------------------------------------------------------------------ 44 | # Create your tuple here. 45 | 46 | # Unpack the tuple here. 47 | -------------------------------------------------------------------------------- /variables/booleans.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Understanding Boolean variables 3 | # ------------------------------------------------------------------------------------ 4 | # Boolean variables are defined by the True and False keywords 5 | # eg: a = True 6 | # We can check type of variables by printing : type(var_name) 7 | # If it is of type boolean it will return : 8 | # bool() method can be used to convert value to boolean value 9 | # It returns True if the parameter or value passed is True 10 | # It returns False if the parameter or value passed is False with some exceptions such as 11 | # If False value is passed, None is passed, an empty sequence is passed such as (), [], ”, etc, or if Zero is passed in any numeric type such as 0, 0.0, etc. 12 | 13 | def Boolean(): 14 | 15 | # Returns True as x is True 16 | x = True 17 | print(bool(x)) 18 | 19 | # Returns False as x is False 20 | x = False 21 | print(bool(x)) 22 | 23 | # Returns False as x is not equal to y 24 | x = 15 25 | y = 18 26 | print(bool(x == y)) 27 | 28 | # Returns False as x is None 29 | x = None 30 | print(bool(x)) 31 | 32 | # Returns False as x is an empty sequence 33 | x = () 34 | print(bool(x)) 35 | 36 | # Returns False as x is an emty mapping 37 | x = [] 38 | print(bool(x)) 39 | 40 | # Returns False as x is 0 41 | x = 0.00 42 | print(bool(x)) 43 | 44 | # Returns True as x is a non empty string 45 | x = 'This is Boolean Tutorial' 46 | print(bool(x)) 47 | 48 | Boolean() 49 | 50 | # any expression in Python is True or False 51 | print("Basic boolean:", 5 == 5, type(5 == 5)) 52 | 53 | def Challenge(arg1, arg2, arg3): 54 | print("Challenge:") 55 | print(bool(arg1)) 56 | print(bool(arg2)) 57 | print(bool(arg3)) 58 | 59 | Challenge([], 125, True) 60 | 61 | # --------------------------------------CHALLENGE---------------------------------------------- 62 | # Challenge: call the Challenge function and pass the values '0.00', '{1, 341, 56}' and 'False' to the function 63 | -------------------------------------------------------------------------------- /functions/using-functions.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: how to declare and call a function 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # the 'def' keyword is used to declare a function. the structure of a function is: 6 | def a_function(): 7 | print('hello world') 8 | 9 | # to call a function simply type its name 10 | a_function() 11 | 12 | # you can declare functions that accept arguments 13 | def another_function(argument1, argument2): 14 | print(argument1, argument2) 15 | 16 | # when calling a function with arguments, pass in the arguments 17 | another_function('hello', 'universe') 18 | 19 | 20 | # ----------------------------------------------------------------------------------- 21 | # Challenge: create a function that takes two integers as arguments and prints the sum. 22 | # call the function and pass the values '1' and '2' to the function 23 | # ------------------------------------------------------------------------------------ 24 | 25 | # You code here 26 | # 27 | # 28 | # 29 | # 30 | # ... 31 | 32 | # --------------------------------------------------- 33 | # More on functions 34 | # --------------------------------------------------- 35 | 36 | # Functions can return something with the 'return' keyword. 37 | def biggestNumber(number1, number2): 38 | maxnumber = max(number1, number2) # The max built-in function returns the highest value of all those passed 39 | 40 | return maxnumber 41 | 42 | # When calling the function, you can use the value returned 43 | oldestPerson = biggestNumber(15, 18) 44 | print("Oldest person:", oldestPerson) 45 | 46 | print(biggestNumber(100 * 0, 1 * 2)) 47 | 48 | # ----------------------------------------------------------------------------------- 49 | # Challenge: modify the previous function you created so it returns the value instead. 50 | # create another piece of code that uses the value returned from your function 51 | # ------------------------------------------------------------------------------------ 52 | 53 | # Your code here 54 | # 55 | # 56 | # ... 57 | -------------------------------------------------------------------------------- /loops/using-continue.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Using continue keyword in python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # It allows us to leave some piece of code when we do not need it or some fixed condition is not met. 6 | # It is just a keyword which allows us to handle our code in specific conditions. 7 | # for example if we say that a particular var has achieved a particular val then we don't proceed with the piece of code after the continue keyword. 8 | 9 | # Note : We also use it when we have some base cases for our test cases while doing competitive programming. 10 | 11 | # Note: continue keyword is only used within loops. 12 | 13 | # Example: 14 | 15 | for x in range(5): 16 | if x == 3: 17 | continue 18 | print(x) 19 | 20 | # In above example as x approaches the value 3 (as in condition) continue statement is trigerred an thus when we look at the output of the code, x=3 is not printed. 21 | # Also there are times we don't want to do anything in a particular condition so what we do is just use the continue statement to keep the iteration going on. 22 | 23 | for x in range(1, 16): 24 | if x % 5 == 0: 25 | continue 26 | print(x) 27 | 28 | # Above example states that when there will be a number in the range which is a multiple of 5 so it will not execute print statement 29 | # Hence, our output will contain all elements in the range which are not multiple of 5. 30 | 31 | # Basically, the code above the continue keyword is considered only if the above condition does not satisfy else the code will process the request and exclude the lines of code below continue. 32 | 33 | # ------------------------------------------------------------------------------------ 34 | # Challenge: Take user input n and print all the odd natural numbers ( where natural numbers is the list - [1,2,3,4,5...,n] ) upto n using continue keyword. 35 | # Example: Input - 18 36 | # Output - { 1, 3, 5, 7, 9, 11, 13, 15, 17 } [ Just consider the values not the pattern ] 37 | # ------------------------------------------------------------------------------------ 38 | -------------------------------------------------------------------------------- /file-handling/scanning-files.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------------------------------------------------------ 2 | # Tutorial: Receives a directory name from the user, scans the directory and then displays the files in the directory to the console 3 | # ------------------------------------------------------------------------------------------------------------------------------------ 4 | 5 | import os # This provides functions for interacting with the operating system. 6 | 7 | # Taking the directory we would like to scan (Similar to selecting a box of apples and other boxes inside it with name labels) 8 | # Make sure you give the full path in case the directory is not in the same location as the program 9 | directorypath = "" # Give your directory name/path here 10 | # directorypath = input("Enter the directory name/path you would like to scan: ") # uncomment if you want to give the directory name while running 11 | 12 | try: 13 | # Since we know which location to scan let's get all the file/folder names in it first (We have to get all the names of apples and boxes) 14 | directorynames = os.listdir(directorypath) # We get a list of files/folders names in the location 15 | for entry in directorynames: # We iterate through each file/folder inside the given folder name and store the name in the entry variable each time(we store the name of the apple/box each time) 16 | if os.path.isfile(os.path.join(directorypath, entry)): # We check whether it is a file or not(Check if it is an apple or box) 17 | print(entry) # We print the name if it is a file(Show if it is an apple, so in this way boxes are filtered out.) 18 | 19 | except (EOFError, FileNotFoundError): 20 | print("Directory not found! Please check if the directory exists in the current path or provide the full path.") 21 | 22 | # --------------------------------------------------------------------------------------------------------------------------------- 23 | # Challenge: Create a folder/directory and add some files and folders. Change the directoryname in the program and verify the output 24 | # --------------------------------------------------------------------------------------------------------------------------------- 25 | -------------------------------------------------------------------------------- /operators/comparison.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Comparision Operators in Python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # So basically there are 6 Comparison Operators in Python , let us learn them one by one . 6 | # Note : One more thing to note is that whenever you compare two "things" , the return value of this Comparision will be either True or False 7 | 8 | # 1. "=="(Equal) -> we use this operator to see if two variables are equal. 9 | a = 5 10 | b = 5 11 | print(a == b) # Here since a and b are equal we will get True in output. 12 | 13 | # 2. "!="(Not Equal) -> we use this operator to see if two variables are equal or not , if they are not equal it will return True else False. 14 | a = 5 15 | b = 5 16 | print(a != b) # Here since a and b are equal we will get False in output. 17 | 18 | # 3. ">"(Greater than ) -> we use this operator to see if one variable is greater than other. 19 | a = 9 20 | b = 5 21 | print(a > b) # Here since a is greater than b , we will get True in output. 22 | 23 | # 4. ">="(Greater than or equal to ) -> we use this operator to see if two variables are equal or one is grater than the other. 24 | a = 5 25 | b = 5 26 | print(a >= b) # Here since a and b are equal, we will get True in output. 27 | 28 | # 5. "<"(Less than ) -> we use this operator to see if one variable is less than other. 29 | a = 9 30 | b = 5 31 | print(a < b) # Here since a is greater than b , we will get False in output. 32 | 33 | # 6. "<="(Less than or equal to ) -> we use this operator to see if two variables are equal or one is less than the other. 34 | a = 3 35 | b = 5 36 | print(a <= b) # Here since a is less than b , we will get True in output. 37 | 38 | # ------------------------------------------------------------------------------------ 39 | # Challenge for you : 40 | # ------------------------------------------------------------------------------------ 41 | 42 | # Given a array of numbers . 43 | 44 | # Traverse the array and print following : 45 | # If the number is less than 10 - print "The number is smaller than 10." 46 | # If the number is greater than 10 - print "The number is greater than 10." 47 | # If the number is equal t0 10 - print "The number is equal to 10." 48 | # The array nums is given below . 49 | nums = [1, 3, 10, -7, 8] 50 | # write your code here 51 | -------------------------------------------------------------------------------- /lists/list-comprehension.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: List comprehension 3 | # ------------------------------------------------------------------------------------ 4 | # It's a Python feature to iterate and create a list from some other list in a 5 | # shorter and declarative way than loops. 6 | 7 | 8 | # In general there is a very common for loop structure that looks like this: 9 | for_loop_squares = [] 10 | 11 | for i in range(10): 12 | for_loop_squares.append(i * i) 13 | 14 | print(for_loop_squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 15 | 16 | 17 | # With list comprehension you can do the exact same thing in one line. 18 | # the syntax is: 19 | # new_list = [expression for member in iterable] 20 | comprehension_squares = [x * x for x in range(10)] 21 | 22 | print(comprehension_squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 23 | 24 | 25 | # You can even add conditionals to the list comprehension, the condition is place at the end of the list comprehension, just like that: 26 | # new_list = [expression for member in iterable if condition] 27 | comprehension_even_squares_numbers = [x * x for x in range(10) if x % 2 == 0] 28 | 29 | print(comprehension_even_squares_numbers) # [0, 4, 16, 36, 64] 30 | 31 | 32 | # But if you can do if/else logic, you need to place the condition before the for loop just like that: 33 | comprehension_even_squares_numbers_and_odd_numbers_is_zero = [x * x if x % 2 == 0 else 0 for x in range(10)] 34 | 35 | print(comprehension_even_squares_numbers_and_odd_numbers_is_zero) # [0, 0, 4, 0, 16, 0, 36, 0, 64, 0] 36 | 37 | 38 | # We can summarize the 3 formats of list comprehension. The basic format of a list comprehension is like: 39 | # new_list = [expression for member in iterable] 40 | 41 | # With only one condition 42 | # new_list = [expression for member in iterable if condition] 43 | 44 | # With if/else logic: 45 | # new_list = [expression if condition else other_expression for x in sequence] 46 | 47 | 48 | # ------------------------------------------------------------------------------------ 49 | # Challenge: FIZZBUZZ 50 | # Create a list comprehesion that returns the numbers from 0 to 100 but: 51 | # 1 -. if the number is divisible by 3 and 5, append to the list the word "FizzBuzz" 52 | # 2 -. else, append to the list the number 53 | # ------------------------------------------------------------------------------------ 54 | -------------------------------------------------------------------------------- /string-formatting/string-reversal.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # We're going to look at a few different ways that you can reverse the structure of a string . 3 | # Let's begin. 4 | # ------------------------------------------------------------------------------------ 5 | 6 | # Single Words , A string is an iterable and anything within these --> "" 7 | # 1. The built-in reverse method 8 | # This method is used on iterables , commonly on lists and strings 9 | # Example of functions that reverse a string. 10 | def reverseString(word): 11 | reversedWord = "".join(reversed(word)) 12 | return reversedWord 13 | ''' 14 | Let's break down what's above: 15 | Remember that all strings are immutable but iterable. So if that's the case , we can't use the .reverse() function like we could on a list. 16 | So we iterate through each letter and use the reversed() function . Now since the reversed() function return an iterable;a list . 17 | We use the join() to concatenate the letters and then we return the reversed String. 18 | ''' 19 | # 2.The reverse slice method 20 | # This method also works on iterables too. 21 | # Let's use the same example with this method too 22 | def backString(word): 23 | reversedWord = word[::-1] 24 | return reversedWord 25 | ''' 26 | Let's break this down as well: 27 | The slicing technique is used to get a certain portion of string and using the starting and ending index values. 28 | e.g [a:b], this slices from position to position before b ; so b-1 . What we don't commonly use is the third option of [a:b:c] <-- C. 29 | What c does is specify the number of characters to jump or skip over . So if c == 2 , we're gonna skip over 2 characters .But if c == -1,this specifies that the string begins from the back. 30 | We commonly use -1 when we want the last letter or character in a string e.g word = "pet",word[-1] == t. 31 | Back to the function , if we don't specify the starting and end values , the computer just assumes it's the whole string . 32 | So e.g [a:] this is from a to the last , [:b] from the first to b , [a::c] from a to the last every c characters , [:b:c] from the first to b every c characters . 33 | So [::-1] means from the first to last in reverse . 34 | ''' 35 | 36 | # ------------------------------------------------------------------------------------ 37 | # The format is the same even for sentences : So write a function that reverses the sentence "I love ketchup". 38 | -------------------------------------------------------------------------------- /lists/indexing-lists.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: indexing lists 3 | # ------------------------------------------------------------------------------------ 4 | # Here you go ! You have lists in python, it's like a fridge, 5 | # and you can store things to a specific place and get them when you want, 6 | # if you remember correctly where you put things ! 7 | 8 | 9 | # a list is with brackets and you can add what you want by separating it with commas 10 | # here, you have a list with fruits (type String) 11 | my_list = ["banana", "apple", "strawberry", "grape", "pear"] 12 | 13 | # but you can store things which aren't all the same type 14 | my_crazy_list = [1, 3, "red", "blue", True] 15 | 16 | 17 | # To access to something of your list we use the index. It's start from 0 to the 18 | # length of you list minus 1 (because it's start from 0) 19 | 20 | # to know the index of something of an element in your list we use the method index() 21 | index = my_list.index('apple') 22 | print('The index of apple:', index) 23 | # output: 1 24 | 25 | 26 | # you can also search the index of an element in part of the list, 27 | # you need to give the start and the end 28 | index = my_list.index('grape', 1, 4) 29 | print('The index of grape:', index) 30 | # output: 3 31 | 32 | 33 | # If you want to see what is on a specific index you just need to call the variable 34 | # where you have stored your list with bracket and the specific index 35 | magic_fruit = my_list[2] 36 | print('Your magic fruit is:', magic_fruit) 37 | 38 | # ------------------------------------------------------------------------------------ 39 | # Challenge: get the right answer ! 40 | # ------------------------------------------------------------------------------------ 41 | # Use what you have seen just before to resolve the challenge 42 | 43 | colors = ["blue", "red", "purple", "orange", "white", "grey", "yellow", "black", "green"] 44 | 45 | # Change the value None to the index of the color grey 46 | index_grey = None 47 | print('You must see here the index of the color grey:', index_grey) 48 | 49 | # Change the value None to access to the color purple with the right index 50 | purple = None 51 | print('You must see here the color purple:', purple) 52 | 53 | # uncomment lines bellow to see if your results is correct 54 | # Will throw an error if your solution is incorrect 55 | 56 | # assert(index_grey == 5) 57 | # assert(purple == 'purple') 58 | -------------------------------------------------------------------------------- /functions/lambda-functions.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Lambda Function in Python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Lambda functions are the anonymous functions which do not need 6 | # to be defined with names but the keyword 'lambda'. A lambda 7 | # function takes any number of arguments and evaluates the expression of it. 8 | 9 | 10 | # Syntax => (lambda arguments: expression)(arguments) 11 | print((lambda y: y * 10)(3)) 12 | 13 | 14 | # ------------------------------------------------------------------------------------ 15 | # A lambda function can also be assigned to a variable and then called as an object. 16 | # Example: 17 | # x = lambda y: y * 10 18 | # print(x(3)) 19 | # ------------------------------------------------------------------------------------ 20 | 21 | 22 | # Usage with multiple arguments 23 | sumup = (lambda a, b: a + b)(3, 5) 24 | print(sumup) 25 | 26 | # Usage with print 27 | (lambda x: print(x))("Great Work!") 28 | 29 | # Usage with If-Else 30 | minimum = (lambda a, b: a if (a < b) else b)(10, 100) 31 | print(minimum) 32 | 33 | 34 | # ------------------------------------------------------------------------------------ 35 | # Challenge: Create a lambda function which can take 3 arguments and evaluates the 36 | # product of it. Print the result in the console by passing the parameters. 37 | # Example => Inputs: 2,3,4 || Output: 24 38 | # ------------------------------------------------------------------------------------ 39 | 40 | 41 | # Pre-requisites : Functions in Python 42 | # Unlike defined functions, a Lambda function cannot have more 43 | # than one expression and do not need return statement. 44 | # Use Lambda when a function is needed for short period of time. 45 | 46 | # Usage of Lambda within Defined functions 47 | def sample(n): 48 | m = (lambda a: abs(a) + 1)(n) 49 | return 1000 * m 50 | 51 | print(sample(-3)) 52 | 53 | # ------------------------------------------------------------------------------------ 54 | # Challenge: Create a lambda function within the max_cube() function to find the 55 | # maximum of two given arguments, and then return the cube of the same. 56 | # ------------------------------------------------------------------------------------ 57 | 58 | def max_cube(a, b): 59 | pass 60 | 61 | print(max_cube(2, 3)) # Once you have completed the challenge, it should print : 27 62 | -------------------------------------------------------------------------------- /dictionaries/using-dictionaries-basic.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Learn how to use Dictionaries in Python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Dictionaries are a collection of key-value pairs. 6 | # Keys can only appear once in a dictionary but can be of any type. 7 | # Dictionaries are unordered. 8 | # Values can appear in any number of keys. 9 | # Keys can be of almost any type, values can be of any type. 10 | 11 | # Defining a dictionary 12 | # Dictionaries are assigned using a pair of curly brackets. 13 | # Key pair values are assigned within the curly brackets with a : between the key and value 14 | # Each pair is separated by a comma 15 | my_dict = { 16 | 'my_key': 'my value', 17 | 'your_key': 42, 18 | 5: 10, 19 | 'speed': 20.0, 20 | } 21 | 22 | # Assigning key-value pairs 23 | # Adding key pairs to an existing dictionary 24 | my_dict['their_key'] = 3.142 25 | 26 | # Retreiving a value 27 | retrieved = my_dict['my_key'] 28 | print("Value of 'my_key': " + str(retrieved)) # Should print "Value of 'my_key': my value" 29 | 30 | retrieved = my_dict.get('your_key') 31 | print("Value of 'your_key': " + str(retrieved)) # Should print "Value of 'your_key': 42" 32 | 33 | # With either of the above options Python will throw a key error if the key doesn't exist. 34 | # To fix this dictionary.get() can be used to return a default value if no key exists 35 | retrieved = my_dict.get('non_existent_key', 'Not here.') 36 | print("Value of 'non_existent_key': " + str(retrieved)) # Should print "Value of 'non_existent_key' not here" 37 | print("") 38 | 39 | # ------------------------------------------------------------------------------------ 40 | # Challenge: Create a dictionary called person. 41 | # The person dictionary should contain the following keys: 42 | # name, height, age 43 | # With the following values: 44 | # 'Sally', 154.9, 15 45 | # Add a key called occupation with value 'student' 46 | # Update the value of age to 18 47 | # Remember to uncomment the print lines 48 | # You should see the output 49 | # Person is called Sally 50 | # Person is 18 51 | # Person is 154.9cm 52 | # Person is student 53 | # ------------------------------------------------------------------------------------ 54 | 55 | # Define person dictionary here 56 | 57 | # Add occupation key here 58 | 59 | # Increase the age to 18 here 60 | 61 | # Uncomment the lines below once you have completed the challenge 62 | # print("Person is called " + str(person.get("name", "Unnamed"))) 63 | # print("Person is " + str(person.get("age", "Ageless"))) 64 | # print("Person is " + str(person.get("height", "Tiny")) + "cm") 65 | # print("Person is " + str(person.get("occupation", "Unemployed"))) 66 | -------------------------------------------------------------------------------- /variables/integers.py: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------- 2 | # Tutorial: An explanation of the int(integer) datatype 3 | # ----------------------------------------------------- 4 | 5 | # In python, numbers without decimals are stored using the int datatype 6 | number1 = 10 # We can directly assign a number to a variable 7 | # We can check the datatype of a variable using the type function. So let's verify if the variable number1 is an int(integer) or not 8 | print("Type of number1 is", type(number1)) 9 | # We can see that Python is smart enough to make the variable number as an int. This is called Dynamically typed. 10 | 11 | # We can also declare an integer using the int() function 12 | number2 = int(20) 13 | # We can see that the variable number2 is an integer too. This is called Static typed as we are giving the type 14 | print("Type of number2 is", type(number2)) 15 | 16 | # We can also convert from other datatype to integer using int() 17 | number3 = int("30") 18 | # Python converts the string to an integer. 19 | print("Type of number3 is", type(number3)) 20 | 21 | # Integers can hold negative numbers too 22 | number4 = -10 23 | print("Type of number4 is", type(number4)) 24 | 25 | 26 | # Operations on int 27 | 28 | # Addition: Two integers can be added using the + sign 29 | sum = number1 + number2 30 | print(f'{number1} + {number2} is {sum}') 31 | 32 | # Subtraction: Integers can be subtracted using the - sign 33 | diff = number3 - number2 34 | print(f'{number3} - {number2} is {diff}') 35 | 36 | # Multiplication: Two integers can be multiplied using the * sign 37 | mul = number1 * number2 38 | print(f'{number1} * {number2} is {mul}') 39 | 40 | # Division: Two integers can be divided using the / sign 41 | div = number3 / number1 42 | # Remember the answer is a decimal even if the numbers are perfectly divisible 43 | print(f'{number3} / {number1} is {div}') 44 | 45 | # Remainder: The remainder left when a number is divided by another number can be found using % sign 46 | rem = number3 % 11 47 | # Gives the remainder when number3 is divided by 11 48 | print(f'{number3} % 11 is {rem}') 49 | 50 | # Power: An integer can be raised to a power using ** operator 51 | pow = number1 ** 2 52 | # Returns number1 to the power of 2 53 | print(f'{number1} to the power 2 is {pow}') 54 | 55 | # ------------------------------------------------------------------------------------------------------------------ 56 | # Challenge 1: Declare two integers and find the sum, difference, product, quotient and remainder of the two numbers 57 | # ------------------------------------------------------------------------------------------------------------------ 58 | 59 | # Add your code here 60 | 61 | # -------------------------------- 62 | # Challenge 2: Find the cube of 39 63 | # -------------------------------- 64 | 65 | # Add your code here 66 | -------------------------------------------------------------------------------- /file-handling/writing-to-files.py: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------------------------- 2 | # Tutorial: Opens/creates a file and writes contents into the file 3 | # ---------------------------------------------------------------- 4 | 5 | # Select a file name in which you would like to write (Similar to selecting a book you want to write) 6 | # Make sure you give the full path in case the file is not present in the same location as the program 7 | # Unlike during read, if the file doesn't exist Python otself creates the file first and then opens it 8 | # If the file already has some content then Python overwrites it (So be careful when selecting the file) 9 | filename = "Test.txt" # Give your file name here 10 | # filename = input("Enter the file name you would like to read: ") # uncomment if you want to give the file name while running 11 | 12 | # Since we know which file to write let's open it first (We have to open the book first so that we can write into it) 13 | fwrite = open(filename, mode="w") # Here the w specifies we want to write new content to the file 14 | # In the above syntax if we give a instead of w then we can append that is insert the content at the end of the file instead of overwriting the file 15 | 16 | # Let's srore what we want to write into the file into a variable 17 | fcontents = f"I have written this content into {filename} using my python program!" 18 | # filename = input("Enter the file contents you would like to write into the file: ") # uncomment if you want to give the file contents while running 19 | 20 | # Now since we have the file open and the contents ready, we can start writing onto it (Once our book is open we can start writing in the book) 21 | fwrite.write(fcontents) # Writes the content stored in fcontents to the file and saves it 22 | print(f"Contents successfully written into the file {filename}") 23 | 24 | # It is always a good practice to close the file once we finished working with it 25 | fwrite.close() 26 | 27 | # ----------------------------------------------------------------------------------------------------------------------------------- 28 | # Challenge: Create a file and add some content into the file using python. Open the file and check if the contents are written to it 29 | # ----------------------------------------------------------------------------------------------------------------------------------- 30 | 31 | # -------------------------------------------------------------------------------------------------------------------------------------------------- 32 | # Challenge 2: In the same file you created in the previous challenge try adding some more content without overwriting what you have already written 33 | # (Hint: Try the a option instead of w) 34 | # -------------------------------------------------------------------------------------------------------------------------------------------------- 35 | -------------------------------------------------------------------------------- /lists/altering-lists.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Learn how to alter lists. 3 | # ------------------------------------------------------------------------------------ 4 | 5 | my_list = [10, 11, 12] 6 | print("Original list") 7 | print(str(my_list) + "\n") 8 | 9 | # To add an item to the end of a list use append() 10 | my_list.append(15) # Will add the integer 15 to the end of the list. 11 | print("List after appending ") 12 | print(str(my_list)) 13 | 14 | # To add an item at a specific index use inset() 15 | my_list.insert(1, 6) # Adds an item at second position 16 | print("List after inserting ") 17 | print(str(my_list)) 18 | 19 | # To append another list to your list use extend() 20 | new_list = [7, 8, 9] 21 | my_list.extend(new_list) 22 | print("List after extending ") 23 | print(str(my_list)) 24 | print("") 25 | 26 | # To remove an item from the list use remove() 27 | # Will throw an error if the item doesn't exist in the list 28 | # If an item is present in the list more than once only the first 29 | # copy will be removed from the list 30 | my_list.remove(6) 31 | print(str(my_list)) 32 | 33 | # To remove an item from the list and return it for further use use pop() 34 | popped = my_list.pop(5) # Will remove the number 8 and return it 35 | print("Popped item " + str(popped)) 36 | print(str(my_list)) 37 | print("") 38 | 39 | # To sort a list without altering the original data use sorted() 40 | sorted_list = sorted(my_list) 41 | print("Original list") 42 | print(str(my_list)) 43 | print("Sorted copy") 44 | print(str(sorted_list)) 45 | print("") 46 | 47 | # To sort a list use sort() 48 | # Sort takes an optional function 49 | my_list.sort() 50 | print("Sorted list " + str(my_list)) 51 | print("") 52 | 53 | # To empty a list use clear() 54 | my_list.clear() 55 | print("Emptied list " + str(my_list)) 56 | 57 | # ------------------------------------------------------------------------------------ 58 | # Challenge: You are in charge of sorting test scores for an exam. 59 | # There are some results missing as in the following points: 60 | # Add the integer 1 to any position in the list 61 | # Add the integer 50 to the end of the list 62 | # Add the list 45, 33, 16 to the end of the list 63 | # then sort the list so it is ordered largest number to smallest 64 | # (eg 100, 50, 45, 33, 25, 22, 16, 10, 5, 3, 1) 65 | # Print the first score in the list to declare the winner of the exam. 66 | # ------------------------------------------------------------------------------------ 67 | 68 | print("\n\nChallenge 1:") 69 | list_to_sort = [100, 5, 10, 25, 3, 22] 70 | # Perform operations here 71 | 72 | print(str(list_to_sort)) 73 | # Fix and uncomment print line below to declare the winner 74 | # print("The winner is" + ) 75 | 76 | # Uncomment the assert line below once you have performed the required actions 77 | # Will throw an error if your solution is incorrect 78 | # assert(list_to_sort == [100, 50, 45, 33, 25, 22, 16, 10, 5, 3, 1]) 79 | -------------------------------------------------------------------------------- /dictionaries/iterating-over-dictionaries.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Learn how to iterate over dictionaries 3 | # ------------------------------------------------------------------------------------ 4 | 5 | my_dict = { 6 | 'first_key': 1, 7 | 'second_key': 'second value', 8 | 'third_key': 3.0, 9 | 'fourth_key': { 10 | 'sub_key1': 'sub_value1', 11 | 'sub_key2': 2, 12 | 'sub_key3': 9.0, 13 | } 14 | } 15 | 16 | # dictionary.keys() will return a list of all the keys in the dictionary. 17 | # If you want to iterate over all keys you can use a for loop 18 | for key in my_dict.keys(): 19 | print("Key: " + str(key)) 20 | print("") 21 | 22 | # You can then pass the value of key back into the dictionary to retrieve the value 23 | for key in my_dict.keys(): 24 | print(str(my_dict[key])) 25 | print("") 26 | 27 | # dictionary.values() will return a list of all the values in the dictionary 28 | for value in my_dict.values(): 29 | print("Value: " + str(value)) 30 | print("") 31 | 32 | # dictionary.items() will return a list of all the key-value pairs in the dictionary 33 | # The items in the list will be tuples in the form (key, value,) 34 | for item in my_dict.items(): 35 | print("Key: " + str(item[0]) + "\t| Value: " + str(item[1])) 36 | print("") 37 | 38 | # As you might expect all the above methods can be applied to values that are dictionaries 39 | print("Iterating over a sub dictionary") 40 | for item in my_dict['fourth_key'].items(): 41 | print("Key: " + str(item[0]) + " | Value: " + str(item[1])) 42 | print("") 43 | 44 | # As stated in using-dictionaries-basic.py keys can be of almost any type. However one type 45 | # that cannot be a key is dictionary. 46 | # For fun let's create a new dictionary. We will set the keys to the values of my_dict 47 | # and the values to the keys of my_dict. 48 | # First we must remove fourth_dict from the dictionary otherwise we will receive a TypeError. 49 | del my_dict['fourth_key'] 50 | 51 | swapped_dict = {} 52 | for item in my_dict.items(): 53 | swapped_dict[item[1]] = item[0] 54 | print("Swapped dictionary: ") 55 | print(swapped_dict) 56 | 57 | # ------------------------------------------------------------------------------------ 58 | # Challenge: You are in charge of restocking at the grocery store. 59 | # Stock is stored by category: fruit, vegetable, bathroom 60 | # Look through all the category keys. 61 | # Look through all the items within the category. 62 | # If an item has a value of 0 (out of stock) add it as a key to 63 | # the restock dictionary and set the value to 5 64 | # HINT: It helps to think of each category as its own dictionary 65 | # HINT: You should be able to do this with 2 nested loops 66 | # ------------------------------------------------------------------------------------ 67 | 68 | stock = { 69 | 'fruit': { 70 | 'pineapple': 5, 71 | 'pear': 0, 72 | }, 73 | 'vegetable': { 74 | 'carrot': 0, 75 | 'radish': 10, 76 | }, 77 | 'bathroom': { 78 | 'soap': 3, 79 | 'shampoo': 0, 80 | }, 81 | } 82 | 83 | restock = {} 84 | 85 | # Type your solution here 86 | 87 | print("\nItems to restock") 88 | print(restock) # Once you've completed the challenge should print "{'pear': 5, 'carrot': 5, 'shampoo': 5}" 89 | -------------------------------------------------------------------------------- /using-modules/using-virtual-environments.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Learn how and when to use virtual environments 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # What is a Virtual Environment 6 | # A virtual environment allows you to create a directory on your computer which has 7 | # a separate set of dependencies and settings from the rest of your computer. 8 | # For example say you have one project that uses PIL 8.0.1 and another that uses PIL 7.1.0 9 | # you will have to keep reinstalling different versions as you work across the projects. 10 | # With virtual environments you can install one version of PIL in one project directory and 11 | # the other version in the other directory and each will run with the correct dependencies each time. 12 | # As long as the virtual environment is active it will use the correct dependencies for the project. 13 | 14 | # How to install Python Virtual Environment System 15 | # In the command line type: 16 | # pip install virtualenv 17 | # For more information on pip see using-modules/installing-with-pip.py 18 | 19 | # How to Create a Virtual Environment 20 | # To create a virtual environment run the following command: 21 | # python -m venv /path/to/ 22 | 23 | # How to Start the Virtual Environment 24 | # Navigate to the root of your project and in Windows type: 25 | # /Scripts/activate 26 | # In most Unix based operating systems (including MacOS) type: 27 | # source /bin/activate 28 | # Once started you will see a little () in your command prompt. 29 | # Any Python program you run or dependency you install while the virtual environment is active 30 | # will use the dependencies and settings defined in that virtual environment. 31 | # You can run multiple virtual environments from multiple command line instances. 32 | 33 | # How to Stop the Virtual Environment 34 | # From the active virtual environment instance run the command: 35 | # deactivate 36 | 37 | # ------------------------------------------------------------------------------------ 38 | # Challenge: Create a virtual environment within /using-modules named ienv 39 | # E.g. TeachMePythonLikeIm5/using-modules/ienv 40 | # Before going further check that pip is installed by running: 41 | # pip --version 42 | # If you see a message similar to pip 18.1 from [installation_path] (python version) 43 | # you can continue. If not, install pip by running: 44 | # python get-pip.py 45 | # For more information on pip see /using-modules/installing-with-pip.py 46 | # 47 | # With pip installed: 48 | # Start the virtual environment. 49 | # While the virtual environment is active run the command 50 | # pip install pillow==8.0.0 51 | # then run this file: 52 | # python using-virtual-environments.py 53 | # Once you have seen that the output is correct (it should print 8.0.0) deactivate the 54 | # virtual environment. 55 | # OPTIONAL: Re-run the script with the virtual environment deactivated. If pillow has not 56 | # previously been installed you will receive an import error (this is OK for the challenge). 57 | # If pillow has been installed on your computer before it will print the version number 58 | # of the previously installed pillow. 59 | # ------------------------------------------------------------------------------------ 60 | 61 | from PIL import Image 62 | print(Image.__version__) 63 | -------------------------------------------------------------------------------- /variables/floats.py: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------- 2 | # Tutorial: An explanation of the float datatype 3 | # ----------------------------------------------------- 4 | 5 | # In python, decimals are stored using the float datatype 6 | number1 = 10.10 # We can directly assign a decimal to a variable 7 | # We can check the datatype of a variable using the type function. So let's verify if the variable number1 is a float or not 8 | print("Type of number1 is", type(number1)) 9 | # We can see that Python is smart enough to make the variable as a float. This is called Dynamically typed. 10 | 11 | # We can also declare a decimal using the float() function 12 | number2 = float(20.20) 13 | # We can see that the variable number2 is a float too. This is called Static typed as we are giving the type before itself 14 | print("Type of number2 is", type(number2)) 15 | 16 | # We can also convert from other datatype to decimal using the float() 17 | number3 = float("30.30") 18 | # Python converts the string to a float. 19 | print("Type of number3 is", type(number3)) 20 | number3 = float(30) 21 | # Python converts the int to a float. 22 | print("Type of number3 is", type(number3)) 23 | 24 | # Floats can be negative decimals too 25 | number4 = -10.10 26 | print("Type of number4 is", type(number4)) 27 | 28 | 29 | # Operations on float 30 | 31 | # Addition: Two floats can be added using the + sign 32 | sum = number1 + number2 33 | print(f'{number1} + {number2} is {sum}') 34 | 35 | # Subtraction: Floats can be subtracted using the - sign 36 | diff = number3 - number2 37 | print(f'{number3} - {number2} is {diff}') 38 | 39 | # Multiplication: Two floats can be multiplied using the * sign 40 | mul = number1 * number2 41 | print(f'{number1} * {number2} is {mul}') 42 | 43 | # Division: Two integers can be divided using the / sign 44 | div = number3 / number1 45 | # Remember the answer is a float too 46 | print(f'{number3} / {number1} is {div}') 47 | 48 | # Remainder: The remainder left when a number is divided by another number can be found using % sign 49 | rem = number3 % 11 50 | # Gives the remainder when number3 is divided by 11 51 | print(f'{number3} % 11 is {rem}') 52 | 53 | # Power: A float can be raised to a power using ** operator 54 | pow = number1 ** 2 55 | # Returns number1 to the power of 2 56 | print(f'{number1} to the power 2 is {pow}') 57 | 58 | 59 | # Printing and formatting floats 60 | 61 | # The number of decimals positions printed while printing a float can be controlled in python 62 | number5 = 1.23456789 63 | # We can use two methods: 64 | # 1) The newer fstrings (Recommended) 65 | # Format: {variable:.nf} where n is the number of decimals to be printed 66 | print(f"{number5:.2f} is {number5} in two decimals using f-string") 67 | 68 | # 2) Using the older format() 69 | # format feeds each of the parameters passed to it into the curly braces sequentially within a string 70 | print("{:.2f} is {} in two decimals using format".format(number5, number5)) 71 | 72 | # ------------------------------------------------------------------------------------------------------------------ 73 | # Challenge 1: Declare two floats and find the sum, difference, product, quotient and remainder of the two numbers 74 | # ------------------------------------------------------------------------------------------------------------------ 75 | 76 | # Add your code here 77 | 78 | # ---------------------------------------- 79 | # Challenge 2: Find the square root of 121 80 | # ---------------------------------------- 81 | 82 | # Add your code here 83 | -------------------------------------------------------------------------------- /using-modules/installing-with-pip.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Learn how to use pip package manager for Python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # What is pip? 6 | # Pip is the most popular package manager for Python. 7 | # A package manager allows you to quickly find, install and update modules for your python project 8 | # It will handle module dependencies and download additional modules as needed. 9 | # Packages can refer to a module or a collection of related modules. 10 | 11 | # Checking if pip is intalled 12 | # pip may be installed on some systems by default. From the command line type: 13 | # pip --version 14 | 15 | # If pip is installed you should see a response similar to: 16 | # pip 18.1 from [installation_path] (python version) 17 | 18 | # Installing pip 19 | # Python has a built in script designed to fetch and install the pip system. 20 | # From the command line run: 21 | # python get-pip.py 22 | # If you are on windows you may need to change this to python.exe 23 | 24 | # Updating pip 25 | # To update pip itself to the latest version you can run 26 | # python -m pip install --upgrade pip 27 | 28 | # Installing packages with pip 29 | # Most popular packages can be found in pip. 30 | # They often give you instructions on what command to run to install the package from pip 31 | # To install a package type: 32 | # pip install 33 | 34 | # Package versions 35 | # pip packages use semantic versioning. 36 | # This is a number like 2.0.0 37 | # Where the first number indicates the major version of the project. If this number changes it means the versions are incompatible with each other 38 | # The second number indicates the minor version. This is used when functionality has been added without breaking compatibility with previous versions 39 | # The third number indicates the patch version. This is used when no functionality has been added but bugs have been fixed. 40 | 41 | # Installing a specific version of a package 42 | # pip allows you to install the latest (default) version of a package or request a specific version 43 | # or a version within a range of versions 44 | # pip install ==0.1.0 # This will install version 0.1.0 45 | 46 | # pip install ~=0.1.0 # This will install the latest version closest to 0.1. For example if 0.1.0 and 0.1.5 both exist it will choose 0.1.5. 47 | 48 | # To install a version within a range of acceptable versions: 49 | # pip install >=0.1.0<0.2 50 | # This will install a suitable version between 0.1 and less than 0.1.*. 51 | # Wildcard operators can also be used 52 | # pip install ==0.1.* will install any available version from the same minor version, it should usually be the latest bugfix patch. 53 | 54 | # Updating packages with pip 55 | # To update a package to the latest version use the following line: 56 | # pip install --upgrade 57 | 58 | # ------------------------------------------------------------------------------------ 59 | # Challenge: Try to install the pillow package then uncomment all the code below and 60 | # run the file. 61 | # Pillow is a Python fork of the PIL image manipulation library. At time of writing 62 | # The version installed should be around 8.0.1. 63 | 64 | # Make sure you run the file from the /using-modules folder otherwise Python won't 65 | # be able to find the image file to edit. 66 | # Upon successfully running the python file you should see a new image in the 67 | # /using-modules folder called inverted.jpg where the colours have been inverted. 68 | # Image source: https://search.creativecommons.org/photos/519f445f-4987-4487-a927-4d7117c53096 69 | # Image license: Public Domain 70 | # ------------------------------------------------------------------------------------ 71 | 72 | # from PIL import Image 73 | # from PIL import ImageChops 74 | 75 | # with Image.open("image.jpg") as im: 76 | # inverted_img = ImageChops.invert(im) 77 | # inverted_img.save("inverted.jpg") 78 | -------------------------------------------------------------------------------- /dictionaries/using-dictionaries-advanced.py: -------------------------------------------------------------------------------- 1 | # ------------------------------------------------------------------------------------ 2 | # Tutorial: Learn how to use Dictionaries in Python 3 | # ------------------------------------------------------------------------------------ 4 | 5 | # Defining a more advanced dictionary 6 | # You can define an empty dictionary by leaving the space between the curly brackets blank 7 | my_dict = {} 8 | 9 | # As stated in the basic tutorial values can be of any type. This includes lists and tuples 10 | my_dict['some_collection'] = [5, 6, 7, 8] 11 | my_dict['tuple_trouble'] = ('bread', 'eggs', 'milk',) 12 | 13 | # To access the value of a list or tuple stored in the dictionary you can use 14 | # dict[key][index] 15 | print("Value of first element of some_collection: " + str(my_dict['some_collection'][0])) 16 | print("Value of third element of tuple_trouble: " + str(my_dict['tuple_trouble'][2])) 17 | print("") 18 | 19 | # They can even be other dictionaries 20 | my_dict['some_child'] = { 21 | 'name': 'Jeremy', 22 | 'sibling': 'Beth', 23 | 'occupation': 'child', 24 | } 25 | # To retrieve the name of some_child use dict[key][key] 26 | print("some_child name is " + str(my_dict['some_child']['name'])) 27 | print("") 28 | 29 | # Checking if a key exists 30 | if 'my_key' in my_dict.keys(): # dict.keys() returns a list of all keys in the dictionary 31 | print("Key exists\n") 32 | 33 | # How to remove a key 34 | del my_dict['some_child'] # This will throw an error if the key doesn't exist 35 | # A better approach would be to check if the key exists first using the above method 36 | if 'some_child' in my_dict.keys(): 37 | del my_dict['some_child'] 38 | print("Key removed\n") # This will not be printed as we already deleted the key with del 39 | else: 40 | print("Can't delete key, it doesn't exist\n") 41 | 42 | # To remove a key and retrieve its value you can use dictionary.pop() 43 | # Using the optional second argument for pop will prevent it throwing a key error if the key doesn't exist 44 | fred = my_dict.pop('fred', None) # Returns the value of the removed key or None if the key doesn't exist 45 | print("Fred is " + str(fred)) # Will print 'Fred is None' 46 | 47 | # Count the number of items (key-value pairs) in the dictionary 48 | size = len(my_dict) 49 | print("\nSize of my_dict: " + str(size)) # Should print 2 50 | print("") 51 | 52 | # You can add one dictionary to another using dictionary.update() 53 | new_dict = { 54 | 'address': '221b Baker Street', 55 | 'owner': 'Holmes', 56 | } 57 | my_dict.update(new_dict) 58 | print("Updated dictionary " + str(my_dict)) 59 | 60 | # ------------------------------------------------------------------------------------ 61 | # Challenge: You are in charge of creating an RPG character for a game. 62 | # Add a key to to the player dictionary called inventory and assign it an array of items 63 | # 'sword', 'waterskin', 'bedroll' 64 | # Define a new dictionary called stats with key pairs as below 65 | # 'hp': 10, 'dexterity': 1, 'strength': 3 66 | # and update the player dictionary with it. 67 | # Call use_item() with the id for 'waterskin' 68 | # It should print "Using item waterskin" 69 | # ------------------------------------------------------------------------------------ 70 | 71 | def use_item(id): 72 | inv = player.get('inventory', []) 73 | if len(inv) > 0: 74 | print("Using item " + str(inv[id])) 75 | else: 76 | print("No inventory") # Your solution is incorrect if you see this line printed 77 | 78 | player = { 79 | 'name': 'the hero', 80 | 'level': 10, 81 | 'xp': 3250, 82 | } 83 | 84 | # Define and add inventory here 85 | 86 | print("\nPlayer dictionary") 87 | print(player) # Should print "{'name': 'the hero', 'level': 10, 'xp': 3250}"" 88 | 89 | # Define stats and update player here 90 | 91 | print("\nUpdated player dictionary") 92 | print(player) # Should print "{'name': 'the hero', 'level': 10, 'xp': 3250, 'inventory': ['sword', 'waterskin', 'bedroll'], 'hp': 10, 'dexterity': 1, 'strenth': 3}"" 93 | 94 | # Call use_item() here 95 | -------------------------------------------------------------------------------- /operators/assigning.py: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------- 2 | # Tutorial: Assignment operators 3 | # ----------------------------------------------------------------------------- 4 | 5 | # The assignment operators are the most important for any program, as they are 6 | # the way to store a value we want to work with. Said value will be stored in a 7 | # variable where we will be able to perform read and write operations. 8 | 9 | # The following lines shows the most basic assignment: 10 | var = 1 11 | # Now the variable called `var` contains the value `1` and allows us to perform 12 | # actions with it, such as performing arithmetic operations or comparisons: 13 | print(var + 4) # 5 14 | print(var == 1) # True 15 | 16 | # The expression on the right of the assignment will be evaluated before 17 | # assigning the value to the target. That means that we can have the variable 18 | # on both sides of the statement, because it's value will be first read (right) 19 | # and later updated (left). For example: 20 | var = var + 2 21 | # In this case, `var` has an original value of 1 (var = 1). In the above 22 | # statement, the expression is first calculated (1 + 2) and the result (3) is 23 | # then assigned to `var`. 24 | print(var) # 3 25 | 26 | 27 | # ARITHMETIC AND BITWISE ASSIGNMENTS 28 | 29 | # There are more assignment operators that intend to shorten a small operation 30 | # on the variable and then an assignment to itself. As an example, the 31 | # following line will do the same as the one above: 32 | var += 2 # var = var + 2 33 | # These kind of assignments always add the target variable on the left side of 34 | # the operation. 35 | 36 | # There are a certain amount of operations with this kind of shortcut. 37 | # Arithmetic assignments: 38 | var += 10 # var = var + 10 39 | var -= 10 # var = var - 10 40 | var *= 10 # var = var * 10 41 | var /= 10 # var = var / 10 42 | var %= 10 # var = var % 10 43 | var //= 10 # var = var // 10 44 | var **= 10 # var = var ** 10 45 | 46 | var = 1 47 | # Bitwise assignments: 48 | var &= 10 # var = var & 10 49 | var |= 10 # var = var | 10 50 | var ^= 10 # var = var ^ 10 51 | var >>= 10 # var = var >> 10 52 | var <<= 10 # var = var << 10 53 | # The variable is always the last part of the expression to be evaluated. That 54 | # means that if on the right side there's an operation, the operation on the 55 | # variable will not be done after that is complete. For example: 56 | var = 2 57 | var *= 3 + 2 58 | # The command above equals to `var * (3 + 2)` and not to `var * 3 + 2`. The 59 | # assignment operator has the least priority of all the operators. 60 | 61 | 62 | # TYPING IN ASSIGNMENTS 63 | 64 | # In Python, variables are not strongly typed, which means that they can change 65 | # their type with every assignment. 66 | var = 1 67 | print(type(var)) # 68 | var = 'string' 69 | print(type(var)) # 70 | 71 | 72 | # CHAINED ASSIGNMENT 73 | 74 | # On simple assignments `=`, multiple variables can be assigned the same 75 | # value in the same line, for instance: 76 | var = var2 = 3 77 | print(var, var2) # 3 3 78 | 79 | 80 | # ASSIGNING TUPLES 81 | 82 | # When working with tuples it's important to know that its values can be 83 | # unpacked in different variables with an assignment: 84 | tup = (1, 2, 3) 85 | a, b, c = tup 86 | print(tup[1]) # 2 87 | print(b) # 2 88 | # Of course, this can be used to assign different values to different values 89 | # on the same line, such as: 90 | value1, value2 = 10, 2 91 | print(value1) # 10 92 | print(value2) # 2 93 | 94 | 95 | # WALRUS OPERATOR 96 | 97 | # On Python 3.8 the walrus operator `:=` was introduced. Said operator allows 98 | # to perform an assignment during the evaluation an expression. 99 | # This allows us to, instead of performing an operation, assigning it to a 100 | # variable (to later reuse it) and evaluating the result in 2 different lines, 101 | # it can be done in one. 102 | # Without the walrus operator: 103 | result_no_walrus = value1 + value2 104 | if result_no_walrus > 10: 105 | print(result_no_walrus) # 12 106 | # With the walrus operator: 107 | if (result_with_walrus := value1 + value2) > 10: 108 | print(result_with_walrus) # 12 109 | 110 | # ----------------------------------------------------------------------------- 111 | # Challenge: Starting with the tuple (5, 10, 15) get the result of adding each 112 | # value multiplied by its position in a single variable ONLY using assignment 113 | # operators. (That's to say: 5 * 1 + 10 * 2 + 15 * 3) 114 | # ----------------------------------------------------------------------------- 115 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to TeachMePythonLikeIm5 2 | 3 | All inputs are welcome! 4 | 5 | ## This repo is part of the [inspirezone.tech](https://inspirezone.tech) portfolio of projects located on our [Github page](https://github.com/inspirezonetech) 6 | 7 | Inspirezone is an online tech blog and community that focuses on encouraging developers of all levels of experience to improve their skills through online collaboration. 8 | 9 | Consider [joining the inspirezone community here!](https://community.inspirezone.tech/) 10 | You don't have to join to contribute to this project. However, joining will give you a number of advantages such as: 11 | - You can join our Github community page 12 | - Have discussions with other members of our community 13 | - Be part of an accountability group that will encourage you to code more 14 | - Potentially become a project maintainer 15 | - Get notified of other projects and activities within our community 16 | - It's fun to improve your skills by working with others! 17 | 18 | ## Please make sure you are assigned to an [Issue](https://github.com/inspirezonetech/TeachMePythonLikeIm5/issues) before submitting a pull request 19 | 20 | Go to the [issue](https://github.com/inspirezonetech/TeachMePythonLikeIm5/issues) page and either 21 | - Request to be assigned to an existing issue 22 | - Create your own issue and use one of the templates provided. Wait for approval and to be assigned the issue before submitting a pull request 23 | 24 | **Note:** You can only be assigned to one issue at a time. Please clear your assigned issue before requesting to be assigned to another. 25 | 26 | ## Contributions you can make to this project 27 | 28 | - Add a tutorial 29 | - Improve an existing tutorial 30 | - Report a bug or problem with the repo or a tutorial 31 | - Suggest a tutorial 32 | - Help with documentation 33 | - Make any suggestion for improvement 34 | 35 | ## Guidelines for submitting a tutorial 36 | 37 | - Tutorial should explain a *BASIC* concept of python 38 | - Each tutorial should be a ".py" file and should be executable 39 | - Each tutorial should come with a challenge that can be verified through a print of the expected result/results to console 40 | - All folders and files should be named using lower cases with words separated by '-' e.g. *for-loops.py* 41 | - Please use the following template for each tutorial: 42 | ``` 43 | # ------------------------------------------------------------------------------------ 44 | # Tutorial: brief description of tutorial content 45 | # ------------------------------------------------------------------------------------ 46 | 47 | # Code here explaining concept with comments to guide 48 | 49 | # ------------------------------------------------------------------------------------ 50 | # Challenge: list challenges to be completed here. minimum of one challenge per tutorial 51 | # ------------------------------------------------------------------------------------ 52 | 53 | ``` 54 | 55 | ### **Feel free to be as creative as you want when coming up with challenges!** 56 | 57 | ## Use [flake8]((https://flake8.pycqa.org/en/latest/)) linting to ensure format of code is consistent with repo 58 | 59 | Run flake8 on your python file before submitting. 60 | 61 | The following flake8 errors can be excluded 62 | - `E302 expected 2 blank lines, found 1` 63 | - `expected 2 blank lines after class or function definition, found 1 flake8(E305)` 64 | - `line too long (x > x characters) flake8(E501)` 65 | 66 | How to run flake8 using command line: 67 | ``` 68 | python -m pip install flake8 69 | 70 | # runs flake8 and ignores the 3 errors 71 | flake8 path/to/code/to/check.py --ignore E302,E305,E501 72 | ``` 73 | 74 | ## How to submit your code - step by step guide 75 | 76 | Please use pull requests. See the [Github docs](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/proposing-changes-to-your-work-with-pull-requests) for details on how pull requests work. 77 | 78 | Steps to make your contribution: 79 | 80 | ### 1. Fork this repo 81 | 82 | ### 2. Clone it locally 83 | 84 | ### 3. Add this repo as the remote upstream and keep it synced by pulling from upstream 85 | ``` 86 | git remote add upstream https://github.com/inspirezonetech/TeachMePythonLikeIm5.git 87 | 88 | git pull upstream main 89 | ``` 90 | 91 | ### 4. Create a new branch and checkout to the branch 92 | ``` 93 | git checkout -b your-branch 94 | ``` 95 | 96 | ### 5. Make your changes and test it works 97 | 98 | ### 6. Commit your changes 99 | ``` 100 | git commit -m "commit message describing change" 101 | ``` 102 | 103 | ### 7. Push to your Fork 104 | ``` 105 | git push origin your-branch 106 | ``` 107 | 108 | ### 8. Go to your Fork on Github and create a pull request to this repo on Github. Fill in the PR submission form. 109 | 110 | ### 9. If needed, respond to code review comments and feedback 111 | 112 | ### 10. If all goes well, your changes will be merged. Congrats! 113 | 114 | ## License 115 | 116 | By contributing, you agree that your contributions will be licensed under its MIT License. 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TeachMePythonLikeIm5 2 | ![GitHub top language](https://img.shields.io/github/languages/top/inspirezonetech/TeachMePythonLikeIm5) 3 | ![GitHub contributors](https://img.shields.io/github/contributors/inspirezonetech/TeachMePythonLikeIm5) 4 | ![GitHub issues](https://img.shields.io/github/issues-raw/inspirezonetech/TeachMePythonLikeIm5) 5 | ![GitHub Workflow Status](https://img.shields.io/github/workflow/status/inspirezonetech/TeachMePythonLikeIm5/python-flake8-linter-run?label=lint) 6 | 7 | 8 | *You are welcome to contribute to this repo. See the [**CONTRIBUTING.md**](./CONTRIBUTING.md) for more info* 9 | 10 | 11 | 12 | ![TeachMePythonLikeIm5](https://inspirezone.tech/wp-content/uploads/2020/10/TeachMePythonLikeIm5-1024x512.png) 13 | ## About this repo 14 | 15 | A collection of super beginner friendly tutorials and challenges to teach the python programming language. 16 | Each file contains: 17 | - A tutorial explaining a concept in python 18 | - A challenge or set of challenges to complete 19 | 20 | ## List of available tutorials 21 | 22 | | Tutorial | Link | 23 | |-------------------------------------------|----------------------------------------------------------------| 24 | | **Getting started** | 25 | |Your first python program | [hello-world.py](getting-started/hello-world.py) | 26 | |Commenting | [commenting.py](getting-started/commenting.py) | 27 | | **Variables** | 28 | |How variables work | [creating-variables.py](variables/creating-variables.py) | 29 | |Booleans | [booleans.py](variables/booleans.py) | 30 | |Integers | [integers.py](variables/integers.py) | 31 | |Floats | [floats.py](variables/floats.py) | 32 | |Strings | [strings.py](variables/strings.py) | 33 | | **Operators** | 34 | |How operators work | [arithmetic.py](operators/arithmetic.py) | 35 | |Assigning | [assigning.py](operators/assigning.py) | 36 | |Comparison | [comparison.py](operators/comparison.py) | 37 | | **Lists** | 38 | |How to alter a list | [alterning-lists.py](lists/altering-lists.py) | 39 | |How to declare a list | [declaring-lists.py](lists/declaring-lists.py) | 40 | |How to index a list | [indexing-lists.py](lists/indexing-lists.py) | 41 | |List comprehension | [list-comprehension.py](lists/list-comprehension.py) | 42 | | **Conditions** | 43 | |How to make conditions | [if-else.py](conditions/if-else.py) | 44 | | **Loops** | 45 | |How for-loop works | [for-loops.py](loops/for-loops.py) | 46 | |How while-loop works | [while-loops.py](loops/while-loops.py) | 47 | |How to break in a loop | [using-break.py](loops/using-break.py) | 48 | |How to continue in a loop | [using-continue.py](loops/using-continue.py) | 49 | |How to pass in a loop | [using-pass.py](loops/using-pass.py) | 50 | | **Functions** | 51 | |How to declare and call functions | [using-functions.py](functions/using-functions.py) | 52 | |How to make a recursive functions | [recursive_func.py](functions/recursive_func.py) | 53 | |How to make a lambda functions | [lambda-functions.py](functions/lambda-functions.py) | 54 | | **Common built-in functions** | 55 | |How enumerate works | [enumerate.py](common-built-in-functions/enumerate.py) | 56 | |How input works | [input.py](common-built-in-functions/input.py) | 57 | |How join works | [join.py](common-built-in-functions/join.py) | 58 | |How len works | [len.py](common-built-in-functions/len.py) | 59 | |How range works | [range.py](common-built-in-functions/range.py) | 60 | |How replace works | [replace.py](common-built-in-functions/replace.py) | 61 | | **Exceptions** | 62 | |How exception works | [exceptions.py](exceptions/handling-exceptions.py) | 63 | | **Using modules** | 64 | |How modules work | [importing-modules.py](using-modules/importing-modules.py) | 65 | |How pip works | [installing-with-pip.py](using-modules/installing-with-pip.py) | 66 | |How to create modules | [creating-modules.py](using-modules/creating-modules.py) | 67 | |How to use virtual environments | [using-virtual-environments.py](using-modules/using-virtual-environments.py)| 68 | | **File handling** | 69 | |How to delete a file | [deleting-files.py](file-handling/deleting-files.py) | 70 | |How to read a file | [reading-files.py](file-handling/reading-files.py) | 71 | |How to scan a file | [scanning-files.py](file-handling/scanning-files.py) | 72 | |How to write a file | [writing-files.py](file-handling/writing-to-files.py) | 73 | | **Dictionaries** | 74 | |How to iterate over a dictionary | [iterating-over-dictionaries.py](dictionaries/iterating-over-dictionaries.py)| 75 | |Basic tutorial on dictionaries | [using-dictionaries-basic.py](dictionaries/using-dictionaries-basic.py) | 76 | |Advanced tutorial on dictionaries | [using-dictionaries-advanced.py](dictionaries/using-dictionaries-advanced.py)| 77 | | **Decorators** | 78 | |How to use decorator | [timer.py](decorators/timer.py) | 79 | | **Sets** | 80 | |How to create a set | [creating-sets.py](sets/creating-sets.py) | 81 | |How to modify a set | [modify-sets.py](sets/modify-sets.py) | 82 | |How to remove set elements | [remove-set-elements.py](sets/remove-set-elements.py) | 83 | | **String formatting** | 84 | |How to use f-strings | [fstrings.py](string-formatting/fstrings.py) | 85 | | **Tuples** | 86 | |Basic tuples | [tuples-basic.py](tuples/tuples-basic.py) | --------------------------------------------------------------------------------