From 2996901993a0e16cb27465a3ea356bc0e8323ad6 Mon Sep 17 00:00:00 2001 From: razorblade23 <81590614+razorblade23@users.noreply.github.com> Date: Wed, 23 Sep 2026 12:15:38 +0200 Subject: [PATCH 1/3] Updated "assigment" to first 3 lessons containing it --- curriculum/03-git-basics/03-git-basics.md | 31 ++++++++++--- .../01-output-variable-datatypes.md | 35 +++++++-------- .../02-math-stringops-comparisons.md | 44 ++++++++++++------- .../03-user-input-and-conditionals.md | 37 ++++++++++------ curriculum/04-python-foundations/04-loops.md | 12 ++--- 5 files changed, 101 insertions(+), 58 deletions(-) diff --git a/curriculum/03-git-basics/03-git-basics.md b/curriculum/03-git-basics/03-git-basics.md index 462b6cf..037c2b4 100644 --- a/curriculum/03-git-basics/03-git-basics.md +++ b/curriculum/03-git-basics/03-git-basics.md @@ -25,11 +25,24 @@ Before starting with commands, it's useful to get to know ourself with some word * **Commit**: A snapshot of your code at the time of creating **commit**. Commits are what allow you to undo your changes to any older commit at any time. * **Branch**: A parallel codebase for you to experiment with and build new features without affecting the **main** branch * **Pull Request (PR)**: When work on the branch is finished, you issue a pull request to your *main* branch so changes can be *merged*. -* **Remote**: A copy of your repository NOT on your local machine (etc.: *Github*) +* **Remote**: A copy of your repository NOT on your local machine (etc.: *GitHub*) + +:::tip +Do not worry about what these words mean just yet or try to remember it all. We will use `git` commonly throuout the course, and you will get plenty of exercise in using it. +::: +## Assignment {#assignment} +1. To keep things organized while you work on projects, choose a directory on your local computer where you will store all of them and `cd` into it. For example create a directory called `Projects` in your `Documents` directory. For the rest of the course, we will assume your `Projects` directory has the following path: `~/Documents/Projects`. +2. Now we need to create a directory which we will use to store our **assigment** project which we will evolve after each lesson. Create a new directory by executing `mkdir simple-bookstore`, then `cd` into it by executing `cd simple-bookstore`. +3. We need to tell `git` to start tracking changes in our directory, which is called **initialization**. Run `git init` command to let `git` know that you want to start tracking this directory. +4. Now we will create our first file: `README.md`. This file serves as description of your project and usually contains information on running your projects. We will not worry about this now, just open your code editor in that directory by executing `code .` command (**NOTE:** don't forget the dot `.` at the end of the command). Create a new file with the name `README.md` and write some content in it, like: + ``` + This is the start of my python journey! + ``` + Or whatever contents you want. ## Assignment {#assignment} 1. Choose a directory on your local computer where you will store all of your projects and `cd` into it. For example create a directory called `Projects` in your `Documents` directory. For the rest of the course, we will assume your `Projects` directory has the following path: `~/Documents/Projects`. -2. Create a new directory by executing `mkdir simple-python-shop`, then `cd` into it by executing `cd simple-python-shop`. +2. Create a new directory by executing `mkdir simple-bookstore`, then `cd` into it by executing `cd simple-bookstore`. 3. Initialize `git` repository by executing `git init` command. This tells `git` to start tracking for changes in our directory. 4. Let's create a `README.md` file as every good repository should have one. Open your code editor in that directory by executing `code .` command (**NOTE:** don't forget the `.` at the end of the command). Create a new file with the name `README.md` and write some content in it, like: ``` @@ -39,10 +52,18 @@ Before starting with commands, it's useful to get to know ourself with some word 5. Let's check the status of our repository by executing `git status` command. You will see your `README.md` in the section **untracked files**. This means `git` knows about your file, but it's not part of the snapshot it will create, so let's fix that in the next step. 6. By executing `git add README.md` we say to `git` that we want to add that file to **staging area** which is like a space where git is aware of your files and which will be included in the snapshot (commit). Like saying a photographer to line up and frame the shot. Now we take the actuall snapshot (commit) in the next step. 7. Execute `git commit -m "Add README file with initial content"` command which tells `git` to make the actuall snapshot (or **commit**). `-m` stands for **message** and its **required** in *commit* command, and not supplying it will open your default terminal text editor to enter the message. Message should be short but descriptive note explaining what you changed and why. -8. Now let's upload our files to *Github* (or **push** the changes we made). First we need to create a repository in our *Github*. Go to [github.com/new](https://github.com/new) and enter the name for your new remote repository. You can use the same name as your local directory: `simple-python-shop`. Then choose visibility setting (public or private). **DO NOT** create files *Github* offers: *README*, *.gitignore*, *license*; we will do these manually. Click on the green *Create repository* button. -9. Github will offer varius ways of getting things done, but the main thing you should be looking for is the command starting with `git remote add origin`. Copy that whole line and paste it in your terminal (be sure you are in our current directory (`simple-python-shop`)). The line should look something like `git remote add origin https://github.com/your-username/simple-python-shop.git`. Execute the command to add our remote repository as **remote** to our current git repository, so we can **push** the changes we made to online repository. +8. Now let's upload our files to *Github* (or **push** the changes we made). First we need to create a repository in our *Github*. Go to [github.com/new](https://github.com/new) and enter the name for your new remote repository. You can use the same name as your local directory: `simple-bookstore`. Then choose visibility setting (public or private). **DO NOT** create files *Github* offers: *README*, *.gitignore*, *license*; we will do these manually. Click on the green *Create repository* button. +9. Github will offer varius ways of getting things done, but the main thing you should be looking for is the command starting with `git remote add origin`. Copy that whole line and paste it in your terminal (be sure you are in our current directory (`simple-bookstore`)). The line should look something like `git remote add origin https://github.com/your-username/simple-bookstore.git`. Execute the command to add our remote repository as **remote** to our current git repository, so we can **push** the changes we made to online repository. 10. Now run `git push -u origin main` to send files to your *remote* we just added in the previus step. The `-u` flag is used only **first time** you push to set up *tracking connections* so in later pushes, we can just do `git push`. -11. Check your *Github* for pushed code. You should see your `README.md` sitting there on your repository view. Congratulations! You’ve just mastered the fundamental workflow of Git and GitHub. +11. Check your *Github* for pushed code. You should see your `README.md` sitting there on your repository view. Congratulations! You've just mastered the fundamental workflow of Git and GitHub. + +:::tip +In the above step 6, we executed `git add README.md`. This is fine when you have a few files to add to staging area, but what if there are dozens, or hundreds? + +Git helps us out with `git add .` (notice the dot `.`) which will add **all** unstaged files to staging area. + +This may not be what you always want, but it is a nice shortcut. +::: ## What's Next {#next-lesson} We are finally done with introductions and essential setup so we can start with python lessons. Let's learn. \ No newline at end of file diff --git a/curriculum/04-python-foundations/01-output-variable-datatypes.md b/curriculum/04-python-foundations/01-output-variable-datatypes.md index 24ce11b..42ec9b7 100644 --- a/curriculum/04-python-foundations/01-output-variable-datatypes.md +++ b/curriculum/04-python-foundations/01-output-variable-datatypes.md @@ -157,29 +157,28 @@ Visit our [python-excercise repository](https://github.com/ThePythonLedger/pytho After cloning, try to solve [excercise-1](https://github.com/ThePythonLedger/python-exercises/tree/main/exercises%2Ffoundations%2F01_hello_world) and [excercise-2](https://github.com/ThePythonLedger/python-exercises/tree/main/exercises%2Ffoundations%2F02_datatypes) for better understanding. ## Assignment {#assignment} -Try the following excercise to establish your knowlege. We will build a shop, starting with defining (declaring) diffrent variables in this lesson and progress with our little shop as we go further along. +Try the following excercise to establish your knowlege. We will build a bookstore, starting with defining (declaring) diffrent variables in this lesson and progress with our little bookstore as we go further along. You will need to do this assignment on your own machine. -1. Create a new directory with the name `simple-python-shop` -2. Navigate inside the newly created directory -3. Instantiate `git` repository -4. Create a new file with the name `main.py` -5. Inside the file define the the following variables: - * `shop_name` - set its value to some **string** - * `item_name` - set its value to some **string** - * `item_quantity` - set its value to some **integer** - * `item_price` - set its value to some **float** - * `item_available` - set its value to some **boolean** -6. Output the variables you defined (using `print()` function) like the following example: +1. Create a new file with the name `main.py` +2. Inside the file define the following variables: + * `bookstore_name` - set its value to some **string** (*eg. `"Willow Creek Books"`*) + * `book_title` - set its value to some **string** (*eg. `"The Last Cartographer"`*) + * `book_quantity` - set its value to some **integer** (*eg. `3`*) + * `book_price` - set its value to some **float** (*eg. `18.5`*) + * `book_available` - set its value to some **boolean** (*eg. `True`*) +3. Output the variables you defined (using `print()` function) like the following example: ``` - Shop name: Merlin Shop - Item name: Excalibur - Item quantity: 3 - Item price: $67.2 - Item available: True + Welcome to Willow Creek Books inventory system. + CURRENT INVENTORY: + - Book: The Last Cartographer -> [price: $18.5, copies: 3, available: True] ``` -7. Make sure your program works as expected then create a repository and push your code to github +4. Make sure your program works as expected then: + * Check *git* status with `git status` command. + * Above command should tell you that your `main.py` is not yet in the staging area, so we need to add it with `git add main.py` command. + * Now that we have our file in staging area, we can finally do a commit with `git commit -m "Added basic variables"` + * Final step is to push the changes to your remote repository, which we can do with `git push` command ## Deepen Your Knowlege Go through these articles to deepen your knowlege about the topics covered in this lesson. diff --git a/curriculum/04-python-foundations/02-math-stringops-comparisons.md b/curriculum/04-python-foundations/02-math-stringops-comparisons.md index d027288..76fb742 100644 --- a/curriculum/04-python-foundations/02-math-stringops-comparisons.md +++ b/curriculum/04-python-foundations/02-math-stringops-comparisons.md @@ -211,28 +211,42 @@ print("not True: ", not True) Try to solve [excercise-3](https://github.com/ThePythonLedger/python-exercises/tree/main/exercises%2Ffoundations%2F03_math_and_comparisons) for better understanding. ## Assignment -In the last assignment we have declared our shop variables and printed the inventory. In this one you are tasked with: -1. Open your code editor in your last project directory `simple-python-shop` +In the last assignment we have declared our bookstore variables and printed the inventory. In this one you are tasked with: + +1. Open your code editor in your last project directory `simple-bookstore` 2. Open `main.py` file we have been working on 3. Standardize your strings: - * Convert `shop_name` to **uppercase** (e.g., `MERLIN SHOP`) - * Convert item name to **titlecase** (e.g., `Excalibur`) + * Convert `bookstore_name` to **uppercase** (e.g., `WILLOW CREEK BOOKS`) + * Convert book title to **capitalised** (e.g., `The last cartographer`) 4. Calculate the checkout price: - * Create variable `total` by multiplying `item_price` and `item_quantity` + * Create variable `inventory_total` by multiplying `book_price` and `book_quantity` 5. Comparison checks: - * Create a boolean `is_large_order` that evaluates whether `item_quantity` is greater then or equal to `3`. + * Modify `book_avilable` so it evaluates whether `book_quantity` is greater than `0`. 6. Update your output to use **f-string** : ``` - Welcome to MERLIN SHOP - -------------------------------- - Item: Excalibur - Purchased: 3 x 67.20 - Total: $201.60 - Large Order: True - -------------------------------- - Thank you for your purchase ! + Welcome to inventory system for WILLOW CREEK BOOKS + - - - - - - - - - - - - - - - - - - - - + CURRENT INVENTORY + - - - - - - - - - - - - - - - - - - - - + Book: The Last Cartographer -> [price:18.5, copies: 3, available: True] + - - - - - - - - - - - - - - - - - - - - + Inventory total: 55.5 + - - - - - - - - - - - - - - - - - - - - + Thank you for using our inventory system. ``` -7. Commit your changes with `git` and push to Github +7. Make sure your program works as expected, then: + * Check your *git* status (`git status`) + * Above command should show that your file `main.py` has changes from the last time. Just run `git commit -m "Added basic receipt"` as we already have `main.py` in our commit from before. + * Finally, `git push` to your remote repository + +:::info +While you are developing our little bookstore, most of your `git` commands will be the same in structure: +* Check status with `git status`. +* Commit changes with `git commit -m ""`. +* Push the changes to remote repository with `git push` + +From now on, we will assume you know what commands to run in order to push the changes to remote repository, so lessons will use a shorter `"Commit and push the changes"` form. +::: ## Deepen Your Knowledge 1. Learn more about [Basic math in Python](https://cs.stanford.edu/people/nick/py/python-math.html#math) from article in **Stanford University**, covering all the topics in this lesson but in a different style and a bit more. diff --git a/curriculum/04-python-foundations/03-user-input-and-conditionals.md b/curriculum/04-python-foundations/03-user-input-and-conditionals.md index 59c2976..7d5f934 100644 --- a/curriculum/04-python-foundations/03-user-input-and-conditionals.md +++ b/curriculum/04-python-foundations/03-user-input-and-conditionals.md @@ -88,22 +88,31 @@ elif age <= 15: ## Assigment Now that you know how to get user input and branch your program using conditional logic (`if`, `elif`, `else`) the code can move away from hardcoded values and become interactive. -**Goal:** use `input()` to collect user choices, cast strings to numbers, and use conditional logic to apply discounts and stock checks. - -1. Open `main.py` file in our `simple-python-shop` project directory. -2. Add a new variable `item_stock` and set it to some integer -3. Interactive input: - * Ask the user for desired `item_quantity` using `input()`. **Don't forget** to cast the string to integer ! -4. Stock & Availability Check - * If `item_quantity` is less or equal to `0` print an error message: `Invalid quantity ordered` - * If `item_quantity` is greater then `item_stock` print `Sorry, we do not have enough stock.` -5. Dynamic discount (conditionals) +1. Open `main.py` file in our `simple-bookstore` project directory. +2. Create a new variable to hold stock count + * `book_stock` - an **int**, for example `3` +3. Now the customer comes in to buy the only book we have at our bookstore, so you must: + * Ask the user (using `input()`) how many books he wants to buy and save that to `book_quantity` variable. **Do not forget** to cast **str** to **int**. +4. We need to check if the customer entered valid order and do we have that much in stock. If any of below conditions is `True` print the warning message to the user and **do not** do calculations or final print. + * `book_quantity` is less or equal to zero + * `book_quantity` is less or equal to `book_stock` +5. Customers have a discount of 10% if their `total` is over `100` * Calculate the total (you should have this from the last lesson) - * If `total` is over `100` apply a **10%** discount (`total * 0.90`) and print: `Discount applied: 10%` - * Otherwise print: `No discount applied` + * If `total` is over `100` apply a **10%** discount (`total * 0.90`) and print: `Discount applied: 10%`, otherwise print: `No discount applied` 6. Receipt Output - * Output the final receipt showing item name, quantity, applied discount state, and final amount due. -7. Commit and push your updated code to Github. + * Output the final receipt showing book title, quantity, applied discount state, and final amount due. + ``` + Welcome to WILLOW CREEK BOOKS + -------------------------------- + Book: The Last Cartographer + Purchased: 3 x 18.50 + No discount applied ! + Total: $55.50 + Bulk Order: True + -------------------------------- + Thank you for your purchase ! + ``` +7. Commit and push your changes. ## Deepen Your Knowledge * Learn more about [Indentation in Python](https://realpython.com/ref/glossary/indentation/) from this **Real Python** article diff --git a/curriculum/04-python-foundations/04-loops.md b/curriculum/04-python-foundations/04-loops.md index 9ff8b79..bc49b82 100644 --- a/curriculum/04-python-foundations/04-loops.md +++ b/curriculum/04-python-foundations/04-loops.md @@ -119,13 +119,13 @@ These statements `break` and `continue` work only in loops. If you try to use th ::: ## Assigment -1. Open `main.py` in your `simple-python-shop` project. -2. Create a new variable named `item_count` and set it to `0` as its initial value. -3. Use a `while` loop to repeatedly prompt the user for an item price. - * If the price entered is 0 break out of the loop - * Otherwise, add the price user entered to `total` and increment `item_count` by 1. +1. Open `main.py` in your `simple-bookstore` project. +2. Create a new variable named `book_count` and set it to `0` as its initial value. +3. Use a `while` loop to ring up a stack of books at checkout: repeatedly prompt for the price printed on the price tag of the next book being scanned (this is a small bookstore without barcode lookup yet, so the cashier reads each tag by hand). + * If the price entered is 0, break out of the loop (no more books to scan) + * Otherwise, add the price entered to `total` and increment `book_count` by 1. 4. When the loop finishes, determine if the `total` can have a discount and print out the final receipt. -5. Make sure your program works, then commit and push your code +5. Make sure your program works, then commit and push changes. ## Deepen Your Knowlege From 65955d8b2ec35eb219955af6f5211602a8a058b2 Mon Sep 17 00:00:00 2001 From: razorblade23 <81590614+razorblade23@users.noreply.github.com> Date: Wed, 23 Sep 2026 18:28:37 +0200 Subject: [PATCH 2/3] Aligned and improved assigment in 03-user-input lesson --- .../02-math-stringops-comparisons.md | 6 +- .../03-user-input-and-conditionals.md | 62 ++++++++++++------- 2 files changed, 42 insertions(+), 26 deletions(-) diff --git a/curriculum/04-python-foundations/02-math-stringops-comparisons.md b/curriculum/04-python-foundations/02-math-stringops-comparisons.md index 76fb742..97b1368 100644 --- a/curriculum/04-python-foundations/02-math-stringops-comparisons.md +++ b/curriculum/04-python-foundations/02-math-stringops-comparisons.md @@ -211,7 +211,7 @@ print("not True: ", not True) Try to solve [excercise-3](https://github.com/ThePythonLedger/python-exercises/tree/main/exercises%2Ffoundations%2F03_math_and_comparisons) for better understanding. ## Assignment -In the last assignment we have declared our bookstore variables and printed the inventory. In this one you are tasked with: +In the last assignment we have declared our bookstore variables and printed the inventory. In this one you are tasked with making code more robust and logical. 1. Open your code editor in your last project directory `simple-bookstore` 2. Open `main.py` file we have been working on @@ -224,11 +224,11 @@ In the last assignment we have declared our bookstore variables and printed the * Modify `book_avilable` so it evaluates whether `book_quantity` is greater than `0`. 6. Update your output to use **f-string** : ``` - Welcome to inventory system for WILLOW CREEK BOOKS + Welcome to WILLOW CREEK BOOKS inventory system - - - - - - - - - - - - - - - - - - - - CURRENT INVENTORY - - - - - - - - - - - - - - - - - - - - - Book: The Last Cartographer -> [price:18.5, copies: 3, available: True] + - Book: The Last Cartographer -> [price:18.5, copies: 3, available: True] - - - - - - - - - - - - - - - - - - - - Inventory total: 55.5 - - - - - - - - - - - - - - - - - - - - diff --git a/curriculum/04-python-foundations/03-user-input-and-conditionals.md b/curriculum/04-python-foundations/03-user-input-and-conditionals.md index 7d5f934..9425777 100644 --- a/curriculum/04-python-foundations/03-user-input-and-conditionals.md +++ b/curriculum/04-python-foundations/03-user-input-and-conditionals.md @@ -85,34 +85,50 @@ elif age <= 15: print(f"{name} is not 15 years old") ``` +:::tip +In below assigment you are tasked with checking some rules and exiting application if any are broken. + +You can use built-in module called `sys` which has some handy functionality to work with our operating system. For now, we are only interested in using its `exit()` functions. It takes in **int** value to provide as **exit code** which other applications can use to interpret whether your program run successfully or failed and in what way. + +It is common to use `0` as **success** and any other positive integer to signify a failure. + +You can use it like this: +```python +import sys +sys.exit(0) # success +sys.exit(1) # failed / error +``` + +We will learn more about built-in, custom and third-party **modules** (called libraries) later in the course. +::: + ## Assigment -Now that you know how to get user input and branch your program using conditional logic (`if`, `elif`, `else`) the code can move away from hardcoded values and become interactive. +Now that you know how to get user input and branch your program using conditional logic the code can move away from hardcoded values and become interactive. 1. Open `main.py` file in our `simple-bookstore` project directory. -2. Create a new variable to hold stock count - * `book_stock` - an **int**, for example `3` -3. Now the customer comes in to buy the only book we have at our bookstore, so you must: - * Ask the user (using `input()`) how many books he wants to buy and save that to `book_quantity` variable. **Do not forget** to cast **str** to **int**. -4. We need to check if the customer entered valid order and do we have that much in stock. If any of below conditions is `True` print the warning message to the user and **do not** do calculations or final print. - * `book_quantity` is less or equal to zero - * `book_quantity` is less or equal to `book_stock` -5. Customers have a discount of 10% if their `total` is over `100` - * Calculate the total (you should have this from the last lesson) - * If `total` is over `100` apply a **10%** discount (`total * 0.90`) and print: `Discount applied: 10%`, otherwise print: `No discount applied` -6. Receipt Output - * Output the final receipt showing book title, quantity, applied discount state, and final amount due. +2. Instead of hardcoding values (`booktore_name`, `book_title`, `book_quantity`, `book_price`) we will ask the user to enter these values using `input()` function. **Remember** that `input()` always returns **str** so we must *cast* the string to desired type (`book_quantity` to **int** and `book_price` to **float**). Replace all of these variables hardcoded values to `input()` function, asking the user to enter the data. +3. Now the system must add some contraints, printing the error message and exiting if any of the rules are broken. Add these below each of the inputs, so that check runs as soon as user enters something. Rules are as follows: + * `bookstore_name` must be between 3 and 20 characters long + * `book_name` must be between 3 and 15 characters long + * `book_quantity` must be positive **integer** (above `0`) + * `book_price` must be positive **float** (above `0.00`) +4. System must now also calculate taxes that depend on the `book_price`, so make another variable `book_tax` and set it to `0`. Then calculate the tax using below rules, assign it to `book_tax` and print out the tax applied. + * If `book_price` is above `5` tax is `3%` (`0.03`) + * If `book_price` is above `10` tax is `5%` (`0.05`) + * If `book_price` is above `18` tax is `10%` (`0.1`) +5. Display inventory listing like this: ``` - Welcome to WILLOW CREEK BOOKS - -------------------------------- - Book: The Last Cartographer - Purchased: 3 x 18.50 - No discount applied ! - Total: $55.50 - Bulk Order: True - -------------------------------- - Thank you for your purchase ! + Welcome to WILLOW CREEK BOOKS inventory system + - - - - - - - - - - - - - - - - - - - - + CURRENT INVENTORY + - - - - - - - - - - - - - - - - - - - - + - Book: The Last Cartographer -> [price:$18.5, tax: 10%, copies: 3, available: True] + - - - - - - - - - - - - - - - - - - - - + Inventory total: $55.5 [VAT: $60.05] + - - - - - - - - - - - - - - - - - - - - + Thank you for using our inventory system. ``` -7. Commit and push your changes. +6. Commit and push your changes. ## Deepen Your Knowledge * Learn more about [Indentation in Python](https://realpython.com/ref/glossary/indentation/) from this **Real Python** article From 82c8128ac401eb496268690899653816a36884b4 Mon Sep 17 00:00:00 2001 From: razorblade23 <81590614+razorblade23@users.noreply.github.com> Date: Mon, 5 Oct 2026 16:27:58 +0200 Subject: [PATCH 3/3] Last update to lesson assigments --- .../03-user-input-and-conditionals.md | 6 ++- curriculum/04-python-foundations/04-loops.md | 41 +++++++++++++++---- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/curriculum/04-python-foundations/03-user-input-and-conditionals.md b/curriculum/04-python-foundations/03-user-input-and-conditionals.md index 9425777..eebfd6b 100644 --- a/curriculum/04-python-foundations/03-user-input-and-conditionals.md +++ b/curriculum/04-python-foundations/03-user-input-and-conditionals.md @@ -88,13 +88,15 @@ elif age <= 15: :::tip In below assigment you are tasked with checking some rules and exiting application if any are broken. -You can use built-in module called `sys` which has some handy functionality to work with our operating system. For now, we are only interested in using its `exit()` functions. It takes in **int** value to provide as **exit code** which other applications can use to interpret whether your program run successfully or failed and in what way. +You can use built-in module called `sys` which has some handy functionality to work with our operating system. For now, we are only interested in using its `exit()` function. It takes in **int** value to provide as **exit code** which other applications can use to interpret whether your program run successfully or failed and in what way. It is common to use `0` as **success** and any other positive integer to signify a failure. +To use other modules, you use `import` keyword, followed by the name of the module. Usually, these are located at the top of the file, before writing your logic. + You can use it like this: ```python -import sys +import sys # once at the top of the file sys.exit(0) # success sys.exit(1) # failed / error ``` diff --git a/curriculum/04-python-foundations/04-loops.md b/curriculum/04-python-foundations/04-loops.md index bc49b82..6c97d98 100644 --- a/curriculum/04-python-foundations/04-loops.md +++ b/curriculum/04-python-foundations/04-loops.md @@ -114,19 +114,42 @@ for item in range(10): :::tip[Both `break` and `continue` work only in loops] -These statements `break` and `continue` work only in loops. If you try to use them outside of the loop you will encounter an error. - +These statements `break` and `continue` work only in loops. If you try to use them outside the loop you will encounter an error. ::: +## `else` In Loops +Both **for** and **while** loops have an optional condition `else` which is used when loop exits *without* hitting a break inside the loop, but the loop exits. Extremly useful and one of the less known Python feature. + +In a `for` loop, the `else` clause is executed after the loop finishes its final iteration, that is, if no break occurred. + +In a `while` loop, it’s executed after the loop’s condition becomes false. + +In either kind of loop, the `else` clause is not executed if the loop was terminated by a `break`. Of course, other ways of ending the loop early, such as a `return` or a `raised exception`, will also skip execution of the `else` clause. + +Let us see this in action: +```python interactive debug +for n in range(2, 10): + for x in range(2, n): + if n % x == 0: + print(n, 'equals', x, '*', n//x) + break + else: + # loop fell through without finding a factor + print(n, 'is a prime number') +``` +Look closely, the `else` clause belongs to the `for` loop, not `if` statement. + ## Assigment 1. Open `main.py` in your `simple-bookstore` project. -2. Create a new variable named `book_count` and set it to `0` as its initial value. -3. Use a `while` loop to ring up a stack of books at checkout: repeatedly prompt for the price printed on the price tag of the next book being scanned (this is a small bookstore without barcode lookup yet, so the cashier reads each tag by hand). - * If the price entered is 0, break out of the loop (no more books to scan) - * Otherwise, add the price entered to `total` and increment `book_count` by 1. -4. When the loop finishes, determine if the `total` can have a discount and print out the final receipt. +2. Create a lock for our application by: + * Create new variable `PIN_CODE` and assign it some integer (*eg. `1234`*). + * Create another variable `UNLOCK_ATTEMPTS` and assign it `3`. + * We need another `correct_pin_code` variable to track the state, so set it to `False` initially. + * Now write a **for** loop that runs `UNLOCK_ATTEMPTS` times + * For each iteration, ask the user to enter PIN code, then check if it is correct and if it is, set `correct_pin_code` to `True`, otherwise `continue` with iteration. + * If the user did not enter correct PIN code in all three iterations, print the message saying that console is locked and exit the application. +3. Write **while** loop that runs while `correct_pin_code` is `True`, then indent the rest of the code so it belongs to that loop. +4. Keep everything else in the loop and replace those `sys.exit()` calls with `continue` so iteration starts over if user enters the wrong information. 5. Make sure your program works, then commit and push changes. -## Deepen Your Knowlege - ## What's Next \ No newline at end of file