12 |
13 | {% endblock %}
--------------------------------------------------------------------------------
/basic_concepts/exercises/variables/variables01.py:
--------------------------------------------------------------------------------
1 | """ The Challenge
2 | Author:
3 | Description: Aling Nena’s Sari-sari store wants a robot that will ask the
4 | customer their total bill and payment amount and tell them their change
5 | (for now, we can allow negative change).
6 | """
7 |
8 | # Build your code below
9 |
--------------------------------------------------------------------------------
/flask/exercises/QuoteSearchEngine/app/static/css/index.css:
--------------------------------------------------------------------------------
1 | @import url(http://fonts.googleapis.com/css?family=Amatic+SC:700);
2 |
3 | body{
4 | text-align: center;
5 | }
6 | h1{
7 | font-family: 'Amatic SC', cursive;
8 | font-weight: normal;
9 | color: #8ac640;
10 | font-size: 2.5em;
11 | }
--------------------------------------------------------------------------------
/flask/exercises/RandomQuoteGenerator/app/static/css/index.css:
--------------------------------------------------------------------------------
1 | @import url(http://fonts.googleapis.com/css?family=Amatic+SC:700);
2 |
3 | body{
4 | text-align: center;
5 | }
6 | h1{
7 | font-family: 'Amatic SC', cursive;
8 | font-weight: normal;
9 | color: #8ac640;
10 | font-size: 2.5em;
11 | }
--------------------------------------------------------------------------------
/flask/exercises/QuoteSearchEngine/app/templates/layout.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Quote Generator
7 |
8 |
9 |
10 |
11 | {% block body %}{% endblock %}
12 |
13 |
14 |
--------------------------------------------------------------------------------
/flask/exercises/RandomQuoteGenerator/app/templates/layout.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Random Quote Generator
7 |
8 |
9 |
10 |
11 | {% block body %}{% endblock %}
12 |
13 |
14 |
--------------------------------------------------------------------------------
/basic_concepts/samples/explain_me.py:
--------------------------------------------------------------------------------
1 | num1 = 20000
2 | num2 = 5000
3 | num3 = 500
4 | num4 = 100
5 | num5 = 500
6 | num6 = 200
7 |
8 | final = num1 + num2 + (num3 - num4) - num5 - num6
9 | print(f'The output is: {final}')
10 |
11 | # Can you explain what this code does?
12 | # As a developer, what makes this code hard for you to read?
13 |
14 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/lists/list.py:
--------------------------------------------------------------------------------
1 | # Write a program that accepts 3 integers and separate these into odd and even numbers.
2 | # Duplicates are permited in the input but not in the output.
3 |
4 | # Example
5 |
6 | # >>> Enter first number: 3567
7 | # >>> Enter second number: 789
8 | # >>> Enter third number: 1234
9 | # odd: {789, 3567}
10 | # even: {1234}
11 |
--------------------------------------------------------------------------------
/flask/exercises/QuoteSearchEngine/app/templates/search.html:
--------------------------------------------------------------------------------
1 | {% extends "layout.html" %}
2 |
3 | {% block body %}
4 |
5 |
6 |
Search Results
7 |
You searched for: {{ search.upper() }}
8 |
9 | {% for result in results %}
10 |
{{ result }}
11 | {% endfor %}
12 |
13 |
14 |
15 | {% endblock %}
--------------------------------------------------------------------------------
/challenge_partial.md:
--------------------------------------------------------------------------------
1 | > Share your work and contribute to the community! Complete how-to share your work instruction [here](getting_started/exercise_upload_step.md).
2 |
3 | > Present your work in front (#ApplaudHer)! You can also share your study group experience in social media and tag us!
4 |
5 | > Feeling crazy? Chat us on [](https://gitter.im/WWCodeManila/Python)
6 |
7 | > Enjoy!
8 |
--------------------------------------------------------------------------------
/basic_concepts/samples/my_strings.py:
--------------------------------------------------------------------------------
1 | firstname = "Adam"
2 | lastname = "Dough"
3 | # We can access each character by using []
4 | # Each character in a string is represented by an index number
5 | # starting from 0
6 | print(firstname[0], firstname[1])
7 | print(lastname[0], lastname[1])
8 |
9 | # TRY TO PRINT THE LAST CHARACTER
10 | #
11 | # TRY TO PRINT AN INDEX GREATER THAN THE LENGTH BY UNCOMMENTING THE CODE BELOW
12 | # firstname[10]
13 |
--------------------------------------------------------------------------------
/resources/references.md:
--------------------------------------------------------------------------------
1 | ## Official Documentation
2 |
3 | - [Official Home of Python Programming Language](https://www.python.org/)
4 |
5 | ## Helpful Tutorial
6 | - [Codecademy](https://www.codecademy.com/)
7 | - [Coursera](https://www.coursera.org/)
8 |
9 | ## Having a Geeky Love Affair with Python
10 | - [100+ Python challenging programming exercise](https://github.com/zhiwehu/Python-programming-exercises)
11 | - [HackerRank](https://www.hackerrank.com)
12 | - [CheckIO](https://checkio.org/)
13 | - [CodeFights](https://codefights.com/)
14 | - [CodingGame](https://www.codingame.com/)
--------------------------------------------------------------------------------
/getting_started/samples/first_python_code.py:
--------------------------------------------------------------------------------
1 | # Basic example on how to print
2 | # text using different approach in
3 | # Python.
4 |
5 | organization = 'WomenWhoCode!'
6 |
7 | # You can print it right away!
8 | print('Hello WomanWhoCode!')
9 |
10 | # Example of string concatenation
11 | print('Hello ' + organization)
12 |
13 | # Using .format() function to attach a string
14 | print('Hello {}'.format(organization))
15 | # print(f'Hello {organization}') # Can use this format with Python3.6
16 |
17 | # First, replace the following text with your name
18 | your_name = ''
19 |
20 | # Then, uncomment the next line by removing the "#" sign
21 | #print('{} loves Python!'.format(your_name))
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "flask/exercises/portfolio-url-routes"]
2 | path = flask/exercises/portfolio-url-routes
3 | url = https://github.com/alyssonalvaran/portfolio-url-routes
4 | [submodule "flask/exercises/portfolio-templates-and-variables"]
5 | path = flask/exercises/portfolio-templates-and-variables
6 | url = https://github.com/alyssonalvaran/portfolio-templates-and-variables
7 | [submodule "flask/exercises/portfolio-hello-world"]
8 | path = flask/exercises/portfolio-hello-world
9 | url = https://github.com/alyssonalvaran/portfolio-hello-world
10 | [submodule "flask/exercises/portfolio-sqlite3"]
11 | path = flask/exercises/portfolio-sqlite3
12 | url = https://github.com/alyssonalvaran/portfolio-sqlite3
13 |
--------------------------------------------------------------------------------
/ren'py/readme.md:
--------------------------------------------------------------------------------
1 | Repo to be merged into [WWCode Manila Python Study Group](https://wwcodemanila.github.io/WWCodeManila-Python/#/) page.
2 |
3 | This is a collaboration between the WWCode Manila Python :snake:, and Game Development :video_game: Study Groups.
4 |
5 | The following should go inside `_sidebar.md` in our docsify.
6 |
7 | - Ren'Py
8 |
9 | - [Introduction](introduction.md)
10 | - [Installation and setting up](installation.md)
11 | - [Creating a new game](create-new-game.md)
12 | - [Aling Nena VN](aling-nena-vn.md)
13 | - [Tutorial Part 1](scene1.md)
14 | - [Tutorial Part 2](scene2.md)
15 | - [Tutorial Part 3](scene3.md)
16 | - [Tutorial Part 4](scene4.md)
17 | - [Tutorial Part 5 - Ending](scene567.md)
18 |
19 | [Sample game](game/), draft only.
20 |
21 |
--------------------------------------------------------------------------------
/wwcodemanila/about.md:
--------------------------------------------------------------------------------
1 | [Women Who Code](https://www.womenwhocode.com) is a global non-profit organization dedicated to inspiring women to excel in technology careers. We work to support this generation of technology professionals in being and becoming leaders and role models in the tech industry.
2 |
3 | 
4 |
5 | ## Our Mission
6 |
7 | Inspiring women to excel in technology careers.
8 |
9 | ## Our Vision
10 |
11 | A world where women are representative as technical executives, founders, VCs, board members and software engineers.
12 |
13 | ## Manila Chapter
14 |
15 | [Women Who Code Manila](http://manila.womenwhocode.com/) started on January 21, 2017. We have conducted a lot of events like study groups, hackathon, fireside chat, etc to achieve our mission of inspiring women in the tech industry.
16 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/loops/loops01.py:
--------------------------------------------------------------------------------
1 | """ Aling Nena's Cashier Challenge
2 | Author:
3 | Description: During closing, Aling Nena counts from her vault the day's total income and
4 | also the total amount of all her paper bills.
5 |
6 | Help Aling Nena count her total income and total amount of her paper bills
7 | from a list of cash money and using a loop!
8 | """
9 |
10 |
11 | def is_coins(money):
12 | """ Determine if the money is a coin
13 | :param money: (Integer)
14 | :return: (Boolean)
15 |
16 | Examples:
17 | >>> print(is_coins(20))
18 | False
19 | >>> print(is_coins(1))
20 | True
21 | """
22 | if money < 20:
23 | return True
24 | return False
25 |
26 |
27 | cash_on_vault = [1, 5, 100, 10, 50, 50, 20, 5, 1, 1000, 1000, 500, 5, 200]
28 |
29 | # Build your code below
30 |
--------------------------------------------------------------------------------
/_coverpage.html:
--------------------------------------------------------------------------------
1 |
25 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/lists/list_solution.py:
--------------------------------------------------------------------------------
1 | # Write a program that accepts 3 integers and separate these into odd and even numbers.
2 | # Duplicates are permited in the input but not in the output.
3 |
4 | # Example
5 |
6 | # >>> Enter first number: 3567
7 | # >>> Enter second number: 789
8 | # >>> Enter third number: 1234
9 | # odd: {789, 3567}
10 | # even: {1234}
11 |
12 |
13 | odd = []
14 | even = []
15 |
16 | num1 = int(input("Enter first number: "))
17 |
18 | if num1 % 2 == 1:
19 | odd.append(num1)
20 | else: even.append(num1)
21 |
22 | num2 = int(input("Enter second number: "))
23 |
24 | if num2 % 2 == 1:
25 | odd.append(num2)
26 | else: even.append(num2)
27 |
28 |
29 | num3 = int(input("Enter third number: "))
30 |
31 | if num3 % 2 == 1:
32 | odd.append(num3)
33 | else: even.append(num3)
34 |
35 |
36 |
37 | print(f"odd: {set(odd)}")
38 | print(f"even: {set(even)}")
--------------------------------------------------------------------------------
/basic_concepts/exercises/conditional_statements/conditional01.py:
--------------------------------------------------------------------------------
1 | """ Challenge
2 | Author:
3 | Description: Aling Nena stores her soft drink stock on two refrigerators.
4 | She stores Coke, Sprite and Royal on her Sari-sari store's refrigerator while
5 | RC and 7UP can be found on her house's refrigerator.
6 |
7 | Help Aling Nena to properly respond to her customer
8 | when buying softdrinks.
9 |
10 | The reply will depend if the soft drink brand is on the store's ref,
11 | on the house's ref or none. If the customer buys a soft drink brand that is:
12 | 1. stored on the store, she will respond 'Got it!'
13 | 2. stored on the house, she will respond 'Please wait for a while!'
14 | 3. not sold by her, she will respond 'Sorry we do not sell that. We only
15 | have '
16 | """
17 |
18 | customer_order = input('Hi! What soft drink brand do you want?')
19 |
20 | # Build your code below
21 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/functions/functions01.py:
--------------------------------------------------------------------------------
1 | """ Mang Toto's ForEx Challenge
2 | Author:
3 | Description: Aling Nena's Sari-sari store just had a new neighbor! It's Mang Toto's ForEx!
4 |
5 | Help Mang Toto to convert `USD, JPY, SGD` to `PHP` by:
6 | * Asking the customer for their currency.
7 | >> Welcome to Mang Toto's ForEx! What is your currency? We accept (usd, jpy, sgd):
8 |
9 | * If they are not exchanging the currrency, notify the customer.
10 | >> Welcome to Mang Toto's ForEx! What is your currency? We accept (usd, jpy, sgd):
11 | >> aud
12 | >> Sorry! We do not exchange aud!
13 |
14 | * If they are in their currency list, ask for the amount and inform the original and equivalent PHP amount.
15 | >> Welcome to Mang Toto's ForEx! What is your currency? We accept (usd, jpy, sgd):
16 | >> usd
17 | >> Your 100.50 usd is equivalent to 5069.22 PHP
18 | """
19 |
20 | PHP_EXCHANGE_RATE = {
21 | 'usd': 50.44,
22 | 'jpy': 0.45,
23 | 'sgd': 36.25
24 | }
25 |
26 |
27 | def converter(currency, amount):
28 | # Replace pass with your block of code
29 | pass
30 |
31 | # Build your code below
32 |
--------------------------------------------------------------------------------
/wwcodemanila/study_groups.md:
--------------------------------------------------------------------------------
1 | Study groups are events where members can come together and help each other learn and understand a specific programming language, technology, or anything related to coding, engineering, design.
2 |
3 | Everyone is welcome to the event as long as they want to learn and share their knowledge with the community and they are following the [code of conduct](https://github.com/WomenWhoCode/guidelines-resources/blob/master/code_of_conduct.md).
4 |
5 | !> Study groups are **not** classes, workshops, seminars, or lectures. It’s about everyone in the **community learning together**.
6 |
7 | Visit our [Meetup page](https://bit.ly/wwcodemanilameetups) for the schedule of upcoming study groups and other events.
8 |
9 |
10 | ## Guidelines
11 |
12 | - If you have a question, just **ask**
13 | - If you have an idea, **share it**
14 | - **Make friends** and learn from the other participants
15 | - **Do not** recruit or promote your business
16 |
17 | ## Code of conduct
18 |
19 | Everyone joining this study group and other Women Who Code events must follow our [code of conduct](https://github.com/WomenWhoCode/guidelines-resources/blob/master/code_of_conduct.md).
20 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/hangman/README.md:
--------------------------------------------------------------------------------
1 | # Hang on mate!
2 |
3 | As a Python coding ninja, you already are equipped with the following skills:
4 | - [ ] Variables, Arithmetic Operations, Keyboard Input
5 | - [ ] Coding conventions of PEP8
6 | - [ ] Strings
7 | - [ ] Lists
8 | - [ ] Conditional Statements
9 | - [ ] Loops
10 |
11 | To polish these more, aside from hanging out with us(lol), we are challenging you to do the never aging `Hangman` game!
12 |
13 | ## Getting Started
14 |
15 | This exercise is from Michael Dawson's "Python Programming for the Absolute Beginner 3rd Edition".
16 | We have given a template file to help you implement the game step-by-step but you could do your own from scratch
17 | if that's easier for you.
18 |
19 | Hang in there and let the game begin!
20 |
21 | ### Resources
22 |
23 | You can use the template file here for this exercise.
24 |
25 | * [Live game example](https://drive.google.com/open?id=1CLafYAmaxWOvoUkOJvfx94dHEp87CnqT)
26 | * Template
27 |
28 | [template](hangman.py ':include :type=code python')
29 |
30 | * To run:
31 |
32 | ```shell
33 | python hangman.py
34 | ```
35 |
36 | [challenge_partial](../../../challenge_partial.md ':include')
37 |
--------------------------------------------------------------------------------
/basic_concepts/pep8.md:
--------------------------------------------------------------------------------
1 | **Scenario: ** Partner A told Partner B that the client wants to input the dividend amount
2 | instead of hardcoding it. Partner A will be on Boracay for a month long
3 | vacation and she left to you this source file:
4 |
5 | [explain_me](samples/explain_me.py ':include :type=code python')
6 |
7 | As partner B, can you explain the code by just scanning it? Can you easily change
8 | it to cater the new requirements?
9 |
10 | Let's read [PEP8](https://www.python.org/dev/peps/pep-0008/) guidelines.
11 |
12 | From PEP8:
13 | * Readability counts - code is read much more often that it is written!
14 | * The guideline is intended to improve the readability of code and make it consistent.
15 | * It is a guide not a law!
16 |
17 | Now, which of the ff. are PEP8 compliant?
18 |
19 | ``` python
20 | income = (gross_wages +
21 | taxable_interest +
22 | (dividends - qualified_dividends) -
23 | ira_deduction -
24 | student_loan_interest)
25 | ```
26 |
27 | or
28 |
29 | ```python
30 | income = (gross_wages
31 | + taxable_interest
32 | + (dividends - qualified_dividends)
33 | - ira_deduction
34 | - student_loan_interest)
35 |
36 | ```
--------------------------------------------------------------------------------
/flask/exercises/QuoteSearchEngine/app/db.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | import sqlite3 as lite
5 | import sys
6 |
7 | con = lite.connect('quotes.db')
8 |
9 | with con:
10 |
11 | cur = con.cursor()
12 | # cur.execute("CREATE TABLE Quotes(Id INT, Value TEXT)")
13 | cur.execute("CREATE TABLE IF NOT EXISTS Quotes(Id INT, Value TEXT)")
14 |
15 | quotes = ( "'If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.' -- John Louis von Neumann ",
16 | "'Computer science is no more about computers than astronomy is about telescopes' -- Edsger Dijkstra ",
17 | "'To understand recursion you must first understand recursion..' -- Unknown",
18 | "'You look at things that are and ask, why? I dream of things that never were and ask, why not?' -- Unknown",
19 | "'Mathematics is the key and door to the sciences.' -- Galileo Galilei",
20 | "'Not everyone will understand your journey. Thats fine. Its not their journey to make sense of. Its yours.' -- Unknown" )
21 |
22 | for i, quote in enumerate(quotes):
23 | cur.execute("INSERT INTO Quotes VALUES(" + str(i) + ", " + repr(quote) + ")")
--------------------------------------------------------------------------------
/basic_concepts/exercises/strings/strings01.py:
--------------------------------------------------------------------------------
1 | """ Aling Nena's Reward System Challenge
2 | Author:
3 | Description: This summer, Aling Nena’s Sari-sari store wants to implement a
4 | reward system where customers can redeem a reward by texting the following:
5 |
6 |
7 | >> Please enter text: 1 nicole i. tibay f
8 |
9 | The system will then reply the following:
10 | Hi ! You have successfully redeem
11 | reward # - ! Thank you for choosing Aling Nena’s
12 | Sari-sari store.
13 |
14 | >> Hi Nicole I. Tibay! You have successfully redeem reward #1 - Coke sakto!
15 | Thank you for choosing Aling Nena’s Sari-sari store.
16 | """
17 |
18 | # You can access this by: rewards[]
19 | # Just like strings the index starts with 0
20 | rewards = [
21 | "Coke sakto", # index 0
22 | "Boy Bawang", # index 1
23 | "15pcs. Yucky candy", # index 2
24 | "15pcs. Pintura candy", # index 3
25 | "15PHP load", # index 4
26 | "3 pcs. Dove conditioner", # index 5
27 | "Cottonbuds", # index 6
28 | "One sheet of Biogesic", # index 7
29 | "100mL Pepper/Pintura", # index 8
30 | ]
31 |
32 | # Build your code below
33 |
--------------------------------------------------------------------------------
/flask/exercises/RandomQuoteGenerator/app/app.py:
--------------------------------------------------------------------------------
1 | from flask import Flask, render_template
2 | from random import randint
3 | app = Flask(__name__)
4 |
5 | @app.route("/")
6 | def index():
7 | return "Welcome!"
8 |
9 | @app.route("/members/")
10 | def members():
11 | return "Members"
12 |
13 | @app.route("/members//")
14 | def getMember(name):
15 | quotes = [ "'If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.' -- John Louis von Neumann ",
16 | "'Computer science is no more about computers than astronomy is about telescopes' -- Edsger Dijkstra ",
17 | "'To understand recursion you must first understand recursion..' -- Unknown",
18 | "'You look at things that are and ask, why? I dream of things that never were and ask, why not?' -- Unknown",
19 | "'Mathematics is the key and door to the sciences.' -- Galileo Galilei",
20 | "'Not everyone will understand your journey. Thats fine. Its not their journey to make sense of. Its yours.' -- Unknown"
21 | ]
22 | randomNumber = randint(0,len(quotes)-1)
23 | quote = quotes[randomNumber]
24 |
25 | return render_template('test.html',**locals())
26 |
27 | if __name__ == "__main__":
28 | app.run()
--------------------------------------------------------------------------------
/getting_started/exercise_upload_step.md:
--------------------------------------------------------------------------------
1 | ### How to share your work
2 |
3 | > Github will allow you to easily share your code to us or to your peers.
4 |
5 | 1. [Create a Github account](https://github.com/join) if none yet, or sign in.
6 |
7 | 2. Create `wwcode-python` repository if none yet.
8 | * In the toolbar(upper right of your screen), select `create new` (plus sign) -> `New Repository`
9 |
10 | 
11 |
12 | * Name your repository `wwcode-python`. Select `Public` and `Initalize this repository with a README`
13 |
14 | 
15 |
16 | 3. To upload your files:
17 | * Click the `Upload files`
18 |
19 | 
20 |
21 | * Upload your work. Write a brief description of it and click `Commit changes`!
22 |
23 | 
24 |
25 | 4. Copy the path of your work.
26 |
27 | 
28 |
29 | 5. [Open an issue](https://github.com/wwcodemanila/WWCodeManila-Python/issues/new) in our repository with title ` - `. For example, `John Doe - Loops`.
30 |
31 | 6. Paste the path of work in the `comment` section and select `Submit new issue`.
32 |
--------------------------------------------------------------------------------
/flask/exercises/QuoteSearchEngine/app/app.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | from flask import Flask, render_template
5 | from random import randint
6 | app = Flask(__name__)
7 |
8 | import sqlite3 as lite
9 | import sys
10 |
11 | @app.route("/")
12 | def index():
13 | return "Welcome!"
14 |
15 | @app.route("/members/")
16 | def members():
17 | return "Members"
18 |
19 | @app.route("/members//")
20 | def getMember(name):
21 | con = lite.connect('app\quotes.db')
22 |
23 | with con:
24 | cur = con.cursor()
25 | cur.execute("SELECT * FROM Quotes;")
26 |
27 | quotes = cur.fetchall()
28 |
29 | randomNumber = randint(0,len(quotes)-1)
30 | quote = quotes[randomNumber][1]
31 | return render_template('test.html',**locals())
32 |
33 | @app.route("/search//")
34 | def search(search):
35 | results = [];
36 |
37 | con = lite.connect('C:\\Users\\aalvara2\\Envs\\QuoteGenerator\\app\\quotes.db')
38 |
39 | with con:
40 | cur = con.cursor()
41 | cur.execute("SELECT * FROM Quotes;")
42 |
43 | quotes = cur.fetchall()
44 |
45 | for quote in quotes:
46 | if search.upper() in quote[1].upper():
47 | results.append(quote[1])
48 |
49 | return render_template('search.html',**locals())
--------------------------------------------------------------------------------
/flask/discussions/03_my_first_flask_app.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 |
3 | - [ ] Create and run your first Flask app
4 | - [ ] Set the values of `FLASK_APP` and `FLASK_DEBUG` environment variables
5 |
6 | ## Getting Started
7 |
8 | A minimal Flask application can easily be created in 3 steps and as little as **5 lines of code**.
9 |
10 | 1. Create a file named `app.py` inside your `portfolio` project folder:
11 |
12 | ```shell
13 | from flask import Flask
14 | app = Flask(__name__)
15 |
16 | @app.route('/')
17 | def hello_world():
18 | return 'Hello, World!'
19 | ```
20 |
21 | 2. In your terminal or console, navigate to the location of your project folder and set the `FLASK_APP` environment variable:
22 |
23 | ```shell
24 | Mac:
25 | export FLASK_APP=app.py
26 |
27 | Windows:
28 | set FLASK_APP=app.py
29 | ```
30 |
31 | 3. Finally, run your application:
32 |
33 | ```shell
34 | flask run
35 | ```
36 |
37 | Congratulations! You can now access your app through the url route generated in your terminal or console using your favorite browser.
38 |
39 | To quit, press `CTRL+C`.
40 |
41 | To deactivate your virtual environment, enter `deactivate`.
42 |
43 | ## Bonus: `FLASK_DEBUG` environment variable
44 |
45 | To run your app in debug mode, set the `FLASK_DEBUG` environment variable to 1 before running the application:
46 |
47 | ```shell
48 | Mac:
49 | export FLASK_DEBUG=1
50 |
51 | Windows:
52 | set FLASK_DEBUG=1
53 | ```
54 |
--------------------------------------------------------------------------------
/ren'py/introduction.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/WWCodeManila/Python)
2 |
3 | # Game development using Ren'Py
4 |
5 | ## A Python x Game Development study groups collaboration
6 |
7 | We will be making a simple interactive game or *visual novel* using a Python engine called Ren'Py. This is a collaboration between the WWCode Manila Python :snake:, and Game Development :video_game: Study Groups!
8 |
9 | **Game development** with Python is under one of our advanced topics. While a working knowledge of Python is needed in order to carry out some of the exercises in this study guide, Ren'Py also has its own syntax. We'll be learning and applying these throughout this study session.
10 |
11 |
12 |
13 | # What is Ren'Py
14 |
15 | Ren'Py is a game engine used to make visual novels - interactive stories with words, sounds, and often with choose-your-own-ending storyline. It has its own simple scripting language, and since it's based on Python, you can also leverage your coding skills in order to make more complex games.
16 |
17 |
18 |
19 |
20 |
21 | # Resources
22 |
23 | If you want to learn more about Ren'Py or developing visual novels, you can check these websites. Games which used Ren'Py are also available in these sites.
24 |
25 | - [The Official Ren'Py website](https://www.renpy.org/)
26 | - [Lemma Soft Forums for creators of visual novels and story-based games ](https://lemmasoft.renai.us/forums/)
27 |
28 | [](https://gitter.im/WWCodeManila/Python)
29 |
30 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/2048/README.md:
--------------------------------------------------------------------------------
1 | # Challenge yourself with 2048
2 |
3 | Good job on learning the basic concepts of programming using Python! Before you say adieu to
4 | our basic track and heading on to a more specific application of Python such as scripting, web application or data analysis,
5 | we challenge you to do our *FUN* game-centered culminating project, [2048](http://gabrielecirulli.github.io/2048/)!
6 |
7 | You might have played it before, but now that you are a coding ninja, you are going to implement it! Don't worry
8 | because we will help you along the way and we assure you that finishing it will level up your skills. Plus,
9 | it's a proud thing to share with your peers!
10 |
11 | ## Getting Started
12 |
13 | This project is from Principles of Computing offered by Rice University in Coursera. Additional instructions
14 | were added on the template file to help you implement the game step-by-step.
15 |
16 | Let the game begin!
17 |
18 | ### Resources
19 |
20 | Please use the files here for your project.
21 |
22 | * [Instruction](https://github.com/enixdark/principlescomputing-001/blob/master/Week0/Instructions.md)
23 | * [Starter kit](https://github.com/wwcodemanila/WWCodeManila-Python/tree/master/basic_concepts/exercises/2048)
24 | * logic.py
25 | * poc_2048_gui.py
26 | * requirements.txt
27 |
28 | * Install the required library for the game GUI:
29 |
30 | ```shell
31 | pip install simpleguitk
32 | ```
33 |
34 | or
35 |
36 | ```shell
37 | pip install -r requirements.txt
38 | ```
39 |
40 | * To run:
41 |
42 | ```shell
43 | python logic.py
44 | ```
45 |
46 |
47 | !> Put your working files(e.g. logic.py, poc_2048_gui.py) under one `2048` folder.
48 |
49 | [challenge_partial](../../../challenge_partial.md ':include')
50 |
--------------------------------------------------------------------------------
/basic_concepts/error_handling.md:
--------------------------------------------------------------------------------
1 | When you run the code below, do you expect it to be like a Eutopian world, one with no errors?
2 |
3 | ```python
4 | age = input('Enter your age:')
5 | print('You are {} next year!'.format(input + 1))
6 | ```
7 |
8 | Nope. The user can input `19` but s/he can also input `foo` which is not a valid age/number. Can you try to input `foo` and see what happens?
9 | Did you get also the following error?
10 |
11 | ```shell
12 | Traceback (most recent call last):
13 | File "", line 1, in
14 | ValueError: invalid literal for int() with base 10: 'foo'
15 | ```
16 |
17 | My two cents - Do not be terrified when your best friend, the Python interpreter, returns/raises an error. S/he is just telling you that something bad happened and you can try to help her/him to handle the error.
18 |
19 | ## Tutorials
20 |
21 | As a Python ninja:
22 | * Learn how to [handle exceptions](https://wiki.python.org/moin/HandlingExceptions).
23 | * Learn how to ask for forgiveness but also know when to take caution first, [EAFP vs LBYL](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-vs-lbyl).
24 | * Know that sometimes it's [okay to fail](https://realpython.com/blog/python/the-most-diabolical-python-antipattern/).
25 |
26 |
27 | ## Challenge
28 |
29 | Rewrite the code above to handle error.
30 |
31 | > Be creative! *Tip*: You may just notify the user for his/her mistake or ask him/her for a new input ;)
32 |
33 | [challenge_partial](../challenge_partial.md ':include')
34 |
35 |
36 | ## Deep Dive
37 | * [Pep 463](http://legacy.python.org/dev/peps/pep-0463/): Exception-catching expressions
38 | * [Diaper Pattern](http://mike.pirnat.com/2009/05/09/the-diaper-pattern-stinks/) also known as [Pokemon Exception Handling](http://wiki.c2.com/?PokemonExceptionHandling)
39 |
--------------------------------------------------------------------------------
/git/README.md:
--------------------------------------------------------------------------------
1 | We know your hands are getting itchy and wants to continue typing on some Python codes.
2 | In the first place, you attended our study group to learn Python and wait.... you are redirected
3 | to a page to learn this three letter word, `git`.
4 |
5 | Just believe in us! Later on your tech career you will thank us for introducing Git.
6 |
7 | ## Why Git
8 |
9 | Git is a helpful tool for code backup, version control/tracking and code sharing!
10 |
11 | 
12 |
13 | 
14 |
15 | Aside from these, we in the Python study group wants you to use Git so that:
16 |
17 | * You can share your work to your peers or your employer ;P
18 | * If you work on an exercise on a workday and need help, we can easily view your codes
19 |
20 | ## Tutorial
21 |
22 | If you have done few exercises, you may have:
23 |
24 | - [ ] Created a GitHub account
25 | - [ ] Created `wwcode-python` repository
26 | - [ ] Uploaded some exercises on your `wwcode-python` repository
27 |
28 | Now, we want you to deep dive into GIT!
29 |
30 | > [Try Git](https://try.github.io) using this tutorial
31 |
32 |
33 | ## Challenge
34 |
35 | !> Please install Git on your machine
36 |
37 | For your succeeding exercises, we want you to upload your work by using `git` instead of the upload button!
38 |
39 | * Clone your `wwcode-python` repository
40 |
41 | ```
42 | git clone [url]
43 | ```
44 |
45 | or
46 |
47 | * Update your `wwcode-python` repository
48 |
49 | ```
50 | git pull
51 | ```
52 |
53 | * Add your exercise file
54 |
55 | ```
56 | git add [file]
57 | ```
58 |
59 | * Push your changes
60 |
61 | ```
62 | git push
63 | ```
64 |
--------------------------------------------------------------------------------
/django/01_introduction.md:
--------------------------------------------------------------------------------
1 | # Web Development with Django
2 |
3 | Welcome to Python - Django Web Framework Study Group. Have a little sip of your :coffee: first before we start building. :computer:
4 |
5 | Before we deep dive into the world of Django, check these things first in your local machine:
6 |
7 | - [x] I have a text editor installed in my computer (e.g. Notepad++, Sublime).
8 | - [x] I have Python installed in my computer.
9 | - [x] I'm familiar with the basics concepts of Python.
10 |
11 | ## What will you learn?
12 |
13 | Once you have finished our study group, you will be able to create a Quora/Reddit-like web application. You will also learn the following in the process:
14 | - Django, DRF, and VueJS
15 | - How to use Vue CLI and Vue Router
16 |
17 | ## What is Django?
18 |
19 | [Django](https://www.djangoproject.com/) is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It’s free and open source.
20 |
21 | ## Why You Should Learn Django?
22 | - It is written in Python (obviously).
23 | - You don't need to rely on external libraries / packages.
24 | - It has an in-depth [documentation](https://www.djangoproject.com/).
25 | - You can ask for help by joining to their [community](https://stackoverflow.com/questions/tagged/django).
26 |
27 | ## Applications powered by Django
28 | - Spotify
29 | - Pinterest
30 | - Instagram
31 | - Mozilla
32 | - Disqus
33 | - National Geograpic
34 | - Knight Foundation
35 |
36 | ## References
37 | - [Django Girls Tutorial](https://tutorial.djangogirls.org/en/)
38 | - [The Complete Guide to Django REST Framework and Vue JS](https://www.udemy.com/course/the-complete-guide-to-django-rest-framework-and-vue-js/learn/lecture/14198644?start=0#overview)
39 | - [10 Popular Websites Built With Django](https://djangostars.com/blog/10-popular-sites-made-on-django/)
--------------------------------------------------------------------------------
/basic_concepts/exercises/dictionaries/dictionaries01.py:
--------------------------------------------------------------------------------
1 | """ Aling Nena's Receipt Challenge
2 | Author:
3 | Description: Just like in grocery stores where items where scanned one by one and the
4 | total amount due is summed, please help Aling Nena's Sari-sari store
5 | to compute a customer's total order amount and print the receipt by:
6 | * Input the customer's products
7 | * The product dictionary contains Aling Nena's products and maps it's price.
8 | * If the product name is NOT in her list, just print 'Item void!'
9 | and skip it from the computation of total amount due.
10 | * If the product is in the list, please print current purchased products and
11 | their quantity.
12 | * If done punching the items:
13 | - Print each purchased products, it's quantity, price, total price (quantity * price)
14 | - Print the total items and total amount due.
15 |
16 | @example
17 | Item name: sunsilk
18 | {'sunsilk': 1}
19 | Are you done? Press y to finish: n
20 | Item name: SUNsilk
21 | {'sunsilk': 2}
22 | Are you done? Press y to finish: n
23 | Item name: ligo
24 | {'sunsilk': 2, 'ligo': 1}
25 | Are you done? Press y to finish: n
26 | Item name: Spam
27 | {'sunsilk': 2, 'ligo': 1, 'spam': 1}
28 | Are you done? Press y to finish: n
29 | Item name: test
30 | Item test void!
31 | Are you done? Press y to finish: n
32 | Item name: ligo
33 | {'sunsilk': 2, 'ligo': 2, 'spam': 1}
34 | Are you done? Press y to finish: y
35 | ***** PRINTING YOUR RECEIPT *****
36 | sunsilk 7.5 * 2 = 15.0
37 | ligo 12.0 * 2 = 24.0
38 | spam 115.25 * 1 = 115.25
39 | 5 items --------- 154.25
40 | """
41 |
42 | products = {
43 | 'sunsilk': 7.50,
44 | 'dove': 8.00,
45 | 'tide': 12.50,
46 | 'coke': 45.75,
47 | 'sprite': 45.75,
48 | 'spam': 115.25,
49 | 'ligo': 12.00
50 | }
51 |
52 | # Let's punch the customer's items!
53 | is_done = 'n'
54 | while is_done != 'y':
55 | item = input('Item name: ').lower()
56 | # Check if done punching items
57 | is_done = input('Are you done? Press y to finish:').lower()
58 |
59 | # Build your code below
60 |
--------------------------------------------------------------------------------
/getting_started/warm_up.md:
--------------------------------------------------------------------------------
1 | ## Let's do some warm up
2 |
3 | Now we will run a very basic Python program that will print `Hello WomenWhoCode!`. This will allow you to run a basic Python program:
4 |
5 | - [ ] from the terminal
6 | - [ ] from your editor
7 |
8 |
9 | ### Copy sample file
10 |
11 | Please copy the sample file below and save as `first_python_code.py`.
12 |
13 | [first_python_code.py](samples/first_python_code.py ':include :type=code python')
14 |
15 |
16 | ### Run your first Python program
17 |
18 | Let's try to run some Python code!
19 |
20 |
21 | #### Using a terminal
22 |
23 | - Open a terminal
24 |
25 | ```
26 | Windows: Click Start -> Type cmd
27 | Mac: Open Applications folder -> Utilities folder
28 | ```
29 | - Go to the directory of the file by running the following command. If you need help finding the directory path, you can ask the mentor how.
30 |
31 | ```
32 | cd
33 | ```
34 |
35 | - Run our `first_python_code.py` by typing the following command.
36 |
37 | ```
38 | python first_python_code.py
39 | ```
40 |
41 | or
42 |
43 | ```
44 | python3 first_python_code.py
45 | ```
46 |
47 | - This is your simple program that prints some text. The output should be
48 |
49 | ```
50 | Hello WomenWhoCode!
51 | Hello WomanWhoCode!
52 | Hello WomenWhoCode!
53 | ```
54 |
55 |
56 | #### Using an editor
57 |
58 | Open the file using your text editor and run the code! You should see the same result.
59 |
60 | ### Try printing your name
61 | - Open the file using your text editor.
62 | - Inside the file, there is an instruction. Follow it! :)
63 | - When you are done, save the file and run it again in your terminal and editor!
64 |
65 | ```
66 | Hello WomenWhoCode!
67 | Hello WomanWhoCode!
68 | Hello WomenWhoCode!
69 | Nicole loves Python!
70 | ```
71 |
72 | Now you have run your first program!
73 |
74 | ## Put your thinking cap on!
75 |
76 | - What is the extension of a Python file?
77 | - What do you call the `cd`? What does it do?
78 | - What does the `print()` do?
79 | - What does the `.format()` do?
80 | - What is the magic of the `#` symbol?
81 |
--------------------------------------------------------------------------------
/basic_concepts/samples/flower.py:
--------------------------------------------------------------------------------
1 | """
2 | Reference: http://blog.tibarazmi.com/draw-flower-using-turtle/
3 |
4 | You can use https://trinket.io/python if you have problem running turtle
5 | """
6 | import turtle
7 | import math
8 |
9 |
10 | def p_line(t, n, length, angle):
11 | """Draws n line segments."""
12 | for i in range(n):
13 | t.fd(length)
14 | t.lt(angle)
15 |
16 |
17 | def polygon(t, n, length):
18 | """Draws a polygon with n sides."""
19 | angle = 360 / n
20 | p_line(t, n, length, angle)
21 |
22 |
23 | def arc(t, r, angle):
24 | """Draws an arc with the given radius and angle."""
25 | arc_length = 2 * math.pi * r * abs(angle) / 360
26 | n = int(arc_length / 4) + 1
27 | step_length = arc_length / n
28 | step_angle = float(angle) / n
29 |
30 | # Before starting reduces, making a slight left turn.
31 | t.lt(step_angle / 2)
32 | p_line(t, n, step_length, step_angle)
33 | t.rt(step_angle / 2)
34 |
35 |
36 | def petal(t, r, angle):
37 | """Draws a petal using two arcs."""
38 | for i in range(2):
39 | arc(t, r, angle)
40 | t.lt(180 - angle)
41 |
42 |
43 | def flower(t, n, r, angle, p):
44 | """Draws a flower with n petals."""
45 | for i in range(n):
46 | petal(t, r, angle)
47 | t.lt(p / n)
48 |
49 |
50 | def leaf(t, r, angle, p):
51 | """Draws a leaf and fill it."""
52 | t.begin_fill() # Begin the fill process.
53 | t.down()
54 | flower(t, 1, 40, 80, 180)
55 | t.end_fill()
56 |
57 |
58 | def main():
59 | window = turtle.Screen() # creat a screen
60 | window.bgcolor("blue")
61 | lucy = turtle.Turtle()
62 | lucy.shape("turtle")
63 | lucy.color("red")
64 | lucy.width(5)
65 | lucy.speed(0)
66 |
67 | # Drawing flower
68 | flower(lucy, 10, 40, 100, 360)
69 |
70 | # Drawing pedicel
71 | lucy.color("brown")
72 | lucy.rt(90)
73 | lucy.fd(200)
74 |
75 | # Drawing leaf
76 | lucy.rt(270)
77 | lucy.color("green")
78 | leaf(lucy, 40, 80, 180)
79 | lucy.ht()
80 | window.exitonclick()
81 |
82 | # call the main function to start!
83 | main()
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Welcome, Pythonistas!
2 |
3 | !> Please go to our official [GitHub Page](https://wwcodemanila.github.io/WWCodeManila-Python/#/)
4 | if you're viewing this from the source code repository.
5 |
6 | ## About this study group
7 |
8 | !> If you're not yet familiar with study groups, read this [document](wwcodemanila/study_groups.md)
9 | first to know what they are.
10 |
11 | This study group is held once a month and is led by our volunteer leaders.
12 |
13 | Everyone is welcome to join, learn, and share their knowledge in the community
14 | as long as they abide by our [code of conduct](https://github.com/WomenWhoCode/guidelines-resources/blob/master/code_of_conduct.md).
15 |
16 | ### Setup
17 |
18 | During the study groups, we usually spend the time:
19 |
20 | - getting to know first-timers,
21 | - discussing questions/issues raised during the last meetup,
22 | - presenting lightning talks (anyone who wants to share/chika something!),
23 | - doing self-paced and/or mini study sessions
24 | - sharing TILS (Today I Learned), and
25 | - communicating announcements.
26 |
27 |
28 | ## Relevant links
29 |
30 | - [GitHub](https://github.com/wwcodemanila/WWCodeManila-Python): View our study group resources.
31 | - [Meetup](https://bit.ly/wwcodemanilameetups): Get updates about our upcoming study groups and events.
32 | - [Facebook](https://facebook.com/wwcodemanila): Get updates about what's happening in the community.
33 | - [Twitter](https://twitter.com/wwcodemanila): Get updates about our current and future events.
34 |
35 |
36 | ## Helping out
37 |
38 | ### Volunteer
39 |
40 | Attend one of our [events](https://bit.ly/wwcodemanilameetups) and talk to us! :smile:
41 |
42 | ### Donate
43 |
44 | Any amount will greatly help us achieve our mission of inspiring women to excel in tech careers. :heart:
45 |
46 | Donations are accepted via [Open Collective](https://opencollective.com/wwcodemanila).
47 |
48 | ### Hosting
49 |
50 | Do you want to help us host one of our study groups? Email us at **manila@womenwhocode.com**.
51 |
52 | ## Mentors
53 |
54 | - Alysson Alvaran
55 | - Angelica Lapastora
56 | - Marylette Roa
57 | - Issa Tingzon
58 | - Iris Uy
59 | - Clau Yagyagan
60 | - Nicole Tibay
61 |
--------------------------------------------------------------------------------
/flask/discussions/01_introduction.md:
--------------------------------------------------------------------------------
1 | # Fun, Friendly, Fabulous Flask
2 | Congratulations, young'un, for coming this far!
3 | Are you ready to enter the wonderful world of web development?
4 |
5 | - [x] I have a text editor installed in my computer (e.g. Notepad++, Sublime).
6 | - [x] I have Python installed in my computer.
7 | - [x] I'm familiar with the basics concepts of Python.
8 |
9 | If you answered **yes** to all three questions, then brace yourself, hang on to your handy Flask -- err, weapon, and let the adventure begin!
10 |
11 | ## Final Output
12 |
13 | This course will help you create your own **portfolio** while exploring Flask. By the end of this course, you should be able to create and deploy your Flask web app.
14 |
15 | ## Flask in a nutshell
16 | Flask is a microframework for Python based on Werkzeug (toolkit), Jinja 2 (templating engine) and good intentions. For more information, visit the official Flask site: http://flask.pocoo.org/.
17 |
18 | ## The "micro" in "microframework"
19 | ### Debunking the misconceptions about Flask as a microframework
20 | * It is not lacking in functionality.
21 | * We don't have to fit our whole web app into a single Python file (although we certainly can).
22 | ### What it really is
23 | * It aims to keep the core simple but extensible. Check out the list of available extensions here: http://flask.pocoo.org/extensions/.
24 | * It won't make many decisions for you, such as what database to use.
25 | * The decisions that it does make, such as what templating engine to use, are easy to change.
26 | * Everything else is up to you. :)
27 | * Flask can be EVERYTHING YOU NEED and NOTHING YOU DON'T.
28 |
29 | ## Reasons to love Flask
30 | * Easy to learn: Flask's Hello World app has to be the simplest out there, clocking in at only 7 lines!
31 | * Best for small apps with simple requirements
32 |
33 | ## Powered by Flask
34 | * Flask website
35 | * Pinterest
36 | * LinkedIn
37 | * Reddit
38 | * Uber
39 | * Netflix
40 | * ...and [a lot more](http://flask.pocoo.org/community/poweredby/)!
41 |
42 | ## References
43 | * http://flask.pocoo.org/docs/0.10/foreword/#what-does-micro-mean
44 | * https://www.airpair.com/python/posts/django-flask-pyramid
45 | * https://www.quora.com/What-is-the-largest-site-created-using-Flask
--------------------------------------------------------------------------------
/ren'py/game/batobato.rpy:
--------------------------------------------------------------------------------
1 | label game:
2 |
3 | $ gamef = True
4 |
5 | scene bg street with fade
6 |
7 | show lita at left with moveinright
8 | show boy at right with moveinleft
9 |
10 | l "Let's play bato-bato pik!"
11 |
12 | show boy at center with moveinright
13 | b "You'll play against me. Best of three!"
14 |
15 | python:
16 | from random import randint
17 | uscore = 0
18 | bscore = 0
19 | while uscore | bscore < 2:
20 |
21 | renpy.say(b, "Bato-bato pik!")
22 |
23 | choices = {"r": "Rock", "p": "Paper", "s": "Scissors"}
24 | uhand = renpy.display_menu([("Rock", "r"), ("Paper", "p"), ("Scissors", "s")])
25 | bhand = choices.keys()[randint(0,2)]
26 |
27 | uhand_c = choices[uhand]
28 | bhand_c = choices[bhand]
29 |
30 | renpy.say(b, "[bhand_c]")
31 |
32 | hands = (uhand, bhand)
33 |
34 | wins = [
35 | ('p', 'r'),
36 | ('r', 's'),
37 | ('s', 'p'),
38 | ]
39 | tie = False
40 | if hands[0] == hands[1]:
41 | tie = True
42 | result = "It's a tie!"
43 | elif hands in wins:
44 | result = "wins"
45 | uscore += 1
46 | else:
47 | result = "loses"
48 | bscore += 1
49 |
50 | if not tie:
51 | renpy.say(l, "[name] picked [uhand_c], Boy picked [bhand_c] \n [name] [result]! {w} \n Boy: [bscore], [name]: [uscore]")
52 | else:
53 | renpy.say(l, "[name] picked [uhand_c], Boy picked [bhand_c] \n [result]! {w} \n Boy: [bscore], [name]: [uscore]")
54 |
55 | if uscore > bscore:
56 | renpy.say(l, "[name] is the WINNER!")
57 | winner = True
58 | else:
59 | renpy.say(l, "Boy wins. [name] LOSES!")
60 | winner = False
61 |
62 | if winner:
63 | show boy at right with moveinleft
64 | l "Well done, [name]."
65 | b "You defeated me!"
66 | else:
67 | show boy at right with moveinleft
68 | b "Oh well, there's always a next time, [name]."
69 |
70 | l "Let's play another game!"
71 | "You spend the rest of the day playing."
72 |
73 | jump ending
74 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Women Who Code Manila Python Study Group
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
47 |
48 |
49 |
50 |
51 |
52 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/2048/poc_2048_gui.py:
--------------------------------------------------------------------------------
1 | """ 2048 GUI
2 | Credit to https://github.com/chrisnatali/2048/blob/master/poc_2048_gui.py
3 |
4 | DO NOT MODIFY. YOUR TASK IS TO CREATE THE GAME LOGIC.
5 | """
6 |
7 | import simpleguitk as simplegui
8 | import math
9 |
10 | # Tile Images
11 | IMAGEURL = "http://codeskulptor-assets.commondatastorage.googleapis.com/assets_2048.png"
12 | TILE_SIZE = 100
13 | HALF_TILE_SIZE = TILE_SIZE / 2
14 | BORDER_SIZE = 45
15 |
16 | # Directions
17 | UP = 1
18 | DOWN = 2
19 | LEFT = 3
20 | RIGHT = 4
21 |
22 |
23 | class GUI:
24 | """
25 | Class to run game GUI.
26 | """
27 |
28 | def __init__(self, game):
29 | self._rows = game.get_grid_height()
30 | self._cols = game.get_grid_width()
31 | self._game = game
32 | self._tiles = simplegui.load_image(IMAGEURL)
33 | self._directions = {
34 | "up": UP,
35 | "down": DOWN,
36 | "left": LEFT,
37 | "right": RIGHT
38 | }
39 |
40 | self._frame = simplegui.create_frame(
41 | '2048',
42 | self._cols * TILE_SIZE + 2 * BORDER_SIZE,
43 | self._rows * TILE_SIZE + 2 * BORDER_SIZE
44 | )
45 | self._frame.add_button('New Game', self.start)
46 | self._frame.set_keydown_handler(self.keydown)
47 | self._frame.set_draw_handler(self.draw)
48 | self._frame.set_canvas_background("#BCADA1")
49 | self._frame.start()
50 |
51 | def keydown(self, key):
52 | """
53 | Keydown handler
54 | """
55 | for dirstr, dirval in self._directions.items():
56 | if key == simplegui.KEY_MAP[dirstr]:
57 | self._game.move(dirval)
58 | break
59 |
60 | def draw(self, canvas):
61 | """
62 | Draw handler
63 | """
64 | for row in range(self._rows):
65 | for col in range(self._cols):
66 | tile = self._game.get_tile(row, col)
67 | if tile == 0:
68 | val = 0
69 | else:
70 | val = int(math.log(tile, 2))
71 | canvas.draw_image(
72 | self._tiles,
73 | [HALF_TILE_SIZE + val * TILE_SIZE, HALF_TILE_SIZE],
74 | [TILE_SIZE, TILE_SIZE],
75 | [
76 | col * TILE_SIZE + HALF_TILE_SIZE + BORDER_SIZE,
77 | row * TILE_SIZE + HALF_TILE_SIZE + BORDER_SIZE
78 | ],
79 | [TILE_SIZE, TILE_SIZE]
80 | )
81 |
82 | def start(self):
83 | """
84 | Start the game.
85 | """
86 | self._game.reset()
87 |
88 |
89 | def run_gui(game):
90 | """
91 | Instantiate and run the GUI.
92 | """
93 | gui = GUI(game)
94 | gui.start()
95 |
--------------------------------------------------------------------------------
/ren'py/aling-nena-vn.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/WWCodeManila/Python)
2 |
3 | # Aling Nena's visual novel
4 |
5 | We'll be going through a simple interactive game featuring Aling Nena and her *apo* (grandchild). You may have met Aling Nena during one of our basic Python study groups.
6 |
7 | ## Plotline
8 |
9 | This game follows the adventure of the player (you!) as Aling Nena's grandchild who have visited her in the province one summer vacation. You'll be interacting with many **characters**:
10 |
11 | - Aling Nena, your grandmother
12 | - Lita and Boy, your friends
13 | - Bert and Tasya, Aling Nena's *suki* (loyal customers) in her *sari-sari* store (a small grocery store)
14 |
15 | The story takes places in various **scenes**:
16 |
17 | - Inside Aling Nena's house
18 | - Outside in the streets
19 | - In Aling Nena's store
20 | - The beach
21 |
22 | Along the way, you'll have to decide what your character will do next by selecting answers in a **menu** screen. Depending on your answers along the branching storyline, you'll either encounter a *good ending* or a *bad ending*.
23 |
24 | ## Materials
25 |
26 | The materials for this Ren'Py game tutorial are [here](http://bit.ly/wwcodemanila-renpy). These include:
27 |
28 | - [ ] code for the game
29 | - [ ] assets (images) for the game
30 |
31 | Feel free to play this game and/or look at the codes `script.rpy` and `batobato.rpy` to familiarize your self with the gameplay as well as how the code is structured.
32 |
33 | !> If you haven't done so already, create a new Ren'Py game from the launcher called `Aling Nena VN` or whatever title you want to put in. Make sure you set the screen size to 1980 px by 720 px.
34 |
35 | ## Scripts
36 |
37 | As mentioned earlier, Ren'Py creates default scripts with example codes and values when a new game is created:
38 |
39 | - `script.rpy` - contains the main dialogue and scenes in our game. This is the file we'll be working with the most in order to create our interactive novel.
40 | - `options.rpy` - here, we can specify some details about the game e.g. the title that will be shown in the main screen and the game version
41 | - `gui.rpy` - this is where we can change how the game will look like including accent colors, fonts, and menu borders.
42 | - `screens.rpy` - here we can set other properties of the game e.g. the positions of the menus and labels in each screen.
43 |
44 | In general, Ren'Py reads all `.rpy` scripts as one so we can actually split multiple parts of the game's narration into different `.rpy` files or just write all in a single file.
45 |
46 | # Exercise
47 |
48 | Open the script `script.rpy`. Clear everything from this file as we will be replacing the default story with our own story.
49 |
50 | Are you ready to learn how to make your own visual novel with Python? Let's begin!
51 |
52 | [](https://gitter.im/WWCodeManila/Python)
53 |
54 |
--------------------------------------------------------------------------------
/flask/discussions/04_url_routes.md:
--------------------------------------------------------------------------------
1 | ## Goal
2 |
3 | - [ ] Understand the different types of URL routes
4 |
5 | ## Getting Started
6 |
7 | Open `app.py` from the portfolio project that you created last time.
8 |
9 | 1. Replace the `hello_world` function name to `home` and change the return string from `Hello, World!` to `Home`.
10 |
11 | ```shell
12 | @app.route("/")
13 | def home():
14 | return "Home"
15 | ```
16 |
17 | The text `Home` should now be displayed when you run your application.
18 |
19 | 2. Add `@app.route("/home/")` after `@app.route("/")`.
20 |
21 | ```shell
22 | @app.route("/")
23 | @app.route("/home/")
24 | def home():
25 | return "Home"
26 | ```
27 |
28 | You should now be able to see the same display text when you go to `/home/` (e.g. http://127.0.0.1:5000/home/).
29 |
30 | 3. Copy and paste the next function `about` to your code.
31 |
32 | ```shell
33 | @app.route("/about")
34 | def about():
35 | return "About"
36 | ```
37 |
38 | If you try to access `/about`, you should be able to see the text `About`. However, if you try to access `/about/`, you will encounter a 404 encounter.
39 |
40 | To fix this, add a trailing slash (/) after the route name. This would let you access the URL regardless of whether you have a trailing slash or not.
41 |
42 | 4. Create a subroute of `about` that will allow users to input their location in the URL.
43 |
44 | ```shell
45 | @app.route("/about//")
46 | def about_location(location):
47 | return "I am from %s." % location
48 | ```
49 |
50 | If you try to access `/about/Earth/`, the text `I am from Earth.` will be displayed.
51 |
52 | 5. Add another route for `skills`.
53 |
54 | ```shell
55 | @app.route("/skills/")
56 | def skills():
57 | return "Skills"
58 | ```
59 |
60 | Then add a subroute that would accept the user's `toeic_score` as an integer.
61 |
62 | ```shell
63 | @app.route("/skills//")
64 | def skills_toeic(toeic_score):
65 | return "My TOEIC score is %d / 90." % toeic_score
66 | ```
67 |
68 | This allows you to specify the data type of the input that you'll receive.
69 |
70 | 6. Add a route named `projects` which accepts an integer named `amount`. Set the default value of `amount` to `0`.
71 |
72 | ```shell
73 | @app.route("/projects/", defaults={'amount': 0})
74 | @app.route("/projects/")
75 | def projects(amount):
76 | return "I have %d project/s to date." % amount
77 | ```
78 |
79 | This allows you to avoid displaying an invalid page in case there's no input from the user.
80 |
81 | 7. Lastly, add a route named `contacts`.
82 |
83 | ```shell
84 | @app.route("/contact/")
85 | def contact():
86 | return "Contact"
87 | ```
88 |
89 | ## Congratulations!
90 |
91 | Your portfolio now contains 5 main pages:
92 |
93 | * Home
94 | * About
95 | * Skills
96 | * Projects
97 | * Contact
98 |
99 | Feel free to customize them and their contents!
100 |
--------------------------------------------------------------------------------
/django/03_start_project.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 |
3 | - [ ] Starting the project
4 | - [ ] Setting things up
5 | - [ ] Running the server
6 |
7 | ## Starting the project
8 |
9 | Once you've installed the `Django` web framework inside your `env` virtual environment, start the project by typing this command:
10 | ```
11 | django-admin startproject forumapp .
12 | ```
13 |
14 | Your directory structure should look like this:
15 | ```
16 | django
17 | C:.
18 | │ manage.py
19 | │ requirements.txt
20 | │
21 | └───forumapp
22 | asgi.py
23 | settings.py
24 | urls.py
25 | wsgi.py
26 | __init__.py
27 | ```
28 | These files are:
29 |
30 | - The outer `django/` root directory is a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.
31 | - `manage.py`: A command-line utility that lets you interact with this Django project in various ways.
32 | - The inner `forumapp/` directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. forumapp.urls).
33 | - `forumapp/__init__.py`: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read [more about packages](https://docs.python.org/3/tutorial/modules.html#tut-packages) in the official Python docs.
34 | - `forumapp/settings.py`: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
35 | - `forumapp/urls.py`: The URL declarations for this Django project; a “table of contents” of your Django-powered site.
36 | - `forumapp/asgi.py`: An entry-point for ASGI-compatible web servers to serve your project. See [How to deploy with ASGI](https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/) for more details.
37 | - `forumapp/wsgi.py`: An entry-point for WSGI-compatible web servers to serve your project. See [How to deploy with WSGI](https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/) for more details.
38 |
39 | ## Setting things up
40 |
41 | Using your favorite text editor, go to `forumapp/settings.py`. The first thing that we need to consider editing is the `TIME_ZONE`. You may get the relevant time zone in the [Wikipedia's list of time zone.](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
42 |
43 | The code should look like this:
44 | ```
45 | TIME_ZONE = 'Asia/Manila'
46 | ```
47 |
48 | The second thing to check is the language. If English is not your native language, you can add this to change the default buttons and notifications from Django to be in your language.
49 | ```
50 | LANGUAGE_CODE = 'en-us'
51 | ```
52 |
53 | ## Running the server
54 | Once checked and ensured that the directory or the project that you are working on has the same structure stated above, run the server by typing this command:
55 | ```
56 | python manage.py migrate
57 | python manage.py runserver
58 | ```
59 |
60 | Check your browser, then go to `localhost:8000` or `http://127.0.0.1:8000/`.
61 |
62 |
--------------------------------------------------------------------------------
/ren'py/installation.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/WWCodeManila/Python)
2 |
3 | # Installation
4 |
5 | You'll need:
6 |
7 | - [ ] the Ren'Py software development kit
8 | - [ ] A code editor
9 |
10 | The Ren'Py binaries already include Python so you don't need to download the Python interpreter beforehand.
11 |
12 | ## Download
13 |
14 | You'll need to download the latest Ren'Py software development kit for your specific operating system. Currently, it is available for Windows XP and up, Mac OS X 10.6 and up, and Linux x86/x86_64.
15 |
16 | [Download it here](https://www.renpy.org/latest.html)
17 |
18 | You'll also need a text editor, preferably with code highlighting. If you have one installed already, you can set it up in *Preferences* (described below). If not, you can download through the Ren'Py engine (described below).
19 |
20 | ## Extract
21 |
22 | Once downloaded, double click on the installer to start the process (Windows). For Mac or Linux systems, you may either double click from the file viewer or use the commandline to extract the compressed file. To start the engine, double-click on `renpy.exe` for Windows, `renpy.app` for Mac or execute the`renpy` shell script for Linux inside the folder `renpy-`.
23 |
24 | You'll then be able to access the main screen of the Ren'Py engine.
25 |
26 |
27 |
28 | From here you can (1) Create new projects `+ Create New Project`; (2) Access the directories and scripts inside each project; (3) Launch a project or game; (3) Modify the settings of the engine `Preferences`; (4) Package a game for distribution, and many others.
29 |
30 | You can also access both the "Tutorial" and a sample Ren'Py game called "The Question". Check these out to learn more about Ren'Py by selecting the project name under `Projects` then clicking `Launch Project`.
31 |
32 | ## Setup editor
33 |
34 | To link a code editor with Ren'Py files (`*.rpy`), go to `Preferences`. Under `Text Editor`, you can then choose to download one of the editors e.g. *Atom, Editra*, or *jEdit*. Or specify an editor that you have already installed in your system in *System Editor*
35 |
36 |
37 |
38 | Once you have finished linking an editor to Ren'Py files, click `Return` to go back to the main screen.
39 |
40 |
41 |
42 | ## Exercise
43 |
44 | Try if you can launch the editor of your choice from the Ren'Py engine by selecting the project "The Question" and then clicking `script.rpy` under `Edit file`. (We'll learn what these scripts are later). You should be able to read the code in your code editor.
45 |
46 | That's it! You have now installed and setup the tools that we'll need in order to make a game (visual novel) using Python.
47 |
48 | [](https://gitter.im/WWCodeManila/Python)
49 |
50 |
--------------------------------------------------------------------------------
/sidebar.md:
--------------------------------------------------------------------------------
1 | - Women Who Code Manila
2 | - [About WWCode Manila](wwcodemanila/about.md)
3 | - [Study Groups](wwcodemanila/study_groups.md)
4 |
5 | - Getting Started
6 | - [Installation](getting_started/installation_guide.md)
7 | - [Run a basic Python program](getting_started/warm_up.md)
8 | - [Sharing your work](getting_started/exercise_upload_step.md)
9 |
10 | - Basic Concepts
11 | - [Variables, Arithmetic Operations, Keyboard Input](basic_concepts/variables.md)
12 | - [Let's go Git!](git/README.md)
13 | - [Strings pa more!](basic_concepts/strings.md)
14 | - [PEP8](basic_concepts/pep8.md)
15 | - [List, tuple, set](basic_concepts/lists.md)
16 | - [Conditional Statements](basic_concepts/conditional_statements.md)
17 | - [Loops](basic_concepts/loops.md)
18 | - [Challenge: I survived Hangman!](basic_concepts/exercises/hangman/README.md)
19 | - [Dictionaries](basic_concepts/dictionaries.md)
20 | - [Functions](basic_concepts/functions.md)
21 | - [Classes and Module](http://introtopython.org/classes.html)
22 | - [Error Handling](basic_concepts/error_handling.md)
23 | - [Challenge: It's 2048!](basic_concepts/exercises/2048/README.md)
24 |
25 | - Advanced Concepts
26 | - [List comprehension](https://hackernoon.com/list-comprehension-in-python-8895a785550b)
27 | - [Generators](https://anandology.com/python-practice-book/iterators.html)
28 | - [Decorators](http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/)
29 |
30 | - Flask
31 | - [Introduction](flask/discussions/01_introduction.md)
32 | - [Setting up Flask and virtual environments](flask/discussions/02_setup.md)
33 | - [Building my first Flask app](flask/discussions/03_my_first_flask_app.md)
34 | - [Creating URL routes](flask/discussions/04_url_routes.md)
35 | - [Styling templates and passing variables](flask/discussions/05_templates_and_variables.md)
36 | - Integrating databases using SQLite :soon:
37 | - Forming forms :soon:
38 | - Using cookies and sessions :soon:
39 | - Deploying my app :soon:
40 | - Wrapping up :soon:
41 |
42 | - Ren'Py
43 | - [Introduction](ren'py/introduction.md)
44 | - [Installation and setting up](ren'py/installation.md)
45 | - [Creating a new game](ren'py/create-new-game.md)
46 | - [Aling Nena VN](ren'py/aling-nena-vn.md)
47 | - [Tutorial Part 1](ren'py/scene1.md)
48 | - [Tutorial Part 2](ren'py/scene2.md)
49 | - [Tutorial Part 3](ren'py/scene3.md)
50 | - [Tutorial Part 4](ren'py/scene4.md)
51 | - [Tutorial Part 5 - Ending](ren'py/scene567.md)
52 |
53 | - Django
54 | - [Introduction](django/01_introduction.md)
55 | - [Setting up Django and virtual environments](django/02_setup.md)
56 | - [Creating your first Django application](django/03_start_project.md)
57 | - [Creating Users module](django/04_create_users_module.md)
58 | - [Creating endpoints](django/05_endpoints.md)
59 | - [Creating Questions module](django/06_create_questions_module.md)
60 |
61 | - Resources
62 | - [References](resources/references.md)
63 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/hangman/hangman.py:
--------------------------------------------------------------------------------
1 | # Hangman Game
2 | #
3 | # Credit to Michael Dawson's "Python Programming for the Absolute Beginner 3rd Edition"
4 | #
5 | # The classic game of Hangman. The computer picks a random word
6 | # and the player wrong to guess it, one letter at a time. If the player
7 | # can't guess the word in time, the little stick figure gets hanged.
8 |
9 | # imports
10 |
11 |
12 | # constants
13 | HANGMAN = (
14 | """
15 | ------
16 | | |
17 | |
18 | |
19 | |
20 | |
21 | |
22 | |
23 | |
24 | ----------
25 | """,
26 | """
27 | ------
28 | | |
29 | | O
30 | |
31 | |
32 | |
33 | |
34 | |
35 | |
36 | ----------
37 | """,
38 | """
39 | ------
40 | | |
41 | | O
42 | | -+-
43 | |
44 | |
45 | |
46 | |
47 | |
48 | ----------
49 | """,
50 | """
51 | ------
52 | | |
53 | | O
54 | | /-+-
55 | |
56 | |
57 | |
58 | |
59 | |
60 | ----------
61 | """,
62 | """
63 | ------
64 | | |
65 | | O
66 | | /-+-/
67 | |
68 | |
69 | |
70 | |
71 | |
72 | ----------
73 | """,
74 | """
75 | ------
76 | | |
77 | | O
78 | | /-+-/
79 | | |
80 | |
81 | |
82 | |
83 | |
84 | ----------
85 | """,
86 | """
87 | ------
88 | | |
89 | | O
90 | | /-+-/
91 | | |
92 | | |
93 | | |
94 | | |
95 | |
96 | ----------
97 | """,
98 | """
99 | ------
100 | | |
101 | | O
102 | | /-+-/
103 | | |
104 | | |
105 | | | |
106 | | | |
107 | |
108 | ----------
109 | """)
110 |
111 | MAX_WRONG = len(HANGMAN)-1
112 | WORDS = ("OCTOPUS", "NEMO", "STARFISH", "ORCA") # Change these as you please
113 |
114 |
115 | # initialize variables
116 | word = "" # pick random word to be guessed
117 | so_far = "-" * len(word) # one dash for each letter in word to be guessed
118 | wrong = 0 # number of wrong guesses player has made
119 | used = [] # letters already guessed
120 |
121 |
122 | print("Welcome to Hangman. Good luck!")
123 |
124 | # Ask for a guess while the game is not yet over
125 | while True:
126 | print(HANGMAN[wrong])
127 | print(f"You have {MAX_WRONG-wrong} guesses left!")
128 | print("\nYou've used the following letters:\n", used)
129 | print("\nSo far, the word is:\n", so_far)
130 |
131 | # Get new user guess with a TWIST :P
132 | guess = input("\n\nEnter your guess: ")
133 |
134 | # Check if guess is right or wrong
135 |
136 | # If right, need to update user_guess
137 |
138 | # If wrong, need to increment wrong count
139 |
140 | # Inform if the user won or lose
141 |
142 | print("\nThe word was", word)
143 |
144 | input("\n\nPress the enter key to exit.")
145 |
146 |
--------------------------------------------------------------------------------
/basic_concepts/loops.md:
--------------------------------------------------------------------------------
1 | Can you tell what the code below does?
2 | ```python
3 | continents = ['Africa', 'Antarctica', 'Asia', 'Australia/Oceania', 'Europe', 'North America', 'South America']
4 | print(continents[0])
5 | print(continents[1])
6 | print(continents[2])
7 | print(continents[3])
8 | print(continents[4])
9 | print(continents[5])
10 | print(continents[6])
11 | ```
12 |
13 | Yes! It prints out the continents of the world! You may have noticed that this is a situation where we want to do some action on each item in a list (in this case, that is to print out the continent name). But what if we have a list containing all the countries of the world and wanted to print out each country? Do we need to painstakingly write a hundred of print statements? Or you started thinking, `Is there a way that allows us to go through the list and execute the same action multiple times`?
14 |
15 | Yes! Python loops allows us to:
16 | * Iterate through the list and perform an action to each element of the list
17 | * Execute a block of code multiple times
18 |
19 | ## Syntax
20 |
21 | ### For loop
22 | The `for` loop has the ff. syntax:
23 | ```shell
24 | for in :
25 |
26 | ```
27 |
28 | Say no to repeated lines of code! Let's rewrite the code above using a for loop!
29 | ```python
30 | continents = ['Africa', 'Antarctica', 'Asia', 'Australia/Oceania', 'Europe', 'North America', 'South America']
31 | for continent in continents:
32 | print(continent)
33 |
34 | # Will print out
35 | # Africa
36 | # Antarctica
37 | # Asia
38 | # Australia/Oceania
39 | # Europe
40 | # North America
41 | # South America
42 | ```
43 |
44 | ### While loop
45 | The `while` loop has the ff. syntax:
46 | ```shell
47 | while :
48 |
49 | ```
50 |
51 | The `while` loop allows us to repeatedly execute a block of code as long as the expression evaluates to `True`. Let's do a New Year countdown!
52 | ```python
53 | count = 10
54 | while count > 0:
55 | print(count)
56 | count = count - 1
57 | print('Happy New Year!')
58 | ```
59 |
60 | ## Takeaways
61 | * We can use `break`, `continue` and `pass` as control statements in the loop. Google it!
62 |
63 | !> Beware of Infinite loop! Use `while` loops with caution because if the expression did **NOT** resolve to a `False` the loooooooooooooop will go on forever just like below.
64 |
65 | ```python
66 | is_hungry = True
67 | while is_hungry:
68 | print('Vikings here I come!')
69 |
70 | ```
71 |
72 |
73 | ## Challenge
74 | During closing, Aling Nena counts from her vault the day's total income and
75 | also the total amount of all her paper bills.
76 |
77 | Help Aling Nena count her total income and total amount of her paper bills
78 | from a list of cash money and using a loop!
79 |
80 | Example:
81 |
82 | ```shell
83 | >> Hi Aling Nena! Your total income for the day is 2947.
84 | >> The total amount of your paper bills is 2920.
85 | ```
86 |
87 |
88 | !> Please use below template
89 |
90 | [loops](exercises/loops/loops01.py ':include :type=code python')
91 |
92 | [challenge_partial](../challenge_partial.md ':include')
93 |
94 |
95 | ## Put your thinking cap on!
96 |
97 | - What are the specific characteristics of the `for` and `while` loop?
98 | - What is the effect of `break`, `continue` and `pass` control statements in a loop?
99 |
--------------------------------------------------------------------------------
/_sidebar.md:
--------------------------------------------------------------------------------
1 | - Women Who Code Manila
2 | - [About WWCode Manila](wwcodemanila/about.md)
3 | - [Study Groups](wwcodemanila/study_groups.md)
4 |
5 | - Getting Started
6 | - [Installation](getting_started/installation_guide.md)
7 | - [Run a basic Python program](getting_started/warm_up.md)
8 | - [Sharing your work](getting_started/exercise_upload_step.md)
9 |
10 | - Basic Concepts
11 | - [Variables, Arithmetic Operations, Keyboard Input](basic_concepts/variables.md)
12 | - [Let's go Git!](git/README.md)
13 | - [Strings pa more!](basic_concepts/strings.md)
14 | - [PEP8](basic_concepts/pep8.md)
15 | - [List, tuple, set](basic_concepts/lists.md)
16 | - [Conditional Statements](basic_concepts/conditional_statements.md)
17 | - [Loops](basic_concepts/loops.md)
18 | - [Challenge: I survived Hangman!](basic_concepts/exercises/hangman/README.md)
19 | - [Dictionaries](basic_concepts/dictionaries.md)
20 | - [Functions](basic_concepts/functions.md)
21 | - [Classes and Module](http://introtopython.org/classes.html)
22 | - [Error Handling](basic_concepts/error_handling.md)
23 | - [Challenge: It's 2048!](basic_concepts/exercises/2048/README.md)
24 |
25 | - Advanced Concepts
26 | - [List comprehension](https://hackernoon.com/list-comprehension-in-python-8895a785550b)
27 | - [Generators](https://anandology.com/python-practice-book/iterators.html)
28 | - [Decorators](http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/)
29 |
30 | - Flask
31 | - [Introduction](flask/discussions/01_introduction.md)
32 | - [Setting up Flask and virtual environments](flask/discussions/02_setup.md)
33 | - [Building my first Flask app](flask/discussions/03_my_first_flask_app.md)
34 | - [Creating URL routes](flask/discussions/04_url_routes.md)
35 | - [Styling templates and passing variables](flask/discussions/05_templates_and_variables.md)
36 | - Integrating databases using SQLite :soon:
37 | - Forming forms :soon:
38 | - Using cookies and sessions :soon:
39 | - Deploying my app :soon:
40 | - Wrapping up :soon:
41 |
42 | - Ren'Py
43 | - [Introduction](ren'py/introduction.md)
44 | - [Installation and setting up](ren'py/installation.md)
45 | - [Creating a new game](ren'py/create-new-game.md)
46 | - [Aling Nena VN](ren'py/aling-nena-vn.md)
47 | - [Tutorial Part 1](ren'py/scene1.md)
48 | - [Tutorial Part 2](ren'py/scene2.md)
49 | - [Tutorial Part 3](ren'py/scene3.md)
50 | - [Tutorial Part 4](ren'py/scene4.md)
51 | - [Tutorial Part 5 - Ending](ren'py/scene567.md)
52 |
53 | - Django
54 | - [Introduction](django/01_introduction.md)
55 | - [Setting up Django and virtual environments](django/02_setup.md)
56 | - [Creating your first Django application](django/03_start_project.md)
57 | - [Creating Users module](django/04_create_users_module.md)
58 | - [Creating Users endpoints](django/05_endpoints.md)
59 | - [Creating Questions module](django/06_create_questions_module.md)
60 | - [Creating the frontend of the application](django/07_create_frontend.md)
61 | - [Adding VueJS to the application](django/08_add_vue.md)
62 | - [Adding VueJS to the application (continuation)](django/09_vue_cont.md)
63 |
64 | - Resources
65 | - [References](resources/references.md)
66 |
--------------------------------------------------------------------------------
/ren'py/create-new-game.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/WWCodeManila/Python)
2 |
3 | The Ren'Py software development kit already provides features such as saving, loading, and adjusting the preferences in a game. When you create a new game, you'll already have access to a game menu interface! All you really need to focus on is on creating the game itself.
4 |
5 | # Creating a new game
6 |
7 | 1. In the Ren'Py engine, click `+ Create New Project` .
8 |
9 |
10 |
11 | 2. The default language settings is in English. If you're going to use another language, go to to `Preferences` and choose the appropriate language. Otherwise, click `Continue` at the next prompt.
12 |
13 |
14 |
15 | 3. Next, you'll need to input the *Project Name*, then click `Continue`.
16 |
17 |
18 |
19 | 4. In the next window, you'll have to specify the *resolution of your game*. Whatever resolution you choose, make sure to fit your assets (backgrounds, character images, and other game images) in this size. Then, click `Continue`.
20 |
21 |
22 |
23 | 5. Choose the *accent and background colors*. You can change these later on in the scripts. Then, click `Continue`.
24 |
25 |
26 |
27 | 6. It will take a few seconds to setup the game environments.
28 |
29 |
30 |
31 | 7. Once done, you'll be able to see the Project Name you specified in the main menu of the Ren'Py engine. Ren'Py has preloaded some of the scripts with the default codes and values. Under `Edit File`, click `All script files` to see all of these scripts in your code editor, or click `Launch Project` to see the default game interface.
32 |
33 |
34 |
35 |
36 |
37 | The default game interface will look like this:
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | # Exercise
46 |
47 | In order to go ahead with the next parts of this study guide, first create a new Ren'Py game from the launcher. Set the title to `Aling Nena VN` or whatever title you want to put in. Make sure you set the screen size to 1980 px by 720 px.
48 |
49 | Next, we'll know more about the plot of Aling Nena's visual novel.
50 |
51 | [](https://gitter.im/WWCodeManila/Python)
52 |
53 |
--------------------------------------------------------------------------------
/flask/discussions/09_deployment.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 |
3 | - [ ] Deploy your first Flask application to Heroku via GitHub
4 |
5 | ## Heroku
6 |
7 | Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.
8 |
9 | While they have a free plan that is ideal for experimenting with cloud applications in a limited sandbox, they also have good pricing options based on dynos consumed. Dynos are smart, lightweight containers built for modern languages and developer productivity. Basically, you only pay for what you use, prorated to the second.
10 |
11 | ## Creating a Heroku application
12 |
13 | After signing up and logging in, you will be redirected to the dashboard.
14 |
15 | It displays your account type, where the default is Personal. You can also create teams to collaborate with other people, although you need to add a valid credit card to do so. Below that, it lists all the applications that you have so far, its name (alyssonalvaran), application type (Python), stack type (heroku-16), and region (United States).
16 |
17 | To create a new app, click the New button across your account type located on the upper right portion of your dashboard and select Create new app.
18 |
19 | You will be asked to provide an app name and region. For demonstration purposes, I created an app named pineapples-on-pizza.
20 |
21 | Once you select Create app, the next screen that will appear is the deploy tab of your newly created application. At this point, you can already access your app by selecting the Open app button on the upper right portion of your dashboard or going to .herokuapp.com, which is my case is https://pineapples-on-pizza.herokuapp.com/.
22 |
23 | Now that you’re done creating a Heroku app, the next thing that you have to do is to prepare your Flask app.
24 |
25 | ## Green unicorn
26 |
27 | Green unicorn, or simply Gunicorn, is a Python Web Server Gateway Interface (WSGI) HTTP server for UNIX, ported from Ruby’s Unicorn project. Basically, this lightweight pre-fork worker model will enable us to deploy our Flask app to Heroku.
28 |
29 | You can install this easily through pip.
30 |
31 | ```
32 | $ pip3 install gunicorn
33 | ```
34 |
35 | After installing, create a file named Procfile (yes, without an extension) and add this line here inside:
36 |
37 | ```
38 | web: gunicorn app:app
39 | ```
40 |
41 | ## requirements.txt
42 |
43 | That’s it! The final preparation that you have to do is to make sure that all of your packages are frozen to the text file requirements.txt. You can do this by simply entering this in the command line:
44 |
45 | ```
46 | $ pip3 freeze > requirements.txt
47 | ```
48 |
49 | ## Connecting your Heroku app to a GitHub repository
50 |
51 | Assuming that you have already pushed your latest changes to your GitHub repository, go back to the deploy tab of your Heroku application. In the Deployment method section, select GitHub. This opens the Connect to GitHub where you can search for a repository to connect to. Just search the name of your repository, which in my case is pineapples-on-pizza, and select the connect button.
52 |
53 | Congratulations! Your Flask app is now deployed at pineapples-on-pizza.herokuapp.com!
54 |
55 | ## Bonus: Automatic deploys
56 |
57 | You can automatically deploy your Heroku app everytime you push something to your GitHub repository by simply choosing a branch to deploy (default is Master) and selecting the Enable Automatic Deploys button in the Automatic deploys section of your Heroku app’s deploy tab.
--------------------------------------------------------------------------------
/getting_started/installation_guide.md:
--------------------------------------------------------------------------------
1 | We need to install the **Python interpreter** first!
2 |
3 | !> For our study group, we will be using `Python 3`, preferably >= `Python 3.6`.
4 |
5 | You also need to have a **text editor** to write your code in. This can be (but not limited to) one of the following:
6 |
7 | * [Atom](https://atom.io)
8 | * [Gedit](https://wiki.gnome.org/Apps/Gedit)
9 | * [Notepad++](https://notepad-plus-plus.org)
10 | * [Sublime Text](https://www.sublimetext.com)
11 | * [Visual Studio Code](https://code.visualstudio.com)
12 |
13 |
14 |
15 | ## Check existing Python installation
16 |
17 | To check if Python is already installed in your system, open your terminal or command prompt.
18 |
19 | - For Windows users, search for `cmd`
20 | - For Linux and Mac users, search for `terminal`
21 |
22 | After opening the terminal/command prompt(cmd), type the following command.
23 | ```shell
24 | python --version
25 | ```
26 |
27 | or
28 |
29 | ```shell
30 | python3 --version
31 | ```
32 |
33 | This will tell you what version of python is currently installed in your computer.
34 |
35 | ```shell
36 | Python 3.6.0
37 |
38 | ```
39 | > If python 3 is already installed, skip the next part.
40 |
41 |
42 | ## Tutorial
43 |
44 | For a detailed installation process, you can [use this tutorial](https://tutorial.djangogirls.org/en/python_installation).
45 |
46 | ### Windows and OS X
47 |
48 | 1. Download the installer for the latest version from the [Python Software Foundation](https://www.python.org/downloads/release).
49 | 2. Run the installer by double-clicking it, and following the succeeding instructions.
50 |
51 | !> For **Windows** users, please don't forget to add Python in your PATH as per below.
52 |
53 | 
54 |
55 |
56 | !> For **OS X** users, ensure your Mac settings allow installing packages that are not from the App Store. Go to `"System Preferences" > "Security & Privacy," > "General"`. Set "Allow apps downloaded from:" to "Mac App Store and identified developers."
57 |
58 |
59 | ### Linux
60 |
61 | Check the Linux distrubution using the `terminal`
62 |
63 | ```
64 | grep ^NAME= /etc/os-release
65 | ```
66 |
67 | Type one of the following commands in the `termimal` depending on your respective Linux distribution.
68 |
69 | * **Debian** or **Ubuntu**
70 |
71 | ```
72 | sudo apt install python3
73 | ```
74 |
75 | * **Fedora**
76 |
77 | ```
78 | sudo dnf install python3
79 | ```
80 |
81 | * **openSUSE**
82 |
83 | ```
84 | sudo zypper intall python3
85 | ```
86 |
87 | You can also try [compiling from source](https://realpython.com/installing-python/#compiling-python-from-source) if you want the latest version or an alternative installation of Python.
88 |
89 | ### Chromebook
90 |
91 | For Chromebook users, you'll need to connect to a cloud IDE provider. You can follow [these instructions](https://tutorial.djangogirls.org/en/chromebook_setup).
92 |
93 |
94 |
95 | Finally, [check if you have successfully installed Python](#check-existing-python-installation).
96 |
97 |
98 | Done! You can now start coding in Python!
99 |
100 | ## Put your thinking cap on!
101 |
102 | - What are my challenges upon installing Python? How did I solved them?
103 | - [Do I need Python 2 or 3?](https://wiki.python.org/moin/Python2orPython3)
104 | - What are the differences between Python 2 and 3?
105 |
--------------------------------------------------------------------------------
/basic_concepts/strings.md:
--------------------------------------------------------------------------------
1 | ## Definition
2 | A string is a series of letters, numbers, symbols enclosed in single quote (‘) or double quote (“).
3 |
4 | ## Creation
5 | Let's try some ways to create strings!
6 |
7 | ```python
8 | greeting = "WWC is awesome!"
9 | title = 'StringPaMore'
10 | hash_symbol = "#"
11 | hashtag = hash_symbol + title
12 | rating = str(5)
13 | print("{} {} stars for them! {}".format(greeting, rating, hashtag))
14 | # print(f"{greeting} {rating} stars for them! {hashtag}") # For versions Python3.6
15 | ```
16 |
17 | ## String methods
18 | Let's try some string methods!
19 |
20 | ```python
21 | movie_title = "My ex and whys"
22 | print(len(movie_title))
23 |
24 | comment = "HINDI AKO GALIT!"
25 | print(comment.lower())
26 | print(comment.islower())
27 |
28 | shout = "darna!"
29 | print(shout.upper())
30 | ```
31 |
32 | ## Accessing string characters
33 | Given a person's firstname and lastname, can we get the name initial?
34 | 
35 |
36 |
37 | !> Experiment on how to print the name initials with the code below!
38 |
39 | ```python
40 | firstname = "Fred"
41 | lastname = "Jowson"
42 |
43 | # TRY TO FIGURE OUT HOW TO PRINT OUT THE NAME INITIALS
44 | ```
45 |
46 | > We can access string characters through this syntax: **your_string[index]**
47 |
48 | > Each character in a string is represented by an index number starting from 0
49 |
50 | Here's an image to guide you with indexing.
51 |
52 | 
53 |
54 | Let's experiment more!
55 |
56 | [my_strings](samples/my_strings.py ':include :type=code python')
57 |
58 |
59 | ## Immutable
60 |
61 | Now, since we can access characters from a string, let's try to change its value!
62 | Is the code below successful?
63 |
64 | ```python
65 | mispelled_word = "beleive"
66 | # This should raise an error
67 | mispelled_word[3] = "i"
68 | mispelled_word[4] = "e"
69 |
70 | # What we can do is to re-assign the variable to a new string
71 | mispelled_word = "believe"
72 | ```
73 |
74 | !> Strings are **immutable**, meaning we cannot change it's value after creation.
75 | Hence, the code above resulted to an error!
76 |
77 |
78 | ## Challenge
79 | This summer, Aling Nena’s Sari-sari store wants to implement a reward system
80 | where customers can redeem a reward by texting the following:
81 |
82 | <**Reward number 1-9**> <**Customer’s name**> <**Gender f or m**>
83 |
84 | ```shell
85 | >> Please enter text: 1 nicole i. tibay f
86 | ```
87 |
88 | The system will then reply the following:
89 |
90 | Hi <**Customer’s name Capitalized**>! You have successfully redeem
91 | reward #<**reward number**> - <**reward**>! Thank you for choosing Aling Nena’s Sari-sari store.
92 |
93 | ```shell
94 | >> Hi Nicole I. Tibay! You have successfully redeem reward #1 - Coke sakto!
95 | Thank your for choosing Aling Nena’s Sari-sari store”
96 | ```
97 |
98 | > Let’s assume that customers will always comply with the text format and give 1-9 number.
99 |
100 | !> Please use below template
101 |
102 | [filename](exercises/strings/strings01.py ':include :type=code python')
103 |
104 | [challenge_partial](../challenge_partial.md ':include')
105 |
106 |
107 | ## Put your thinking cap on!
108 |
109 | - What is the reasoning behind PEP8's break before binary operations?
110 | - What does the `str()` function do?
111 | - Do you find any difference in using `len()` and `.lower()`? Can you explain?
112 | - Explain string immutability.
113 |
--------------------------------------------------------------------------------
/django/07_create_frontend.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 | - [ ] Create a Registration Link on the Login Page
3 | - [ ] Create a Login Link on the Registration Page
4 | - [ ] Adding Margins to Layout
5 | - [ ] Adding a Border
6 |
7 | ## Create a Registration Link on the Login Page
8 | Yay! We are done setting-up the backend of our application! Now, we will be focusing on the front-end side of the app. We want to make it more `user-friendly` that is why we are going to modify or add a few things.
9 |
10 | Open `templates/registration/login.html`. Add this line of code after `
Login
`:
11 |
12 | ```
13 |
Share Your Knowledge!
14 | ```
15 |
16 | Also, add the registration link inside the class `login-form-container` after the `form` tag:
17 |
18 | ```
19 |
38 | {% endblock %}
39 | ```
40 |
41 | Go to url `http://localhost:8000/accounts/login/` and see the changes.
42 |
43 | ## Create a Login Link on the Registration Page
44 | In this part, we are going to do the same steps. In `templates/django_registration/registration_form.html`, add this code inside the class `registration-form-container`, under the `form` tag.
45 |
46 | ```
47 |
64 | {% endblock %}
65 | ```
66 |
67 | Then check the changes by accessing this url: `http://localhost:8000/accounts/register/`.
68 |
69 | ## Adding Margins to Layout
70 | In this part, we are going to add some margins to our `registration` page and `login` page.
71 | In `templates/auth_layout.html`, add a css class called `outer-area`. The style would look as follows:
72 | ```
73 | .outer-area {
74 | margin-top: 100px;
75 | }
76 | ```
77 | Then add a new div tag outside the div class `auth-box text-center`. In the newly added div tag, call the `outer-area` class. It should look like this:
78 |
79 | ```
80 |
81 |
82 |
83 |
84 | {% block content %}
85 | {% endblock %}
86 |
87 |
88 |
89 |
90 | ```
91 |
92 | ## Adding a Border
93 | To add a border on registration and login page, add a css class named `auth-box`. Then add these other details:
94 | ```
95 | .auth-box {
96 | border: 3px solid lightgray;
97 | border-radius: 10px;
98 | padding-top: 25px;
99 | padding-bottom: 25px;
100 | width: 600px;
101 | margin: auto;
102 | }
103 | ```
--------------------------------------------------------------------------------
/basic_concepts/conditional_statements.md:
--------------------------------------------------------------------------------
1 | In our everyday living, we perform action based on a decision, situation or condition:
2 | ```shell
3 | Take a taxi if we are already late for work; else, we will take the jeepney.
4 | ```
5 |
6 | Now let's switch to our geeky world and alas, we were in a situation where:
7 | * We only want to execute a block of code depending on a condition:
8 | ```shell
9 | Add points to a customer if s/he presented a reward card.
10 | ```
11 |
12 | * We need to perform different actions based on the situation:
13 | ```shell
14 | Sends out SMS if customer has enough load, else prompt for an insufficient balance message.
15 | ```
16 |
17 | Python offers decision making statements in order for us to conditionally execute a block of code. But before introducing those, let us recall that an action will only be executed if it meets a `condition` or `situation`, expressions that evaluates to `True` or `False`. Let's try to code some expressions!
18 |
19 | ## Conditional Expressions
20 |
21 | !> Conditional expressions are expressions that evaluates to either True or False.
22 |
23 | ```python
24 | # EXPRESSIONS
25 |
26 | # Using literal values
27 | is_late = True
28 | is_card_presented = False
29 | print(is_late, is_card_presented)
30 |
31 | # Null or Zero values evaluates to False
32 | customer_card = None
33 | print(customer_card)
34 |
35 | # Using operations
36 | customer_load = 99
37 |
38 | customer_load == 100 # Evaluates to False
39 | customer_load > 0 # Evaluates to True
40 | "Nissin".startswith("c") # Evaluates to False
41 | ```
42 |
43 | Expressions? Checked! Let's dive to some Python decision making statements:
44 |
45 | ## Conditional Statements
46 |
47 | * If statements
48 |
49 | ```python
50 | is_card_presented = False
51 | customer_points = 10
52 | if is_card_presented:
53 | # Can you shorten the expression below?
54 | customer_points = customer_points + 1
55 | ```
56 |
57 | * If...else statements
58 |
59 | ```python
60 | def send_message(message):
61 | # This is a function, we will learn more about this on our next session!
62 | print('Sending: {}'.format(message))
63 |
64 |
65 | customer_load = 100
66 | message = 'Happy to serve!'
67 | if customer_load > 0:
68 | # call our function
69 | send_message(message)
70 | print('Your message is sent!')
71 | # Again, can you shorten the expression below?
72 | customer_load = customer_load - 1
73 | else:
74 | print('You have insufficient balance.')
75 | ```
76 |
77 |
78 | ## Takeaways
79 | * Notice how we group the actions(block of codes) above? We use the colon `:` to indicate the start of an indented block of code and grouped them by `whitespaces`.
80 | * PEP8 recommends using `4` whitespaces for code indentation.
81 |
82 |
83 | ## Challenge
84 | Aling Nena stores her soft drink stock on two refrigerators.
85 | She stores `Coke, Sprite and Royal` on her Sari-sari store's refrigerator while
86 | `RC and 7UP` can be found on her house's refrigerator.
87 |
88 | Help Aling Nena to properly respond to her customer when buying softdrinks.
89 |
90 | The reply will depend if the soft drink brand is on the store's ref,
91 | on the house's ref or none. If the customer buys a soft drink brand that is:
92 | 1. stored on the store, she will respond `Got it!`
93 | 2. stored on the house, she will respond `Please wait for a while!`
94 | 3. not sold by her, she will respond `Sorry we do not sell that. We only have `
95 |
96 |
97 | !> Please use below template
98 |
99 | [filename](exercises/conditional_statements/conditional01.py ':include :type=code python')
100 |
101 | [challenge_partial](../challenge_partial.md ':include')
102 |
103 | ## Put your thinking cap on!
104 |
105 | - What are the different ways to write conditional statements?
106 |
--------------------------------------------------------------------------------
/django/05_endpoints.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 | - [ ] Create a homepage endpoint
3 | - [ ] Create endpoints for users module
4 |
5 | ## Create a homepage endpoint
6 | We are now going to create our endpoint. Endpoints provide a useful information about the user that is currently connected to the application.
7 |
8 | We saw in the `settings.py` file that the URLs are set to these. Now, we are going to create a path that points to homepage('/') and link a view to render the template.
9 | ```
10 | LOGIN_REDIRECT_URL = '/'
11 | ```
12 |
13 | Create a folder in the root directory called `core`. Inside the folder create `__init__.py` and `views.py`. Inside the view, add this script.
14 | ```
15 | from django.contrib.auth.mixins import LoginRequiredMixin
16 | from django.views.generic.base import TemplateView
17 |
18 |
19 | class IndexTemplateView(LoginRequiredMixin, TemplateView):
20 |
21 | # overwrite the method
22 | def get_template_names(self):
23 | template_name = 'index.html'
24 | return template_name
25 | ```
26 | We have the the `template_name` to `index.html`, but we don't have it yet, so we are going to create it inside the folder `templates`.
27 | ```
28 |
29 |
30 |
31 |
32 |
33 |
34 | Forum App
35 |
36 |
37 |
38 |
Vue JS
39 |
40 |
41 |
42 |
43 |
44 | ```
45 |
46 | Create a path for the class `IndexTemplateView`. Import it inside the `forumapp/urls.py`.
47 |
48 | ```
49 | from core.views import IndexTemplateView
50 |
51 | # Put this at the end of the urlpatterns
52 | re_path(r"^.*$", IndexTemplateView.as_view(), name='entry-point'),
53 | ```
54 |
55 | Check again your browser, then go to `localhost:8000` or `http://127.0.0.1:8000/`. You should be seeing Vue JS text.
56 |
57 | ## Create endpoints for users module
58 | We will continue creating endpoints for the users module. Create the folder `api` in `users` module. Inside it, create the ff folders:
59 | ```
60 | - serializers.py
61 | - urls.py
62 | - views.py
63 | ```
64 |
65 | Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes, then rendered to `JSON`, or `XML`.
66 |
67 | In `users/api/serializers.py`, add this set of code:
68 | ```
69 | from rest_framework import serializers
70 | from users.models import CustomUser
71 |
72 |
73 | class UserDisplaySerializer(serializers.ModelSerializer):
74 |
75 | class Meta:
76 | model = CustomUser
77 | fields = ["username"]
78 | ```
79 |
80 | The view function, takes a web request and returns a web response. It is important to know that views handles the logic that gets processed each time a different URL is visited.
81 |
82 | In `users/api/views.py`, add this block of code:
83 |
84 | ```
85 | from rest_framework.response import Response
86 | from rest_framework.views import APIView
87 | from users.api.serializers import UserDisplaySerializer
88 |
89 |
90 | class CurrentUserAPIView(APIView):
91 |
92 | def get(self, request):
93 | serializer = UserDisplaySerializer(request.user)
94 | return Response(serializer.data)
95 | ```
96 |
97 | We need to ensure that our created view is registered in `users/api/urls.py`.
98 | ```
99 | from django.urls import path
100 | from users.api.views import CurrentUserAPIView
101 |
102 | urlpatterns = [
103 | path("user/", CurrentUserAPIView.as_view(), name="current-user")
104 | ]
105 | ```
106 |
107 | And in `forumapp/urls.py`, register the api under users.
108 | ```
109 | path("api/", include("users.api.urls")),
110 | ```
111 |
112 | Again reload and check your browser! Access this URL:
113 | `localhost:8000/api/user/`
114 |
115 | As you can see in the browser, the `username` is shown. It is because of what we did earlier in the serializer and view.
116 |
117 |
118 |
--------------------------------------------------------------------------------
/flask/discussions/02_setup.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 |
3 | - [ ] Understand the importance of virtual environments
4 | - [ ] Install and create a virtual environment
5 | - [ ] Install and use `virtualenvwrapper`
6 | - [ ] Install Flask through pip
7 |
8 | ## Virtual Environments
9 |
10 | A **virtual environment** is a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages. It is used to isolate a particular project to avoid conflicts with the requirements of another project. **`virtualenv`** is a tool used to create Python virtual environments.
11 |
12 | ## Installing 'virtualenv'
13 |
14 | Check if `virtualenv` already exists in your system through your terminal or console:
15 |
16 | ```shell
17 | $ virtualenv --version
18 | ```
19 |
20 | If you see a version number, that means you already have it installed and may now proceed to the next step. Otherwise, install `virtualenv` through the Python package manager, a.k.a. `pip`:
21 |
22 | ```shell
23 | $ pip install virtualenv
24 | ```
25 |
26 | Visit this [link](https://packaging.python.org/guides/installing-using-pip-and-virtualenv/) for more info on how to make sure you have the latest version of pip installed.
27 |
28 | ## Working with 'virtualenv'
29 |
30 | To create a virtual environment, go to your project's directory and run `virtualenv`:
31 |
32 | ```shell
33 | cd path/to/directory
34 | virtualenv env
35 | ```
36 |
37 | The second argument refers to the location where you want to create the `virtualenv`. Generally, you can just create this in your project and call it `env`. `virtualenv` will create a virtual Python installation in the `env` folder.
38 |
39 | **Note**: Don't forget to exclude your `virtualenv` directory from your version control system using .gitignore or similar.
40 |
41 | To activate your `virtualenv`:
42 |
43 | ```shell
44 | Windows
45 | $ .\env\Scripts\activate
46 |
47 | Linux and macOS
48 | $ source env/bin/activate
49 | ```
50 |
51 | To confirm if you're in the `virtualenv` by checking the location of your Python interpreter, which should point to the `env` directory:
52 |
53 | ```shell
54 | Windows
55 | $ where python
56 |
57 | Linux and macOS
58 | $ which python
59 | ```
60 |
61 | As long as your `virtualenv` is activated, pip will install packages into that specific environment and you'll be able to import and use packages in your Python application.
62 |
63 | To leave your `virtualenv`, simply run:
64 |
65 | ```shell
66 | $ deactivate
67 | ```
68 |
69 | ## Bonus: virtualenvwrapper
70 |
71 | To make working with virtual environments easier (especially for Windows uers), you can use [virtualenvwrapper](http://virtualenvwrapper.readthedocs.io/en/latest/), which is a set of extensions to the `virtualenv` tool. It also places all of your virtual environments in a single location.
72 |
73 | ```shell
74 | Mac:
75 | $ pip install virtualenvwrapper
76 | $ export WORKON_HOME=~/Envs
77 | $ source /usr/local/bin/virtualenvwrapper.sh
78 |
79 | Windows:
80 | $ pip install virtualenvwrapper-win
81 | ```
82 |
83 | Once you've installed `virtualenvwrapper`, create a new isolated development environment:
84 |
85 | ```shell
86 | mkvirtualenv portfolio
87 | ```
88 |
89 | This produced a folder named `portolio` inside the `Envs` folder with a clean copy of Python inside.
90 |
91 | To activate `virtualenv` with `virtualenvwrapper`:
92 |
93 | ```shell
94 | $ workon portfolio
95 | ```
96 |
97 | You may also check the list of existing virtual environments in your `Envs` folder by typing:
98 |
99 | ```shell
100 | $ workon
101 | ```
102 |
103 | ## Installing Flask
104 |
105 | To install flask through `pip`, just run:
106 |
107 | ```shell
108 | $ pip install flask
109 | ```
110 |
111 | ## Saving packages
112 |
113 | To save the list of packages installed in your environment for easier reproduction:
114 |
115 | ```shell
116 | $ pip freeze > requirements.txt
117 | ```
118 |
119 | This will save what you've installed so far in a text file named `requirements.txt`.
120 |
121 | To install the packages listed in a `requirements.txt` file:
122 |
123 | ```shell
124 | $ pip install -r requirements.txt
125 | ```
126 |
--------------------------------------------------------------------------------
/basic_concepts/exercises/2048/logic.py:
--------------------------------------------------------------------------------
1 | """ Clone of 2048 game.
2 | Credit to:
3 | http://flothesof.github.io/2048-game.html
4 | https://github.com/enixdark/principlescomputing-001/tree/master/Week0
5 |
6 | Game instruction:
7 | https://github.com/enixdark/principlescomputing-001/blob/master/Week0/Instructions.md
8 | To run:
9 | python logic.py
10 | """
11 | import poc_2048_gui
12 |
13 | # Directions, DO NOT MODIFY
14 | UP = 1
15 | DOWN = 2
16 | LEFT = 3
17 | RIGHT = 4
18 |
19 | # Offsets for computing tile indices in each direction.
20 | # DO NOT MODIFY this dictionary.
21 | OFFSETS = {
22 | UP: (1, 0),
23 | DOWN: (-1, 0),
24 | LEFT: (0, 1),
25 | RIGHT: (0, -1)
26 | }
27 |
28 | # Symbol for an empty tile, DO NOT MODIFY
29 | EMPTY_TILE = 0
30 |
31 |
32 | def merge(line):
33 | """
34 | Helper function that merges a single row or column in 2048
35 | Example:
36 | [2 0 2 2] -> [4 2 0 0]
37 | [0 2 2 0] -> [4 0 0 0]
38 | [2 2 2 8] -> [4 2 8 0]
39 | [0 2 2 4] -> [4 4 0 0]
40 | [2 2 2 2] -> [4 4 0 0]
41 | [256 256 2 4] -> [512 2 4 0]
42 | [256 128 64 32] -> [256 128 64 32]
43 | [2 0 2 0] -> [4 0 0 0]
44 | [2 0 2 4] -> [4 4 0 0]
45 | [0 0 2 2] -> [4 0 0 0]
46 | [8 16 16 8] -> [8 32 8 0]
47 | """
48 | # replace with your code (Phase 1)
49 | return []
50 |
51 |
52 | class TwentyFortyEight:
53 | """
54 | Class to run the game logic.
55 | """
56 |
57 | def __init__(self, grid_height=4, grid_width=4):
58 | # Store the board's height (Phase 2)
59 |
60 | # Store the board's width (Phase 2)
61 |
62 | # Store each direction's initial indices (Phase 3)
63 |
64 | # Initialize your board (Phase 2)
65 | pass
66 |
67 | def __str__(self):
68 | """
69 | Returns a string representation of the board for debugging.
70 | """
71 | # replace with your code (Phase 2)
72 | return ""
73 |
74 | def reset(self):
75 | """
76 | Reset the game so the board is empty except for two
77 | initial tiles.
78 | """
79 | # Initialize your height * width board with empty tiles (Phase 2)
80 |
81 | # Create two new tiles (Phase 3)
82 | pass
83 |
84 | def get_grid_height(self):
85 | """
86 | Returns the height of the board.
87 | """
88 | # replace with your code (Phase 2)
89 | return 0
90 |
91 | def get_grid_width(self):
92 | """
93 | Returns the width of the board.
94 | """
95 | # replace with your code (Phase 2)
96 | return 0
97 |
98 | def move(self, direction):
99 | """
100 | Move all tiles in the given direction and add
101 | a new tile if any tiles moved.
102 | """
103 | # replace with your code (Phase 3)
104 | pass
105 |
106 | def new_tile(self):
107 | """
108 | Creates a new tile in a randomly selected empty
109 | square. The tile should be 2 90% of the time and
110 | 4 10% of the time.
111 | """
112 | # replace with your code (Phase 3)
113 |
114 | # Bonus: Check if board is full and do not generate new tile
115 |
116 | # Generate a random number up to 1
117 |
118 | # Assign new tile depending on generated number
119 |
120 | # Place new tile on randomly selected empty square from board
121 | pass
122 |
123 | def set_tile(self, row, col, value):
124 | """
125 | Set the tile at position row, col to have the given value.
126 | """
127 | # replace with your code (Phase 2)
128 | pass
129 |
130 | def get_tile(self, row, col):
131 | """
132 | Return the value of the tile at position row, col.
133 | """
134 | # replace with your code (Phase 2)
135 | return 0
136 |
137 |
138 | game = TwentyFortyEight()
139 |
140 | # Try to show your board
141 | # print(game)
142 |
143 | # It is advisable to use the GUI once you are in Phase 3
144 | # poc_2048_gui.run_gui(TwentyFortyEight())
145 |
--------------------------------------------------------------------------------
/django/02_setup.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 |
3 | - [ ] Understand the importance of virtual environments
4 | - [ ] Install and create a virtual environment
5 | - [ ] Install and use `virtualenvwrapper`
6 | - [ ] Install Django and Django Rest Framework through pip
7 |
8 | ## Virtual Environments
9 |
10 | A **virtual environment** is a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages. It is used to isolate a particular project to avoid conflicts with the requirements of another project. **`virtualenv`** is a tool used to create Python virtual environments.
11 |
12 | ## Installing 'virtualenv'
13 |
14 | Check if `virtualenv` already exists in your system through your terminal or console:
15 |
16 | ```shell
17 | $ virtualenv --version
18 | ```
19 |
20 | If you see a version number, that means you already have it installed and may now proceed to the next step. Otherwise, install `virtualenv` through the Python package manager, a.k.a. `pip`:
21 |
22 | ```shell
23 | $ pip install virtualenv
24 | ```
25 |
26 | Visit this [link](https://packaging.python.org/guides/installing-using-pip-and-virtualenv/) for more info on how to make sure you have the latest version of pip installed.
27 |
28 | ## Working with 'virtualenv'
29 |
30 | To create a virtual environment, go to your project's directory and run `virtualenv`:
31 |
32 | ```shell
33 | cd path/to/directory
34 | virtualenv env
35 | ```
36 |
37 | The second argument refers to the location where you want to create the `virtualenv`. Generally, you can just create this in your project and call it `env`. `virtualenv` will create a virtual Python installation in the `env` folder.
38 |
39 | **Note**: Don't forget to exclude your `virtualenv` directory from your version control system using .gitignore or similar.
40 |
41 | To activate your `virtualenv`:
42 |
43 | ```shell
44 | Windows
45 | $ .\env\Scripts\activate
46 |
47 | Linux and macOS
48 | $ source env/bin/activate
49 | ```
50 |
51 | To confirm if you're in the `virtualenv` by checking the location of your Python interpreter, which should point to the `env` directory:
52 |
53 | ```shell
54 | Windows
55 | $ where python
56 |
57 | Linux and macOS
58 | $ which python
59 | ```
60 |
61 | As long as your `virtualenv` is activated, pip will install packages into that specific environment and you'll be able to import and use packages in your Python application.
62 |
63 | To leave your `virtualenv`, simply run:
64 |
65 | ```shell
66 | $ deactivate
67 | ```
68 |
69 | ## Bonus: virtualenvwrapper
70 |
71 | To make working with virtual environments easier (especially for Windows uers), you can use [virtualenvwrapper](http://virtualenvwrapper.readthedocs.io/en/latest/), which is a set of extensions to the `virtualenv` tool. It also places all of your virtual environments in a single location.
72 |
73 | ```shell
74 | Mac:
75 | $ pip install virtualenvwrapper
76 | $ export WORKON_HOME=~/Envs
77 | $ source /usr/local/bin/virtualenvwrapper.sh
78 |
79 | Windows:
80 | $ pip install virtualenvwrapper-win
81 | ```
82 |
83 | Once you've installed `virtualenvwrapper`, create a new isolated development environment:
84 |
85 | ```shell
86 | mkvirtualenv portfolio
87 | ```
88 |
89 | This produced a folder named `portolio` inside the `Envs` folder with a clean copy of Python inside.
90 |
91 | To activate `virtualenv` with `virtualenvwrapper`:
92 |
93 | ```shell
94 | $ workon portfolio
95 | ```
96 |
97 | You may also check the list of existing virtual environments in your `Envs` folder by typing:
98 |
99 | ```shell
100 | $ workon
101 | ```
102 |
103 | ## Installing Django and Django Rest Framework
104 |
105 | To install Django through `pip`, just run:
106 |
107 | ```shell
108 | $ pip install django djangorestframework
109 | ```
110 |
111 | ## Saving packages
112 |
113 | To save the list of packages installed in your environment for easier reproduction:
114 |
115 | ```shell
116 | $ pip freeze > requirements.txt
117 | ```
118 |
119 | This will save what you've installed so far in a text file named `requirements.txt`.
120 |
121 | To install the packages listed in a `requirements.txt` file:
122 |
123 | ```shell
124 | $ pip install -r requirements.txt
125 | ```
126 |
--------------------------------------------------------------------------------
/basic_concepts/functions.md:
--------------------------------------------------------------------------------
1 | Let's have a simple USD-PHP converter program!
2 |
3 | ```python
4 | exchange_rate = {'usd': 50.44, 'jpy': 0.45}
5 | dollars = float(input("How much USD?"))
6 | peso = dollars * exchange_rate['usd']
7 | print("Hello! your {}USD is equivalent to {:.2f}PHP".format(dollars, peso))
8 | ```
9 |
10 | But what if we also want make use of the JPY-PHP conversion? Maybe we can tweak some code above?
11 | ```python
12 | exchange_rate = {'usd': 50.44, 'jpy': 0.45}
13 | dollars = float(input("How much USD?"))
14 | peso = dollars * exchange_rate['usd']
15 | print("Hello! your {}USD is equivalent to {:.2f}PHP".format(dollars, peso))
16 |
17 | jpy = float(input("How much JPY?"))
18 | peso = jpy * exchange_rate['jpy']
19 | print("Hello! your {}JPY is equivalent to {:.2f}PHP".format(jpy, peso))
20 | ```
21 |
22 | Can you look again and check if there are lines of code that does the same thing? What if we can reuse those to make our code
23 | more [modular](https://www.quora.com/What-is-modular-programming-Where-is-it-used) and [reusable](https://www.quora.com/What-is-code-reusability)? Oh wait, can it also improve readability?
24 |
25 | And we have `functions`!
26 |
27 | ## What is a function
28 | We have encountered functions before! Specifically, [builtin functions](https://docs.python.org/3/library/functions.html) which are functions provided by Python packages and libraries.
29 | Remember this?
30 |
31 | ```python
32 | str = "Banana"
33 | # len and print are actually functions!
34 | print(len(str))
35 | ```
36 |
37 | From here can you try to explain to yourself what functions are? `Functions` are just a block of reusable code that does some tasks!
38 | The `len` function accepts an object and returns it length! Now we can reuse that function anywhere in our code to get
39 | the length of objects like strings or dictionaries!
40 |
41 | ## Writing our own function
42 | To write your own function like below:
43 |
44 | ```python
45 | # Declaration
46 | def booster(number, boost=2):
47 | # Block of code (what the function does)
48 | print('Power booster!')
49 | # Return statement is optional
50 | return number * boost
51 | ```
52 |
53 | 1. **Declare** your function using the `def` keyword followed by your function name.
54 | 2. Write the **arguments** enclosed in parenthesis followed by a colon `:`. Functions can accept arguments/parameters just like the `number` and `boost` in our booster function. We have two types of parameters:
55 | * **Required/Mandatory** - We need to provide the parameter value everytime we call the function just like `number`.
56 | * **Optional** - We can omit to pass the parameter and a default value will be given just like `boost`.
57 | 3. Write the task of the function (the block of code inside the function)
58 | 4. Write the return statement (Optional)
59 |
60 | ## Take aways
61 | * [Playing with function parameters](http://pythoncentral.io/fun-with-python-function-parameters/)
62 |
63 | ## Challenge
64 | Gooood job! You finished basic programming concepts with Python! For your last challenge...
65 |
66 | Aling Nena's Sari-sari store just had a new neighbor! It's Mang Toto's ForEx!
67 | Help Mang Toto to convert `USD, JPY, SGD` to `PHP` by:
68 | * Asking the customer for their currency.
69 |
70 | ```shell
71 | >> Welcome to Mang Toto's ForEx! What is your currency? We accept (usd, jpy, sgd):
72 | ```
73 |
74 | * If they are not exchanging the currrency, notify the customer.
75 |
76 | ```shell
77 | >> Welcome to Mang Toto's ForEx! What is your currency? We accept (usd, jpy, sgd):
78 | >> aud
79 | >> Sorry! We do not exchange aud!
80 | ```
81 |
82 | * If they are in their currency list, ask for the amount and inform the original and equivalent PHP amount.
83 |
84 | ```shell
85 | >> Welcome to Mang Toto's ForEx! What is your currency? We accept (usd, jpy, sgd):
86 | >> usd
87 | >> Your 100.50 usd is equivalent to 5069.22 PHP
88 | ```
89 |
90 |
91 | !> Please use below template
92 |
93 | [functions01](exercises/functions/functions01.py ':include :type=code python')
94 |
95 | [challenge_partial](../challenge_partial.md ':include')
96 |
97 |
98 | ## Put your thinking cap on!
99 |
100 | - What does `:.2f` do during string formatting?
101 | - Should the required parameters be declared first on a function? Or we can order in YOLO the required and optional parameters?
102 | - Are function parameters passed `by value` or `by reference`?
103 |
--------------------------------------------------------------------------------
/basic_concepts/variables.md:
--------------------------------------------------------------------------------
1 | ## Variables
2 |
3 | Let's try to store some values!
4 |
5 | Open a terminal
6 |
7 | ```shell
8 | Windows: Click Start -> Type cmd
9 | Mac: Open Applications folder -> Utilities folder
10 | ```
11 |
12 | After opening the terminal/command prompt(cmd), type the following command to run the Python shell:
13 |
14 | ```shell
15 | python
16 | ```
17 |
18 | Type the following codes to create variables and to print their values!
19 |
20 | ```python
21 | # Let's store values/data to variables
22 | num = 88
23 | dec = 99.99
24 | is_wwc_great = True
25 | has_forever = False
26 | movie_title = 'superwoman'
27 | # Let's print out their values
28 | print(num, dec, is_wwc_great, has_forever, movie_title)
29 | ```
30 |
31 | Magic? Nope. Let's explain what happened.
32 |
33 | ### Definition
34 |
35 | Variables are like `containers` that allows us to store values/data.
36 |
37 | ### Data types
38 | We have different types of data in Python! Some are:
39 | * Integer - positive/negative whole numbers
40 |
41 | ```python
42 | # We declare a variable named num
43 | # We assign/store the number 88 to our variable num
44 | num = 88
45 | ```
46 |
47 | * Float/Decimal - positive/negative numbers with decimal
48 |
49 | ```python
50 | # We declare a variable named dec
51 | # We assigned a decimal value of 99.99 to dec
52 | dec = 99.99
53 | ```
54 |
55 | * Boolean - `True` or `False`
56 |
57 | ```python
58 | # We declare a variable named is_wwc_great and has_forever
59 | # We assign/store Boolean values to these
60 | is_wwc_great = True
61 | has_forever = False
62 | ```
63 |
64 | * String - series of characters enclosed in single/double quotes
65 |
66 | ```python
67 | # We declared a variable named movie_title
68 | # We store a string value to it
69 | movie_title = 'superwoman'
70 | ```
71 |
72 | * Lists/Dictionaries - Meh. Just keep in mind you heard it here. We will discuss it on succeeding sessions :)
73 |
74 | ### Re-assignment
75 | Now, let's try if we can re-assign values for these variables.
76 |
77 | ```python
78 | num = 100
79 | has_forever = True
80 | print(num, has_forever)
81 |
82 | # Let's change the value of our variable num
83 | num = 500
84 | print(num)
85 |
86 | # Let's change the value of our variable has_forever
87 | has_forever = False
88 | print(has_forever)
89 | ```
90 |
91 | ## Arithmetic Operations
92 |
93 | Let's try to do some arithmetic operations using Python!
94 |
95 | Still using the Python shell, type the following codes and check their results.
96 |
97 | ```python
98 | # Addition: result is 30
99 | 20 + 10
100 |
101 | # Subtraction: result is 10
102 | 20 - 10
103 |
104 | # Multiplication: result is 200
105 | 20 * 10
106 |
107 | # Division: result is 2
108 | 20 / 10
109 |
110 | # Floor divsion: can you explain what it's different with normal division?
111 | 9 // 2
112 | 10 // 3
113 |
114 | # Exponent: result is 16
115 | 4 ** 2
116 |
117 | # Modulo: can you explain what module is?
118 | 10 % 3
119 | 99 % 33
120 | ```
121 |
122 | ## Keyboard Input
123 |
124 | Let's ask user's for an input!
125 |
126 | Still using the Python shell, type the following codes, answer the input and see the output!
127 |
128 | ```python
129 | name = input('Your name:')
130 | tweet = input('Tweet your day:')
131 | print('{} tweeted {}'.format(name, tweet)) # String formatting replaces {} with variable values
132 | # print(f'{name} tweeted {tweet}') # New string formatting added on Python3.6
133 | ```
134 |
135 | ### Definition
136 | * Keyboard input will stop the program flow and asks the user for an input.
137 | * Keyboard input has the ff. syntax: `input()`
138 | * It can have an optional prompt string: `input('Enter your age:')`
139 |
140 | ## Challenge
141 |
142 | Let's apply what you have learned! For this topic's challenge:
143 |
144 | Aling Nena’s Sari-sari store wants a robot that will ask the
145 | customer their total bill and payment amount and tell them their change
146 | (for now, we can allow negative change). For example:
147 |
148 | ```shell
149 | >> How much is your total bill? 150
150 | >> How much is your payment? 200
151 | >> Hi! Your change is 50.00
152 | ```
153 |
154 | !> Please use below template
155 |
156 | [filename](exercises/variables/variables01.py ':include :type=code python')
157 |
158 | [challenge_partial](../challenge_partial.md ':include')
159 |
160 |
161 |
162 | ## Put your thinking cap on!
163 |
164 | - Does a variable really holds values?
165 | - How to know/print a variable's type?
166 | - What is `floor divison`?
167 | - What does the `modulo` operation do?
168 | - Explain the magic of `input()`?
169 |
--------------------------------------------------------------------------------
/ren'py/scene4.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/WWCodeManila/Python)
2 |
3 | # Scene 4
4 |
5 | This scene takes place inside Aling Nena's store. You're then tasked to assist two customers: Bert and Tasya. The manner with which you answer their concerns will determine the succeeding scenes.
6 |
7 | At this point, we've already covered much of what can be learned in implementing a basic visual novel using Ren'Py. We'll only need to discuss
8 |
9 | - [ ] Custom-defined positions
10 |
11 | You'll first need to add our last two characters before the `label start` block along with the other characters:
12 |
13 | ```python
14 | define r = Character("Bert")
15 | define t = Character("Tasya")
16 | ```
17 |
18 | And these flags below where you defined the characters and before the `label start` block.
19 |
20 | ```python
21 | define correct_change = False
22 | define correct_item = False
23 | ```
24 |
25 | Next, copy the assets `bg store.png` , `bert.png`, `tasya.png`, `store prices.png` and `store rewards.png` from the `assets` folder into `game/images`.
26 |
27 | Here is the code that we'll be using. Replace the codes below the`label store` block in your `script.rpy` code and add a new block `label reward` after it:
28 |
29 | ```python
30 | label store:
31 | $ storef = True
32 | scene bg store with fade
33 |
34 | show nena
35 | n "Thanks, [name], for helping me in the store today."
36 | u "It's okay Lola Nena."
37 |
38 | hide nena
39 | show bert with moveinright
40 |
41 | r "Good day, Aling Nena."
42 | n "Good day, Bert. What is your business today?"
43 | show store prices at Position(xpos = 0.10, ypos=0.10, xanchor = 0.0, yanchor = 0.0) with dissolve
44 | r "I need 2 kilos of rice, 2 cans of sardines, and 1 liter of oil, please."
45 | u "I'll help you today, Bert."
46 |
47 | with fade
48 |
49 | u "Here you go."
50 | "You give the items to Bert."
51 | r "Hohoho. Thanks, [name]. Here's Php 100."
52 | u "Wait a minute, Bert..."
53 | "{i}He bought 2 kilos of rice, 2 cans of sardines, and 1 liter of oil ... {w} And he gave me Php 100. That means ... {/i}"
54 |
55 | menu:
56 | "I should give him a change of {b}Php 20{/b}":
57 | u "Your change is Php 20."
58 | "You give the change to Bert."
59 | $ correct_change = True
60 | "I should give him a change of {b}Php 10{/b}":
61 | u "Your change is Php 10."
62 | "You give the change to Bert."
63 | "{b}No change{/b}":
64 | u "Oops. Nothing."
65 |
66 | if correct_change:
67 | "Bert smiles and walks away."
68 | hide store prices
69 | hide bert with moveoutleft
70 | else:
71 | "You pocket the rest of the change."
72 | "Bert frowns and walks away."
73 | hide store prices
74 | hide bert with moveoutleft
75 |
76 | with fade
77 | show tasya with moveinleft
78 |
79 | t "Good day Aling Nena and [name]."
80 | u "What brings you here, Tasya?"
81 | t "I'm here to collect my reward from Aling Nena's Sari-sari store."
82 | u "Congratulations, Tasya! What reward number did you avail?"
83 | show store rewards at Position(xpos = 0.90, ypos=0.10, xanchor = 1.0, yanchor = 0.0) with dissolve
84 | t "It's number 5."
85 |
86 | "You give her ... "
87 |
88 | menu:
89 | "Coke Sakto":
90 | "... Coke Sakto."
91 | "Boy Bawang":
92 | "... Boy Bawang."
93 | "Php 15 load":
94 | "... Php 15 load."
95 | $ correct_item = True
96 |
97 | if correct_item:
98 | "Tasya smiles and walks away."
99 | hide store rewards
100 | hide tasya with moveoutright
101 | else:
102 | "You keep the reward for your self."
103 | "Tasya frowns and walks away."
104 | hide store rewards
105 | hide tasya with moveoutright
106 |
107 | if correct_change and correct_item:
108 | jump reward
109 | else:
110 | jump ending
111 |
112 | label reward:
113 | pass
114 | ```
115 |
116 | ## Custom-defined image positions
117 |
118 | As mentioned earlier, you can specify where in the screen an image will show instead of using the pre-defined Ren'Py positions. This can be done using the class `Position()`.
119 |
120 | For example:
121 |
122 | ```
123 | show store prices at Position(xpos = 0.10, ypos=0.10, xanchor = 0.0, yanchor = 0.0) with dissolve
124 | ```
125 |
126 | In this case you'll need to set the following arguments:
127 |
128 | `xpos` or `ypos`: Point on the screen defined by x (horizontal) and y (vertical) positions
129 |
130 | `xanchor` or `yanchor`: An x and y position of a point on the image. If specified, this point will be positioned on the screen at the location indicated by`xpos` and `ypos`.
131 |
132 | Along the x-axis, `0.0` is on the extreme left, while `1.0` is on the extreme right. Along the y-axis, `0.0` is on the top-most, while a value of `1.0` is the bottom-most of the screen or image.
133 |
134 | # Exercise
135 |
136 | Practice with repositioning the images `store prices.png` and `store rewards.png` somewhere else in the screen by changing the keywords in the `Position()` class.
137 |
138 | [](https://gitter.im/WWCodeManila/Python)
139 |
140 |
--------------------------------------------------------------------------------
/ren'py/scene3.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/WWCodeManila/Python)
2 |
3 | # Scene 3
4 |
5 | In this scene, you played *bato-bato pik* (rock, paper, scissors) with your friends Lita and Boy who you met previously in Scene 2.
6 |
7 | Here, we'll learn more about
8 |
9 | - [ ] Python equivalent statements in Ren'Py
10 |
11 | ## Exercise
12 |
13 | Try making our own implementation of Rock, Paper, Scissors in Python first . A player wins if he or she scores 2 points first (best of three) against the computer. Only wins or loses count towards any point, ties do not change the scores.
14 |
15 | Replace the code in `batobato.rpy` from the previous section with the following code. Go over the `python` block carefully. We won't be discussing this particular implementation in detail, instead we'll focus on the Ren'Py code.
16 |
17 | ```python
18 | label game:
19 |
20 | $ gamef = True
21 |
22 | scene bg street with fade
23 |
24 | show lita at left with moveinright
25 | show boy at right with moveinleft
26 |
27 | l "Let's play bato-bato pik!"
28 |
29 | show boy at center with moveinright
30 | b "You'll play against me. Best of three!"
31 |
32 | python:
33 | from random import randint
34 | uscore = 0
35 | bscore = 0
36 | while uscore | bscore < 2:
37 |
38 | renpy.say(b, "Bato-bato pik!")
39 |
40 | choices = {"r": "Rock", "p": "Paper", "s": "Scissors"}
41 | uhand = renpy.display_menu([("Rock", "r"), ("Paper", "p"), ("Scissors", "s")])
42 | bhand = choices.keys()[randint(0,2)]
43 |
44 | uhand_c = choices[uhand]
45 | bhand_c = choices[bhand]
46 |
47 | renpy.say(b, "[bhand_c]")
48 |
49 | hands = (uhand, bhand)
50 |
51 | wins = [
52 | ('p', 'r'),
53 | ('r', 's'),
54 | ('s', 'p'),
55 | ]
56 | tie = False
57 | if hands[0] == hands[1]:
58 | tie = True
59 | result = "It's a tie!"
60 | elif hands in wins:
61 | result = "wins"
62 | uscore += 1
63 | else:
64 | result = "loses"
65 | bscore += 1
66 |
67 | if not tie:
68 | renpy.say(l, "[name] picked [uhand_c], Boy picked [bhand_c] \n [name] [result]! {w} \n Boy: [bscore], [name]: [uscore]")
69 | else:
70 | renpy.say(l, "[name] picked [uhand_c], Boy picked [bhand_c] \n [result]! {w} \n Boy: [bscore], [name]: [uscore]")
71 |
72 | if uscore > bscore:
73 | renpy.say(l, "[name] is the WINNER!")
74 | winner = True
75 | else:
76 | renpy.say(l, "Boy wins. [name] LOSES!")
77 | winner = False
78 |
79 | if winner:
80 | show boy at right with moveinleft
81 | l "Well done, [name]."
82 | b "You defeated me!"
83 | else:
84 | show boy at right with moveinleft
85 | b "Oh well, there's always a next time, [name]."
86 |
87 | l "Let's play another game!"
88 | "You spend the rest of the day playing."
89 |
90 | jump ending
91 |
92 | ```
93 |
94 | In `script.py`, add the following `label` statement:
95 |
96 | ```python
97 | label ending:
98 | pass
99 | ```
100 |
101 | Try to run the game using the Ren'Py launcher.
102 |
103 | !> Tip: You can use `Back` in the game screen to view the dialogue before or `Skip` to go ahead until some decision point is reached. Try these in order to view the different outcomes of your decision.
104 |
105 | ## Python equivalent statements
106 |
107 | The `renpy.` offers a convinient interface to integrate Python into your Ren'Py code. We've already used one of these when we discussed user-defined inputs in Scene 1: `renpy.input()`
108 |
109 | You'll need to implement these equivalent statements under a `python` block.
110 |
111 | In this code we used:
112 |
113 | - `renpy.say()`
114 | - `renpy.display_menu()`
115 |
116 | Notice that, when displaying a variable in a `renpy.say()` statement, we can just enclose it with `[]` as in:
117 |
118 | ```python
119 | renpy.say(l, "[name] picked [uhand_c], Boy picked [bhand_c] \n [name] [result]! {w} \n Boy: [bscore], [name]: [uscore]")
120 | ```
121 |
122 | Other equivalent statements and there usages can be found [here](https://www.renpy.org/doc/html/statement_equivalents.html). Here are some that we have already encountered in the previous sections.
123 |
124 | - `renpy.jump()` - `jump` statement
125 | - `renpy.scene()` - `scene` statement
126 | - `renpy.show()` - `show` statement
127 | - `renpy.with_statement()` - transitions, i.e. `with`
128 |
129 | ## Misc
130 |
131 | You can actually write the code in`batobato.rpy` inside `script.rpy`. Ren'Py consolidates all `label` statements into one when it is run, so it doesn't really matter whether you partition your code into different files. In cases of large games; however, it might be more efficient or readible to divide the game into different files. This section just demonstrates that making multiple files is possible.
132 |
133 | ## Exercise
134 |
135 | If you made your own Rock, Paper, Scissors game in Python, implement your code in this Ren'Py game instead.
136 |
137 | You may also want to make your own mini-game (examples are: Hangman, Guess the Number, or even *Pinoy Henyo*) instead of or in addition to the one we used here. You can try coding it in Python first then integate it into this Ren'Py game using equivalent statements.
138 |
139 | What does the text-tag `{w}{/w}` do?
140 |
141 | What does `\n` do ?
142 |
143 | [challenge_partial](../challenge_partial.md ':include')
144 |
145 | [](https://gitter.im/WWCodeManila/Python)
146 |
147 |
--------------------------------------------------------------------------------
/basic_concepts/dictionaries.md:
--------------------------------------------------------------------------------
1 | Imagine that we will create a simple PostalPH bot that allows a user to ask his/her postal code giving the bot his/her area.
2 |
3 | ```
4 | PostalPHBot: Hello! What is your area?
5 | Goblin: binondo
6 | PostalPHBot: Hi! Your postal area is 1006.
7 | ```
8 |
9 | How will you store the ff. mapping in Python?
10 |
11 | ```
12 | Binondo: 1006
13 | Intramuros: 1002
14 | Malate: 1004
15 | Ermita: 1000
16 | Paco: 1007
17 | Inagi-shi: 13225
18 | Hino-shi: 13212
19 | and many more...
20 | ```
21 |
22 | Hmmm.... with a loooong conditional statements like this?
23 |
24 | ```python
25 | area = input('Hello! What is your area?').lower()
26 |
27 | if area == 'binondo':
28 | print('Hi! Your postal area is 1006.')
29 | elif area == 'intramuros':
30 | print('Hi! Your postal area is 1004.')
31 | # and a lot more if-else!
32 |
33 | ```
34 |
35 | ## Creation and Value Access
36 |
37 | Good thing, Python allows us to store collections for mapping or associating a `key` with a `value`, just like how a dictionary allows us to search for a word(the key) and its meaning(the value)!
38 | Python dictionaries are collections just like lists but instead of having numbers as its index, we can use strings, numbers or tuples instead. Let's try to use dictionary to our postal bot!
39 |
40 | ```python
41 | postal_mapping = {
42 | 'binondo': 1006,
43 | 'intramuros': 1002,
44 | 'malate': 1004,
45 | 'ermita': 1000,
46 | 'paco': 1007,
47 | 'inagi-shi': 13225,
48 | 'hino-shi': 13212
49 | }
50 |
51 | area = input('Hello! What is your area?').lower()
52 |
53 | if area in postal_mapping:
54 | print('Hi! Your postal area is {}'.format(postal_mapping[area]))
55 | else:
56 | print('Sorry! The area you provided was not found on our records.')
57 |
58 | ```
59 |
60 | We created a dictionary by enclosing in braces(`{}`) the key-value pairs which are separated by colon(`:`).
61 |
62 | See how we accessed the dictionary value? We used strings(the area) as the dictionary key and used that `key` to retrieve the postal value.
63 | ```
64 | your_dictionary[key]
65 | ```
66 |
67 | Why did we check first if the area is in our dictionary? See what will happen if we have the code below and we input 'makati' to our postal bot.
68 |
69 | ```python
70 | postal_mapping = {
71 | 'binondo': 1006,
72 | 'intramuros': 1002,
73 | 'malate': 1004,
74 | 'ermita': 1000,
75 | 'paco': 1007,
76 | 'inagi-shi': 13225,
77 | 'hino-shi': 13212
78 | }
79 |
80 | area = input('Hello! What is your area?').lower()
81 | # We removed the checking. YOLO!
82 | print('Hi! Your postal area is {}'.format(postal_mapping[area]))
83 | ```
84 |
85 | ## Dictionary update and methods
86 |
87 | Postal Bot update! Let's add Quaipo to our dictionary and also, remove the odd Inagi-shi and Hino-shi as we found out it was for PostJP bot not PostPH bot!
88 |
89 | ```python
90 | postal_mapping = {
91 | 'binondo': 1006,
92 | 'intramuros': 1002,
93 | 'malate': 1004,
94 | 'ermita': 1000,
95 | 'paco': 1007,
96 | 'inagi-shi': 13225,
97 | 'hino-shi': 13212
98 | }
99 |
100 | # Let's add Quiapo
101 | postal_mapping['quaipo'] = 1001
102 |
103 | # Let's delete Inagi-shi
104 | del postal_mapping['inagi-shi']
105 |
106 | # Dictionaries have methods too!
107 | # Let's delete Hino-shi using the pop method
108 | deleted_value = postal_mapping.pop('hino-shi')
109 | print('Removed {} from mapping'.format(deleted_value))
110 |
111 | # Dictionaries have functions too!
112 | # Let's print its length using the len function
113 | print('We now have a total of {} postal mapping'.format(len(postal_mapping)))
114 | ```
115 |
116 | ## Challenge
117 | Good job! You are nearly complete in knowing some basic programming concepts using Python! Let's get our fingers and mind working!
118 |
119 | Just like in grocery stores where items where scanned one by one and the
120 | total amount due is summed, please help Aling Nena's Sari-sari store
121 | to compute a customer's total order amount and print the receipt by:
122 | * Input the customer's products
123 | * The product dictionary contains Aling Nena's products and maps it's price.
124 | * If the product name is NOT in her list, just print 'Item void!'
125 | and skip it from the computation of total amount due.
126 | * If the product is in the list, please print current purchased products and
127 | their quantity.
128 | * If done punching the items:
129 | - Print each purchased products, it's quantity, price, total price (quantity * price)
130 | - Print the total items and total amount due.
131 |
132 | Example:
133 | ```shell
134 | >> Item name: sunsilk
135 | {'sunsilk': 1}
136 | >> Are you done? Press y to finish: n
137 | >> Item name: SUNsilk
138 | {'sunsilk': 2}
139 | >> Are you done? Press y to finish: n
140 | >> Item name: ligo
141 | {'sunsilk': 2, 'ligo': 1}
142 | >> Are you done? Press y to finish: n
143 | >> Item name: Spam
144 | {'sunsilk': 2, 'ligo': 1, 'spam': 1}
145 | >> Are you done? Press y to finish: n
146 | >> Item name: test
147 | Item test void!
148 | >> Are you done? Press y to finish: n
149 | >> Item name: ligo
150 | {'sunsilk': 2, 'ligo': 2, 'spam': 1}
151 | >> Are you done? Press y to finish: y
152 | ***** PRINTING YOUR RECEIPT *****
153 | sunsilk 7.5 * 2 = 15.0
154 | ligo 12.0 * 2 = 24.0
155 | spam 115.25 * 1 = 115.25
156 | 5 items --------- 154.25
157 | ```
158 |
159 |
160 | !> Please use below template
161 |
162 | [dictionaries01](exercises/dictionaries/dictionaries01.py ':include :type=code python')
163 |
164 | [challenge_partial](../challenge_partial.md ':include')
165 |
166 |
167 | ## Put your thinking cap on!
168 |
169 | - Is there a way to avoid a KeyError when using `pop()` to an non-existent key?
170 | - What are the allowed keys of a dictionary? What attribute do they share in common?
171 | - How do you check if a certain key exists in a dictionary?
172 | - How do you loop through a dictionary, getting both it's key and value pair?
173 |
--------------------------------------------------------------------------------
/django/08_add_vue.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 | - [ ] Install NPM
3 | - [ ] Install VueCLI
4 | - [ ] Add Vue to application
5 |
6 | ## Install NPM
7 | Go to `https://nodejs.org/en/download/`, download the latest or the LTS version of Node. Install node with the recommended settings. Check if Node and NPM is installed by checking in your terminal:
8 |
9 | ```
10 | > npm --version
11 | 6.14.14
12 | > node --version
13 | v14.17.4
14 | ```
15 |
16 | ## Install VueCLI
17 | Once the NodeJS has been installed in your computer, you may now install the VueCLI. In your terminal, type this command:
18 | ```
19 | sudo npm i -g @vue/cli
20 | ```
21 | Then test if its working by typing
22 | ```
23 | vue create hello-vue
24 | Vue CLI v4.5.13
25 | ? Please pick a preset: Manually select features
26 | ? Check the features needed for your project: Choose Vue version, Babel, Router, Linter
27 | ? Choose a version of Vue.js that you want to start the project with 2.x
28 | ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
29 | ? Pick a linter / formatter config: Prettier
30 | ? Pick additional lint features: Lint on save
31 | ? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
32 | ? Save this as a preset for future projects? (y/N) N
33 | ```
34 |
35 | Wait for a few minutes, then once completed, will show a prompt like this:
36 |
37 | ```
38 | 📄 Generating README.md...
39 |
40 | 🎉 Successfully created project hello-vue2.
41 | 👉 Get started with the following commands:
42 |
43 | $ cd hello-vue
44 | $ npm run serve
45 | ```
46 |
47 | Go to `hello-vue` and type `npm run serve`. It will remind you to access to `http://localhost:/`. Go to that url and check if Vue is showing. This indicates that Vue is properly installed to your computer.
48 |
49 |
50 | ## Add Vue to application
51 | We are going to create a simple Vue project in our Django project. Ensure that the project name is `frontend`, like so:
52 | ```
53 | vue create frontend
54 | ```
55 |
56 | Set the config like the ones below:
57 | ```
58 | vue create hello-vue
59 | Vue CLI v4.5.13
60 | ? Please pick a preset: Manually select features
61 | ? Check the features needed for your project: Choose Vue version, Babel, Router, Linter
62 | ? Choose a version of Vue.js that you want to start the project with 2.x
63 | ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
64 | ? Pick a linter / formatter config: Prettier
65 | ? Pick additional lint features: Lint on save
66 | ? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
67 | ? Save this as a preset for future projects? (y/N) N
68 | ```
69 |
70 | Then, we're going to install a package `webpack-bundle-tracker` to keep track of the code in our frontend application.
71 | Go to `frontend` folder then install the webpack tracker:
72 | ```
73 | cd frontend
74 |
75 | npm install --save-dev webpack-bundle-tracker@0.4.3
76 | ```
77 |
78 | Next, create a file inside the folder `frontend`. Name it `vue.config.js`.
79 | ```
80 | const BundleTracker = require("webpack-bundle-tracker");
81 |
82 | module.exports = {
83 | // on Windows you might want to set publicPath: "http://127.0.0.1:8080/"
84 | publicPath: "http://127.0.0.1:8081/",
85 | outputDir: './dist/',
86 |
87 | chainWebpack: config => {
88 |
89 | config
90 | .plugin('BundleTracker')
91 | .use(BundleTracker, [{filename: './webpack-stats.json'}])
92 |
93 | config.output
94 | .filename('bundle.js')
95 |
96 | config.optimization
97 | .splitChunks(false)
98 |
99 | config.resolve.alias
100 | .set('__STATIC__', 'static')
101 |
102 | config.devServer
103 | // the first 3 lines of the following code have been added to the configuration
104 | .public('http://127.0.0.1:8080')
105 | .host('127.0.0.1')
106 | .port(8080)
107 | .hotOnly(true)
108 | .watchOptions({poll: 1000})
109 | .https(false)
110 | .disableHostCheck(true)
111 | .headers({"Access-Control-Allow-Origin": ["\*"]})
112 |
113 | },
114 |
115 | // uncomment before executing 'npm run build'
116 | // css: {
117 | // extract: {
118 | // filename: 'bundle.css',
119 | // chunkFilename: 'bundle.css',
120 | // },
121 | // }
122 |
123 | };
124 |
125 | ```
126 |
127 | Next, we are going to install a webpack loader in Django environment. This will help us read the changes given by the bundle tracker.
128 | ```
129 | pip install django-webpack-loader==0.7.0
130 | ```
131 |
132 | Update the requirements.txt file.
133 | ```
134 | pip freeze > requirements.txt
135 | ```
136 |
137 | Then add the webpack_loader library to `settings.py`.
138 | ```
139 | INSTALLED_APPS = [
140 | 'webpack_loader',
141 | ]
142 |
143 | // on the bottom of settings.py file
144 | WEBPACK_LOADER = {
145 | 'DEFAULT': {
146 | 'BUNDLE_DIR_NAME': 'dist/',
147 | 'STATS_FILE': BASE_DIR / 'frontend' / 'webpack-stats.json'
148 | }
149 | }
150 | ```
151 |
152 | Add this code inside the file `templates/index.html`, on the first line of the code:
153 | ```
154 | {% load render_bundle from webpack_loader %}
155 | ```
156 | Also, add this inside the body of the code, after the div id app:
157 | ```
158 | {% render_bundle 'app' %}
159 | ```
160 |
161 | The index file should look this this:
162 | ```
163 | {% load render_bundle from webpack_loader %}
164 |
165 |
166 |
167 |
168 |
169 |
170 | Forum App
171 |
172 |
173 |
174 |
Vue JS
175 |
176 |
177 |
178 | {% render_bundle 'app' %}
179 |
180 |
181 |
182 | ```
183 |
184 | Run server of both django and vue separately.
185 | ```
186 | python manage.py runserver
187 |
188 | npm run serve
189 | ```
190 |
191 |
192 | (Optional) You may also explore the vue project by typing this command.
193 | ```
194 | vue ui
195 | ```
--------------------------------------------------------------------------------
/ren'py/scene567.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/WWCodeManila/Python)
2 |
3 | At this point, we've covered all there is to discuss in our simple visual novel.
4 |
5 | We'll just need to complete our game with three more `label` blocks: reward, beach, ending.
6 |
7 | Add these flags below where you defined the characters and before the `label start` block.
8 |
9 | ```python
10 | define baonf = False
11 | define beachf = False
12 | define rewardf = False
13 | ```
14 |
15 | Copy the assets `bg beach.png` and `nena sad.png` from the `assets` folder into `game/images`.
16 |
17 | # Scene 5
18 |
19 | This scene is only run when both `$ correct_change` and `$ correct_item` are `True`.
20 |
21 | Replace the `pass` statement in the `label reward` block in `script.rpy`:
22 |
23 | ```python
24 | label reward:
25 |
26 | $ rewardf = True
27 |
28 | with fade
29 | show nena
30 |
31 | n "You did well, [name]! Because you helped me a lot today, I will give you a reward."
32 | n "Which will it be?"
33 |
34 | menu:
35 | "I can give you a baon to spend with your friends.":
36 | $ baonf = True
37 | u "Thanks for the allowance, Lola. I'll go play with Lita and Boy now."
38 | n "Go ahead, Apo. You deserve it."
39 | jump game
40 | "We'll go to the beach.":
41 | $ beachf = True
42 | u "Let's go the beach, Lola!"
43 | jump beach
44 | ```
45 |
46 | Notice that in this scene, if the player decides to have a *baon* (allowance) as a reward, the game will run "back to" Scene 3 wherein we made a mini-game. `jump` statements can be powerful tools to facilitate any loops in the narration or storyline.
47 |
48 | # Scene 6
49 |
50 | Add the following in `script.rpy`:
51 |
52 | ```python
53 | label beach:
54 | $ baonf = True
55 | scene bg beach with fade
56 |
57 | u "Wow, Lola! The beach is so pretty."
58 | n "Yes, it is. Glad you like it here."
59 |
60 | jump ending
61 | ```
62 |
63 | # Scene 7 / Ending
64 |
65 | Last, add the following in `script.rpy`, replace the statement under the `label ending` block:
66 |
67 | ```python
68 | label ending:
69 |
70 | scene bg inside house with fade
71 |
72 | if rewardf:
73 | if baonf:
74 | "You were able to spend the rest of the day with your friends Lita and Boy."
75 | "You bought snacks for the three of you from the allowance Aling Nena gave you."
76 | elif beachf:
77 | pass
78 |
79 | "And just like that, your summer vacation in the province passed in bliss and happiness."
80 |
81 | with fade
82 |
83 | show nena
84 |
85 | u "Thank you Lola Nena for letting me stay with you for the summer."
86 | n "You're always welcome here, [name]."
87 | u "I'll comeback again next vacation!"
88 | n "Sure, apo!"
89 |
90 | scene bg inside house with fade
91 |
92 | "THE END"
93 |
94 | else:
95 | "You went home after a long day."
96 | show nena sad
97 | "Your Lola Nena is waiting for you. She doesn't look happy."
98 | n "Apo, I have called your Mom and Dad. They will fetch you here tomorrow."
99 | u "But.. but Lola..."
100 |
101 | if gamef:
102 | $ desc = "a lazy"
103 | n "You only played all day with your friends even though you promised to help me."
104 | elif storef:
105 | if correct_change == False:
106 | $ desc = "a dishonest"
107 | n "Bert told me that you did not give him the correct change."
108 | n "Instead, you pocketed the excess amount!"
109 | if correct_item == False:
110 | $ desc = "an untrustworthy"
111 | n "Tasya said that you didn't give her the correct reward."
112 | n "Instead, you kept it to your self!"
113 |
114 | n "I have no use for [desc] grandchild."
115 |
116 | scene bg inside house with fade
117 |
118 | "And just like that, your summer vacation in the province is OVER."
119 |
120 | "THE END"
121 |
122 | return
123 | ```
124 |
125 | Try to run the game using the Ren'Py launcher.
126 |
127 | !> Tip: You can use `Back` in the game screen to view the dialogue before or `Skip` to go ahead until some decision point is reached. Try these in order to view the different outcomes of your decision.
128 |
129 | Note that in this scene, we have defined a variable by preceeding the variable name with `$ ` and equating it to a value, e.g.
130 |
131 | ```python
132 | $ desc = "a lazy"
133 | ```
134 |
135 | This is the same as when we previously defined a *flag* variable, although in this case we did not write a `define` statement for the `desc` variable first. You can do the same thing with our flag variables only that, sometimes, it is more readable to write or define the flags first thing in the code. (For instance, it's more efficient to find them after many lines of coding).
136 |
137 | ## Return statement
138 |
139 | The `return` statement, like `label start` is another special statement in Ren'Py which means the end of the game. When this statement is run, no matter where in the game it is, the game immediately terminates.
140 |
141 | For example, if we have inserted `return` in the `label beach` block before the `jump ending` statement:
142 |
143 | ```python
144 | label beach:
145 | $ baonf = True
146 | scene bg beach with fade
147 |
148 | u "Wow, Lola! The beach is so pretty."
149 | n "Yes, it is. Glad you like it here."
150 |
151 | return
152 | jump ending
153 | ```
154 |
155 | What do you think will happen? Try this by modifying this block as above. The game will immediately terminate without the character ever experiencing the ending!
156 |
157 | That's it! Congratulations on creating a simple virtual novel.
158 |
159 | # Project
160 |
161 | Make a visual novel of your own. Write or choose a story, gather your own assets, build awesome characters, make up interesting dialogues! Share your work! We'll love to play it! :heart:
162 |
163 | [challenge_partial](../challenge_partial.md ':include')
164 |
165 | [](https://gitter.im/WWCodeManila/Python)
166 |
167 |
--------------------------------------------------------------------------------
/ren'py/scene2.md:
--------------------------------------------------------------------------------
1 | [](https://gitter.im/WWCodeManila/Python)
2 |
3 | # Scene 2
4 |
5 | Our next scene happens on your way to Aling Nena's store. You bump into your friends Lita and Boy and you're now faced with another decision - will you break your promise to Aling Nena or remain true to your words?
6 |
7 | In implementing this scene, we'll learn about:
8 |
9 | - [ ] Positioning images
10 | - [ ] Transitions
11 | - [ ] Flags and if-else statements
12 | - [ ] Jump statements
13 |
14 | You'll first need to add two characters before the `label start` block along with the previous two characters.
15 |
16 | ```python
17 | define b = Character("Boy")
18 | define l = Character("Lita")
19 | ```
20 |
21 | In addition, we'll define two other variables called `gamef` and `storef` and set their values to `False`. Write them just below where you defined the characters before the `label start` block.
22 |
23 | ```python
24 | define gamef = False
25 | define storef = False
26 | ```
27 |
28 | Next, copy the assets `bg street.png` , `lita.png`, and `boy.png` from the `assets` folder into `game/images`.
29 |
30 | Here is the full code for the next scene. Copy the following code into `script.rpy` after the `label start` block. It's a new `label` statement so it *should not be* indented inside the previous block.
31 |
32 | ```python
33 | label street:
34 |
35 | scene bg street with fade
36 |
37 | show nena
38 |
39 | n "Right, let's get started. We need to go to my Sari-sari store. Please help me for the day, Apo."
40 |
41 | hide nena
42 |
43 | show lita at left with moveinright
44 | l "Hi, Aling Nena and [name]!"
45 |
46 | show boy at right with moveinleft
47 | b "Hello po!"
48 | b "Long time no see, [name]! Tara, let's play!"
49 |
50 | show nena
51 | n "Naku apo, you said you'll help me."
52 |
53 | menu:
54 | "Lola, mamaya na. I'll play with my friends first.":
55 | n "Ay naku, apo. Bahala ka."
56 | jump game
57 | "Sorry Lita and Boy, I promised my Lola I'll help her today.":
58 | jump store
59 |
60 | label store:
61 | $ storef = True
62 | pass
63 | ```
64 |
65 | Create a new script called `batobato.rpy`. Write the following code:
66 |
67 | ```python
68 | label game:
69 | $ gamef = True
70 | pass
71 | ```
72 |
73 | Try to run the game using the Ren'Py launcher.
74 |
75 | !> Tip: You can use `Back` in the game screen to view the dialogue before or `Skip` to go ahead until some decision point is reached. Try these in order to view the different outcomes of your decision.
76 |
77 | ## Positioning images
78 |
79 | Continuing with our discussion about inserting images to our visual novel, positioning images in Ren'Py is as straight forward as using the `at` preposition, e.g:
80 |
81 | ```python
82 | show lita at left
83 | ```
84 |
85 | Ren'Py has a pre-defined set of positions: `left`, `right`, `center` (default), and `truecenter` (centered horizontally and vertically). You can also define your own custom position using the `Position()` class. We'll revisit how to use this class later in Scene 4.
86 |
87 | ## Transitions
88 |
89 | Instead of simply popping in a scene or character image, transitions can be used to aide your storytelling. Like positions, this can simply be introduced using `with`:
90 |
91 | ```python
92 | scene bg street with fade
93 | ```
94 |
95 | Transitions can be combined with positions:
96 |
97 | ```python
98 | show lita at left
99 | with moveinright
100 | ```
101 |
102 | which is the same as
103 |
104 | ```python
105 | show lita at left with moveinright
106 | ```
107 |
108 | Like positions, Ren'Py has predefined transitions such as `fade`, `dissolve`, and `pixellate`. Likewise, you can define your own transitions using the different *transition classes*. You can learn more about the different pre-defined transitions and transition classes [here](https://www.renpy.org/doc/html/transitions.html).
109 |
110 | ## Jump statement
111 |
112 | The `jump` statement indicates that a particular `label` statement should be run next:
113 |
114 | ```python
115 | #...
116 | menu:
117 | "Play":
118 | # ...
119 | jump game
120 | "Store":
121 | # ...
122 | jump store
123 | label game:
124 | "Player chooses play"
125 | label store:
126 | pass
127 | ```
128 |
129 | You can think of the label name as pointers and the jump names as directives to run codes in these pointers next.
130 |
131 | If you haven't decided what to put inside the next `label` block yet, you can prepare a `label` statement beforehand and just use`pass`, just like a regular Python `pass` statement:
132 |
133 | ```python
134 | label store:
135 | pass
136 | ```
137 |
138 | Otherwise, the game will terminate in an error when it couldn't find the the next labelled block.
139 |
140 | Let's fill out `label game` and `label store` in Scenes 3 and 4.
141 |
142 | ## Flags and If-else statements
143 |
144 | In our game, it is important to remember the choices of the player since some of these choices can determine what happens later on.
145 |
146 | Ren'Py supports the use of *flags*. Just like characters, these can be set using the `define` statement before the `label` block.
147 |
148 | ```python
149 | define flag = False
150 | label game:
151 | $ flag = True
152 | label home:
153 | "Home"
154 | ```
155 |
156 | Later on in the game, these flags can be used in an `if-else` statement.
157 |
158 | ```python
159 | label evaluate:
160 | if flag:
161 | "You played a game."
162 | else:
163 | "You went home."
164 | ```
165 |
166 | Notice that you don't have to define an `if-else` statement inside a `python` block and that instead of writing the variable as `$ flag` in the `if` statement, you just use the name of the variable without `$`. If you need this variable outside the `if-else` or even `elif` statements, you'll need to precede it as `$ flag`.
167 |
168 | In our code above for Scene 2, the variables `gamef` and `storef` are first set to `False` and then switched to `True` when the game ran the respective `label` blocks ... which, in turn, depended on the choice of the player under the `menu` block:
169 |
170 | ```python
171 | define gamef = False
172 | define storef = False
173 |
174 | # ...
175 |
176 | label street:
177 |
178 | # ...
179 |
180 | menu:
181 | "Lola, mamaya na. I'll play with my friends first.":
182 | n "Ay naku, apo. Bahala ka."
183 | jump game
184 | "Sorry Lita and Boy, I promised my Lola I'll help her today.":
185 | jump store
186 |
187 | label store:
188 | $ storef = True
189 | pass
190 | ```
191 |
192 | and in `batobato.rpy`
193 |
194 | ```python
195 | label game:
196 | $ gamef = True
197 | pass
198 | ```
199 |
200 | This is how the game remembers that a particular choice has been made. It doesn't really matter if you change the value of the flag inside the `menu` block or inside the `label` block, so long as this aides the readability of your code i.e. if you write all other flags in your code in the same manner.
201 |
202 | We'll use this values later on in the `label ending` block, in Scene 7 (the last scene):
203 |
204 | ```python
205 | label ending:
206 | #...
207 | if gamef:
208 | #...
209 | elif storef:
210 | # ..
211 | ```
212 |
213 |
214 |
215 | In the next part, we'll learn how to use other Python equivalent statements in Ren'Py by making a mini-game *bato-bato pik* (rock, paper, scissors).
216 |
217 | [](https://gitter.im/WWCodeManila/Python)
218 |
219 |
--------------------------------------------------------------------------------
/ren'py/game/options.rpy:
--------------------------------------------------------------------------------
1 | ## This file contains options that can be changed to customize your game.
2 | ##
3 | ## Lines beginning with two '#' marks are comments, and you shouldn't uncomment
4 | ## them. Lines beginning with a single '#' mark are commented-out code, and you
5 | ## may want to uncomment them when appropriate.
6 |
7 |
8 | ## Basics ######################################################################
9 |
10 | ## A human-readable name of the game. This is used to set the default window
11 | ## title, and shows up in the interface and error reports.
12 | ##
13 | ## The _() surrounding the string marks it as eligible for translation.
14 |
15 | define config.name = _("My VN")
16 |
17 |
18 | ## Determines if the title given above is shown on the main menu screen. Set
19 | ## this to False to hide the title.
20 |
21 | define gui.show_name = True
22 |
23 |
24 | ## The version of the game.
25 |
26 | define config.version = "1.0"
27 |
28 |
29 | ## Text that is placed on the game's about screen. Place the text between the
30 | ## triple-quotes, and leave a blank line between paragraphs.
31 |
32 | define gui.about = _p("""
33 | """)
34 |
35 |
36 | ## A short name for the game used for executables and directories in the built
37 | ## distribution. This must be ASCII-only, and must not contain spaces, colons,
38 | ## or semicolons.
39 |
40 | define build.name = "MyVN"
41 |
42 |
43 | ## Sounds and music ############################################################
44 |
45 | ## These three variables control which mixers are shown to the player by
46 | ## default. Setting one of these to False will hide the appropriate mixer.
47 |
48 | define config.has_sound = True
49 | define config.has_music = True
50 | define config.has_voice = True
51 |
52 |
53 | ## To allow the user to play a test sound on the sound or voice channel,
54 | ## uncomment a line below and use it to set a sample sound to play.
55 |
56 | # define config.sample_sound = "sample-sound.ogg"
57 | # define config.sample_voice = "sample-voice.ogg"
58 |
59 |
60 | ## Uncomment the following line to set an audio file that will be played while
61 | ## the player is at the main menu. This file will continue playing into the
62 | ## game, until it is stopped or another file is played.
63 |
64 | # define config.main_menu_music = "main-menu-theme.ogg"
65 |
66 |
67 | ## Transitions #################################################################
68 | ##
69 | ## These variables set transitions that are used when certain events occur.
70 | ## Each variable should be set to a transition, or None to indicate that no
71 | ## transition should be used.
72 |
73 | ## Entering or exiting the game menu.
74 |
75 | define config.enter_transition = dissolve
76 | define config.exit_transition = dissolve
77 |
78 |
79 | ## Between screens of the game menu.
80 |
81 | define config.intra_transition = dissolve
82 |
83 |
84 | ## A transition that is used after a game has been loaded.
85 |
86 | define config.after_load_transition = None
87 |
88 |
89 | ## Used when entering the main menu after the game has ended.
90 |
91 | define config.end_game_transition = None
92 |
93 |
94 | ## A variable to set the transition used when the game starts does not exist.
95 | ## Instead, use a with statement after showing the initial scene.
96 |
97 |
98 | ## Window management ###########################################################
99 | ##
100 | ## This controls when the dialogue window is displayed. If "show", it is always
101 | ## displayed. If "hide", it is only displayed when dialogue is present. If
102 | ## "auto", the window is hidden before scene statements and shown again once
103 | ## dialogue is displayed.
104 | ##
105 | ## After the game has started, this can be changed with the "window show",
106 | ## "window hide", and "window auto" statements.
107 |
108 | define config.window = "auto"
109 |
110 |
111 | ## Transitions used to show and hide the dialogue window
112 |
113 | define config.window_show_transition = Dissolve(.2)
114 | define config.window_hide_transition = Dissolve(.2)
115 |
116 |
117 | ## Preference defaults #########################################################
118 |
119 | ## Controls the default text speed. The default, 0, is infinite, while any other
120 | ## number is the number of characters per second to type out.
121 |
122 | default preferences.text_cps = 0
123 |
124 |
125 | ## The default auto-forward delay. Larger numbers lead to longer waits, with 0
126 | ## to 30 being the valid range.
127 |
128 | default preferences.afm_time = 15
129 |
130 |
131 | ## Save directory ##############################################################
132 | ##
133 | ## Controls the platform-specific place Ren'Py will place the save files for
134 | ## this game. The save files will be placed in:
135 | ##
136 | ## Windows: %APPDATA\RenPy\
137 | ##
138 | ## Macintosh: $HOME/Library/RenPy/
139 | ##
140 | ## Linux: $HOME/.renpy/
141 | ##
142 | ## This generally should not be changed, and if it is, should always be a
143 | ## literal string, not an expression.
144 |
145 | define config.save_directory = "MyVN-1569378769"
146 |
147 |
148 | ## Icon ########################################################################
149 | ##
150 | ## The icon displayed on the taskbar or dock.
151 |
152 | define config.window_icon = "gui/window_icon.png"
153 |
154 |
155 | ## Build configuration #########################################################
156 | ##
157 | ## This section controls how Ren'Py turns your project into distribution files.
158 |
159 | init python:
160 |
161 | ## The following functions take file patterns. File patterns are case-
162 | ## insensitive, and matched against the path relative to the base directory,
163 | ## with and without a leading /. If multiple patterns match, the first is
164 | ## used.
165 | ##
166 | ## In a pattern:
167 | ##
168 | ## / is the directory separator.
169 | ##
170 | ## * matches all characters, except the directory separator.
171 | ##
172 | ## ** matches all characters, including the directory separator.
173 | ##
174 | ## For example, "*.txt" matches txt files in the base directory, "game/
175 | ## **.ogg" matches ogg files in the game directory or any of its
176 | ## subdirectories, and "**.psd" matches psd files anywhere in the project.
177 |
178 | ## Classify files as None to exclude them from the built distributions.
179 |
180 | build.classify('**~', None)
181 | build.classify('**.bak', None)
182 | build.classify('**/.**', None)
183 | build.classify('**/#**', None)
184 | build.classify('**/thumbs.db', None)
185 |
186 | ## To archive files, classify them as 'archive'.
187 |
188 | # build.classify('game/**.png', 'archive')
189 | # build.classify('game/**.jpg', 'archive')
190 |
191 | ## Files matching documentation patterns are duplicated in a mac app build,
192 | ## so they appear in both the app and the zip file.
193 |
194 | build.documentation('*.html')
195 | build.documentation('*.txt')
196 |
197 | ## Set this to a string containing your Apple Developer ID Application to enable
198 | ## codesigning on the Mac. Be sure to change it to your own Apple-issued ID.
199 |
200 | # define build.mac_identity = "Developer ID Application: Guy Shy (XHTE5H7Z42)"
201 |
202 |
203 | ## A Google Play license key is required to download expansion files and perform
204 | ## in-app purchases. It can be found on the "Services & APIs" page of the Google
205 | ## Play developer console.
206 |
207 | # define build.google_play_key = "..."
208 |
209 |
210 | ## The username and project name associated with an itch.io project, separated
211 | ## by a slash.
212 |
213 | # define build.itch_project = "renpytom/test-project"
214 |
--------------------------------------------------------------------------------
/ren'py/game/script.rpy:
--------------------------------------------------------------------------------
1 | define n = Character("Aling Nena")
2 | define u = Character("[name]")
3 | define b = Character("Boy")
4 | define l = Character("Lita")
5 | define r = Character("Bert")
6 | define t = Character("Tasya")
7 |
8 | define gamef = False
9 | define storef = False
10 | define correct_change = False
11 | define correct_item = False
12 | define baonf = False
13 | define beachf = False
14 | define rewardf = False
15 |
16 | label start:
17 | scene bg inside house
18 |
19 | "It's the start of summer vacation."
20 | "You decided to go to the province to spend some time with your lola --"
21 | show nena
22 | "Aling Nena"
23 | n "Apo, what's your name again?"
24 |
25 | "{i}Ay naku, my lola always forgets my name.{/i}"
26 |
27 | python:
28 | name = renpy.input("What is your name?").title()
29 |
30 | u "I'm [name], Lola Nena."
31 | n "Ah, yes. [name]. I remember now."
32 | u "..."
33 | n "Can you help with my errands today, apo?"
34 |
35 | menu:
36 | "Yes, Lola. You can always count on me.":
37 | n "Thanks Apo. I'm sure I can count on you."
38 | "Hmm. I rather sleep.":
39 | n "Really? Your Mom and Dad will hear about this!"
40 | u "Alright, Lola. I'll help you."
41 |
42 | label street:
43 |
44 | scene bg street with fade
45 |
46 | show nena
47 |
48 | n "Right, let's get started. We need to go to my Sari-sari store. Please help me for the day, Apo."
49 |
50 | hide nena
51 |
52 | show lita at left with moveinright
53 | l "Hi, Aling Nena and [name]!"
54 |
55 | show boy at right with moveinleft
56 | b "Hello po!"
57 | b "Long time no see, [name]! Tara, let's play!"
58 |
59 | show nena
60 | n "Naku apo, you said you'll help me."
61 |
62 | menu:
63 | "Lola, mamaya na. I'll play with my friends first.":
64 | n "Ay naku, apo. Bahala ka."
65 | jump game
66 | "Sorry Lita and Boy, I promised my Lola I'll help her today.":
67 | jump store
68 |
69 | label store:
70 | $ storef = True
71 | scene bg store with fade
72 |
73 | show nena
74 | n "Thanks, [name], for helping me in the store today."
75 | u "It's okay Lola Nena."
76 |
77 | hide nena
78 | show bert with moveinright
79 |
80 | r "Good day, Aling Nena."
81 | n "Good day, Bert. What is your business today?"
82 | show store prices at Position(xpos = 0.10, ypos=0.10, xanchor = 0.0, yanchor = 0.0) with dissolve
83 | r "I need 2 kilos of rice, 2 cans of sardines, and 1 liter of oil, please."
84 | u "I'll help you today, Bert."
85 |
86 | with fade
87 |
88 | u "Here you go."
89 | "You give the items to Bert."
90 | r "Hohoho. Thanks, [name]. Here's Php 100."
91 | u "Wait a minute, Bert..."
92 | "{i}He bought 2 kilos of rice, 2 cans of sardines, and 1 liter of oil ... {w} And he gave me Php 100. That means ... {/i}"
93 |
94 | menu:
95 | "I should give him a change of {b}Php 20{/b}":
96 | u "Your change is Php 20."
97 | "You give the change to Bert."
98 | $ correct_change = True
99 | "I should give him a change of {b}Php 10{/b}":
100 | u "Your change is Php 10."
101 | "You give the change to Bert."
102 | "{b}No change{/b}":
103 | u "Oops. Nothing."
104 |
105 | if correct_change:
106 | "Bert smiles and walks away."
107 | hide store prices
108 | hide bert with moveoutleft
109 | else:
110 | "You pocket the rest of the change."
111 | "Bert frowns and walks away."
112 | hide store prices
113 | hide bert with moveoutleft
114 |
115 | with fade
116 | show tasya with moveinleft
117 |
118 | t "Good day Aling Nena and [name]."
119 | u "What brings you here, Tasya?"
120 | t "I'm here to collect my reward from Aling Nena's Sari-sari store."
121 | u "Congratulations, Tasya! What reward number did you avail?"
122 | show store rewards at Position(xpos = 0.90, ypos=0.10, xanchor = 1.0, yanchor = 0.0) with dissolve
123 | t "It's number 5."
124 |
125 | "You give her ... "
126 |
127 | menu:
128 | "Coke Sakto":
129 | "... Coke Sakto."
130 | "Boy Bawang":
131 | "... Boy Bawang."
132 | "Php 15 load":
133 | "... Php 15 load."
134 | $ correct_item = True
135 |
136 | if correct_item:
137 | "Tasya smiles and walks away."
138 | hide store rewards
139 | hide tasya with moveoutright
140 | else:
141 | "You keep the reward for your self."
142 | "Tasya frowns and walks away."
143 | hide store rewards
144 | hide tasya with moveoutright
145 |
146 | if correct_change and correct_item:
147 | jump reward
148 | else:
149 | jump ending
150 |
151 | label reward:
152 |
153 | $ rewardf = True
154 |
155 | with fade
156 | show nena
157 |
158 | n "You did well, [name]! Because you helped me a lot today, I will give you a reward."
159 | n "Which will it be?"
160 |
161 | menu:
162 | "I can give you a baon to spend with your friends.":
163 | $ baonf = True
164 | u "Thanks for the allowance, Lola. I'll go play with Lita and Boy now."
165 | n "Go ahead, Apo. You deserve it."
166 | jump game
167 | "We'll go to the beach.":
168 | $ beachf = True
169 | u "Let's go the beach, Lola!"
170 | jump beach
171 |
172 | label beach:
173 | $ baonf = True
174 | scene bg beach with fade
175 |
176 | u "Wow, Lola! The beach is so pretty."
177 | n "Yes, it is. Glad you like it here."
178 |
179 | jump ending
180 |
181 | label ending:
182 |
183 | scene bg inside house with fade
184 |
185 | if rewardf:
186 | if baonf:
187 | "You were able to spend the rest of the day with your friends Lita and Boy."
188 | "You bought snacks for the three of you from the allowance Aling Nena gave you."
189 | elif beachf:
190 | pass
191 |
192 | "And just like that, your summer vacation in the province passed in bliss and happiness."
193 |
194 | with fade
195 |
196 | show nena
197 |
198 | u "Thank you Lola Nena for letting me stay with you for the summer."
199 | n "You're always welcome here, [name]."
200 | u "I'll comeback again next vacation!"
201 | n "Sure, apo!"
202 |
203 | scene bg inside house with fade
204 |
205 | "THE END"
206 |
207 | else:
208 | "You went home after a long day."
209 | show nena sad
210 | "Your Lola Nena is waiting for you. She doesn't look happy."
211 | n "Apo, I have called your Mom and Dad. They will fetch you here tomorrow."
212 | u "But.. but Lola..."
213 |
214 | if gamef:
215 | $ desc = "a lazy"
216 | n "You only played all day with your friends even though you promised to help me."
217 | elif storef:
218 | if correct_change == False:
219 | $ desc = "a dishonest"
220 | n "Bert told me that you did not give him the correct change."
221 | n "Instead, you pocketed the excess amount!"
222 | if correct_item == False:
223 | $ desc = "an untrustworthy"
224 | n "Tasya said that you didn't give her the correct reward."
225 | n "Instead, you kept it to your self!"
226 |
227 | n "I have no use for [desc] grandchild."
228 |
229 | scene bg inside house with fade
230 |
231 | "And just like that, your summer vacation in the province is OVER."
232 |
233 | "THE END"
234 |
235 | return
--------------------------------------------------------------------------------
/flask/discussions/05_templates_and_variables.md:
--------------------------------------------------------------------------------
1 | ## Goals
2 |
3 | - [ ] Render HTML templates
4 | - [ ] Pass variables from URL routes
5 | - [ ] Style pages using Jinja
6 |
7 | ## Getting Started
8 |
9 | Open the portfolio project directory that you created last time.
10 |
11 | 1. Create a new folder named `templates`.
12 |
13 | ```shell
14 | mkdir templates
15 | ```
16 |
17 | This is where we'll place all of the HTML templates that we'll create later on.
18 |
19 | 2. Create a new folder named `static` with subfolders named `css` and `js`.
20 |
21 | ```shell
22 | mkdir static
23 | cd static
24 | mkdir css
25 | mkdir js
26 | cd ..
27 | ```
28 |
29 | This is where we'll place all of our CSS and JS files.
30 |
31 | Your project directory should now contain the following:
32 |
33 |
34 |
35 | 3. Create a file named `about.html` and place it inside the templates folder.
36 |
37 | ```shell
38 |
Welcome to the About page.
39 | ```
40 |
41 | 4. Open `app.py` and render `about.html` inside your `about` function by replacing the return string `About` with `render_template(file_name)`.
42 |
43 | ```shell
44 | from flask import render_template
45 |
46 | @app.route("/about/")
47 | def about():
48 | return render_template("about.html")
49 | ```
50 |
51 | If you try to access `/about/`, the contents of `about.html` will be displayed.
52 |
53 | *You may remove your `about_location()` function since we won't be using it anymore.*
54 |
55 | 5. Create a file named `layout.html` and place it inside the templates folder.
56 |
57 | ```shell
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | ```
69 |
70 | 6. Check out the following links and save them inside your `static` folder:
71 |
72 | * [jquery-3.3.1.min.js](https://code.jquery.com/jquery-3.3.1.min.js)
73 | * [bootstrap.min.js](https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js)
74 | * [bootstrap.min.css](https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css)
75 |
76 | 7. Inside the head tag of your `layout.html`, add a `title` and reference your CSS files.
77 |
78 | ```shell
79 | Your Name
80 |
81 | ```
82 |
83 | The `url_for()` function is used to get the relative path of a file.
84 |
85 | 8. Reference your JS files inside the body tag.
86 |
87 | ```shell
88 |
89 |
90 | ```
91 |
92 | 9. Add a navigation bar inside the body tag as well. Make sure that the JS references are located at the bottom most part of the body.
93 |
94 | ```shell
95 |
108 | ```
109 |
110 | The `url_for()` function can also be used to get the relative path and URL route of the functions in your `app.py`. In this case, `url_for('about')` refers to `/about/`.
111 |
112 | 10. Add a block named `body` below the navigation bar.
113 |
114 | ```shell
115 | {% block body %}{% endblock %}
116 | ```
117 |
118 | Blocks are used to load dynamic content on a static page.
119 |
120 | 11. Go back to your `app.py`. Add an optional string input `username` to the `skills` function and set the default value to `None`.
121 |
122 | ```shell
123 | @app.route("/skills/", defaults={'username': None})
124 | @app.route("/skills//")
125 | def skills():
126 | return "Skills"
127 | ```
128 |
129 | 12. Allow the `skills` function to accept the `username` variable and replace the return string with a rendered `skills.html` template that accepts the variable `username`.
130 |
131 | ```shell
132 | @app.route("/skills/", defaults={'username': None})
133 | @app.route("/skills//")
134 | def skills(username):
135 | return render_template("skills.html", username=username)
136 | ```
137 |
138 | A variable can be passed to a template by referencing it as a second parameter of the `render_template()` function.
139 |
140 | *You may remove your `skills_toeic()` function since we won't be using it anymore.*
141 |
142 | 13. Since we don't have `skills.html` yet, create it and place it inside the `templates` folder.
143 |
144 | ```shell
145 |
Welcome to the Skills page.
146 | ```
147 |
148 | 14. To utilize the `layout.html` that we made earlier, extend it inside your `skills.html` and put your welcome header inside the `body` block.
149 |
150 | ```shell
151 | {% extends "layout.html" %}
152 |
153 | {% block body %}
154 |
155 |
Welcome to the Skills page.
156 |
157 | {% endblock %}
158 | ```
159 |
160 | Contents added in between the block tags are loaded with the layout page specified. If you try to access `/skills/`, the contents of `layout.html` and `skills.html` will be displayed.
161 |
162 | 15. To use the variable `username` inside `skills.html`, encase the variable name inside double curly braces.
163 |
164 | ```shell
165 |
166 | Hi, {{username|title}}!
167 |
168 | ```
169 |
170 | Use the `title` keyword to make the first letter of each word capitalized.
171 |
172 | 16. What happens when the value of `username` is `None`? Use an if-else statement with Jinja to handle this problem.
173 |
174 | ```shell
175 |
182 | ```
183 |
184 | If you try to access `/skills/` without an input, it will now display the message:
185 |
186 | > Hi, stranger. What's your name?
187 |
188 | 17. Go back to your `app.py`. Remove the optional integer input `amount` from the URL routes of `projects` function and render `projects.html` instead.
189 |
190 | ```shell
191 | @app.route("/projects/")
192 | def projects():
193 | return render_template("projects.html")
194 | ```
195 |
196 | 18. Inside the `projects` function, define a list of projects inside the variable `projects`.
197 |
198 | ```shell
199 | projects = ["Facebook", "Twitter", "Instagram", "Uber", "Grab"]
200 | ```
201 |
202 | 19. Import `randint()` from `random` and use it to assign a random integer to a variable named `randNo`.
203 |
204 | Add this to the top part of your code:
205 |
206 | ```shell
207 | from random import randint
208 | ```
209 |
210 | Add this inside `projects` function:
211 |
212 | ```shell
213 | randNo = randint(0, len(projects) - 1)
214 | ```
215 |
216 | The first parameter of `randint()` refers to the lowest possible number while the second parameter refers to the highest possible number, which is equal to the number of projects minus 1 since we started counting from 0.
217 |
218 | 20. Create a variable named `project` which contains a random project from the list of projects and pass all the variables to `projects.html`.
219 |
220 | ```shell
221 | project = projects[randNo]
222 |
223 | return render_template("projects.html", **locals())
224 | ```
225 |
226 | The `**locals` keyword is used to pass multiple variables.
227 |
228 | 21. Create `projects.html` inside the static folder with the same structure as `skills.html`.
229 |
230 | ```shell
231 | {% extends "layout.html" %}
232 |
233 | {% block body %}
234 |
235 |
Welcome to the Projects page.
236 |
237 | {% endblock %}
238 | ```
239 |
240 | 22. Finally, use the variables that we created earlier inside the `projects` function while utilizing the for loop statement.
241 |
242 | ```shell
243 |
These are what I\'ve done so far:
244 |
245 | {% for p in projects %}
246 |
{{ p }}
247 | {% endfor %}
248 |
249 |
250 |
... and {{ project }} is the one that I enjoyed coding the most.
251 | ```
252 |
253 | This displays a bulleted list of projects and the randomly selected project as follows:
254 |
255 | > **There are what I've done so far:**
256 | > * Facebook
257 | > * Twitter
258 | > * Instagram
259 | > * Uber
260 | > * Grab
261 | >
262 | > ... and **Facebook** is the one that I enjoyed coding the most.
263 |
264 | ## Congratulations!
265 |
266 | You're halfway through the entire tutorial. Now try to create a template for all of your existing pages and feel free to customize them and their contents!
267 |
--------------------------------------------------------------------------------