├── .gitignore ├── LICENSE ├── Outline.md ├── Outline.pdf ├── README.md ├── python-logo-200x200.png ├── units ├── database │ └── 1 │ │ ├── Database and SQL - Presentation.md │ │ ├── database-and-sql.md │ │ └── examples │ │ └── exercise.sql ├── django │ ├── 1 │ │ ├── examples │ │ │ └── wsgi │ │ │ │ ├── hello.py │ │ │ │ ├── hello_html.py │ │ │ │ └── html │ │ │ │ └── hello.html │ │ └── wsgi-pip-and-virtualenv.md │ ├── 2 │ │ └── django-helloworld.md │ ├── 3 │ │ └── templates-and-views.md │ ├── 4 │ │ └── database-orm-and-models.md │ ├── 5 │ │ └── form-processing.md │ ├── 6 │ │ └── validation.md │ ├── 7 │ │ └── ajax.md │ ├── 8 │ │ └── auth.md │ ├── 9 │ │ └── finalization.md │ ├── 10 │ │ └── hashtags.md │ ├── 11 │ │ └── rest-api.md │ └── 12 │ │ ├── examples │ │ ├── test_rest.py │ │ └── test_rest_input.py │ │ └── heroku-deployment.md ├── git │ ├── Git-Logo-Black.png │ ├── VCS, Git & GitHub - Presentation.md │ ├── VCS, Git & GitHub.pdf │ ├── distributed-git.svg │ ├── distributed.png │ └── vcs-git-and-github.md ├── python │ ├── 1 │ │ ├── Python - Variables, Types & Operators - Presentation.md │ │ ├── Python - Variables, Types & Operators.pdf │ │ ├── distance_formula.png │ │ ├── python-variables-types-and-operators.md │ │ └── quadratic_formula.png │ ├── 2 │ │ ├── Strings and Formatting - Presentation.md │ │ ├── Strings and Formatting.pdf │ │ ├── ex_2.py │ │ ├── ex_3.py │ │ ├── example.py │ │ ├── example_1.py │ │ ├── example_2.py │ │ ├── example_3.py │ │ ├── example_4.py │ │ └── strings-and-formatting.md │ ├── 3 │ │ ├── Lists and Dictionaries - Presentation.md │ │ ├── Lists and Dictionaries.pdf │ │ ├── example_1.py │ │ ├── example_2.py │ │ ├── example_3.py │ │ ├── example_4.py │ │ ├── example_5.py │ │ └── lists-and-dictionaries.md │ ├── 4 │ │ ├── Conditionals and Loops - Presentation.md │ │ ├── Conditionals and Loops.pdf │ │ ├── conditionals-and-loops.md │ │ ├── example_1.py │ │ ├── example_2.py │ │ ├── example_3.py │ │ ├── example_4.py │ │ ├── example_5.py │ │ ├── example_6.py │ │ ├── example_7.py │ │ ├── example_8.py │ │ ├── example_9.py │ │ ├── exercise_1.py │ │ ├── exercise_4.py │ │ └── list_of_dicts.py │ ├── 5 │ │ ├── Functions and Lambdas - Presentation.md │ │ ├── Functions and Lambdas.pdf │ │ ├── example_4.py │ │ ├── example_5.py │ │ └── functions-and-lambdas.md │ ├── 6 │ │ ├── Exception Handling - Presentation.md │ │ ├── Exception Handling.pdf │ │ ├── example_1.py │ │ ├── exception-handling.md │ │ ├── exercise_3.py │ │ ├── handling_exceptions.py │ │ └── handling_exceptions_improved.py │ ├── 7 │ │ ├── Modules and Packages - Presentation.md │ │ ├── Modules and Packages.pdf │ │ ├── examples │ │ │ ├── example_2.py │ │ │ ├── example_3.py │ │ │ ├── fib.py │ │ │ ├── foo.py │ │ │ ├── foo │ │ │ │ ├── __init__.py │ │ │ │ └── bar │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── baz.py │ │ │ ├── test.py │ │ │ └── util.py │ │ └── modules-and-packages.md │ └── 8 │ │ ├── classes-and-objects.md │ │ └── examples │ │ ├── example_3.py │ │ ├── example_4.py │ │ └── exercise_1.py └── web │ ├── 1 │ └── web-basics-and-http.md │ └── 2 │ ├── examples │ ├── anim │ │ ├── css │ │ │ └── style.css │ │ ├── index.html │ │ └── js │ │ │ └── anim.js │ ├── calculator │ │ ├── css │ │ │ └── style.css │ │ ├── index.html │ │ └── js │ │ │ └── calculator.js │ └── hello-world │ │ ├── css │ │ └── style.css │ │ ├── index.html │ │ └── js │ │ └── hello.js │ └── frontend-and-javascript.md └── workshop ├── Introduction.md ├── Presentation.md ├── Presentation.pdf └── python-logo-200x200.png /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .pyc 3 | -------------------------------------------------------------------------------- /Outline.md: -------------------------------------------------------------------------------- 1 | # Python, Django & Web Development 2 | 3 | ## Course Intro 4 | **Level**: Intermediate 5 | 6 | **Prerequisites**: 7 | * Programming Fundamentals (C, C++ or any programming language). 8 | * Basic Knowledge about Databases. 9 | 10 | **Would be helpful**: 11 | * Familiarity with Web & Web Technologies like HTML, CSS, Javascript. 12 | * Familiarity with Linux, CLI(Command Line Interface) & tools. 13 | 14 | ## Outline 15 | This is a 60 hours course, 2.5 hours per each class, 3 classes a week and 24 classes in total, and would be a 8 weeks long course. This course mainly focuses on Python (20 hrs), Django Framework (30 hrs) and the rest of the 10 hours are to be spent on the Web Development basics, Databases & Version Control System which are platform agnostic and are preliminaries to be covered in Web Development in any platform. 16 | 17 | The 2.5 hours of class would contain theoretical discussions, practical lessons, implementation, exercises and discussions about assignments. Students are given assignments after each class and we'll use GitHub for submitting the assignments as well. Students will just be maintaining their own history of assignments and exercises they do in their own github account. This is why we'll begin with the first class on Git & Github basics followed by others. 18 | 19 | ## Course break down 20 | 21 | #### Version Control - 2.5 hrs 22 | 1. Git & Github 23 | 24 | #### Python - 20 hrs 25 | 1. Variables, Data Types & Operators 26 | 2. String, Formatting & Operations 27 | 3. Lists & Dictionaries 28 | 4. Conditions 29 | 5. Loops 30 | 6. Functions & Lamdas 31 | 7. Modules & Packages 32 | 8. Classes & Objects 33 | 34 | #### Database & SQL (PostgreSQL) - 2.5 hrs 35 | 1. DBMS, Database and SQL 36 | 37 | #### Web Development Basics - 5 hrs 38 | 1. Web, Client, Server and HTTP 39 | 2. Javascript basics and the Frontend 40 | 41 | #### Web Development with Django - 30 hrs 42 | 1. WSGI, pip & virtualenv 43 | 2. Django - Hello World 44 | 3. Templates & Views 45 | 4. Database, ORM & Models 46 | 5. HTML Forms & Form Processing 47 | 6. Validation 48 | 7. Authentication 49 | 8. Django Admin 50 | 9. Full backend development 51 | 10. REST API Development 52 | 11. Best Practices 53 | 12. Application Deployment to Heroku 54 | -------------------------------------------------------------------------------- /Outline.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/Outline.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn Python, Django & Web Development 2 | 3 | This is a course targeted for beginners who are familiar with Programming Fundamentals (at least academically) and the contents are well suited especially for Fresh Computing students with no prior professional development experience. 4 | 5 | This course mainly focuses on [Python](https://www.python.org/), [Django](https://www.djangoproject.com/) and slightly touches the basics of Web Development, Databases & Version Control System which are platform agnostic and are preliminaries to be covered in Web Development in any platform. 6 | 7 | **This is a work in progress, I'm still writing up regularly for the topics listed below. So, stay tuned.** 8 | 9 | ## Course 10 | #### Introduction 11 | 1. [Learning Python](workshop/Introduction.md) [[Slides](https://speakerdeck.com/kabirbaidhya/learning-python)] 12 | 13 | #### Version Control 14 | 1. [VCS, Git & Github](units/git/vcs-git-and-github.md) [[Slides](https://speakerdeck.com/kabirbaidhya/vcs-git-and-github)] 15 | 16 | #### Python 17 | 1. [Variables, Data Types & Operators](units/python/1/python-variables-types-and-operators.md) [[Slides](https://speakerdeck.com/kabirbaidhya/python-variables-data-types-and-operators)] 18 | 2. [String and Formatting](units/python/2/strings-and-formatting.md) [[Slides](https://speakerdeck.com/kabirbaidhya/python-strings-and-formatting)] 19 | 3. [Lists & Dictionaries](units/python/3/lists-and-dictionaries.md) [[Slides](https://speakerdeck.com/kabirbaidhya/python-lists-and-dictionaries)] 20 | 4. [Conditionals and Loops](units/python/4/conditionals-and-loops.md) [[Slides](https://speakerdeck.com/kabirbaidhya/python-conditionals-and-loops)] 21 | 5. [Functions & Lamdas](units/python/5/functions-and-lambdas.md) [[Slides](https://speakerdeck.com/kabirbaidhya/python-functions-and-lambdas)] 22 | 6. [Exception Handling](units/python/6/exception-handling.md) [[Slides](https://speakerdeck.com/kabirbaidhya/python-exception-handling)] 23 | 7. [Modules & Packages](units/python/7/modules-and-packages.md) [[Slides](https://speakerdeck.com/kabirbaidhya/python-modules-and-packages)] 24 | 8. [Classes & Objects](units/python/8/classes-and-objects.md) [[Slides](https://speakerdeck.com/kabirbaidhya/python-classes-and-objects)] 25 | 26 | #### Database & SQL (PostgreSQL) 27 | 1. [Database and SQL](units/database/1/database-and-sql.md) [[Slides](https://speakerdeck.com/kabirbaidhya/database-and-sql)] 28 | 29 | #### Web Development Basics 30 | 1. [Web basics and HTTP](units/web/1/web-basics-and-http.md) 31 | 2. [Frontend and JavaScript Basics](units/web/2/frontend-and-javascript.md) 32 | 33 | #### Web Development with Django 34 | 1. [WSGI, pip & virtualenv](units/django/1/wsgi-pip-and-virtualenv.md) 35 | 2. [Django - Hello World](units/django/2/django-helloworld.md) 36 | 3. [Templates & Views](units/django/3/templates-and-views.md) 37 | 4. [Database, ORM & Models](units/django/4/database-orm-and-models.md) 38 | 5. [Form Processing](units/django/5/form-processing.md) 39 | 6. [Validation](units/django/6/validation.md) 40 | 7. [Asynchronous HTTP Requests (Ajax)](units/django/7/ajax.md) 41 | 8. [Django Authentication](units/django/8/auth.md) 42 | 9. [TodoApp Finalization](units/django/9/finalization.md) 43 | 10. [Add Hashtags](units/django/10/hashtags.md) 44 | 11. [REST API Development](units/django/11/rest-api.md) 45 | 12. [Deployment to Heroku](units/django/12/heroku-deployment.md) 46 | 47 | 48 | ## Stay Tuned 49 | More Write ups & slides for the remaining topics are coming up shortly. Stay Tuned :) 50 | 51 | ## License & Copyright 52 | 53 | Copyright (c) 2017 Kabir Baidhya. 54 | 55 | Licensed under [Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International](https://creativecommons.org/licenses/by-nc-nd/4.0/) 56 | -------------------------------------------------------------------------------- /python-logo-200x200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/python-logo-200x200.png -------------------------------------------------------------------------------- /units/database/1/Database and SQL - Presentation.md: -------------------------------------------------------------------------------- 1 | 4 | ###### Database 5 | Database & SQL (PostgreSQL) 6 | ================== 7 | 8 | # ![](../../../python-logo-200x200.png) 9 | 10 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 11 | 12 | --- 13 | 16 | # Reflections 17 | --- 18 | ### So far, 19 | We've covered all these things 20 | 21 | 1. Python Basics 22 | 23 | Note: If you're not aware of these. Read them at https://github.com/kabirbaidhya/learn-python-django-web 24 | 25 | --- 26 | # Before we begin 27 | --- 28 | 31 | ### Database 32 | 33 | A structured repository of data held in a computer, for easier retrieval and manipulation. 34 | 35 | --- 36 | ### DBMS 37 | A software that provides a systematic way to create, manage and work with databases. 38 | 39 | Modern DBMSs are available generally in two types: **SQL/Relational Databases and NoSQL Databases**. 40 | 41 | Well-known DBMSs: MySQL, PostgreSQL, MongoDB, MariaDB, Microsoft SQL Server, etc. 42 | 43 | --- 44 | ### Table 45 | A table is a structured collection of data about a specific entity in a database. In a relation database, data is organized in terms of relations or tables. 46 | 47 | --- 48 | ### Table 49 | A table consists of rows (records) and columns (fields). Each row in a table consists of a complete information about an instance of the entity related with the table eg: a user. And each column of the row is a specific attribute of that particular entity eg: user's name or email. 50 | 51 | --- 52 | 55 | ### For example 56 | A table with data about users would look like: 57 | 58 | 59 | id | name | email 60 | ---|------------|-------------------- 61 | 1 | Test User | foo@bar.com 62 | 2 | Test User | foo@bar.com 63 | 4 | New User 1 | newuser1@gmail.com 64 | 5 | New User 2 | newuser2@gmail.com 65 | 6 | New User 3 | newuser3@gmail.com 66 | 7 | New User 4 | newuser4@gmail.com 67 | 8 | New User 5 | newuser5@gmail.com 68 | 9 | New User 6 | newuser6@gmail.com 69 | 70 | 71 | 72 | --- 73 | 76 | ### Primary Key 77 | A Primary Key (PK) is a special column (or combination of columns) in a table which uniquely identifies each record in the table. 78 | 79 | The value of PK column: 80 | 1. Must be UNIQUE across all the records in the table. 81 | 2. Must not contain NULL values. 82 | 83 | --- 84 | 87 | # SQL 88 | --- 89 | 92 | ### SQL 93 | SQL(Structured Query Language) is the defacto language for managing, retrieving, & manipulating data and databases in the relational database world. 94 | 95 | The SQL language consists entire vocabulary for database management, querying, insertion, manipulation or removal of data in relational databases. 96 | 97 | --- 98 | 101 | ### For example 102 | This is an example SQL query that retrieves a list of users whose emails start with `foo@`: 103 | 104 | ``` 105 | SELECT * FROM users WHERE email LIKE 'foo@%'; 106 | ``` 107 | 108 | The result set that is retrieved would look like this: 109 | 110 | 111 | 112 | id | name | email 113 | ---|------------|-------------------- 114 | 1 | Test User | foo@bar.com 115 | 2 | Test User | foo@bar.com 116 | 117 | 118 | 119 | --- 120 | 123 | # PostgreSQL 124 | --- 125 | 128 | ### PostgreSQL 129 | > PostgreSQL is a powerful, open source object-relational database system. 130 | 131 | As per https://www.postgresql.org/about/ 132 | 133 | 134 | --- 135 | ### PostgreSQL 136 | PostgreSQL is one of the most popular and reliable choice in the relational database world along with MySQL, Oracle & Ms SQL Server. 137 | 138 | --- 139 | ### Why PostgreSQL? 140 | 1. Modern relational database 141 | 2. 15+ years of active development 142 | 3. Strong reputation for reliability, data integrity, and correctness 143 | 4. Open source 144 | 5. An enterprise class database with proven architecture 145 | 146 | --- 147 | --- 148 | 151 | ###### This slide was a part of course 152 | #### Python, Django & Web Development 153 | ###### [github.com/kabirbaidhya/learn-python-django-web](https://github.com/kabirbaidhya/learn-python-django-web) 154 | --- 155 | # Thank You 156 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 157 | ###### kabirbaidhya@gmail.com 158 | 159 | -------------------------------------------------------------------------------- /units/database/1/examples/exercise.sql: -------------------------------------------------------------------------------- 1 | 2 | CREATE TABLE users ( 3 | id serial PRIMARY KEY, 4 | first_name varchar (20) NOT NULL, 5 | last_name varchar (20) NOT NULL, 6 | email varchar (50) NOT NULL UNIQUE, 7 | address varchar (100), 8 | password varchar (50) NOT NULL, 9 | created_at timestamp NOT NULL 10 | ); 11 | 12 | CREATE TABLE todos ( 13 | id serial PRIMARY KEY, 14 | user_id integer NOT NULL REFERENCES users(id), 15 | title varchar (50) NOT NULL, 16 | description text, 17 | completed boolean NOT NULL DEFAULT false, 18 | created_at timestamp NOT NULL 19 | ); 20 | 21 | -- This is a comment. 22 | -- Insert Users 23 | INSERT INTO users (first_name, last_name, email, address, password, created_at) 24 | VALUES 25 | ('Test 1', 'Test', 'test1@test.com', 'Kathmandu, Nepal', 'test', NOW()), 26 | ('Test 2', 'Test', 'test2@test.com', 'Kathmandu, Nepal', 'test', NOW()), 27 | ('Test 3', 'Test', 'test3@test.com', 'Kathmandu, Nepal', 'test', NOW()); 28 | 29 | 30 | INSERT INTO todos (user_id, title, created_at) 31 | VALUES 32 | (1, 'Test to do 1', NOW()), 33 | (1, 'Test to do 2', NOW()), 34 | (2, 'Test to do 3', NOW()), 35 | (2, 'Test to do 4', NOW()), 36 | (2, 'Test to do 5', NOW()), 37 | (3, 'Test to do 6', NOW()), 38 | (3, 'Test to do 7', NOW()), 39 | (3, 'Test to do 8', NOW()), 40 | (1, 'Test to do 9', NOW()), 41 | (1, 'Test to do 10', NOW()), 42 | (2, 'Test to do 11', NOW()), 43 | (2, 'Test to do 12', NOW()), 44 | (1, 'Test to do 13', NOW()), 45 | (1, 'Test to do 14', NOW()), 46 | (3, 'Test to do 15', NOW()), 47 | (3, 'Test to do 16', NOW()); 48 | 49 | -- 50 | -- Select Query 51 | SELECT t.id, title, user_id, t.created_at, 52 | concat(u.first_name, ' ', u.last_name) as user_full_name 53 | from todos as t 54 | JOIN users as u ON u.id = t.user_id; 55 | -------------------------------------------------------------------------------- /units/django/1/examples/wsgi/hello.py: -------------------------------------------------------------------------------- 1 | from wsgiref.simple_server import make_server 2 | 3 | 4 | def application(env, start_response): 5 | status = '200 OK' 6 | headers = [ 7 | ('Content-Type', 'text/plain') 8 | ] 9 | start_response(status, headers) 10 | 11 | return [b'Hello World'] 12 | 13 | # Instantiate the server 14 | PORT = 8051 15 | httpd = make_server('localhost', PORT, application) 16 | 17 | print("Server is listening on port", PORT) 18 | # Serve the HTTP requests 19 | httpd.serve_forever() 20 | -------------------------------------------------------------------------------- /units/django/1/examples/wsgi/hello_html.py: -------------------------------------------------------------------------------- 1 | import os 2 | from wsgiref.validate import validator 3 | from wsgiref.simple_server import make_server 4 | 5 | 6 | def application(env, start_response): 7 | # Read the html from the file 8 | html = read_html('html/hello.html') 9 | 10 | # Convert it to byte string 11 | html = html.encode('ASCII') 12 | 13 | headers = [ 14 | ('Content-Type', 'text/html'), 15 | ('Content-Length', str(len(html))) 16 | ] 17 | start_response('200 OK', headers) 18 | 19 | return [html] 20 | 21 | 22 | def read_html(filename): 23 | directory = os.path.dirname(os.path.realpath(__file__)) 24 | full_path = os.path.join(directory, filename) 25 | f = open(full_path) 26 | data = f.read() 27 | f.close() 28 | 29 | return data 30 | 31 | # Instantiate the server 32 | PORT = 8000 33 | httpd = make_server('localhost', PORT, application) 34 | 35 | print("Server is listening on port", PORT) 36 | # Serve the HTTP requests 37 | httpd.serve_forever() 38 | -------------------------------------------------------------------------------- /units/django/1/examples/wsgi/html/hello.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Hello World! 4 | 5 | 6 |

Hello World

7 | 8 | 9 | -------------------------------------------------------------------------------- /units/django/1/wsgi-pip-and-virtualenv.md: -------------------------------------------------------------------------------- 1 | WSGI, pip and virtualenv 2 | ======================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/web/2/frontend-and-javascript.md) | [Next →]() 4 | 5 | 6 | Before we directly jump into Web Development (backend) with Django we need to be familiar with few concepts and tools. In this session we're going to be discussing about them. 7 | 8 | ## pip 9 | [`pip`](https://packaging.python.org/key_projects/#pip) is a package manager used to install and manage packages in the python world. Real world applications compose of many different dependencies, third-party libraries/packages maintaining them manually along with their dependencies could be a hassle. Thankfully we have package managers like pip to the rescue. 10 | 11 | If you are a Linux user you might be familiar with the tools like `apt-get`, `yum` etc. you can think of `pip` as similar tool for managing application level packages for python projects. 12 | 13 | You can read about installing pip [here](https://packaging.python.org/installing/#requirements-for-installing-packages). 14 | 15 | Once you have `pip` installed, you can verify it with: 16 | ``` 17 | $ pip --version 18 | ``` 19 | It should print the version something like this: 20 | ```plain 21 | pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7) 22 | ``` 23 | 24 | Now let's try installing a popuplar CLI tool made in python [`httpie`](https://httpie.org/) using pip. 25 | 26 | ```bash 27 | $ pip install httpie 28 | ``` 29 | 30 | ## virtualenv 31 | Virtualenv is another popular tool used in the python community. It is used to create virtual environments for python projects such that each one can have a different version of Python, and a different sets of libraries. 32 | 33 | Imagine a situation where you have to work on a project that relies upon python 2.7 but you also have another project that uses python 3.5. Virtualenv helps us maintain such different environments. 34 | 35 | ### Installation 36 | 37 | You can install `virtualenv` using `pip` like this: 38 | 39 | ```bash 40 | $ pip install virtualenv 41 | ``` 42 | 43 | Now test your installation: 44 | ``` 45 | $ virtualenv --version 46 | ``` 47 | 48 | ## WSGI 49 | WSGI is one of the common term that you should come across when you're beginning Web Development using Python. So, what does WSGI mean? WSGI stands for Web Server Gateway Interface. 50 | 51 | WSGI is nothing but a standard specification how Web Servers should communicate with Web applications written in Python. Almost all the popular web based frameworks like Django or Flask are WSGI compliant and follows the spec. 52 | 53 | As web frameworks are built on top of the WSGI spec, you'll be able to understand how these frameworks work behind the scenes after learning about WSGI. 54 | 55 | ### WSGI - Hello World 56 | 57 | Let's try a hello world example to see what WSGI is all about. 58 | 59 | Create a new file `hello.py`: 60 | ```python 61 | from wsgiref.simple_server import make_server 62 | 63 | 64 | def application(env, start_response): 65 | status = '200 OK' 66 | headers = [ 67 | ('Content-Type', 'text/plain') 68 | ] 69 | start_response(status, headers) 70 | 71 | return [b'Hello World'] 72 | 73 | # Instantiate the server 74 | PORT = 8000 75 | httpd = make_server('localhost', PORT, application) 76 | 77 | print("Server is listening on port", PORT) 78 | # Serve the HTTP requests 79 | httpd.serve_forever() 80 | 81 | ``` 82 | 83 | Here we've created a simplest WSGI based HTTP server that would send back "Hello World" to the HTTP Clients when requested. 84 | 85 | Now let's run by: 86 | ```bash 87 | $ python hello.py 88 | ``` 89 | 90 | You should see the output: 91 | ``` 92 | Server is listening on port 8000 93 | ``` 94 | 95 | This means our simples http server has started listening for http requests on port 8000. Let's try opening this url [http://localhost:8000](http://localhost:8000) in the browser to see the response. 96 | 97 | You should see the output "Hello World" printed on your browser. 98 | Great. You just created a simplest web server in python. 99 | 100 | Now let's try sending a request to our server using `httpie` CLI tool. 101 | 102 | ```bash 103 | $ http GET http://localhost:8000 104 | ``` 105 | 106 | You should now see the whole http response sent by our server: 107 | ```plain 108 | HTTP/1.0 200 OK 109 | Content-Length: 11 110 | Content-Type: text/plain 111 | Date: Thu, 27 Apr 2017 20:24:28 GMT 112 | Server: WSGIServer/0.2 CPython/3.5.2 113 | 114 | Hello World 115 | ``` 116 | 117 | ### WSGI - Hello World with HTML 118 | Now let's try sending html content instead of just plain text. 119 | 120 | First let's create a new python script `hello_html.py`: 121 | ```python 122 | import os 123 | from wsgiref.validate import validator 124 | from wsgiref.simple_server import make_server 125 | 126 | 127 | def application(env, start_response): 128 | # Read the html from the file 129 | html = read_html('html/hello.html') 130 | 131 | # Convert it to byte string 132 | html = html.encode('ASCII') 133 | 134 | headers = [ 135 | ('Content-Type', 'text/html'), 136 | ('Content-Length', str(len(html))) 137 | ] 138 | start_response('200 OK', headers) 139 | 140 | return [html] 141 | 142 | 143 | def read_html(filename): 144 | directory = os.path.dirname(os.path.realpath(__file__)) 145 | full_path = os.path.join(directory, filename) 146 | f = open(full_path) 147 | data = f.read() 148 | f.close() 149 | 150 | return data 151 | 152 | # Instantiate the server 153 | PORT = 8051 154 | httpd = make_server('localhost', PORT, application) 155 | 156 | print("Server is listening on port", PORT) 157 | # Serve the HTTP requests 158 | httpd.serve_forever() 159 | 160 | ``` 161 | Similarly let's create a directory `html` in the current directory and let's add a file `hello.html` inside it. 162 | 163 | Save the file `html/hello.html` with the following contents: 164 | ```html 165 | 166 | 167 | Hello World! 168 | 169 | 170 |

Hello World

171 | 172 | 173 | ``` 174 | 175 | By checking the above code you might have already understood what we're going to do here. All we're doing is just sending the contents of the file `html/hello.html` to the browsers as `Content-Type: text/html`. 176 | 177 | Now, let's run this server and see the output in the browser just like what we did before. 178 | 179 | ```bash 180 | $ python hello_html.py 181 | ``` 182 | After you see this line printed in the CLI: 183 | ``` 184 | Server is listening on port 8000 185 | ``` 186 | You can check the url [http://localhost:8000](http://localhost:8000) in your browser and you'll be able to see "Hello World" as a Web page in your browser. 187 | 188 | You can also try this with `httpie`, you should get the following output: 189 | ```plain 190 | ➜ http GET http://localhost:8000 191 | HTTP/1.0 200 OK 192 | Content-Length: 110 193 | Content-Type: text/html 194 | Date: Thu, 27 Apr 2017 20:35:24 GMT 195 | Server: WSGIServer/0.2 CPython/3.5.2 196 | 197 | 198 | 199 | Hello World! 200 | 201 | 202 |

Hello World

203 | 204 | 205 | ``` 206 | 207 | This was the basic web server implemented using just WSGI that sends out responses as html content. 208 | 209 | ## Read More? 210 | 1. http://wsgi.readthedocs.io/en/latest/ 211 | 2. https://www.fullstackpython.com/wsgi-servers.html 212 | 3. https://pip.pypa.io/en/stable/ 213 | 4. https://packaging.python.org/key_projects/#pip 214 | 5. http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/ 215 | -------------------------------------------------------------------------------- /units/django/10/hashtags.md: -------------------------------------------------------------------------------- 1 | Adding Hashtags 2 | ===================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/9/finalization.md) | [Next →]() 4 | 5 | In this tutorial we'll try to add hash tags and filters to the todoapp. 6 | 7 | ## Step by Step Instructions 8 | 1. Ability to add hash tags in the todo form. 9 | 2. Save hash tags in the database 10 | 3. In the todo list display hash tags of each todo item in addition to the title. 11 | 4. Hash tags should be clickable and should link to filter items by that tag. 12 | 5. Filtered todo list 13 | - Should display "Filtered by: {hashtag}" in the top of the list 14 | - That list should only contain the items that has the hash tag. 15 | - Should also have a cross button at the right side to clear the filter. 16 | 6. Ability to filter todo items by "Completed", "Not Completed (Pending)" or All statuses. 17 | 18 | 19 | ## Read More 20 | 21 | 1. https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/ 22 | 2. https://docs.djangoproject.com/en/1.11/topics/db/models/ 23 | -------------------------------------------------------------------------------- /units/django/11/rest-api.md: -------------------------------------------------------------------------------- 1 | REST API Development 2 | ===================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/10/hashtags.md) | [Next →]() 4 | 5 | ## Slides 6 | Slides [here](https://www.slideshare.net/beveganbevegan/rest-46394978). 7 | 8 | ## API Development 9 | So far we've covered about developing a CRUD Web Application using Django and we have used a traditional MVC approach on developing the TodoApp. Now we'll see how we can expose a REST API for our TodoApp. 10 | 11 | To understand more about what REST is, you can check this [stackoverflow thread](https://stackoverflow.com/questions/671118/what-exactly-is-restful-programming#answer-671132). 12 | 13 | ## Setting Up 14 | Firstly we'll need to add a new package `djangorestframework` into our django application. As django by default isn't REST friendly for developing application we need to add this new package to make developing RESTful applications easier. 15 | 16 | ```bash 17 | $ pip install djangorestframework 18 | ``` 19 | 20 | After you've installed this, go and add `rest_framework` on the `INSTALLED_APPS` list in the `settings.py` file: 21 | ```python 22 | INSTALLED_APPS = [ 23 | 'django.contrib.sessions', 24 | 'django.contrib.messages', 25 | 'django.contrib.staticfiles', 26 | 'rest_framework', 27 | 'todos' 28 | ] 29 | ``` 30 | 31 | ## Serialization 32 | Since our REST API is going to be fully JSON based, we'll need to add serializer classes which will automatically handle the serialization/deserialization task for us. 33 | 34 | So, go and create a new file `serializers.py` under our `todos` directory: 35 | 36 | ```python 37 | from rest_framework import serializers 38 | from .models import Todo 39 | 40 | 41 | class TodoSerializer(serializers.ModelSerializer): 42 | ''' Serializer to map the Todo model to JSON. ''' 43 | 44 | class Meta: 45 | """Meta class to map serializer's fields with the model fields.""" 46 | model = Todo 47 | fields = ('id', 'title', 'description', 'completed', 'created_at', 'user') 48 | read_only_fields = ('created_at', 'id') 49 | ``` 50 | In the above code, we've just created a new serializer `TodoSerializer` for our `Todo` model class. 51 | 52 | ## Adding a list view 53 | In RESTful API routes there are generally two kinds of endpoints: collection endpoints and resource endpoints. 54 | 55 | The collection endpoints are those which would return a list of resources on `GET` and which would create a new resource on `POST` and other HTTP verbs like `OPTIONS`, `HEAD` etc are supported as always. 56 | 57 | Our our TodoApp todos collection endpoint would look like this: 58 | ``` 59 | GET /api/todos 60 | POST /api/todos 61 | ``` 62 | So, to handle these we'll create a new view `TodoListView` since it's a collection endpoint. Go to your `views.py` and add a new class `TodoListView`. 63 | 64 | ```python 65 | from rest_framework import generics 66 | from todos.models import Todo 67 | from todos.serializers import TodoSerializer 68 | 69 | class TodoListView(generics.ListCreateAPIView): 70 | queryset = Todo.objects.all() 71 | serializer_class = TodoSerializer 72 | ``` 73 | 74 | Now this view will be responsible for creating a new todo item when it gets a `POST` request with payload and will return a list of todo items (in JSON) when it gets a `GET` request. 75 | 76 | We'll still need to add a new url that points to this view, let's add this new url for `/api/todos` in our `urls.py` file: 77 | 78 | ```python 79 | 80 | from todos import views 81 | 82 | urlpatterns = [ 83 | ... 84 | url(r'^api/todos$', views.TodoListView.as_view(), name='api_todo_list') 85 | ] 86 | ``` 87 | 88 | ### Using Postman for testing 89 | Now that we have our todo list API ready, let's go and test it using Postman. 90 | 91 | #### Retrieving 92 | You can go and send a `GET` request on `http://localhost:8000/api/todos` and you should receive a list of todo items in JSON as a response. 93 | 94 | #### Creating 95 | And if you try a `POST` request on the same url `http://localhost:8000/api/todos` with a JSON payload of data you want to create, you'll see that it creates a new item. 96 | 97 | ## Adding an item view 98 | With the above `TodoListView` we are able to add `Create` and `Read` of CRUD functionality in our TodoApp using REST API. 99 | Now we also need to be able to `Update`, `Delete` and `Read` individual todo items to complete all the CRUD operations for the todolist. 100 | 101 | To to this, we'll have to create a new API endpoint which we'll be a resouce endpoint unlike the collection endpoint we've created above. 102 | 103 | For this we'll add a new view class in our `view.py` file, `TodoItemView`: 104 | 105 | ```python 106 | class TodoItemView(generics.RetrieveUpdateDestroyAPIView): 107 | queryset = Todo.objects.all() 108 | serializer_class = TodoSerializer 109 | ``` 110 | 111 | Now, this new view will be responsible for updating, retrieving and deleting individual todo items using the REST API. 112 | 113 | Finally, we'll need to add a new url that would point to this new view when a resource endpoint is hit. 114 | 115 | The endpoint will have to be something like `/api/todos/:id` that supports methods `GET`, `PUT`, `PATCH` and `DELETE`. 116 | ``` 117 | GET /api/todos/:id 118 | PUT /api/todos/:id 119 | PATCH /api/todos/:id 120 | DELETE /api/todos/:id 121 | ``` 122 | This new endpoint will need to have `id` (Primary Key) as it needs to know which resource is going to be manipulated or retrieved. 123 | 124 | For this endpoint we'll add the following urn patten in our `urls.py` file: 125 | ```python 126 | urlpatterns = [ 127 | ... 128 | url(r'^api/todos$', views.TodoListView.as_view(), name='api_todo_list'), 129 | url(r'^api/todos/(?P[0-9]+)$', views.TodoItemView.as_view(), name='api_todo_item') 130 | ] 131 | ``` 132 | 133 | Now that we have both list and item endpoints ready for the todolist, we have exposed the full CRUD functionalities of our application into REST Api endpoints. 134 | 135 | ### Using Postman for testing 136 | Using Postman let's tryout this new endpoint `/api/todos/:id`. 137 | 138 | #### Retrieving 139 | Do a `GET` request on `http://localhost:8000/api/todos/:id` with any todo item `id` you have in your database and you should receive the data for that particular todo item. 140 | 141 | #### Updating 142 | A `PATCH` request on the same url `http://localhost:8000/api/todos/:id` with a JSON payload of data for any item `id` will update the data in the database according to the data sent in the payload. 143 | 144 | ### Deleting 145 | A `DELETE` request on the same url `http://localhost:8000/api/todos/:id` will delete the item in the database given by the provided `id`. 146 | 147 | ## Read More 148 | 149 | 1. https://www.slideshare.net/beveganbevegan/rest-46394978 150 | 2. http://www.django-rest-framework.org/#tutorial 151 | 3. https://scotch.io/tutorials/build-a-rest-api-with-django-a-test-driven-approach-part-1 152 | -------------------------------------------------------------------------------- /units/django/12/examples/test_rest.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | print('Loading data') 4 | 5 | API_URL = 'https://django-todoapp.herokuapp.com/api/todos' 6 | response = requests.get(API_URL) 7 | print('Response received: ', response.status_code) 8 | 9 | todo_items = response.json() 10 | 11 | print('{} items loaded\n'.format(len(todo_items))) 12 | 13 | for item in todo_items: 14 | print('id: {}'.format(item['id'])) 15 | print('title: {}'.format(item['title'])) 16 | print('description: {}'.format(item['description'])) 17 | print('created_at: {}'.format(item['created_at'])) 18 | print('-' * 50) 19 | 20 | -------------------------------------------------------------------------------- /units/django/12/examples/test_rest_input.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | API_URL = 'https://django-todoapp.herokuapp.com/api/todos'- 4 | 5 | print('Enter todo details:\n') 6 | title = input('Title: ') 7 | description = input('Description: ') 8 | user = input('User Id: ') 9 | 10 | print('Creating a new user...') 11 | 12 | result = requests.post(API_URL, data = { 13 | 'title': title, 14 | 'description': description, 15 | 'user': user 16 | }) 17 | -------------------------------------------------------------------------------- /units/django/12/heroku-deployment.md: -------------------------------------------------------------------------------- 1 | Deployment to Heroku 2 | ===================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/11/rest-api.md) | [Next →]() 4 | 5 | ## Deployment 6 | So far we've developed a todoapp with pretty much the basic features and have now finalized it. So, we'll be deploying the application to [Heroku](https://dashboard.heroku.com/apps). 7 | 8 | ## Before we begin 9 | You need to [signup](https://signup.heroku.com/?c=70130000001x9jEAAQ) for a new account on Heroku if you haven't already. After you have an account, you also need to download the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) which we'll be using for deploying our application. 10 | 11 | Here's how you [install](https://devcenter.heroku.com/articles/heroku-cli#download-and-install) it. 12 | 13 | ## Login 14 | Once you have your heroku account and the cli tool installed you can login to heroku via CLI. 15 | ```bash 16 | $ heroku login 17 | ``` 18 | 19 | This will ask you for your credentials and will get you logged in. 20 | 21 | ## Adding more dependencies 22 | We need to add few more dependencies which we'll need before deploying our application. But first make sure you already have activated your virtual environment. 23 | ```bash 24 | $ source ~/envs/py3-django-pg/bin/activate 25 | ``` 26 | 27 | ```bash 28 | $ pip install dj-database-url gunicorn whitenoise python-dotenv psycopg2 29 | ``` 30 | 31 | Now you'll need to write down all your application dependencies to a `requirements.txt` using: 32 | ```bash 33 | $ pip freeze > requirements.txt 34 | ``` 35 | 36 | ## Add a Procfile 37 | You'll need to create a new file `Procfile` in the root of your project with the following contents. 38 | ``` 39 | web: gunicorn todoapp.wsgi --log-file - 40 | ``` 41 | 42 | Heroku will use this file to run your application. 43 | 44 | ## Static files configuration 45 | 46 | Now we'll need to make few tweaks to our application config and settings before we can deploy it. 47 | 48 | Open your `settings.py` file and replace the line 49 | ```python 50 | STATIC_URL = '/static/' 51 | ``` 52 | with these contents 53 | ```python 54 | ALLOWED_HOSTS = ['*'] 55 | PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) 56 | 57 | STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') 58 | STATIC_URL = '/static/' 59 | 60 | # Extra places for collectstatic to find static files. 61 | STATICFILES_DIRS = ( 62 | # os.path.join(PROJECT_ROOT, 'static'), 63 | ) 64 | 65 | STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' 66 | ``` 67 | 68 | Also, make few changes in your `wsgi.py` file by adding `whitenose` initialization code something like this: 69 | 70 | ```python 71 | import os 72 | 73 | from django.core.wsgi import get_wsgi_application 74 | from whitenoise.django import DjangoWhiteNoise 75 | 76 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todoapp.settings') 77 | 78 | application = get_wsgi_application() 79 | application = DjangoWhiteNoise(application) 80 | ``` 81 | 82 | ## Database Configuration 83 | Furthermore, in the `settings.py` add the following lines below your database configuration, 84 | ```python 85 | # Update database configuration with $DATABASE_URL. 86 | import dj_database_url 87 | 88 | db_from_env = dj_database_url.config(conn_max_age=500) 89 | DATABASES['default'].update(db_from_env) 90 | ``` 91 | 92 | Your database configuration should look similar to this now. 93 | ```python 94 | DATABASES = { 95 | 'default': { 96 | 'ENGINE': 'django.db.backends.postgresql', 97 | 'NAME': os.environ.get('DB_NAME'), 98 | 'USER': os.environ.get('DB_USER'), 99 | 'HOST': os.environ.get('DB_HOST'), 100 | 'PORT': os.environ.get('DB_PORT'), 101 | 'PASSWORD': os.environ.get('DB_PASSWORD'), 102 | } 103 | } 104 | 105 | # Update database configuration with $DATABASE_URL. 106 | import dj_database_url 107 | 108 | db_from_env = dj_database_url.config(conn_max_age=500) 109 | DATABASES['default'].update(db_from_env) 110 | ``` 111 | 112 | Here we've configured to set the database details using the `DATABASE_URL` environment variable which heroku will set for us when we setup our postgres database on heroku. 113 | 114 | So, for our local development environment it would just take the database credentials using our predefined parameters and on heroku it will use the `DATABASE_URL` env variable. 115 | 116 | ## Create a new app 117 | Now that setup our application for deployment do commit all your changes to the `master` branch of your repository. 118 | 119 | And create a new app on heroku by using the command: 120 | ```bash 121 | $ heroku create django-todoapp 122 | ``` 123 | 124 | This command will create a new application on heroku `django-todoapp`. 125 | **Note:** The app name `django-todoapp` should already be occupied so give a different name. Or, even if you omit the app name by just using `heroku create` it would select a random name for you. 126 | 127 | ## Add a PostgreSQL database 128 | Add a postgresql database to the application on heroku. 129 | ```bash 130 | $ heroku addons:create heroku-postgresql:hobby-dev 131 | ``` 132 | 133 | Now that we've created our app and the database you can go and see them in the [Heroku Dashboard](https://id.heroku.com/login) after login. 134 | 135 | ## Deploy 136 | We're all set for deployment now. Now deployint to heroku is super easy, just push your master branch to the `heroku` remote and it will handle the rest for you. 137 | 138 | ```bash 139 | $ git push heroku master 140 | ``` 141 | 142 | You would see the following output similar to this. 143 | 144 | ``` 145 | ➜ git push heroku master 146 | Counting objects: 4, done. 147 | Delta compression using up to 4 threads. 148 | Compressing objects: 100% (4/4), done. 149 | Writing objects: 100% (4/4), 395 bytes | 0 bytes/s, done. 150 | Total 4 (delta 3), reused 0 (delta 0) 151 | remote: Compressing source files... done. 152 | remote: Building source: 153 | remote: 154 | remote: -----> Python app detected 155 | remote: -----> Installing requirements with pip 156 | remote: 157 | remote: -----> $ python manage.py collectstatic --noinput 158 | remote: /app/.heroku/python/lib/python2.7/site-packages/dotenv/main.py:24: UserWarning: Not loading - it doesn't exist. 159 | remote: warnings.warn("Not loading %s - it doesn't exist." % dotenv_path) 160 | remote: 122 static files copied to '/tmp/build_34e7863071464e51736c94588a92fe6d/todoapp/staticfiles', 168 post-processed. 161 | remote: 162 | remote: -----> Discovering process types 163 | remote: Procfile declares types -> web 164 | remote: 165 | remote: -----> Compressing... 166 | remote: Done: 56.7M 167 | remote: -----> Launching... 168 | remote: Released v6 169 | remote: https://django-todoapp.herokuapp.com/ deployed to Heroku 170 | remote: 171 | remote: Verifying deploy... done. 172 | To https://git.heroku.com/django-todoapp.git 173 | 6bf00b0..30af97f master -> master 174 | ``` 175 | 176 | Now that we've pushed our code and deployed we need to run run migrations to complete the entire deployment process. 177 | 178 | Use the following command to run migrations on the heroku's server. 179 | ```bash 180 | $ heroku run python manage.py migrate 181 | ``` 182 | 183 | After you're done with the migrations. Go to `https://django-todoapp.herokuapp.com/` i.e `https://.herokuapp.com` and you should be able to see your app is up and running on heroku. 184 | 185 | ## Source Code 186 | Check the full source code [here](https://github.com/kabirbaidhya/django-todoapp/tree/step-30). 187 | 188 | ## Read More 189 | 190 | 1. https://www.heroku.com/ 191 | 2. https://devcenter.heroku.com/articles/deploying-python 192 | 3. https://docs.djangoproject.com/en/1.11/howto/deployment/ 193 | 4. https://devcenter.heroku.com/articles/getting-started-with-python#introduction 194 | 5. https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment 195 | -------------------------------------------------------------------------------- /units/django/2/django-helloworld.md: -------------------------------------------------------------------------------- 1 | Django - Hello World 2 | ==================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/1/wsgi-pip-and-virtualenv.md) | [Next →](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/3/templates-and-views.md) 4 | 5 | In this session we're going to dive into the [django](https://www.djangoproject.com/) framework and create our very first project using django. 6 | 7 | Here we'll try to create a TodoApp. I hope by now you're pretty clear about the [basics](https://github.com/kabirbaidhya/learn-python-django-web#python) and the concepts of [web](https://github.com/kabirbaidhya/learn-python-django-web#web-development-basics), [wsgi and some pythonic tools](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/1/wsgi-pip-and-virtualenv.md) we've discussed in our [previous sessions](https://github.com/kabirbaidhya/learn-python-django-web) so far, if not then you might want to check these links. 8 | 9 | ## TodoApp 10 | Now let's start building our app. 11 | 12 | ### Setup virtualenv 13 | Let's start by setting up `virtualenv` with Python 3+. 14 | 15 | We'll create a virtualenv named `py3` under `envs` directory. 16 | ```bash 17 | ➜ mkdir ~/envs 18 | ➜ virtualenv -p /usr/local/bin/python3 ~/envs/py3 19 | ``` 20 | 21 | Now activate it. 22 | ```bash 23 | ➜ source ~/envs/py3/bin/activate 24 | ``` 25 | You should now be able to see a virtualenv identifier `py3` near your prompt in the terminal like this: 26 | ```bash 27 | (py3) 28 | [kabir@leapfrog] ~ 29 | ➜ 30 | ``` 31 | 32 | ### Install django 33 | Now it's time to install django. Install it using `pip`: 34 | ```bash 35 | ➜ pip install django 36 | ``` 37 | 38 | Test your installation 39 | ```bash 40 | ➜ django-admin --version 41 | ``` 42 | 43 | ### Create a project 44 | Now, let's go and create our very first project. 45 | ```bash 46 | ➜ django-admin startproject todoapp 47 | ``` 48 | 49 | You should be able to see that `todoapp` directory has been created with some boilerplate code already generated by `django-admin`. Open it using your favorite code editor and go through the code. 50 | 51 | Folder structure should look similar to this: 52 | ``` 53 | todoapp 54 | ├─todoapp 55 | │ ├── __init__.py 56 | │ ├── settings.py 57 | │ ├── urls.py 58 | │ └── wsgi.py 59 | └── manage.py 60 | ``` 61 | 62 | ### Create new todos app 63 | Now we need to create a new django app `todos`. 64 | We can do this using: 65 | ```bash 66 | ➜ cd todoapp 67 | ➜ python manage.py startapp todos 68 | ``` 69 | 70 | Check the code again, you can see new directory `todos` has been created with some more code. Go through them too. 71 | 72 | Now the new directory structure would look like: 73 | ``` 74 | todoapp 75 | ├── todoapp 76 | │ ├── __init__.py 77 | │ ├── settings.py 78 | │ ├── urls.py 79 | │ └── wsgi.py 80 | ├── todos 81 | │ ├── __init__.py 82 | │ ├── admin.py 83 | │ ├── apps.py 84 | │ ├── migrations 85 | │ ├── models.py 86 | │ ├── tests.py 87 | │ └── views.py 88 | └── manage.py 89 | ``` 90 | 91 | You now need to register this new app `todos` into our `todoapp` project. 92 | Open `todoapp/settings.py` and append `todos` to `INSTALLED_APPS` list: 93 | ```python 94 | INSTALLED_APPS = [ 95 | 'django.contrib.admin', 96 | 'django.contrib.auth', 97 | 'django.contrib.contenttypes', 98 | 'django.contrib.sessions', 99 | 'django.contrib.messages', 100 | 'django.contrib.staticfiles', 101 | 'todos' 102 | ] 103 | ``` 104 | 105 | ### Run the server 106 | Let's run the development server now to test our very first app. 107 | ```bash 108 | ➜ python manage.py runserver 109 | ``` 110 | You would see server has started now. 111 | 112 | ```bash 113 | ➜ python manage.py runserver 114 | Performing system checks... 115 | 116 | System check identified no issues (0 silenced). 117 | 118 | You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. 119 | Run 'python manage.py migrate' to apply them. 120 | 121 | April 28, 2017 - 21:56:40 122 | Django version 1.11, using settings 'todoapp.settings' 123 | Starting development server at http://127.0.0.1:8000/ 124 | Quit the server with CONTROL-C. 125 | [28/Apr/2017 21:56:54] "GET / HTTP/1.1" 200 1716 126 | Not Found: /favicon.ico 127 | [28/Apr/2017 21:56:54] "GET /favicon.ico HTTP/1.1" 404 1963 128 | [28/Apr/2017 22:00:31] "GET / HTTP/1.1" 200 1716 129 | ``` 130 | Go to [http://127.0.0.1:8000/](http://127.0.0.1:8000/) you should be able to see our app is up and running. 131 | 132 | But you may see some warnings shown on the page. This is because we still haven't run the database migrations yet. 133 | 134 | ### Migrations 135 | Let's run the database migrations now. First you need to press `Ctrl + C` to end the server in your terminal. 136 | 137 | Then you can run: 138 | ```bash 139 | ➜ python manage.py migrate 140 | ``` 141 | 142 | You should be able to see the migrations running. 143 | ```bash 144 | ➜ python manage.py migrate 145 | Operations to perform: 146 | Apply all migrations: admin, auth, contenttypes, sessions 147 | Running migrations: 148 | Applying contenttypes.0001_initial... OK 149 | Applying auth.0001_initial... OK 150 | Applying admin.0001_initial... OK 151 | Applying admin.0002_logentry_remove_auto_add... OK 152 | Applying contenttypes.0002_remove_content_type_name... OK 153 | Applying auth.0002_alter_permission_name_max_length... OK 154 | Applying auth.0003_alter_user_email_max_length... OK 155 | Applying auth.0004_alter_user_username_opts... OK 156 | Applying auth.0005_alter_user_last_login_null... OK 157 | Applying auth.0006_require_contenttypes_0002... OK 158 | Applying auth.0007_alter_validators_add_error_messages... OK 159 | Applying auth.0008_alter_user_username_max_length... OK 160 | Applying sessions.0001_initial... OK 161 | ``` 162 | 163 | Now re-run our server using: 164 | ```bash 165 | ➜ python manage.py runserver 166 | ``` 167 | And go to [http://127.0.0.1:8000/](http://127.0.0.1:8000/) again, you can see the warnings are gone by now. 168 | 169 | Great. You've just created your first app with django. Now let's change some code. 170 | Check the full source code for the todoapp [here](https://github.com/kabirbaidhya/django-todoapp). 171 | 172 | ## Exercises 173 | 1. Create a bootstrap templates for the following pages: 174 | - Todo list 175 | - Add todo form 176 | - Edit todo form 177 | 178 | ## Next Step 179 | In the [next tutorial](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/3/templates-and-views.md) we'll be working more with the templates and views to complete the UI of our application. 180 | -------------------------------------------------------------------------------- /units/django/3/templates-and-views.md: -------------------------------------------------------------------------------- 1 | Templates and Views 2 | =================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/2/django-helloworld.md) | [Next →]() 4 | 5 | In this tutorial we'll be adding more templates and design improvements on our todo application we built using django in the [previous tutorial](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/2/django-helloworld.md). 6 | 7 | Here we'll be mostly working with the UI of the todoapp using django template tags, html & css to finish our app's looks. 8 | 9 | We'll start with the following steps: 10 | 11 | 1. Create a new url route for "Create TODO" page and link it with the Add button. 12 | 2. Extract a base template the app from `index.html`. 13 | 3. Add a new template for the create form. 14 | 4. Add template for the TODO list. 15 | 5. Add actions (Edit/Remove) for each of the TODO item on the list. 16 | 6. Display the actions (Edit/Remove) only when the TODO items are hovered. 17 | 7. Render the todo list dynamically using a list of todo items. 18 | 8. Strike-through and fade the completed items. 19 | 9. Add a new url for saving the TODO items. 20 | 10. When Add form is saved: 21 | - Create a new TODO item. 22 | - Redirect back to the index page. 23 | 11. Create a new url for the TODO edit page and display edit page when "Edit" link is clicked. 24 | 12. When Edit form is saved: 25 | - Save the changes made on the edited item. 26 | - Redirect back to the index page. 27 | 28 | Check the full source code [here](https://github.com/kabirbaidhya/django-todoapp). 29 | -------------------------------------------------------------------------------- /units/django/5/form-processing.md: -------------------------------------------------------------------------------- 1 | Form Processing 2 | ======================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/4/database-orm-and-models.md) | [Next →]() 4 | 5 | In the [previous tutorial]((https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/4/database-orm-and-models.md)) we've integrated our app with [the database](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/database/1/database-and-sql.md) and introduced the concept of [Django Models](https://docs.djangoproject.com/en/1.11/topics/db/models/). Also, 6 | we used the `Todo` model to fetch all the todo items from the database and display it on the UI dynamically. In this tutorial we'll go one step further, by adding a feature to allow creating a new todo item from the form and also allow editing an existing todo item. 7 | 8 | ## Create/Update data 9 | In the previous tutorial, we've seen how we can use `Todo.objects.all()` method to get the list of todo items from the database. Now we're concerned about how we're going to create them or update them. 10 | However using Django's Models, these tasks become much easier. Let's try these in the django shell. 11 | 12 | ```bash 13 | ➜ python manage.py shell 14 | ``` 15 | 16 | ### Creating a new entry 17 | Creating a new todo item is as simple as calling `Todo.objects.create` method. 18 | 19 | ```python 20 | >>> from django.utils import timezone 21 | >>> timezone.now() 22 | datetime.datetime(2017, 5, 5, 23, 35, 37, 755504, tzinfo=) 23 | >>> todo = Todo.objects.create(title='Yet another todo', created_at=timezone.now()) 24 | >>> todo.__dict__ 25 | {'description': None, 'title': 'Yet another todo', 'completed': False, 'created_at': datetime.datetime(2017, 5, 5, 23, 36, 12, 106900, tzinfo=), 'id': 8, '_state': } 26 | ``` 27 | 28 | ### Updating the entry 29 | Updating it is also simple as this. 30 | ```python 31 | >>> todo.title = 'Just another todo' 32 | >>> todo.description = 'Just a todo item' 33 | >>> todo.save() 34 | ``` 35 | 36 | Now go and check the database you should be able to find your table has been updated. 37 | 38 | ``` 39 | todoapp=# SELECT * FROM todos_todo; 40 | id | title | description | completed | created_at 41 | ----+-------------------+------------------------------------+-----------+---------------------------------- 42 | 1 | Item 1 | No eam nisl assum impetus, dicta . | f | 2017-05-01 05:08:08.407942+05:45 43 | 2 | Item 2 | No eam nisl assum impetus, dicta . | t | 2017-05-02 05:08:08.407942+05:45 44 | 3 | Item 3 | No eam nisl assum impetus, dicta . | f | 2017-05-03 05:08:08.407942+05:45 45 | 4 | Item 4 | No eam nisl assum impetus, dicta . | f | 2017-05-04 05:08:08.407942+05:45 46 | 5 | Item 5 | No eam nisl assum impetus, dicta . | f | 2017-05-05 05:08:08.407942+05:45 47 | 8 | Just another todo | Just a todo item | f | 2017-05-06 05:21:12.1069+05:45 48 | (6 rows) 49 | ``` 50 | 51 | ## Forms 52 | Now that we know how to create or manipulate our data. We need to work on our forms so as to allow our users to create and update data using them. 53 | 54 | ### Create Todo Form 55 | We already have setup a page with the create todo form previously now we're going to make it fully functional. Before doing that we need to add a new url to which the form will be submitted to. 56 | 57 | #### Add a new url 58 | So, we'll start by adding a new url `save` to our `todos/urls.py` file, which should look like this: 59 | 60 | ```python 61 | from django.conf.urls import url 62 | from todos import views 63 | 64 | urlpatterns = [ 65 | url(r'^$', views.index, name='index'), 66 | url(r'^create$', views.create, name='create'), 67 | url(r'^save$', views.save, name='save') 68 | ] 69 | ``` 70 | #### Add a new view function 71 | Now we'll also need to add `views.save` function that we're referenced above, which should look like this: 72 | 73 | ```python 74 | from django.shortcuts import render, redirect 75 | 76 | def save(request): 77 | # TODO: Logic to save the todo item here. 78 | 79 | return redirect('index') 80 | ``` 81 | 82 | Currently, the above code does nothing but just redirect back to `index` page url. But here we need to get the data received from the form, save it and then finally redirect to index. 83 | 84 | ### Saving the form data 85 | Let's update the `save` function we've just created to receive data from the form and save it using our `Todo` model. The code should look like this: 86 | 87 | ```python 88 | from django.shortcuts import render, redirect 89 | from django.utils import timezone 90 | from todos.models import Todo 91 | 92 | def save(request): 93 | # Get the form data from the request. 94 | title = request.POST.get('title') 95 | description = request.POST.get('description') 96 | 97 | # Create a new todo item with the data. 98 | Todo.objects.create( 99 | title=title, 100 | description=description, 101 | created_at=timezone.now() 102 | ) 103 | 104 | # Redirect back to index page 105 | return redirect('index') 106 | 107 | ``` 108 | 109 | ### Updating the HTML form 110 | We now need to update our HTML form to submit the data properly to the server like what we've expected in the above code. 111 | 112 | We'll need to ensure the following things: 113 | 1. Form should be submitted to url `save` (`name='save'`). 114 | 2. Form should be submitted using method `POST` 115 | 3. Two form fields are required to be sent `title` and `description` for the todo item. 116 | 4. And CSRF token should be sent along with the form too. 117 | 118 | After making these changes to our plain html form it should look like this: 119 | ```html 120 | {% extends 'base.html' %} 121 | {% block content%} 122 |

Add Todo

123 |
124 |
125 | {% csrf_token %} 126 |
127 | 128 | 129 |
130 |
131 | 132 | 133 |
134 | 135 | 136 |
137 |
138 | {% endblock %} 139 | ``` 140 | ### Test your form 141 | Now that you've written all the code for the form and form processing. Let's go and test it in the browser. 142 | 143 | First run the app server. 144 | ```bash 145 | ➜ python manage.py runserver 146 | ``` 147 | 148 | And check it on the browser. When you submit the create todo form now, it should add a new todo item and take you back to the index page showing you the latest data. 149 | 150 | ## Further form processing 151 | If you've made it upto here, that's awesome. Now that we have the ability to create a new todo item, we should have a feature of editing an existing todo item too. 152 | 153 | Let's see how we can do that. We'll do it in the following steps: 154 | 155 | 1. Firstly create a new url to show the edit form `r'^edit/todos/(\d+)/$'`. 156 | 2. Create a view function to handle the edit page request which should send back the edit form html with existing data populated. 157 | 3. Create a form edit html form for the edit page 158 | 4. Make changes in the `save` view function to support form submission from the edit page too which should update the item. 159 | 5. Link "Edit" link of individual todo items to it's edit page. 160 | 161 | ## Source Code 162 | Check the full source code [here](https://github.com/kabirbaidhya/django-todoapp/tree/step-18). 163 | 164 | ## Read More? 165 | 1. https://docs.djangoproject.com/en/1.11/topics/forms/ 166 | 2. https://docs.djangoproject.com/en/1.11/topics/http/urls/ 167 | 3. https://docs.djangoproject.com/en/1.11/ref/request-response/ 168 | 4. https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Models 169 | 5. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms 170 | -------------------------------------------------------------------------------- /units/django/6/validation.md: -------------------------------------------------------------------------------- 1 | Validation 2 | ======================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/5/form-processing.md) | [Next →]() 4 | 5 | In the [previous tutorial](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/5/form-processing.md) we've learned how we can create and update the todo item using the forms. But we haven't added any validation in our forms nor in the backend to prevent any invalid data to go into our database. In this tutorial we're going to cover that part. 6 | 7 | Generally in any web application whenever we're taking in user input, we need to validate the data first and this has to be done both on the frontend (client-side) and on the backend (server-side). We'll see how we can do that here. 8 | 9 | ## Backend Validation 10 | Backend validation is important regardless of the fact that whether data is already validated on the client ordjango.contrib not. 11 | 12 | In our todoapp the validation logic would be very simple as we have only few fields. 13 | Let's add a logic to validate data in our `views.py` before the data gets saved. 14 | 15 | The validation logic would look like this: 16 | ```python 17 | # Validation logic 18 | if title is None or title.strip() == '': 19 | messages.error(request, 'Item not saved. Please provide the title.') 20 | return redirect(request.META.get('HTTP_REFERER')) 21 | ``` 22 | After adding this to our existing code, our `save` function would look like this: 23 | 24 | ```python 25 | from django.contrib import messages 26 | 27 | def save(request): 28 | # Get the form data from the request. 29 | title = request.POST.get('title') 30 | description = request.POST.get('description') 31 | 32 | # Get hidden form data. 33 | form_type = request.POST.get('form_type') 34 | id = request.POST.get('id') 35 | 36 | print('Form type received:', form_type) 37 | print('Form todo id received:', id) 38 | 39 | # Validation logic 40 | if title is None or title.strip() == '': 41 | messages.error(request, 'Item not saved. Please provide the title.') 42 | return redirect(request.META.get('HTTP_REFERER')) 43 | 44 | if form_type == 'create': 45 | # Create a new todo item with the data. 46 | todo = Todo.objects.create( 47 | title=title, 48 | description=description, 49 | created_at=timezone.now() 50 | ) 51 | print('New Todo created: ', todo.__dict__) 52 | elif form_type == 'edit' and id.isdigit(): 53 | todo = Todo.objects.get(pk=id) 54 | print('Got todo item: ', todo.__dict__) 55 | 56 | # Save logic 57 | todo.title = title 58 | todo.description = description 59 | 60 | todo.save() 61 | print('Todo updated: ', todo.__dict__) 62 | 63 | # Add save success message 64 | messages.info(request, 'Todo Item Saved.') 65 | # Redirect back to index page 66 | return redirect('index') 67 | ``` 68 | 69 | Now that we've added a validation logic in our `view.py`, we need to display the validation messages in our templates too. 70 | 71 | Firstly, create a new template `templates/messages.html` that would be responsible for displaying these messages. 72 | ```html 73 | {% if messages %} 74 | 83 | {% endif %} 84 | ``` 85 | 86 | Now, we'll need to include it in our `form.html` template just below the `

` heading tag. 87 | ```html 88 |

89 | {% if form_type == 'create' %} 90 | Add Todo 91 | {% elif form_type == 'edit' %} 92 | Edit Todo 93 | {% endif %} 94 |

95 | {% include 'messages.html' %} 96 | ``` 97 | 98 | Now if you refresh the application in the browser and try to save the form with empty title, you should see the validation message in the form. 99 | 100 | Great. We've just added the backend validation before saving. 101 | 102 | ## Frontend Validation 103 | We know validating the user's data in the backend is really crucial. But when it comes to User Experience(UX) it might feel slow, as the form has to be submitted to the server first and then server would send back the error. 104 | 105 | The user experience could feel really bad if there are too many fields in the form and the internet connection is poor, that way if the validation errors occur in the backend the user will be keep on redirected to the form only after the whole form has been submitted and validated on the server. 106 | 107 | To make this better, we can validate the data on the client side using javascript too and that will be before submitting the form. 108 | 109 | For that we will add a new javascript file to our application. Create a new file `todo.js` under `static/todos/js`. 110 | 111 | ```javascript 112 | window.addEventListener('load', handleLoad); 113 | 114 | function handleLoad() { 115 | var form = document.querySelector('.todo-form form'); 116 | 117 | if (form) { 118 | form.addEventListener('submit', handleFormSubmit); 119 | } 120 | } 121 | 122 | function handleFormSubmit(e) { 123 | var titleInput = document.querySelector('#input-todo-title'); 124 | var title = titleInput.value.trim(); 125 | 126 | if (!title || title === '') { 127 | alert('Please enter the title.'); 128 | titleInput.focus(); 129 | e.preventDefault(); 130 | } 131 | } 132 | ``` 133 | 134 | This code should prevent the form from submission if the title is empty. 135 | 136 | Don't forget to include this javascript file to our html template `base.html` in order to load it. 137 | 138 | You can put this tag inside the `` tag at the last. 139 | ```html 140 |
141 |

© 2016 Company, Inc.

142 |
143 | 144 | 145 | 146 | 147 | 148 | ``` 149 | Now you can refresh your browser and test the application by trying to submit the form with empty title field. You should get the javascript `alert` saying `'Please enter the title.'`. 150 | 151 | ### HTML5 validation 152 | Now a final step to complete the frontend validation would be to add HTML5 validation attributes like `required` to your input tags. 153 | 154 | Let's add `required` attribute to our `` tag for title. It should look like this. 155 | ```html 156 | 163 | ``` 164 | 165 | ## Source Code 166 | Check the full source code [here](https://github.com/kabirbaidhya/django-todoapp/tree/step-20). 167 | 168 | ## Read More? 169 | 1. https://docs.djangoproject.com/en/1.11/ref/forms/validation/#using-validators 170 | 2. https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ 171 | 3. https://docs.djangoproject.com/en/1.11/ref/contrib/messages/ 172 | 5. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms 173 | -------------------------------------------------------------------------------- /units/django/8/auth.md: -------------------------------------------------------------------------------- 1 | Django Authentication 2 | ===================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/7/ajax.md) | [Next →]() 4 | 5 | In this tutorial we'll try to build a login and user authentication system in our todo application. 6 | 7 | ## Step by Step Instructions 8 | 9 | We'll do following tasks step-by-step for building the user login and authorization system. 10 | 11 | 1. Create a login page. 12 | - Add a new url for the login page 13 | - Create a login form template 14 | - Create a view function to render the login page 15 | - Add a link in the home page to go to login 16 | 17 | 2. Authenticate the user when login form submitted 18 | - Add a new url for login form submission. 19 | - Add a new view function to login and authenticate the user. 20 | - It should redirect the user to home page if login was successful. 21 | - It should redirect to the same for if login failed and show messages. 22 | - Hide the login link if user has been logged in. 23 | - Display the username instead of the Login in the header if user is logged in. 24 | 25 | 3. Create a signup page. 26 | - Add a new url for the signup page 27 | - Create a signup form template 28 | - Create a view function to render the signup page 29 | - Add a link in the home page to go to signup 30 | 31 | 4. Authorization 32 | - Allow only the logged in users to view the todo list 33 | - Allow only the logged in users to view the Add todo form 34 | - Allow only the logged in users to edit the Todo item 35 | - Allow only the logged in users to delete the Todo item 36 | - Allow only the logged in users to view the home page. So, redirect the user to login if user is not logged in. 37 | 38 | ## Read More 39 | 40 | 1. https://docs.djangoproject.com/en/1.11/topics/auth/default/#how-to-log-a-user-in 41 | 2. https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication 42 | -------------------------------------------------------------------------------- /units/django/9/finalization.md: -------------------------------------------------------------------------------- 1 | TodoApp Finalization 2 | ===================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/8/auth.md) | [Next →]() 4 | 5 | In this tutorial we'll try to finalize the todo app. 6 | 7 | ## Step by Step Instructions 8 | 1. Display "No items in the list" message if there are no items in the todo list. 9 | 2. Display the todo-items only for the logged in users. 10 | - Link the todo item with the user. 11 | - Add a new attribute `user` in the `Todo` model that references to the `User` model. 12 | - Create migration and run it. 13 | - Set the current user while saving the todo item. 14 | - Display only the user-specific todo items in the todo list. The list should display items created by the logged in user. 15 | 3. Restrict non-creator users to edit the todo item. 16 | 4. Restrict non-creator users to delete the todo item. 17 | 5. Display custom message on a custom 404 Not Found page. 18 | 19 | 20 | ## Read More 21 | 22 | 1. https://docs.djangoproject.com/en/1.11/topics/auth/default/#how-to-log-a-user-in 23 | 2. https://docs.djangoproject.com/en/1.11/topics/db/models/ 24 | -------------------------------------------------------------------------------- /units/git/Git-Logo-Black.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/git/Git-Logo-Black.png -------------------------------------------------------------------------------- /units/git/VCS, Git & GitHub - Presentation.md: -------------------------------------------------------------------------------- 1 | 2 | ###### Version Control 3 | Git & GitHub 4 | ================= 5 | 6 | # ![](Git-Logo-Black.png) 7 | 8 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 9 | 10 | --- 11 | 14 | # Version Control 15 | --- 16 | 19 | # What is VCS? 20 | --- 21 | > Version control systems are a category of software tools that help a software team manage changes to source code over time. 22 | https://www.atlassian.com/git/tutorials/what-is-version-control 23 | 24 | 25 | --- 26 | ### Why Version Control? 27 | 1. Collaboration 28 | 2. Track complete change history 29 | 3. Branching and Merging 30 | 4. Versions 31 | 5. Revert/Rollback 32 | 33 | --- 34 | ### Distributed Version Control Systems 35 | * Code is hosted in a repository 36 | * Every client has a complete copy of the repository 37 | * Synchronize the changes in between client & server 38 | * Every clone is really a full backup of the repository 39 | * Example: Git, Mercurial, etc. 40 | --- 41 | ### Distributed Version Control Systems 42 | # ![](distributed-git.svg) 43 | --- 44 | # Git 45 | --- 46 | # What is Git? 47 | --- 48 | #### A Distributed Version Control System (VCS). 49 | --- 50 | ###### More precisely, 51 | ##### The most popular & widely used modern version control system today. 52 | --- 53 | ###### Originally developed by 54 | ##### Linus Torvalds 55 | ###### the creator of the Linux kernel. 56 | --- 57 | # What's the big deal about Git? 58 | --- 59 | ## Easy to learn 60 | --- 61 | ## Powerful 62 | --- 63 | ## Performance 64 | --- 65 | ## Flexible 66 | --- 67 | ## Open Source 68 | --- 69 | ## And it's a de facto standard 70 | --- 71 | # Getting Started with Git 72 | --- 73 | ### Installation 74 | ##### Linux 75 | 76 | ###### Ubuntu/Debain 77 | ```bash 78 | $ sudo apt-get install git 79 | ``` 80 | 81 | ###### Centos/RHEL/Fedora 82 | 83 | ```bash 84 | $ sudo yum install git 85 | ``` 86 | 87 | For other distros check the official installation docs. 88 | 89 | --- 90 | ### Installation 91 | ##### Windows 92 | 93 | 1. Download the installer from 94 | https://git-for-windows.github.io/ 95 | 2. Install Git 96 | 97 | --- 98 | ### Check Installation 99 | Veriy that git is proplery installed with 100 | 101 | ```bash 102 | $ git --version 103 | ``` 104 | It should print the git version installed on your system like this. 105 | ```plain 106 | git version 2.7.4 107 | ``` 108 | 109 | --- 110 | # Configuration 111 | --- 112 | ### Configure git user 113 | The first thing you do after installing git is to set up your user name and email. 114 | ```bash 115 | $ git config --global user.name 116 | $ git config --global user.email 117 | ``` 118 | Then you can check your config with 119 | ```bash 120 | $ git config --list 121 | 122 | user.name=Kabir Baidhya 123 | user.email=kabirbaidhya@gmail.com 124 | core.editor=vim 125 | core.excludesfile=/home/kabir/.gitignore_global 126 | ``` 127 | --- 128 | # Setting up a repository 129 | --- 130 | ### Initialize 131 | The `git init` command creates a new Git repository. 132 | 133 | ```bash 134 | # Go to your project directory 135 | $ cd /your/project/directory 136 | 137 | # Initialize a git repository 138 | $ git init 139 | ``` 140 | --- 141 | ### Clone 142 | 143 | The `git clone` command clones a remote repository into the local machine. 144 | 145 | This will create a complete copy of remotely hosted repository in your local computer. 146 | ```bash 147 | $ git clone [directory] 148 | ``` 149 | --- 150 | # Saving Changes 151 | --- 152 | ### Adding files 153 | In order to save your changes to the repository you'll need to `commit` your changes. 154 | 155 | You first need to select files you want to commit using this `git add` command. 156 | ```bash 157 | # Add specific file(s) 158 | $ git add 159 | 160 | # Add whole path or directory 161 | $ git add 162 | 163 | # Add all of your changes 164 | $ git add --all 165 | ``` 166 | --- 167 | ### Committing changes 168 | The git commit command commits the staged changes to the history. 169 | 170 | ``` 171 | $ git commit 172 | ``` 173 | This will ask you to enter a commit message for your commit. 174 | 175 | In case you don't like to be prompted for the message, you can set directly using the `-m` option like this 176 | ``` 177 | $ git commit -m "This was my first commit" 178 | ``` 179 | --- 180 | # Inspecting the repository 181 | --- 182 | ### Checking status 183 | We use `git status` command to display the status of the working directory and the staging area. 184 | 185 | ```bash 186 | $ git status 187 | ``` 188 | If you have nothing to be committed or no untracked files then it would just show some message like this 189 | ```bash 190 | $ git status 191 | On branch master 192 | nothing to commit, working directory clean 193 | ``` 194 | But if you have some changes to be committed it lists them. 195 | 196 | --- 197 | ### History 198 | We can use the `git log` command to display the history of committed changes on the repository. 199 | 200 | ```bash 201 | $ git log 202 | ``` 203 | There are lots of options available for better inspection of history. For instance, 204 | ```bash 205 | $ git log --oneline # Shows each commit on one line 206 | $ git log -n 207 | $ git log --author="" 208 | $ git log .. 209 | ``` 210 | --- 211 | # Working with remote 212 | --- 213 | ### Adding a remote 214 | You need to add remote repository urls of a remote server to be able to synhronize your changes with the remote repository. 215 | You can do this using the `git remote add` command. 216 | 217 | ```bash 218 | $ git remote add 219 | ``` 220 | You can verify added remotes by doing 221 | ```bash 222 | $ git remote -v 223 | ``` 224 | It should list the urls to the remote repositories you've added so far. 225 | 226 | --- 227 | ### Pushing your changes 228 | Push all the changes (commits) you did to your local repository to the remote repositories is pretty simple with `git push` command. 229 | 230 | ```bash 231 | # Push a local branch changes to remote 232 | $ git push 233 | 234 | # Push all the changes of local branches to remote 235 | $ git push --all 236 | ``` 237 | For instance: 238 | ```bash 239 | $ git push origin master 240 | ``` 241 | --- 242 | ### Pulling remote changes 243 | The `git pull` command fetches the changes of the current branch from remote and merges it into the local branch. 244 | 245 | This is same as running the combination of `git fetch` and then `git merge`. 246 | 247 | ```bash 248 | $ git pull [branch] 249 | ``` 250 | Example: 251 | ```bash 252 | $ git pull origin master 253 | ``` 254 | 255 | --- 256 | # Checking out code 257 | --- 258 | ### Checking out 259 | Checking out code actually means to take your working directory to a specific change (commit), branch, tag or or even different versions of files. 260 | 261 | You can do all these things with just a simple command `git checkout`. 262 | 263 | ```bash 264 | $ git checkout # go to that commit 265 | $ git checkout # checkout that file to previous version 266 | $ git checkout # go to another branch 267 | $ git checkout # go to a tagged version of the repository 268 | ``` 269 | 270 | --- 271 | # Branching & Merging 272 | --- 273 | ### Branching 274 | The `git branch` command allows you to list, create and delete branches. 275 | 276 | To create a new branch you can do 277 | ```bash 278 | $ git branch 279 | ``` 280 | 281 | --- 282 | ### Merging 283 | You can use `git merge` command to merge changes of a branch into the current `HEAD`. 284 | 285 | Merging a branch into your current branch is as simple as: 286 | ```bash 287 | $ git merge 288 | ``` 289 | --- 290 | # GitHub 291 | --- 292 | ### GitHub 293 | - Software development platform 294 | - Sort of Social networking platform for developers 295 | - Provides Git repository hosting services & web based platform to manage repositories and projects 296 | - Popular for open source projects 297 | --- 298 | # Read More? 299 | --- 300 | ### Links 301 | 1. https://git-scm.com/book/en/v2 302 | 2. https://www.atlassian.com/git/tutorials/what-is-version-control 303 | 3. https://try.github.io 304 | 4. https://www.git-tower.com/blog/git-cheat-sheet/ 305 | --- 306 | 309 | # Thank You 310 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 311 | ###### kabirbaidhya@gmail.com 312 | 313 | -------------------------------------------------------------------------------- /units/git/VCS, Git & GitHub.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/git/VCS, Git & GitHub.pdf -------------------------------------------------------------------------------- /units/git/distributed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/git/distributed.png -------------------------------------------------------------------------------- /units/git/vcs-git-and-github.md: -------------------------------------------------------------------------------- 1 | VCS, Git & GitHub 2 | ================== 3 | 4 | ## Version Control 5 | 6 | #### What is VCS? 7 | > Version control systems are a category of software tools that help a software team manage changes to source code over time. 8 | 9 | https://www.atlassian.com/git/tutorials/what-is-version-control 10 | 11 | #### Why Version Control? 12 | 1. Collaboration 13 | 2. Track complete change history 14 | 3. Branching and Merging 15 | 4. Releases and Versions 16 | 5. Revert/Rollback 17 | 18 | #### Distributed Version Control Systems 19 | * Code is hosted in a repository 20 | * Every client has a complete copy of the repository 21 | * Synchronize the changes in between client and server 22 | * Every clone is really a full backup of the repository 23 | * Example: Git, Mercurial, etc. 24 | 25 | ![](https://rawgit.com/kabirbaidhya/learn-python-django-web/master/units/git/distributed-git.svg) 26 | 27 | ## Git 28 | 29 | #### What is Git? 30 | Git is a Distributed Version Control System (VCS). More precisely, the most popular and widely used modern version control system used today. 31 | 32 | It was originally developed by Linus Torvalds the creator of the Linux kernel. 33 | 34 | 35 | #### So, what's the big deal about Git? 36 | * Easy to learn 37 | * Powerful 38 | * Performance 39 | * Flexible 40 | * Open Source 41 | * And it's a de facto standard for VCS these days 42 | 43 | #### Installation 44 | ##### Linux 45 | **Ubuntu/Debain** 46 | ```bash 47 | $ sudo apt-get install git 48 | ``` 49 | 50 | **Centos/RHEL/Fedora** 51 | ```bash 52 | $ sudo yum install git 53 | ``` 54 | 55 | For other distros check the official docs https://git-scm.com/downloads. 56 | 57 | ##### Windows 58 | 1. Download the installer from 59 | https://git-for-windows.github.io/ 60 | 2. Install Git 61 | 62 | **Note: This tutorial more focuses on CLI usage. If you're a windows user and prefer GUI instead, please go through this instadinstadtutorial: https://code.tutsplus.com/tutorials/git-on-windows-for-newbs--net-25847.** 63 | 64 | ##### Check Installation 65 | Once installation is completed, veriy git is properly installed on your computer using 66 | 67 | ```bash 68 | $ git --version 69 | ``` 70 | It should print the git version installed on your system like this. 71 | ```plain 72 | git version 2.7.4 73 | ``` 74 | 75 | #### Configuration 76 | 77 | The first thing you do after installing git is to configure your user name and email. 78 | ```bash 79 | $ git config --global user.name 80 | $ git config --global user.email 81 | ``` 82 | Then you can check your config with 83 | ```bash 84 | $ git config --list 85 | 86 | user.name=Kabir Baidhya 87 | user.email=kabirbaidhya@gmail.com 88 | core.editor=vim 89 | core.excludesfile=/home/kabir/.gitignore_global 90 | ``` 91 | 92 | 93 | #### Setting up a repository 94 | 95 | You can use `git init` command to create a new Git repository. 96 | 97 | ```bash 98 | # Go to your project directory 99 | $ cd /your/project/directory 100 | 101 | # Initialize a git repository 102 | $ git init 103 | ``` 104 | 105 | To clone a remote repository, run `git clone` command. This clones a remote repository into the local machine. 106 | 107 | This will create a complete copy of remotely hosted repository in your local computer. 108 | ```bash 109 | $ git clone [directory] 110 | ``` 111 | 112 | #### Adding files 113 | In order to save your changes to the repository you'll need to `commit` your changes. 114 | 115 | You first need to select files you want to commit using this `git add` command. 116 | ```bash 117 | # Add specific file(s) 118 | $ git add 119 | 120 | # Add whole path or directory 121 | $ git add 122 | 123 | # Add all of your changes 124 | $ git add --all 125 | ``` 126 | 127 | #### Committing changes 128 | The git commit command commits the staged changes to the history. 129 | 130 | ``` 131 | $ git commit 132 | ``` 133 | This will ask you to enter a commit message for your commit. 134 | 135 | In case you don't like to be prompted for the message, you can set directly using the `-m` option like this 136 | ``` 137 | $ git commit -m "This was my first commit" 138 | ``` 139 | 140 | #### Checking status 141 | We use `git status` command to display the status of the working directory and the staging area. 142 | 143 | ```bash 144 | $ git status 145 | ``` 146 | If you have nothing to be committed or no untracked files then it would just show some message like this 147 | ```bash 148 | $ git status 149 | On branch master 150 | nothing to commit, working directory clean 151 | ``` 152 | But if you have some changes to be committed it lists them. 153 | 154 | #### History 155 | We can use the `git log` command to display the history of committed changes on the repository. 156 | 157 | ```bash 158 | $ git log 159 | ``` 160 | There are lots of options available for better inspection of history. For instance, 161 | ```bash 162 | $ git log --oneline # Shows each commit on one line 163 | $ git log -n 164 | $ git log --author="" 165 | $ git log .. 166 | ``` 167 | 168 | #### Adding a remote 169 | You need to add remote repository urls of a remote server to be able to synhronize your changes with the remote repository. 170 | You can do this using the `git remote add` command. 171 | 172 | ```bash 173 | $ git remote add 174 | ``` 175 | You can verify added remotes by doing 176 | ```bash 177 | $ git remote -v 178 | ``` 179 | It should list the urls to the remote repositories you've added so far. 180 | 181 | #### Pushing your changes 182 | 183 | Push all the changes (commits) you did to your local repository to the remote repositories is pretty simple with `git push` command. 184 | 185 | ```bash 186 | # Push a local branch changes to remote 187 | $ git push 188 | 189 | # Push all the changes of local branches to remote 190 | $ git push --all 191 | ``` 192 | For instance: 193 | ```bash 194 | $ git push origin master 195 | ``` 196 | 197 | #### Pulling remote changes 198 | The `git pull` command fetches the changes of the current branch from remote and merges it into the local branch. 199 | 200 | This is same as running the combination of `git fetch` and then `git merge`. 201 | 202 | ```bash 203 | $ git pull [branch] 204 | ``` 205 | Example: 206 | ```bash 207 | $ git pull origin master 208 | ``` 209 | 210 | #### Checking out 211 | Checking out code actually means to take your working directory to a specific change (commit), branch, tag or or even different versions of files. 212 | 213 | You can do all these things with just a simple command `git checkout`. 214 | 215 | ```bash 216 | $ git checkout # go to that commit 217 | $ git checkout # checkout that file to previous version 218 | $ git checkout # go to another branch 219 | $ git checkout # go to a tagged version of the repository 220 | ``` 221 | 222 | #### Branching 223 | The `git branch` command allows you to list, create and delete branches. 224 | 225 | To create a new branch you can do 226 | ```bash 227 | $ git branch 228 | ``` 229 | 230 | #### Merging 231 | You can use `git merge` command to merge changes of a branch into the current `HEAD`. 232 | 233 | Merging a branch into your current branch is as simple as: 234 | ```bash 235 | $ git merge 236 | ``` 237 | 238 | ## Exercises 239 | 1. Create a git repository 240 | 2. Add a python source file "hello.py" to print "Hello World!" 241 | 3. Commit it 242 | 4. Add a README.md file with some information about your repository. 243 | 5. Commit README file too. 244 | 6. Create a new repository on GitHub 245 | 7. Add a remote `origin` pointing towards your github repository 246 | 8. Push your local changes to GitHub 247 | 9. Create a new branch `my-new-branch` 248 | 10. Add a new python source file with some printing code 249 | 11. Commit that file. 250 | 12. Make some changes in the README and commit that too. 251 | 13. Push your branch 252 | 14. Create a pull request from your new branch 253 | 15. Invite some collaborators into your repository. 254 | 16. Add somebody as reviewer/assignee to your pull request 255 | 17. Review/Merge pull request 256 | 18. Pull the changes to your local repository 257 | 258 | ## Read More 259 | 260 | 1. https://git-scm.com/book/en/v2 261 | 2. https://www.atlassian.com/git/tutorials/what-is-version-control 262 | 3. https://try.github.io 263 | 4. https://www.git-tower.com/blog/git-cheat-sheet/ 264 | -------------------------------------------------------------------------------- /units/python/1/Python - Variables, Types & Operators - Presentation.md: -------------------------------------------------------------------------------- 1 | 4 | ###### Python 5 | Variables, Types & Operators 6 | === 7 | 8 | # ![](../../python-logo-200x200.png) 9 | 10 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 11 | 12 | --- 13 | 16 | # Before We Begin 17 | --- 18 | ### Reflections 19 | What we've learned from the past lessons. 20 | 1. Python - Hello World! 21 | 2. Git 22 | 3. Version Control 23 | 4. GitHub 24 | 25 | Note: If you're not aware of these. Read them at https://github.com/kabirbaidhya/learn-python-django-web 26 | 27 | --- 28 | 31 | # Variables 32 | --- 33 | 36 | > A variable is a symbolic name for (or reference to) information. The variable's name represents what information the variable contains. 37 | 40 | 41 | --- 42 | ### For Instance 43 | `foo` and `bar` could be variables that are just symbolic names that represent some information in the memory. 44 | 45 | ```python 46 | # Variable foo contains "Some Information" 47 | foo = "Some Information" 48 | 49 | # And variable bar contains 15.04 50 | bar = 15.64 51 | 52 | # Now variable `foo` can be used to get the reference of that "Some Information" 53 | print("It contains", foo) 54 | 55 | # And they could be used in expressions too 56 | print("Result = ", 5 * bar + 2) 57 | ``` 58 | 61 | 62 | --- 63 | 66 | ### Variables in Python 67 | * Dynamically typed. 68 | * Every variable is an object. 69 | * Names are case sensitive. 70 | * Assigned to a value using `=` operator eg: `foo = 10`. 71 | * Name can contain letters, underscores (`_`) followed by numbers. 72 | * **Naming Convention**: lowercase names using underscore `_` to separate words. eg: `first_name`, `last_name`, etc. 73 | --- 74 | ### For instance 75 | Let's say we have a numeric value `20.0` and we want to store it as the radius of a circle. 76 | We do that like this. 77 | ```python 78 | radius = 20.0 79 | ``` 80 | 81 | **Here,** 82 | 1. `radius` is a variable. 83 | 2. `20.0` is the value assigned to that variable. 84 | 85 | 86 | 87 | --- 88 | 89 | ### For instance 90 | Suppose that we need to store another constant value `3.14` as pi. 91 | 92 | We can do that as well. 93 | ```python 94 | PI = 3.14 95 | ``` 96 | 97 | Now, `PI` is another variable that holds 3.14. 98 | 99 | --- 100 | 101 | ### Using them in expressions 102 | Let's do some computation with these values we have now. 103 | ```python 104 | # Values we have 105 | radius = 20.0 106 | PI = 3.14 107 | 108 | # Compute area of the circle 109 | area = PI * radius * radius 110 | 111 | # Print the results 112 | print("Area of Circle =", area) 113 | ``` 114 | --- 115 | ### In a Nutshell 116 | 117 | ###### A variable is a symbol that stand in for a value 118 | ###### in the program. 119 | 120 | --- 121 | ### Example 1 122 | ```python 123 | first_name = "Kabir" 124 | last_name = "Baidhya" 125 | home_town = "Kathmandu, Nepal" 126 | 127 | print("Hi! I am", first_name, last_name, ".") 128 | print("I'm from", home_town, ".") 129 | ``` 130 | Output: 131 | ```plain 132 | Hi! I am Kabir Baidhya . 133 | I'm from Kathmandu, Nepal . 134 | ``` 135 | --- 136 | 139 | # Data Types 140 | --- 141 | 144 | ### Buit-in Data types 145 | * **Numeric**: int, float, long 146 | * **Boolean**: bool 147 | * **Sequences**: str, list, tuple, bytes 148 | * **Mappings**: dict 149 | * **Sets**: set, frozen set 150 | 151 | --- 152 | ### Immutable & Mutable types 153 | 154 | 1. Immutable types 155 | - int, float, long, str, tuple, frozen set, etc. 156 | 2. Mutable types 157 | - list, dict, set, etc. 158 | --- 159 | ### Integer 160 | Integers are positive or negative whole numbers with no decimal points. 161 | In python 2.x there are two `int` types: `int` and `long`. 162 | 163 | But in python 3.x onwards both have been unified into `int` and it behaves as `long`. 164 | 165 | ```python 166 | total_lessons = 24 167 | ``` 168 | --- 169 | ### Float 170 | They represent real numbers and are written with a decimal point. 171 | 172 | ```python 173 | percentage = 70.05 174 | ``` 175 | --- 176 | ### Boolean 177 | Variables with boolean type can represent only two values `True` or `False`. 178 | 179 | ```python 180 | success = True 181 | failure = not success 182 | ``` 183 | --- 184 | #### Example 2: Basic data types 185 | ```python 186 | an_integer = 6 187 | a_floating_point = 17.60 188 | a_boolean = True 189 | a_string = "Foo" 190 | 191 | print("Integer value =", an_integer) 192 | print("Float value =", a_floating_point) 193 | print("Boolean value =", a_boolean) 194 | print("String value =", a_string) 195 | ``` 196 | 197 | Output: 198 | ```plain 199 | Integer value = 6 200 | Float value = 17.60 201 | Boolean value = True 202 | String value = Foo 203 | ``` 204 | 205 | --- 206 | 207 | 210 | # Operators 211 | --- 212 | 215 | ### Arithmetic Operators 216 | 217 | Python supports all the basic arithmetic operators just like any other programming languages. 218 | 219 | 220 | 221 | |Operator | Operation | Example | 222 | |:---------:|---------------|:---------:| 223 | | + | Addition | a + b | 224 | | _ | Subtration | a - b | 225 | | * | Multiplication| a * b | 226 | | / | Division | a / b | 227 | | \** | Exponentiation| a \** b | 228 | | % | Modulo | a % b | 229 | 230 | 231 | 232 | --- 233 | ### Comparison Operators 234 | 235 | Common comparison operators in python are `<`, `>`, `==`, `>=`, `<=`, and `!=`. 236 | All of these operators return boolean results. 237 | 238 | 239 | 240 | |Operator | Comparison | Example | 241 | |:---------:|-------------------------------|:---------:| 242 | | > | Is greater than | a > b | 243 | | < | Is less than | a < b | 244 | | == | Is equal to | a == b | 245 | | >= | Is greater than or equal to | a >= b | 246 | | <= | Is less than or equal to | a <= b | 247 | | != | Is not equal to | a != b | 248 | 249 | 250 | 251 | --- 252 | ### Logical Operators 253 | 254 | All of these operators return boolean results. 255 | 256 | 257 | 258 | |Operator | Operation | Example | 259 | |:---------:|---------------------------|:---------:| 260 | | and | Logical AND | a and b | 261 | | or | Logical OR | a or b | 262 | | not | Logical NOT | not a | 263 | 264 | 265 | 266 | --- 267 | ### Example 3 268 | Try these in Python shell. 269 | ```python 270 | >>> (1 * 4) + (4 / 2) - (3 * 2) 271 | >>> 7 % 3 272 | >>> 2 ** 3 273 | >>> 1 > 2 274 | >>> 1 >= 1 275 | >>> 1 < 5 276 | >>> 1 <= 5 277 | >>> 7 == 5 278 | >>> 8 != 5 279 | >>> 7 > 2 and 5 < 8 280 | >>> 7 > 10 or 5 < 8 281 | >>> not (5 > 7) 282 | ``` 283 | --- 284 | 287 | ### Exercise 1 288 | 289 | ###### Write a program to calculate the diameter, circumference, and the area of circle using the value of `radius` and constant `PI = 3.14159`. 290 | 291 | --- 292 | ### Exercise 2 293 | 294 | ###### Write a program to calculate the distance between two points represented by coordinates `(x1, y1)` and `(x2, y2)` respectively. 295 | 296 | --- 297 | ##### Use Distance Formula 298 | # ![](./distance_formula.png) 299 | 300 | --- 301 | ### Exercise 3 302 | 303 | ###### Write a program to compute the possible values of `x` from a quadratic equation ax2 + bx + c = 0 (a ≠ 0) using the quadratic equation formula. 304 | 305 | --- 306 | ##### Use Quadratic Formula 307 | # ![](./quadratic_formula.png) 308 | 309 | --- 310 | 313 | # User Input 314 | --- 315 | 318 | ### Input 319 | Getting the user input is an important part of every program. 320 | In python you can use the `input` function to get the user input easily. 321 | 322 | ```python 323 | # Get the input and store it in the variable. 324 | name = input("Please enter your name: ") 325 | 326 | # Print the entered value. 327 | print("Hi", name) 328 | ``` 329 | Note: `input` only works in python3. You need to use `raw_input` if you're using python2. 330 | 331 | --- 332 | 335 | ### Exercise 4 336 | ###### Make changes in the program you wrote for exercise 1 to get the radius from the user. 337 | 338 | --- 339 | ### Exercise 5 340 | ###### Make changes in the program you wrote for exercise 2 to get x1, y1 & x2, y2 from the user. 341 | --- 342 | ### Exercise 6 343 | ###### Make changes in the program you wrote for exercise 3 to get the values of a, b & c from the user. 344 | --- 345 | ### Exercise 7 346 | ###### Write a program that asks for a number and prints if it's an even number or not. 347 | 348 | --- 349 | 352 | # Read More? 353 | --- 354 | 357 | ### Links 358 | 1. https://docs.python.org/3.5/tutorial/introduction.html 359 | 2. https://www.digitalocean.com/community/tutorials/how-to-use-variables-in-python-3 360 | 3. https://learnpythonthehardway.org/book/ex5.html 361 | 4. http://www.pythonforbeginners.com/basics/python-variables 362 | 5. https://www.learnpython.org/en/Variables_and_Types 363 | --- 364 | ### More links 365 | 6. https://en.wikibooks.org/wiki/Python_Programming/Data_Types 366 | 7. https://docs.python.org/3.6/reference/expressions.html#operator-precedence 367 | --- 368 | 371 | # Thank You 372 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 373 | ###### kabirbaidhya@gmail.com 374 | 375 | -------------------------------------------------------------------------------- /units/python/1/Python - Variables, Types & Operators.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/1/Python - Variables, Types & Operators.pdf -------------------------------------------------------------------------------- /units/python/1/distance_formula.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/1/distance_formula.png -------------------------------------------------------------------------------- /units/python/1/python-variables-types-and-operators.md: -------------------------------------------------------------------------------- 1 | Variables, Types & Operators 2 | ============================ 3 | ## Before We Begin 4 | Make sure you're aware of the following things that we've done in previous lessons. 5 | 6 | 1. Python - Hello World! 7 | 2. Git 8 | 3. Version Control 9 | 4. GitHub 10 | 11 | Note: If you're not aware of these. Read them at https://github.com/kabirbaidhya/learn-python-django-web 12 | 13 | ## Variables 14 | 15 | > A variable is a symbolic name for (or reference to) information. The variable's name represents what information the variable contains. 16 | 17 | From http://www.cs.utah.edu/~germain/PPS/Topics/variables.html 18 | 19 | 20 | **For Instance**: `foo` and `bar` could be variables that are just symbolic names that represent some information in the memory. 21 | 22 | ```python 23 | # Variable foo contains "Some Information" 24 | foo = "Some Information" 25 | 26 | # And variable bar contains 15.04 27 | bar = 15.64 28 | 29 | # Now variable `foo` can be used to get the reference of that "Some Information" 30 | print("It contains", foo) 31 | 32 | # And they could be used in expressions too 33 | print("Result = ", 5 * bar + 2) 34 | ``` 35 | 36 | #### Variables in Python 37 | * Dynamically typed. 38 | * Every variable is an object. 39 | * Names are case sensitive. 40 | * Assigned to a value using `=` operator eg: `foo = 10`. 41 | * Name can contain letters, underscores (`_`) followed by numbers. 42 | * **Naming Convention**: lowercase names using underscore `_` to separate words. eg: `first_name`, `last_name`, etc. 43 | 44 | **For instance** 45 | Let's say we have a numeric value `20.0` and we want to store it as the radius of a circle. 46 | We do that like this. 47 | ```python 48 | radius = 20.0 49 | ``` 50 | 51 | Here, 52 | 1. `radius` is a variable. 53 | 2. `20.0` is the value assigned to that variable. 54 | 55 | Suppose that we need to store another constant value `3.14` as pi. 56 | 57 | We can do that as well. 58 | ```python 59 | PI = 3.14 60 | ``` 61 | 62 | Now, `PI` is another variable that holds 3.14. 63 | 64 | Let's do some computation with these values we have now. 65 | ``` 66 | # Values we have 67 | radius = 20.0 68 | PI = 3.14 69 | 70 | # Compute area of the circle 71 | area = PI * radius * radius 72 | 73 | # Print the results 74 | print("Area of Circle =", area) 75 | ``` 76 | 77 | #### In a Nutshell 78 | 79 | **A variable is a symbol that stand in for a value in the program.** 80 | 81 | #### Example 1 82 | ```python 83 | first_name = "Kabir" 84 | last_name = "Baidhya" 85 | home_town = "Kathmandu, Nepal" 86 | 87 | print("Hi! I am", first_name, last_name, ".") 88 | print("I'm from", home_town, ".") 89 | ``` 90 | Output: 91 | ```plain 92 | Hi! I am Kabir Baidhya . 93 | I'm from Kathmandu, Nepal . 94 | ``` 95 | 96 | ## Data Types 97 | 98 | #### Buit-in Data types 99 | * **Numeric**: int, float, long 100 | * **Boolean**: bool 101 | * **Sequences**: str, list, tuple, bytes 102 | * **Mappings**: dict 103 | * **Sets**: set, frozen set 104 | 105 | #### Immutable & Mutable types 106 | 107 | 1. Immutable types 108 | - int, float, long, str, tuple, frozen set, etc. 109 | 2. Mutable types 110 | - list, dict, set, etc. 111 | 112 | 113 | #### Integer 114 | Integers are positive or negative whole numbers with no decimal points. 115 | In python 2.x there are two `int` types: `int` and `long`. 116 | 117 | But in python 3.x onwards both have been unified into `int` and it behaves as `long`. 118 | 119 | ```python 120 | total_lessons = 24 121 | ``` 122 | 123 | #### Float 124 | They represent real numbers and are written with a decimal point. 125 | 126 | ```python 127 | percentage = 70.05 128 | ``` 129 | 130 | #### Boolean 131 | Variables with boolean type can represent only two values `True` or `False`. 132 | 133 | ```python 134 | success = True 135 | failure = not success 136 | ``` 137 | 138 | #### Example 2 139 | ```python 140 | an_integer = 6 141 | a_floating_point = 17.60 142 | a_boolean = True 143 | a_string = "Foo" 144 | 145 | print("Integer value =", an_integer) 146 | print("Float value =", a_floating_point) 147 | print("Boolean value =", a_boolean) 148 | print("String value =", a_string) 149 | ``` 150 | 151 | Output: 152 | ```plain 153 | Integer value = 6 154 | Float value = 17.60 155 | Boolean value = True 156 | String value = Foo 157 | ``` 158 | 159 | ## Operators 160 | 161 | #### Arithmetic Operators 162 | 163 | Python supports all the basic arithmetic operators just like any other programming languages. 164 | 165 | |Operator | Operation | Example | 166 | |:---------:|---------------|:---------:| 167 | | + | Addition | a + b | 168 | | _ | Subtration | a - b | 169 | | * | Multiplication| a * b | 170 | | / | Division | a / b | 171 | | \** | Exponentiation| a \** b | 172 | | % | Modulo | a % b | 173 | 174 | 175 | #### Comparison Operators 176 | 177 | Common comparison operators in python are `<`, `>`, `==`, `>=`, `<=`, and `!=`. 178 | All of these operators return boolean results. 179 | 180 | 181 | |Operator | Comparison | Example | 182 | |:---------:|-------------------------------|:---------:| 183 | | > | Is greater than | a > b | 184 | | < | Is less than | a < b | 185 | | == | Is equal to | a == b | 186 | | >= | Is greater than or equal to | a >= b | 187 | | <= | Is less than or equal to | a <= b | 188 | | != | Is not equal to | a != b | 189 | 190 | 191 | #### Logical Operators 192 | 193 | All of these operators return boolean results. 194 | 195 | 196 | |Operator | Operation | Example | 197 | |:---------:|---------------------------|:---------:| 198 | | and | Logical AND | a and b | 199 | | or | Logical OR | a or b | 200 | | not | Logical NOT | not a | 201 | 202 | 203 | #### Example 3 204 | Try these in the Python shell. 205 | 206 | ```python 207 | >>> (1 * 4) + (4 / 2) - (3 * 2) 208 | >>> 7 % 3 209 | >>> 2 ** 3 210 | >>> 1 > 2 211 | >>> 1 >= 1 212 | >>> 1 < 5 213 | >>> 1 <= 5 214 | >>> 7 == 5 215 | >>> 8 != 5 216 | >>> 7 > 2 and 5 < 8 217 | >>> 7 > 10 or 5 < 8 218 | >>> not (5 > 7) 219 | ``` 220 | 221 | ## User Input 222 | Getting the user input is an important part of every program. 223 | In python you can use the `input` function to get the user input easily. 224 | 225 | ```python 226 | # Get the input and store it in the variable. 227 | name = input("Please enter your name: ") 228 | 229 | # Print the entered value. 230 | print("Hi", name) 231 | ``` 232 | Note: `input` only works in python3. You need to use `raw_input` if you're using python2. 233 | 234 | ## Exercises 235 | 236 | 1. Write a program to calculate the diameter, circumference, and the area of circle using the value of `radius` and constant `PI = 3.14159`. 237 | 2. Write a program to calculate the distance between two points represented by coordinates `(x1, y1)` and `(x2, y2)` respectively. 238 | 239 | Hints: Use Distance Formula 240 | ##### ![](./distance_formula.png) 241 | 242 | 3. Write a program to compute the possible values of `x` from a quadratic equation ax2 + bx + c = 0 (a ≠ 0) using the quadratic equation formula. 243 | 244 | Hints: Use Quadratic Formula 245 | ##### ![](./quadratic_formula.png) 246 | 247 | 4. Make changes in the program you wrote for exercise 1 to get the radius from the user. 248 | 5. Make changes in the program you wrote for exercise 2 to get x1, y1 & x2, y2 from the user. 249 | 6. Make changes in the program you wrote for exercise 3 to get the values of a, b & c from the user. 250 | 7. Write a program that asks for a number and prints if it's an even number or not. 251 | 252 | ## Read More? 253 | Want to read more? Go through these links. 254 | 1. https://docs.python.org/3.5/tutorial/introduction.html 255 | 2. https://www.digitalocean.com/community/tutorials/how-to-use-variables-in-python-3 256 | 3. https://learnpythonthehardway.org/book/ex5.html 257 | 4. http://www.pythonforbeginners.com/basics/python-variables 258 | 5. https://www.learnpython.org/en/Variables_and_Types 259 | 6. https://en.wikibooks.org/wiki/Python_Programming/Data_Types 260 | 7. https://docs.python.org/3.6/reference/expressions.html#operator-precedence 261 | -------------------------------------------------------------------------------- /units/python/1/quadratic_formula.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/1/quadratic_formula.png -------------------------------------------------------------------------------- /units/python/2/Strings and Formatting.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/2/Strings and Formatting.pdf -------------------------------------------------------------------------------- /units/python/2/ex_2.py: -------------------------------------------------------------------------------- 1 | # Input the equation in y = mx + c form. 2 | equation = input('Equation: ') 3 | 4 | # 'y', 'mx +c' 5 | rhs = equation.split('=')[1] 6 | 7 | # 'mx', 'c' 8 | parts = rhs.split('+') 9 | 10 | # Parse out the values of m & c 11 | m = parts[0].replace('x', '').strip() 12 | c = parts[1].strip() 13 | 14 | # Print them out 15 | print('Slope of line: {}'.format(m)) 16 | print('Y-Intercept: {}'.format(c)) 17 | -------------------------------------------------------------------------------- /units/python/2/ex_3.py: -------------------------------------------------------------------------------- 1 | # Program to ask for the date of birth 2 | # and calculate the user's age. 3 | 4 | dob = input('Enter your Date of Birth(yyyy-mm-dd): ') 5 | dob = dob.split('-') 6 | 7 | # Calculate the date timestamp in years. 8 | dob_timestamp = float(dob[0]) + float(dob[1])/12 + float(dob[2])/365 9 | 10 | # Calculate the today's timestamp in years. 11 | today = ['2017', '03', '17'] 12 | today_timestamp = float(today[0]) + float(today[1])/12 + float(today[2])/365 13 | 14 | # Compute the difference 15 | years = today_timestamp - dob_timestamp 16 | months = (years - int(years)) * 12 17 | 18 | print('Your age is %d years %d months' % (years, months)) 19 | -------------------------------------------------------------------------------- /units/python/2/example.py: -------------------------------------------------------------------------------- 1 | s = input('Enter a string: ') 2 | 3 | print("No. of characters = %d" % len(s)) 4 | print("First Character = %s" % s[0]) 5 | print("Last Character = %s" % s[len(s) - 1]) 6 | 7 | # Count the number of vowels 8 | print("No. of 'a' = %s" % s.count('a')) 9 | print("No. of 'e' = %s" % s.count('e')) 10 | print("No. of 'i' = %s" % s.count('i')) 11 | print("No. of 'o' = %s" % s.count('o')) 12 | print("No. of 'u' = %s" % s.count('u')) 13 | 14 | # Calculate Percentage of vowels 15 | total_vowels = s.count('a') + s.count('e') + s.count('i') + s.count('o') + s.count('u') 16 | percentage = (float(total_vowels) / len(s)) * 100 17 | print("%.2f%% are vowels." % percentage) 18 | -------------------------------------------------------------------------------- /units/python/2/example_1.py: -------------------------------------------------------------------------------- 1 | text = input('Enter a string: ') 2 | 3 | print("capitalize() = ", text.capitalize()) 4 | print("strip() = ", text.strip()) 5 | print("swapcase() = ", text.swapcase()) 6 | print("title() = ", text.title()) 7 | print("upper() = ", text.upper()) 8 | print("lower() = ", text.lower()) 9 | print("replace('a', 'b') = ", text.replace('a', 'b')) 10 | print("endswith('foo') = ", text.endswith('foo')) 11 | print("startswith('bar') = ", text.startswith('bar')) 12 | print("find('foo') = ", text.find('foo')) 13 | print("split(' ') = ", text.split(' ')) 14 | -------------------------------------------------------------------------------- /units/python/2/example_2.py: -------------------------------------------------------------------------------- 1 | # Ask the user to enter first and last name. 2 | first_name = input('Your first name: ') 3 | last_name = input('Your last name: ') 4 | 5 | # Print a blank line 6 | print("\n") 7 | print("Hi %s %s!" % (first_name, last_name)) 8 | print("It's nice to meet you.") 9 | 10 | -------------------------------------------------------------------------------- /units/python/2/example_3.py: -------------------------------------------------------------------------------- 1 | # Ask the user to enter first and last name. 2 | radius = input('Enter radius of circle(meters): ') 3 | PI = 3.1415 4 | 5 | area = PI * float(radius) ** 2 6 | 7 | print("\nArea of circle = %.2f sq. metres" % area) 8 | -------------------------------------------------------------------------------- /units/python/2/example_4.py: -------------------------------------------------------------------------------- 1 | amount = input('Enter amount in USD: ') 2 | rate = 100.00 3 | 4 | amount_npr = float(amount) * rate 5 | print('Equivalent amount: NPR. {:.2f}'.format(amount_npr)) 6 | -------------------------------------------------------------------------------- /units/python/2/strings-and-formatting.md: -------------------------------------------------------------------------------- 1 | Strings, Formatting & Operators 2 | ============================ 3 | 4 | In our previous lesson we discussed about Variables, basic data types and operators. If you haven't gone through it [read it here](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/python/1/python-variables-types-and-operators.md). 5 | 6 | ## Strings 7 | A string is traditionally a sequence of characters. Strings are one of the common data types in all programming languages and python is not an exception. 8 | 9 | String in Python is handled with `str` object and strings are immutable sequences. 10 | Strings can be represented in various of ways in Python: 11 | 12 | ```python 13 | # Using Single Quotes 14 | my_string1 = 'This is a string' 15 | 16 | # Using Double Quotes 17 | my_string2 = "This is a string too". 18 | 19 | # Using Triple Quotes (Multiline strings) 20 | my_string3 = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, 21 | sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ''' 22 | 23 | # You could write it with double quotes as well 24 | my_string3 = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, 25 | sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. """ 26 | 27 | ``` 28 | 29 | ## Common Operations 30 | The operations in the following table are supported by most sequence types, both mutable and immutable. Since strings are also sequences they support them all. 31 | 32 | | Operation | Result | 33 | |-----------------------|-----------------------------------------------------------| 34 | | x in s | True if an item of s is equal to x, else False | 35 | | x not in s | False if an item of s is equal to x, else True | 36 | | s + t | the concatenation of s and t | 37 | | s * n or n * s | equivalent to adding s to itself n times | 38 | | s[i] | ith item of s, origin 0 | 39 | | s[i:j] | slice of s from i to j | 40 | | s[i:j:k] | slice of s from i to j with step k | 41 | | len(s) | length of s | 42 | | min(s) | smallest item of s | 43 | | max(s) | largest item of s | 44 | | s.index(x[, i[, j]]) | index of the first occurrence of x in s (at or after index i and before index j) | 45 | | s.count(x) | total number of occurrences of x in s | 46 | 47 | Check the official about these operations [here](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations). 48 | 49 | ## String Methods 50 | 51 | Following are some of the common string methods supported by `str` objects. 52 | 53 | |Method | Description | 54 | |---------------------------------------|-----------------------------------------------------------------------------------------------| 55 | | capitalize() | Return a new string with its first character capitalized and the rest lowercased. | 56 | | endswith(suffix[, start[, end]) | Check if the string ends with the given suffix. Return boolean result `True` or `False` | 57 | | startswith(prefix[, start[, end]]) | Check if the string starts with the given prefix and return boolean result `True` or `False` | 58 | | find(sub[, start[, end]]) | Return the first index in the string where substring `sub` is found within `start` to `end` of the string. Return -1 if not found. | 59 | | strip([chars]) | Return a new string with the leading and trailing characters removed. The optional `chars` argument defaults to removing whitespace. | 60 | | swapcase() | Return a new string with uppercase characters converted to lowercase and vice versa. | 61 | | title() | Return a new titlecased version of the string where words start with an uppercase character and other letters are lowercased. | 62 | | upper() | Return a new uppercased version of the string. | 63 | | lower() | Return a new lowercased version of the string. | 64 | | split(sep=None, maxsplit=-1) | Splits the string into substring using the `sep` argument as the separator. Return the list of splitted substrings. | 65 | | format(*args, **kwargs) | Perform a string formatting operation and return the formatted string. | 66 | | replace(old, new[, count]) | Return a new string by replacing all occurrences of substring `old` with `new`. If `count` argument is provided, only `count` number of replacements would be done. | 67 | 68 | The above listed methods are just some handful of common string methods. Check the official docs for the [full list](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str). 69 | 70 | #### Example 1 71 | ```python 72 | text = input('Enter a string: ') 73 | 74 | print("capitalize() = ", text.capitalize()) 75 | print("strip() = ", text.strip()) 76 | print("swapcase() = ", text.swapcase()) 77 | print("title() = ", text.title()) 78 | print("upper() = ", text.upper()) 79 | print("lower() = ", text.lower()) 80 | print("replace('a', 'b') = ", text.replace('a', 'b')) 81 | print("endswith('foo') = ", text.endswith('foo')) 82 | print("startswith('bar') = ", text.startswith('bar')) 83 | print("find('foo') = ", text.find('foo')) 84 | print("split(' ') = ", text.split(' ')) 85 | ``` 86 | 87 | ## C-Style formatting 88 | You probably remember the `printf` function if you've programmed in C. You can do similar string formatting in Python as well. 89 | 90 | You would do something like this. 91 | ```python 92 | print("Hello %s!" % name) 93 | ``` 94 | 95 | #### Example 2 96 | ```python 97 | # Ask the user to enter first and last name. 98 | first_name = input('Your first name: ') 99 | last_name = input('Your last name: ') 100 | 101 | print("\nHi %s %s!" % (first_name, last_name)) 102 | print("It's nice to meet you.") 103 | ``` 104 | 105 | #### Example 3 106 | ```python 107 | # Ask the user to enter first and last name. 108 | PI = 3.1415 109 | radius = input('Enter radius of circle(meters): ') 110 | area = PI * float(radius) ** 2 111 | 112 | print("\nArea of circle = %.2f sq. metres" % area) 113 | ``` 114 | 115 | Following are the supported conversion types. 116 | 117 | | Conversion | Meaning | 118 | |---------------|---------------------------------------------------| 119 | | 'd' | Signed integer decimal. | 120 | | 'i' | Signed integer decimal. | 121 | | 'o' | Signed octal value. | 122 | | 'u' | Obsolete type – it is identical to 'd'. | 123 | | 'x' | Signed hexadecimal (lowercase). | 124 | | 'X' | Signed hexadecimal (uppercase). | 125 | | 'e' | Floating point exponential format (lowercase). | 126 | | 'E' | Floating point exponential format (uppercase). | 127 | | 'f' | Floating point decimal format. | 128 | | 'F' | Floating point decimal format. | 129 | | 'g' | Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. | 130 | | 'G' | Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. | 131 | | 'c' | Single character (accepts integer or single character string). | 132 | | 'r' | String (converts any Python object using repr()). | 133 | | 's' | String (converts any Python object using str()). | 134 | | 'a' | String (converts any Python object using ascii()). | 135 | | '%' | No argument is converted, results in a '%' character in the result. | 136 | 137 | For in-depth information about the C-style formatting [check the official docs](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting). 138 | 139 | 140 | ## New style formatting 141 | The C-Style formatting is already powerful. But python provides another way for formatting as well. 142 | 143 | That is using `str.format()` method. 144 | 145 | Something like this: 146 | 147 | ```python 148 | print("Hello {}!".format(name)) 149 | ``` 150 | 151 | Pretty much the same, right? 152 | 153 | Okay, check this example on what difference this new syntax makes. 154 | 155 | #### Example 3 156 | ```python 157 | first_name = input('Your first name: ') 158 | last_name = input('Your last name: ') 159 | 160 | # Old style formatting. 161 | print('Hello %s %s!' % (first_name, last_name)) 162 | 163 | # New Style formatting 164 | print('Hello {} {}!'.format(first_name, last_name)) 165 | print('Hello {0} {1}!'.format(first_name, last_name)) 166 | 167 | # This is where, you will feel the difference. 168 | print('Hello {1} {0}!'.format(first_name, last_name)) 169 | print('Hello {0} {0} {1}!'.format(first_name, last_name)) 170 | ``` 171 | 172 | #### Example 4 173 | ```python 174 | amount = input('Enter amount in USD: ') 175 | rate = 100.00 176 | 177 | amount_npr = float(amount) * rate 178 | print('Equivalent amount: NPR. {:.2f}'.format(amount_npr)) 179 | ``` 180 | 181 | ## Exercises 182 | 1. Write a program to ask for the marks of 5 different subjects and print the total marks obtained and the total percentage. 183 | 2. Write a program to ask for the equation of a line in the form `y = mx + c`. And print the values of slope and y-intercept of the line. (Hint: Use `split()`.) 184 | 185 | 3. Write a program to ask for the user's date of birth in `YYYY-MM-DD` format and calculate the user's age. (Hint: Use `split()` method to split the date parts.) 186 | 187 | ## Read More? 188 | Want to read more? Go through these links. 189 | 1. https://docs.python.org/3/library/stdtypes.html#old-string-formatting 190 | 2. https://pyformat.info/ 191 | 3. https://www.tutorialspoint.com/python/python_strings.htm 192 | -------------------------------------------------------------------------------- /units/python/3/Lists and Dictionaries.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/3/Lists and Dictionaries.pdf -------------------------------------------------------------------------------- /units/python/3/example_1.py: -------------------------------------------------------------------------------- 1 | names = ['John Doe', 'Jane Doe', 'Johnny Turk'] 2 | # Change the first name in the list 3 | names[0] = 'Foo Bar' 4 | print('Names now:', names) 5 | 6 | # Append some more names 7 | names.append('Molly Mormon') 8 | names.append('Joe Bloggs') 9 | print('Names finally:', names) 10 | print('Last name in the list: %s' % names[-1]) 11 | 12 | # You can join lists using str.join() method 13 | joined_names = '\n'.join(names) 14 | print('\nList of names:') 15 | print(joined_names) 16 | -------------------------------------------------------------------------------- /units/python/3/example_2.py: -------------------------------------------------------------------------------- 1 | # Create a list of squares of numbers upto 10 2 | squares = [x**2 for x in range(10)] 3 | print('Squares:', squares) 4 | 5 | # You can create lists using existing lists. 6 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 7 | even_numbers = [x for x in numbers if x % 2 ==0] 8 | odd_numbers = [x for x in numbers if x % 2 !=0] 9 | print('Numbers:', numbers) 10 | print('Even numbers:', even_numbers) 11 | print('Odd numbers:', odd_numbers) 12 | 13 | -------------------------------------------------------------------------------- /units/python/3/example_3.py: -------------------------------------------------------------------------------- 1 | # You can even create new lists by processing existing lists. 2 | words = ['this', 'is', 'just', 'a', 'test'] 3 | capitalized_words = [x.capitalize() for x in words] 4 | 5 | print('Words:', words) 6 | print('Capitalized Words:', capitalized_words) 7 | 8 | # Can use it for filtering the list items as well. 9 | words = ['hello', 'world', 'foo', 'bar', 'test', 'python', 'is', 'awesome'] 10 | short_words = [x for x in words if len(x) <= 3] 11 | other_words = [x for x in words if x not in short_words] 12 | words_with_e = [x for x in words if x.count('e') >= 1] 13 | 14 | print('Words:', words) 15 | print('Short Words:', short_words) 16 | print('Other Words:', other_words) 17 | print('Words with "e":', words_with_e) 18 | -------------------------------------------------------------------------------- /units/python/3/example_4.py: -------------------------------------------------------------------------------- 1 | names = ['John Doe', 'Jane Doe', 'Johnny Turk'] 2 | 3 | print('Names:') 4 | 5 | for name in names: 6 | print(' - %s' % name) 7 | 8 | -------------------------------------------------------------------------------- /units/python/3/example_5.py: -------------------------------------------------------------------------------- 1 | my_list = [] 2 | 3 | if len(my_list) == 0: 4 | print('No items on the list.') 5 | else: 6 | print(my_list) 7 | -------------------------------------------------------------------------------- /units/python/4/Conditionals and Loops - Presentation.md: -------------------------------------------------------------------------------- 1 | 4 | ###### Python 5 | Conditionals and Loops 6 | === 7 | 8 | # ![](../../../python-logo-200x200.png) 9 | 10 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 11 | 12 | --- 13 | 16 | # Reflections 17 | --- 18 | ## What we already know 19 | From the last session. 20 | 21 | 1. Lists 22 | 2. Dictionaries 23 | 24 | 25 | Note: If you're not aware of these. Read them at https://github.com/kabirbaidhya/learn-python-django-web 26 | 27 | --- 28 | # Conditional Statements 29 | --- 30 | 33 | ### Conditional Statements 34 | 35 | - The basic building blocks of every programming language. 36 | - Every language offers them in one way or another. 37 | - In Python the simplest of conditional statements is the `if` statement. 38 | 39 | --- 40 | ### The `if` statement 41 | 42 | ```python 43 | if CONDITION: 44 | STATEMENT1 45 | STATEMENT2 46 | ... 47 | ``` 48 | 49 | The `CONDITION` could be any valid expression that results boolean value. 50 | 51 | The statements inside the block are run only if the `CONDITION` holds true else the indented code block will be ignored. 52 | 53 | --- 54 | ### Dont' Forget 55 | 1. The colon `:` in the `if` block, which actually starts the block. 56 | 2. Indentation, which is the part of syntax in python and a must have (unlike C-style languages where it's optional). 57 | 3. End of indent means end of the block. 58 | --- 59 | 60 | 61 | ### Example 1 62 | ```python 63 | if input('word: ') == 'Foo': 64 | print('Great!') 65 | print('You entered "Foo"') 66 | 67 | # Normal statements out of the block 68 | print('Good Bye!') 69 | ``` 70 | 71 | --- 72 | ### The `if-else` statement 73 | ```python 74 | if CONDITION: 75 | STATEMENT1 76 | STATEMENT2 77 | ... 78 | else: 79 | STATEMENT1 80 | STATEMENT2 81 | ... 82 | ``` 83 | 84 | The statements inside the `if` block are run if the `CONDITION` holds true otherwise the code from the `else` block will be run. 85 | 86 | Only either one of these two blocks are run. 87 | 88 | --- 89 | ### Example 2 90 | ```python 91 | if input('word: ') == 'Foo': 92 | print('Great!') 93 | print('You entered "Foo"') 94 | else: 95 | print('Hey!') 96 | print('That was something else') 97 | 98 | # Normal statements out of the block 99 | print('Good Bye!') 100 | ``` 101 | --- 102 | ### The `if-elif-else` statement 103 | ```python 104 | if CONDITION1: 105 | STATEMENTS 106 | 107 | elif CONDITION2: 108 | STATEMENTS 109 | 110 | elif CONDITION3: 111 | STATEMENTS 112 | ... 113 | else: 114 | STATEMENTS 115 | ``` 116 | --- 117 | ### The `if-elif-else` statement 118 | * Conditions are checked one by one, and the first code block for which the condition results `True` will be executed and all other blocks are skipped. 119 | * If none of the conditions holds true, the `else` block is executed. And if there isn't any `else` block, nothing happens. 120 | * There can be any number of `elif` blocks. But only one of the block is run no matter what. 121 | * **Remember it is `elif`, not `elseif`** 122 | --- 123 | ### Example 3 124 | ```python 125 | word = input('word: ') 126 | 127 | if word == 'Foo': 128 | print('Great!') 129 | print('You entered "Foo"') 130 | elif word == 'Bar': 131 | print('Wow!') 132 | print('You entered "Bar"') 133 | elif word == 'Baz': 134 | print('Awesome!') 135 | print('You entered "Baz"') 136 | else: 137 | print('Hey!') 138 | print('That was something else') 139 | 140 | # Normal statements out of the block 141 | print('Good Bye!') 142 | ``` 143 | --- 144 | 147 | # Loops 148 | --- 149 | 152 | ### Loops in Python 153 | Loops are the programming constructs that allow us execute or iterate over a statement block multiple times depending upon some condition. 154 | 155 | Generally we use two types of loops in python: 156 | 1. While Loop 157 | 2. For Loop 158 | 159 | --- 160 | ### The `while` loop 161 | 162 | It's the simplest of all. 163 | 164 | **Syntax** 165 | 166 | ```python 167 | while CONDITION: 168 | STATEMENTS 169 | 170 | ``` 171 | 172 | It iterates over a block of code as long as the base condition holds true. 173 | 174 | --- 175 | ### Example 4 176 | ```python 177 | a = 0 178 | 179 | # This will print out numbers 1 to 5 180 | while a < 5: 181 | a = a + 1 182 | print(a) 183 | ``` 184 | --- 185 | ### Example 5 186 | ```python 187 | n = 0 188 | sum = 0 189 | 190 | # Calculate the sum of 5 numbers entered by user 191 | while n < 5: 192 | value = input('Enter Number %s: ' % (n + 1)) 193 | sum = sum + float(value) 194 | n += 1 195 | 196 | print('Sum = %.2f' % sum) 197 | ``` 198 | --- 199 | ### Example 6 200 | 201 | ```python 202 | # Print Fibonacci series upto n 203 | a = 0 204 | b = 1 205 | n = 25 206 | 207 | while a < n: 208 | print(a) 209 | (a, b) = (b, a + b) 210 | 211 | ``` 212 | --- 213 | ### Example 7 214 | ```python 215 | # Lists and the while loop 216 | names = ['John Doe', 'Jane Doe', 'Johnny Turk'] 217 | i = 0 218 | total_names = len(names) 219 | print('Users:') 220 | 221 | while i < total_names: 222 | end = ' and\n' if i == total_names - 2 else '\n' 223 | print(' - %s' % names[i], end=end) 224 | i += 1 225 | 226 | ``` 227 | --- 228 | ### The `for` loop 229 | 230 | Loop dedicated for iterating over a sequence types. 231 | 232 | **Syntax** 233 | ```python 234 | for VARIABLE in SEQUENCE: 235 | STATEMENTS 236 | ``` 237 | 238 | Iterates over the given sequence `SEQUENCE`. 239 | 240 | The `VARIABLE` would hold the current item over each iteration of the loop. 241 | 242 | --- 243 | ### Example 8 244 | ```python 245 | # Loop over a list of numbers 246 | 247 | for num in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: 248 | print(num) 249 | 250 | print('--') 251 | 252 | # Do the same thing using range. 253 | for num in range(10): 254 | print(num + 1) 255 | 256 | ``` 257 | --- 258 | ### Example 9 259 | Redoing the last `while` example with `for` loop. 260 | 261 | ```python 262 | # Lists and the for loop 263 | names = ['John Doe', 'Jane Doe', 'Johnny Turk'] 264 | print('Users:') 265 | 266 | for name in names: 267 | end = ' and\n' if name == names[-2] else '\n' 268 | 269 | print(' - %s' % name, end=end) 270 | ``` 271 | 272 | --- 273 | ### Index in the `for` loop 274 | Use `enumerate()` to get a tuple `(index, value)` instead of regular item of sequence. 275 | 276 | ```python 277 | names = ['John Doe', 'Jane Doe', 'Johnny Turk'] 278 | 279 | 280 | for (index, value) in enumerate(names): 281 | print(' %d \t %s' %(index, value)) 282 | 283 | ``` 284 | 285 | --- 286 | ### Loop over dictionaries 287 | Use `dict.items()` method to get a list of tuples for each key value pair in the dictionary. 288 | 289 | ```python 290 | user = { 291 | 'name': 'John Doe', 292 | 'email': 'johndoe@example.com', 293 | 'phone': '(111) 111-1112', 294 | 'address': '123 6th St. Melbourne, FL 32904', 295 | } 296 | 297 | for (key, val) in user.items(): 298 | print(' %s : %s' % (key, val)) 299 | 300 | ``` 301 | --- 302 | 305 | # Exercises 306 | --- 307 | ### Exercise 1 308 | ###### 1. Program to ask for the age of the person and print out the following depending upon the age. 309 | 310 | 311 | 312 | | Age | Message | 313 | |------------------------|------------------------------| 314 | | Less than or is Zero | Invalid input for age. | 315 | | Less than 1 year | You're an infant | 316 | | 2 - 12 | You're just a kid. | 317 | | 13 - 19 | You're a teenager. | 318 | | 20 - 45 | You are adult now. | 319 | | 46 - 59 | You are middle-aged. | 320 | | 60+ | You are old now. | 321 | | 120+ | You're too old to still be alive. | 322 | 323 | 324 | 325 | --- 326 | 327 | ### Exercise 2 328 | ###### Program to ask for a co-ordinate point `(x, y)`. And print in which quadrant it lies in. If it lies in any axes print the name of the axis instead. For eg: `(5, 0)` should print `'X-Axis'` but `(5, - 5)` should print `'4st Quadrant'`. 329 | 330 | --- 331 | ### Exercise 3 332 | ###### Program to calculate the factorial of integer `n` taken from user input. 333 | 334 | --- 335 | ### Exercise 4 336 | ###### Program to store a list of several users with information: username, email and password. Ask user name and password from the user and check if the combination of username/password matches with the credentials we have in our predefined list. 337 | 338 | --- 339 | 342 | # Read More? 343 | --- 344 | 347 | ### Links 348 | 1. https://docs.python.org/3/reference/compound_stmts.html 349 | 2. http://www.openbookproject.net/books/bpp4awd/ch04.html 350 | 3. http://en.wikipedia.org/wiki/Conditional_%28programming%29 351 | 4. http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/ifstatements.html 352 | --- 353 | ### More Links 354 | 5. https://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements 355 | 6. https://docs.python.org/3/reference/expressions.html#conditional-expressions 356 | --- 357 | 360 | ###### This slide was a part of course 361 | #### Python, Django & Web Development 362 | ###### [github.com/kabirbaidhya/learn-python-django-web](https://github.com/kabirbaidhya/learn-python-django-web) 363 | --- 364 | # Thank You 365 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 366 | ###### kabirbaidhya@gmail.com 367 | 368 | -------------------------------------------------------------------------------- /units/python/4/Conditionals and Loops.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/4/Conditionals and Loops.pdf -------------------------------------------------------------------------------- /units/python/4/example_1.py: -------------------------------------------------------------------------------- 1 | if input('word: ') == 'Foo': 2 | print('Great!') 3 | print('You entered "Foo"') 4 | 5 | # Normal statements out of the block 6 | print('Good Bye!') 7 | 8 | -------------------------------------------------------------------------------- /units/python/4/example_2.py: -------------------------------------------------------------------------------- 1 | if input('word: ') == 'Foo': 2 | print('Great!') 3 | print('You entered "Foo"') 4 | else: 5 | print('Hey!') 6 | print('That was something else') 7 | 8 | # Normal statements out of the block 9 | print('Good Bye!') 10 | 11 | -------------------------------------------------------------------------------- /units/python/4/example_3.py: -------------------------------------------------------------------------------- 1 | word = input('word: ') 2 | 3 | if word == 'Foo': 4 | print('Great!') 5 | print('You entered "Foo"') 6 | elif word == 'Bar': 7 | print('Wow!') 8 | print('You entered "Bar"') 9 | elif word == 'Baz': 10 | print('Awesome!') 11 | print('You entered "Baz"') 12 | else: 13 | print('Hey!') 14 | print('That was something else') 15 | 16 | # Normal statements out of the block 17 | print('Good Bye!') 18 | -------------------------------------------------------------------------------- /units/python/4/example_4.py: -------------------------------------------------------------------------------- 1 | a = 0 2 | while a < 5: 3 | a = a + 1 4 | print(a) 5 | 6 | -------------------------------------------------------------------------------- /units/python/4/example_5.py: -------------------------------------------------------------------------------- 1 | n = 0 2 | sum = 0 3 | 4 | # Calculate the sum of 5 numbers entered by user 5 | while n < 5: 6 | value = input('Enter Number %s: ' % (n + 1)) 7 | sum = sum + float(value) 8 | n += 1 9 | 10 | print('Sum = %.2f' % sum) 11 | 12 | -------------------------------------------------------------------------------- /units/python/4/example_6.py: -------------------------------------------------------------------------------- 1 | # Print Fibonacci series upto n 2 | a = 0 3 | b = 1 4 | n = 25 5 | 6 | while a < n: 7 | print(a) 8 | (a, b) = (b, a + b) 9 | 10 | 11 | -------------------------------------------------------------------------------- /units/python/4/example_7.py: -------------------------------------------------------------------------------- 1 | names = ['John Doe', 'Jane Doe', 'Johnny Turk', 'Molly Mormon'] 2 | i = 0 3 | total_names = len(names) 4 | print('Users:') 5 | 6 | while i < total_names: 7 | 8 | # This is same as doing. 9 | # 10 | # if i == total_names - 2: 11 | # end = ' and\n' 12 | # else: 13 | # end = '\n' 14 | end = ' and\n' if i == total_names - 2 else '\n' 15 | 16 | print(' - %s' % names[i], end=end) 17 | i += 1 18 | 19 | 20 | -------------------------------------------------------------------------------- /units/python/4/example_8.py: -------------------------------------------------------------------------------- 1 | # Loop over a list of numbers 2 | 3 | for num in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: 4 | print(num) 5 | 6 | print('--') 7 | 8 | # Do the same thing using range. 9 | for num in range(10): 10 | print(num + 1) 11 | 12 | -------------------------------------------------------------------------------- /units/python/4/example_9.py: -------------------------------------------------------------------------------- 1 | # Lists and the for loop 2 | names = ['John Doe', 'Jane Doe', 'Johnny Turk', 'Molly Mormon'] 3 | print('Users:') 4 | 5 | for name in names: 6 | end = ' and\n' if name == names[-2] else '\n' 7 | 8 | print(' - %s' % name, end=end) 9 | 10 | -------------------------------------------------------------------------------- /units/python/4/exercise_1.py: -------------------------------------------------------------------------------- 1 | age = int(input('Enter age: ')) 2 | 3 | if age <= 0: 4 | print('Invalid age') 5 | elif age <= 1: 6 | print("You're an infant") 7 | elif age <= 12: 8 | print('You\'re just a kid.') 9 | elif age <= 19: 10 | print('You\'re a teenager.') 11 | elif age <= 45: 12 | print('You are adult now.') 13 | elif age <=59: 14 | print('You are middle-aged.') 15 | elif age <= 120: 16 | print('You are old now.') 17 | else: 18 | print('You\'re too old to still be alive.') 19 | 20 | 21 | -------------------------------------------------------------------------------- /units/python/4/exercise_4.py: -------------------------------------------------------------------------------- 1 | authorized_users = [ 2 | { 3 | 'name': 'John Doe', 4 | 'email': 'johndoe@example.com', 5 | 'password': 'aaa' 6 | }, 7 | { 8 | 'name': 'Admin', 9 | 'email': 'admin@example.com', 10 | 'password': 'admin' 11 | } 12 | ] 13 | 14 | def main(): 15 | email = input('Enter Email: ') 16 | password = input('Enter Password: ') 17 | 18 | print() 19 | 20 | (user_exists, login_sucess) = check_login(email, password) 21 | 22 | # If user doesn't exist then let him know. 23 | if user_exists == False: 24 | print('User with email {} does not exist in our system.'.format(email)) 25 | 26 | # If login_sucess is still false, show the error. 27 | if login_sucess == False: 28 | print('Access Denied') 29 | 30 | 31 | def check_login(email, password): 32 | login_sucess = False 33 | user_exists = False 34 | 35 | for user in authorized_users: 36 | # Check if the combination of email and password matches 37 | if email == user['email'] and password == user['password']: 38 | login_sucess = True 39 | print('User found:') 40 | print('Name: {}'.format(user['name'])) 41 | print('Email: {}'.format(user['email'])) 42 | break 43 | 44 | # But if the user's email exists 45 | elif email == user['email']: 46 | user_exists = True 47 | 48 | return (login_sucess, user_exists) 49 | 50 | # Start the program 51 | main() 52 | -------------------------------------------------------------------------------- /units/python/4/list_of_dicts.py: -------------------------------------------------------------------------------- 1 | data = [ 2 | { 3 | 'name': 'Kabir Baidhya', 4 | 'email': 'kabirbaidhya@gmail.com' 5 | }, 6 | { 7 | 'name': 'John Doe', 8 | 'email': 'johndoe@example.com' 9 | }, 10 | { 11 | 'name': 'John Doe', 12 | 'email': 'johndoe@example.com' 13 | }, 14 | { 15 | 'name': 'John Doe', 16 | 'email': 'johndoe@example.com' 17 | } 18 | ] 19 | 20 | for (i, item) in enumerate(data): 21 | print('\nUser %d' % (i + 1)) 22 | print('Name: %s' % item['name']) 23 | print('Email: %s' % item['email']) 24 | 25 | -------------------------------------------------------------------------------- /units/python/5/Functions and Lambdas - Presentation.md: -------------------------------------------------------------------------------- 1 | 4 | ###### Python 5 | Functions and Lambdas 6 | === 7 | 8 | # ![](../../../python-logo-200x200.png) 9 | 10 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 11 | 12 | --- 13 | 16 | # Reflections 17 | --- 18 | ## What we already know 19 | From the last session. 20 | 21 | 1. Data Types in Python 22 | 2. Conditionals and Loops 23 | 24 | 25 | Note: If you're not aware of these. Read them at https://github.com/kabirbaidhya/learn-python-django-web 26 | 27 | --- 28 | # Functions 29 | --- 30 | 33 | ### Functions 34 | 35 | A function is a block of code that performs a single action or performs some computation. 36 | 37 | Usually functions take in some input, process it and returns the output. 38 | 39 | --- 40 | ### Using Functions 41 | In programming use of functions do provide: 42 | - Modularity 43 | - Reusability 44 | - Maintainability 45 | - Separation of Concern 46 | - Better Code Organization 47 | 48 | --- 49 | ### Functions in Python 50 | In python we can define a function with the following syntax: 51 | ```python 52 | def function_name(): 53 | STATEMENTS 54 | ``` 55 | 56 | If the function needs to accept parameters then it will have following syntax: 57 | ```python 58 | def function_name(parameters): 59 | STATEMENTS 60 | ``` 61 | --- 62 | ### Example 1 63 | This could be an example of a function that computes sum of two numbers. 64 | ```python 65 | def sum(x, y): 66 | return x + y 67 | ``` 68 | --- 69 | ### Example 2 70 | And similarly this could be an example of a function which returns the maximum in between two numbers. 71 | 72 | ```python 73 | def max(a, b): 74 | if a > b: 75 | return a 76 | 77 | return b 78 | 79 | # Print maximum value 80 | print(max(5, 6)) 81 | ``` 82 | --- 83 | ### Example 3 84 | The earlier example can be done using the inline conditional operator like this: 85 | ```python 86 | def max(a, b): 87 | return a if a > b else b 88 | 89 | # Print maximum value 90 | print(max(5, 6)) 91 | ``` 92 | --- 93 | ### Example 4 94 | Function to print the fibonacci series. 95 | ```python 96 | def fib(n): 97 | a, b = 0, 1 98 | 99 | while a < n: 100 | print(a) 101 | (a, b) = (b, a + b) 102 | 103 | # Print the series 104 | fib(50) 105 | ``` 106 | --- 107 | ### Don't Forget 108 | 1. The colon `:`, which actually starts the function block. 109 | 2. Indentation, which is the part of syntax in python and a must have (unlike C-style languages where it's optional). 110 | 3. End of indent means end of the block. 111 | --- 112 | ### Naming Convention 113 | 114 | In python it's a community wide convention to use `snake_case` (i.e lowercase with underscores to separate words) for naming functions and variables. 115 | 116 | For example these could be some examples of good function names: 117 | ```python 118 | get_user_name() 119 | create_user() 120 | add_user() 121 | validate() 122 | ``` 123 | --- 124 | 125 | ### Default Arguments 126 | It's possible to set default arguments in python by assignning default values to parameters. 127 | 128 | They also act as optional parameters as the user can omit them. 129 | 130 | ```python 131 | def greet(message = 'Hello'): 132 | return message + ' World!' 133 | 134 | # Invoke this function 135 | print(greet()) # Hello World! 136 | print(greet('Hi')) # Hi World! 137 | ``` 138 | 139 | --- 140 | ### Function Invocation 141 | Calling/invoking the function is as simple as 142 | ```python 143 | sum(5, 6) 144 | ``` 145 | 146 | 147 | 148 | Do Remember: 149 | * Parentheses are the must haves, both during definition and invocation. 150 | * All parameters are passed by reference in Python. 151 | 152 | 153 | 154 | --- 155 | ### Positional Arguments 156 | Calling a function with positional argument means calling it by providing the arguments in the order they're defined as parameters in the function. 157 | 158 | For instance: 159 | ```python 160 | def sum(x, y, z = 0): 161 | return x + y + z 162 | 163 | 164 | sum(1, 2, 3) # 3 positional arguments 165 | sum(1, 5) # 2 positional arguments for x & y, z takes the default value 0 166 | ``` 167 | --- 168 | ### Keyword Arguments 169 | Functions can also be called using keyword arguments using the parameter names in the form `arg=value`. 170 | 171 | For instance: 172 | 173 | ```python 174 | def sum(x, y, z = 0): 175 | return x + y + z 176 | 177 | sum(x=1, y=2, z=3) # keyword arguments 178 | sum(y=5, z=1, x=4) # position of args doesn't matter here. 179 | sum(x=1, y=5) # 2 keyword arguments for x & y, z takes the default value 0 180 | ``` 181 | --- 182 | ### Combine both positional and keyword arguments 183 | You can use both the positional and keyword arguments like this: 184 | 185 | 186 | ```python 187 | sum(1, y=3, z=5) 188 | sum(5, 6, z=10) 189 | sum(10, y=2) 190 | ``` 191 | 192 | But ensure that keyword arguments do follow positional arguments and same arguments aren't provided more than once. 193 | 194 | --- 195 | ### The `return` statement 196 | Returns a value from inside the function to the caller of the function. 197 | 198 | For example: 199 | ```python 200 | def foo(): 201 | # This function returns the value 'Bar' 202 | return 'Bar' 203 | 204 | 205 | def baz(): 206 | # This function returns nothing 207 | return 208 | 209 | a = foo() # a = 'Bar' 210 | b = baz() # b = None 211 | ``` 212 | 213 | --- 214 | # Using the `main()` function 215 | --- 216 | ## Using the `main()` function 217 | 218 | Although python gives you full flexibility to structure your code as you like. It is recommended that you make your code organized and modular. 219 | 220 | In many programming languages they strictly enforce you to define a `main()` function and don't allow to write code outside a function. 221 | a 222 | Python doesn't force you to do the same, but it's a good practice to have something like `main()` function to keep your code organized. 223 | 224 | --- 225 | ### For Example 226 | 227 | ```python 228 | def fib(n): 229 | a, b = 0, 1 230 | 231 | while a < n: 232 | print(a) 233 | (a, b) = (b, a + b) 234 | 235 | 236 | def main(): 237 | n = int(input('N = ')) 238 | 239 | # Print the series upto n 240 | fib(n) 241 | 242 | 243 | main() 244 | ``` 245 | --- 246 | 249 | # Lambdas 250 | --- 251 | 254 | ### Lambda Expressions 255 | A lambda is a short anonymous function that can be used in expressions. 256 | 257 | For example: Lamda expression for computing the product of two numbers 258 | ```python 259 | c = (lambda a, b: a * b)(2, 5) 260 | ``` 261 | Or 262 | ```python 263 | func = lambda a, b: a * b 264 | c = func(2, 5) 265 | ``` 266 | --- 267 | ### Use Cases 268 | Lambda functions are pretty handy tool when you make use of a lot of higher order functions and closures. Or need to use functions in expressions or pass them to other functions as arguments. 269 | 270 | Especially while doing functional programming, lambdas become pretty common. 271 | 272 | --- 273 | ### Example 5 274 | A very basic use case of lambda functions. 275 | 276 | ```python 277 | # A function that returns another function 278 | # to add a number with another number 279 | def get_adder_of(a = 1): 280 | return lambda x: x + a 281 | 282 | add_five = get_adder_of(5) 283 | add_two = get_adder_of(2) 284 | add_seven = get_adder_of(7) 285 | 286 | print('10 + 5 = %d' % add_five(10)) 287 | print('8 + 2 = %d' % add_two(8)) 288 | print('8 + 7 = %d' % add_seven(8)) 289 | ``` 290 | --- 291 | ### Example 6 292 | Using map() function and lambda to get a new list of squares of the original list. 293 | 294 | ```python 295 | my_list = [1, 2, 3, 4, 5] 296 | 297 | squares = list(map(lambda x: x ** 2, my_list)) 298 | 299 | # The same thing could be achieved using list comprehension. 300 | squares_2 = [x ** 2 for x in my_list] 301 | 302 | print(squares) 303 | print(squares_2) 304 | ``` 305 | --- 306 | 309 | # Exercises 310 | --- 311 | #### Do all the exercises we've done so far in previous lessons using functions to wrap up the logic. 312 | --- 313 | 314 | ### Guidelines 315 | 1. Write the primary logic of the program using function(s). 316 | 2. Do not invoke the functions directly. Use a `main()` function instead. 317 | 3. Protip Read user inputs and print the outputs in the `main()` function keeping just the core logic in the other functions. 318 | 319 | --- 320 | 323 | # Read More? 324 | --- 325 | 328 | ### Links 329 | 1. http://www.cs.utah.edu/~germain/PPS/Topics/functions.html 330 | 2. https://docs.python.org/3/tutorial/controlflow.html 331 | 3. https://www.tutorialspoint.com/python/python_functions.htm 332 | 4. http://stackoverflow.com/questions/9450656/positional-argument-v-s-keyword-argument 333 | --- 334 | 337 | ###### This slide was a part of course 338 | #### Python, Django & Web Development 339 | ###### [github.com/kabirbaidhya/learn-python-django-web](https://github.com/kabirbaidhya/learn-python-django-web) 340 | --- 341 | # Thank You 342 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 343 | ###### kabirbaidhya@gmail.com 344 | 345 | -------------------------------------------------------------------------------- /units/python/5/Functions and Lambdas.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/5/Functions and Lambdas.pdf -------------------------------------------------------------------------------- /units/python/5/example_4.py: -------------------------------------------------------------------------------- 1 | def fib(n): 2 | a, b = 0, 1 3 | 4 | while a < n: 5 | print(a) 6 | (a, b) = (b, a + b) 7 | 8 | fib(9999999) 9 | -------------------------------------------------------------------------------- /units/python/5/example_5.py: -------------------------------------------------------------------------------- 1 | def get_adder_of(a = 1): 2 | return lambda x: x + a 3 | 4 | add_five = get_adder_of(5) 5 | add_two = get_adder_of(2) 6 | add_seven = get_adder_of(7) 7 | 8 | print('10 + 5 = %d' % add_five(10)) 9 | print('8 + 2 = %d' % add_two(8)) 10 | print('8 + 7 = %d' % add_seven(8)) 11 | 12 | -------------------------------------------------------------------------------- /units/python/5/functions-and-lambdas.md: -------------------------------------------------------------------------------- 1 | Functions and Lambdas 2 | ============================ 3 | 4 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [Slides](https://speakerdeck.com/kabirbaidhya/python-functions-and-lambdas) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/python/4/conditionals-and-loops.md) | [Next →](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/python/6/exception-handling.md) 5 | 6 | 7 | ## Functions 8 | A function is a block of code that performs a single action or performs some computation. Usually functions take in some input, process it and returns the output. 9 | 10 | Functions makes our code organized as it encapsulates a task or an action by wrapping up the actual logic or statements inside it and by abstracting the internal complexities and details to perform the task. 11 | 12 | In programming use of functions provide: 13 | - Modularity 14 | - Reusability 15 | - Maintainability 16 | - Separation of Concern 17 | - Better Code Organization 18 | 19 | ## Functions in Python 20 | 21 | In python we can define a function with the following syntax: 22 | ```python 23 | def function_name(): 24 | STATEMENTS 25 | ``` 26 | 27 | If the function needs to accept parameters then it will have following syntax: 28 | ```python 29 | def function_name(parameters): 30 | STATEMENTS 31 | ``` 32 | 33 | And as already stated before about blocks and indentation, **don't forget:** 34 | 1. The colon `:`, which actually starts the function block. 35 | 2. Indentation, which is the part of syntax in python and a must have (unlike C-style languages where it's optional). 36 | 3. End of indent means end of the block. 37 | 38 | #### Naming Convention 39 | In python it's a community wide convention to use `snake_case` (i.e lowercase with underscores to separate words) for naming functions and variables. 40 | 41 | For example these could be some examples of good function names: 42 | ```python 43 | get_user_name() 44 | create_user() 45 | add_user() 46 | validate() 47 | ``` 48 | 49 | #### Example 1 50 | This could be an example of a function that computes sum of two numbers. 51 | ```python 52 | def sum(x, y): 53 | return x + y 54 | ``` 55 | 56 | #### Example 2 57 | And similarly this could be an example of a function which returns the maximum in between two numbers. 58 | 59 | ```python 60 | def max(a, b): 61 | if a > b: 62 | return a 63 | 64 | return b 65 | 66 | # Print maximum value 67 | print(max(5, 6)) 68 | ``` 69 | 70 | #### Example 3 71 | The earlier example can be done using the inline conditional operator like this: 72 | ```python 73 | def max(a, b): 74 | return a if a > b else b 75 | 76 | # Print maximum value 77 | print(max(5, 6)) 78 | ``` 79 | 80 | #### Example 4 81 | Function to print the fibonacci series. 82 | ```python 83 | def fib(n): 84 | a, b = 0, 1 85 | 86 | while a < n: 87 | print(a) 88 | (a, b) = (b, a + b) 89 | 90 | # Print the series 91 | fib(50) 92 | ``` 93 | 94 | ## Default Arguments 95 | Python allows you to set default values for arguments to use in case when the user doesn't provide any value for these arguments while calling the function. 96 | 97 | Assigning default values make the arguments act as optional parameters as they user can omit them while calling the function. 98 | 99 | For instance: 100 | ```python 101 | def greet(message = 'Hello'): 102 | return message + ' World!' 103 | 104 | # Invoke this function 105 | print(greet()) # Hello World! 106 | print(greet('Hi')) # Hi World! 107 | ``` 108 | 109 | ## Function Invocation 110 | Calling/invoking the function is as simple as 111 | ```python 112 | sum(5, 6) 113 | ``` 114 | 115 | Parentheses are the must haves when it comes to functions, both during definition and invocation. 116 | Not all functions do have parameters. But when they do, you need to invoke them with arguments inside parentheses as well. 117 | 118 | It should be noted that all parameters (arguments) are passed by reference in Python. 119 | 120 | In python, you can call a function using positional arguments, keyword arguments or a combination of both. 121 | 122 | ### Positional Arguments 123 | Calling a function with positional argument means calling it by providing the arguments in the order they're defined as parameters in the function. 124 | 125 | For instance: 126 | ```python 127 | def sum(x, y, z = 0): 128 | return x + y + z 129 | 130 | # Call using positional arguments 131 | sum(1, 2, 3) # 3 positional arguments 132 | sum(1, 5) # 2 positional arguments for x & y, z takes the default value 0 133 | ``` 134 | 135 | ### Keyword Arguments 136 | Functions can also be called using keyword arguments using the parameter names in the form `arg=value`. 137 | 138 | For instance: 139 | 140 | ```python 141 | def sum(x, y, z = 0): 142 | return x + y + z 143 | 144 | # Call using keyword arguments 145 | sum(x=1, y=2, z=3) # keyword arguments 146 | sum(y=5, z=1, x=4) # position of args doesn't matter here. 147 | sum(x=1, y=5) # 2 keyword arguments for x & y, z takes the default value 0 148 | ``` 149 | 150 | ### Combine both positional and keyword arguments 151 | You can call functions using both the positional and keyword arguments. But you need to ensure keyword arguments do follow positional arguments. No argument should receive a value more than once. 152 | 153 | ```python 154 | sum(1, y=3, z=5) 155 | sum(5, 6, z=10) 156 | sum(10, y=2) 157 | ``` 158 | 159 | ## The `return` statement 160 | The `return` keyword allows you to return a value from inside the function to the caller of the function. The use of `return` inside a function also halts the excecution and returns from the function immediately. 161 | 162 | You can either return a value or return nothing from the function. 163 | 164 | For example: 165 | ```python 166 | def foo(): 167 | # This function returns the value 'Bar' 168 | return 'Bar' 169 | 170 | 171 | def baz(): 172 | # This function returns nothing 173 | return 174 | 175 | a = foo() # a = 'Bar' 176 | b = baz() # b = None 177 | ``` 178 | 179 | ## Using the `main()` function 180 | Although python gives you full flexibility to structure your code as you like. It is recommended that you make your code organized and modular. And you can make use of functions for that. 181 | 182 | While you already do write functions for each of the logical actions, tasks or computations you do, you still need to write some code to trigger or kickstart them when your program starts. In many programming languages like C, C++, java, go, etc. they strictly enforce you to define a `main()` function for that particular purpose. Although python doesn't enforce you to do the same, it is actually a good practice to do have something like a `main()` function to keep your code more readable and organized. 183 | 184 | For instance: 185 | You can do the fibonacci series from our earlier example like this: 186 | 187 | ```python 188 | def fib(n): 189 | a, b = 0, 1 190 | 191 | while a < n: 192 | print(a) 193 | (a, b) = (b, a + b) 194 | 195 | 196 | def main(): 197 | n = int(input('N = ')) 198 | 199 | # Print the series upto n 200 | fib(n) 201 | 202 | 203 | # Now this is what triggers everything 204 | # when the program starts. 205 | main() 206 | ``` 207 | 208 | ## Lambdas 209 | A lambda is a short anonymous function that can be used in expressions and easily passed as arguments to other function calls. 210 | 211 | For example: 212 | 213 | This is a simple function that computes a product of two numbers: 214 | ```python 215 | def product(a, b): 216 | return a * b 217 | 218 | c = product(2, 5) 219 | ``` 220 | Now you can do the same using `lambda` function as well. 221 | ```python 222 | c = (lambda a, b: a * b)(2, 5) 223 | ``` 224 | This creates an anonymous function on the fly to compute the product and invokes it immediately with the arguments 2 and 5. 225 | If this is hard for you to understand. You can do it like this as well. 226 | ```python 227 | func = lambda a, b: a * b 228 | c = func(2, 5) 229 | ``` 230 | Here we're doing the exact same thing; the only difference is that we're using an intermediate variable `func` to store the lambda function and use it to compute the value of c in the next line. 231 | 232 | Lambda functions are pretty handy tool when you make use of a lot of higher order functions and closures. Or need to use functions in expressions or pass them to other functions as arguments. 233 | 234 | Especially while doing functional programming, lambdas become pretty common. 235 | 236 | #### Example 5 237 | This program will demonstrate a very basic use case of lambda functions. 238 | 239 | ```python 240 | # A function that returns another function 241 | # to add a number with another number 242 | def get_adder_of(a = 1): 243 | return lambda x: x + a 244 | 245 | add_five = get_adder_of(5) 246 | add_two = get_adder_of(2) 247 | add_seven = get_adder_of(7) 248 | 249 | print('10 + 5 = %d' % add_five(10)) 250 | print('8 + 2 = %d' % add_two(8)) 251 | print('8 + 7 = %d' % add_seven(8)) 252 | ``` 253 | 254 | #### Example 6 255 | This is another use case of a lambda function. 256 | 257 | ```python 258 | my_list = [1, 2, 3, 4, 5] 259 | 260 | # Using map() function and lambda to 261 | # get a new list of squares of the original list. 262 | squares = list(map(lambda x: x ** 2, my_list)) 263 | # The same thing could be achieved using list comprehension. 264 | squares_2 = [x ** 2 for x in my_list] 265 | 266 | print(squares) 267 | print(squares_2) 268 | ``` 269 | 270 | ## Exercises 271 | Do all the exercises we've done so far in previous lessons using functions to wrap up the logic. 272 | 273 | Guidelines: 274 | 1. Write the primary logic of the program using function(s). 275 | 2. Do not invoke the functions directly. Use a `main()` function instead. 276 | 3. Protip Read user inputs and print the outputs in the `main()` function keeping just the core logic in the other functions. 277 | 278 | ## Read More? 279 | Want to read more? Go through these links. 280 | 1. http://www.cs.utah.edu/~germain/PPS/Topics/functions.html 281 | 2. https://docs.python.org/3/tutorial/controlflow.html 282 | 3. https://www.tutorialspoint.com/python/python_functions.htm 283 | 4. http://stackoverflow.com/questions/9450656/positional-argument-v-s-keyword-argument 284 | -------------------------------------------------------------------------------- /units/python/6/Exception Handling - Presentation.md: -------------------------------------------------------------------------------- 1 | 4 | ###### Python 5 | Errors and Exception Handling 6 | ================== 7 | 8 | # ![](../../../python-logo-200x200.png) 9 | 10 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 11 | 12 | --- 13 | 16 | # Reflections 17 | --- 18 | ## What we already know 19 | From the last session. 20 | 21 | 1. Python basics, conditionals and Loops 22 | 2. Functions 23 | 24 | Note: If you're not aware of these. Read them at https://github.com/kabirbaidhya/learn-python-django-web 25 | 26 | --- 27 | # Exceptions 28 | --- 29 | 32 | ### Exceptions 33 | 34 | When there are errors in your syntax, your code won't run, that is for sure. But even if your syntax is 100% correct and runs fine, there could be cases when you get errors during the runtime of your program. 35 | 36 | These errors that get triggered in the runtime are called **Exceptions**. 37 | 38 | --- 39 | 42 | ### For instance 43 | Consider this example, when you're trying to divide two numbers, both received from the user input. 44 | 45 | ```python 46 | a = float(input('First Number: ')) 47 | b = float(input('Second Number: ')) 48 | 49 | result = a / b 50 | ``` 51 | 52 | It would raise a runtime error `ZeroDivisionError` and the program would halt. 53 | 54 | --- 55 | # Handling Exceptions 56 | --- 57 | ### Handling Exceptions 58 | 59 | We can handle exceptions using `try` block. 60 | 61 | Handling exceptions ensures that the program still continues to run regardless of the exceptions. 62 | 63 | 64 | ```python 65 | a = float(input('First Number: ')) 66 | b = float(input('Second Number: ')) 67 | 68 | try: 69 | result = a / b 70 | except ZeroDivisionError: 71 | print('Error: Division by Zero') 72 | ``` 73 | 74 | --- 75 | ### Improved Example 76 | 77 | 78 | 79 | ```python 80 | while True: 81 | a = float(input('First Number: ')) 82 | b = float(input('Second Number: ')) 83 | 84 | try: 85 | result = a / b 86 | print('Result = {}'.format(result)) 87 | 88 | except ZeroDivisionError: 89 | print('Error: Division by Zero') 90 | 91 | try_again = input('\nTry Again (Y/N)? ') 92 | 93 | # If the user doesn't want to try again exit the loop. 94 | if try_again.upper() != 'Y': 95 | break 96 | 97 | print() 98 | 99 | # Program will exit finally 100 | print('Good Bye!') 101 | ``` 102 | 103 | 104 | 105 | --- 106 | ### The `try` statement 107 | You've already seen how and why we use `try` statement. Let's get into details about how it actually works. 108 | 109 | **Syntax** 110 | 111 | ```python 112 | try: 113 | STATEMENTS 114 | except SomeException: 115 | # Code to handle exception 116 | ``` 117 | --- 118 | ### How it works? 119 | 120 | 121 | Firstly the statements inside the `try` block are executed. If any statement causes exceptions the rest of the code in the block are skipped. 122 | 123 | If the raised exception is there in the `except` clause, then that particular except block is executed. 124 | 125 | In case the raised exception is not in the `except` clause it will propagate to the higher level. If it couldn't find any handlers even after reaching the highest level, the program terminates with that exception. 126 | 127 | If no exception occurs inside the `try` block, the `except` blocks are skipped. 128 | 129 | 130 | 131 | --- 132 | ### Example 1 133 | Consider the following example we did in our previous lesson. 134 | 135 | ```python 136 | n, sum = 0, 0 137 | 138 | while n < 5: 139 | value = input('Enter Number %s: ' % (n + 1)) 140 | sum = sum + float(value) 141 | n += 1 142 | 143 | print('Sum = %.2f' % sum) 144 | ``` 145 | 146 | This program expects numeric values from the user. 147 | 148 | --- 149 | ### Example 1 - Error 150 | 151 | Go and try it with some input like `abx`, `xyz` etc. 152 | 153 | You'll get an error like this: 154 | ```plain 155 | Traceback (most recent call last): 156 | File "units/python/4/example_5.py", line 7, in 157 | sum = sum + float(value) 158 | ValueError: could not convert string to float: 'abc' 159 | ``` 160 | --- 161 | ### Example 1 - Exception Handled 162 | Let's handle this error now. 163 | 164 | ``` 165 | n, sum = 0, 0 166 | 167 | while n < 5: 168 | value = input('Enter Number %s: ' % (n + 1)) 169 | 170 | try: 171 | value = float(value) 172 | sum = sum + value 173 | n += 1 174 | 175 | except ValueError: 176 | print('Invalid Input. Please enter a numeric value.\n') 177 | 178 | print('\nSum = %.2f' % sum) 179 | ``` 180 | --- 181 | # Possible Variations 182 | #### of `try...except` statements 183 | --- 184 | #### Multiple `except` blocks 185 | There could be any number of `except` clauses following a `try` statement. 186 | 187 | ```python 188 | try: 189 | STATEMENTS 190 | except SomeException: 191 | # Code to handle exception 192 | except SomeOtherException: 193 | # Code to handle exception 194 | except AndAnotherException: 195 | # Code to handle exception 196 | ``` 197 | --- 198 | #### Multiple exceptions in one `except` clause 199 | A single `except` clause can also accept multiple exceptions as parenthesized tuple. 200 | 201 | ```python 202 | try: 203 | STATEMENTS 204 | except (RuntimeError, TypeError, NameError): 205 | # Code to handle exception 206 | ``` 207 | 208 | --- 209 | #### The exception instance 210 | You can get the instance of the actual error or exception object using the following syntax. 211 | 212 | ```python 213 | try: 214 | STATEMENTS 215 | except SomeException as e: 216 | # Do something with this `e` 217 | ``` 218 | --- 219 | ## Raising Exceptions 220 | 221 | We can use the `raise` keyword to raise exceptions like this: 222 | ```python 223 | raise Exception('Hey, this was a test exception.') 224 | raise ValueError('Hey, this was another exception.') 225 | ``` 226 | 227 | The only argument required for the `raise` keyword is the exception itself. This could be either an exception instance or exception class(a class that derives from Exception). 228 | 229 | --- 230 | ### Built-in Exceptions 231 | There are various types of exceptions in python. Check [the official docs](https://docs.python.org/3/library/exceptions.html) to know about the Built-in Exceptions in python. 232 | 233 | --- 234 | 237 | # Exercises 238 | --- 239 | ### Exercise 1 240 | ###### Improvements on the program to find the area of circle. 241 | - Move the logic to compute the area to a function 242 | - Handle runtime exceptions 243 | - Ability to try again in case of invalid input. 244 | 245 | --- 246 | ### Exercise 2 247 | ###### Improvements on the program we did to compute the age of the user by checking his date of birth. 248 | - Refactor it using functions. 249 | - Handle runtime exceptions. 250 | - Ability to try again in case of invalid input. 251 | 252 | --- 253 | ### Exercise 3 254 | ###### Improvements on the program to parse out the value of `m` and `c` from the equation of line `y = mx + c` 255 | - Refactor the logic for parsing the equation to a function 256 | - Take two user inputs: equation of two lines 257 | - Write a function to get the intersection of two lines 258 | - Write a function to get the angle between two lines 259 | - Print angle between two lines and the point of intersection 260 | - Print if they're parallel or perpendicular to each other 261 | - Handle runtime exceptions. 262 | - Ability to try again in case of invalid input. 263 | 264 | --- 265 | 266 | ### Exersise 4 267 | ###### Program to ask for a filename and read the contents of the file and print it on the screen. Ensure there are no unhandled exceptions. 268 | 269 | --- 270 | 273 | # Read More? 274 | --- 275 | 278 | ### Links 279 | Want to read more? Go through these links. 280 | 1. https://docs.python.org/3/tutorial/errors.html 281 | 2. https://wiki.python.org/moin/HandlingExceptions 282 | 3. https://docs.python.org/3/library/exceptions.html 283 | 4. http://stackoverflow.com/questions/730764/try-except-in-python-how-do-you-properly-ignore-exceptions 284 | 5. https://www.tutorialspoint.com/python/python_exceptions.htm 285 | 286 | --- 287 | 290 | ###### This slide was a part of course 291 | #### Python, Django & Web Development 292 | ###### [github.com/kabirbaidhya/learn-python-django-web](https://github.com/kabirbaidhya/learn-python-django-web) 293 | --- 294 | # Thank You 295 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 296 | ###### kabirbaidhya@gmail.com 297 | 298 | -------------------------------------------------------------------------------- /units/python/6/Exception Handling.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/6/Exception Handling.pdf -------------------------------------------------------------------------------- /units/python/6/example_1.py: -------------------------------------------------------------------------------- 1 | n, sum = 0, 0 2 | 3 | while n < 5: 4 | value = input('Enter Number %s: ' % (n + 1)) 5 | 6 | try: 7 | value = float(value) 8 | sum = sum + value 9 | n += 1 10 | except ValueError: 11 | print('Invalid Input. Please enter a numeric value.\n') 12 | 13 | print('\nSum = %.2f' % sum) 14 | 15 | -------------------------------------------------------------------------------- /units/python/6/exception-handling.md: -------------------------------------------------------------------------------- 1 | Exception Handling 2 | ============================ 3 | 4 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [Slides](https://speakerdeck.com/kabirbaidhya/python-exception-handling) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/python/5/functions-and-lambdas.md) | [Next →](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/python/7/modules-and-packages.md) 5 | 6 | ## Exceptions 7 | When there are errors in your syntax, your code won't run, that is for sure. But even if your syntax is 100% correct and runs fine, there could be cases when you get errors during the runtime of your program. These errors that get triggered in the runtime are called **Exceptions**. 8 | 9 | For instance consider this example, when you're trying to divide two numbers, both received from the user input. 10 | 11 | ```python 12 | a = float(input('First Number: ')) 13 | b = float(input('Second Number: ')) 14 | 15 | result = a / b 16 | ``` 17 | As the user can provide any values for the inputs, guess what happens when he provides the second value as zero. Obviously, it would throw an error. Yes, it would throw an error in the runtime named `ZeroDivisionError` and the program would halt. 18 | 19 | There might me numerous cases like this when we detect errors only in the runtime which obviously causes unexpected termination of program with error. 20 | 21 | We need to handle exceptions because unexpected termination of our program at the runtime due to some random error is certainly not what we want. 22 | 23 | ## Handling Exceptions 24 | We can handle exceptions and runtime errors in python using `try` block. 25 | 26 | Something like this: 27 | 28 | ```python 29 | a = float(input('First Number: ')) 30 | b = float(input('Second Number: ')) 31 | 32 | try: 33 | result = a / b 34 | except ZeroDivisionError: 35 | print('Error: Division by Zero') 36 | ``` 37 | 38 | Handling exceptions ensures that the program still continues to run regardless of the exceptions. To better understand this, consider the following improvement to the program where user can try again and the program continues to run until the user chooses to exit. 39 | 40 | ```python 41 | while True: 42 | a = float(input('First Number: ')) 43 | b = float(input('Second Number: ')) 44 | 45 | try: 46 | result = a / b 47 | print('Result = {}'.format(result)) 48 | 49 | except ZeroDivisionError: 50 | print('Error: Division by Zero') 51 | 52 | try_again = input('\nTry Again (Y/N)? ') 53 | 54 | # If the user doesn't want to try again exit the loop. 55 | if try_again.upper() != 'Y': 56 | break 57 | 58 | print() 59 | 60 | # Program will exit finally 61 | print('Good Bye!') 62 | ``` 63 | 64 | ## The `try` statement 65 | You've already seen how and why we use `try` statement. Let's get into details about how it actually works. 66 | 67 | **Syntax** 68 | 69 | ```python 70 | try: 71 | STATEMENTS 72 | except SomeException: 73 | # Code to handle exception 74 | ``` 75 | Firstly the statements inside the `try` block are executed one by one. If any of the statement causes any exceptions the rest of the code in the block are skipped. 76 | 77 | It will check if the exception which is raised is there in the `except` clause or not. If yes, then that particular except block is executed. 78 | 79 | In case the exception raised is not in the `except` clause it will propagate to the higher level. If that particular exception has no handler even after reaching the highest level then the program terminates with that exception with it's message shown. 80 | 81 | If no exception occurs inside the `try` block after execution of the statements in the code block, the `except` blocks are skipped. 82 | 83 | #### Example 1 84 | Consider the following example we did in our previous lesson. 85 | 86 | ```python 87 | n, sum = 0, 0 88 | 89 | while n < 5: 90 | value = input('Enter Number %s: ' % (n + 1)) 91 | sum = sum + float(value) 92 | n += 1 93 | 94 | print('Sum = %.2f' % sum) 95 | ``` 96 | 97 | This program expects numeric values from the user. Guess what would happen if the user supplies a non-numeric value in the prompt. Go and try it with some input like `abx`, `xyz` etc. 98 | 99 | You'll get an error like this: 100 | ```plain 101 | Traceback (most recent call last): 102 | File "units/python/4/example_5.py", line 7, in 103 | sum = sum + float(value) 104 | ValueError: could not convert string to float: 'abc' 105 | ``` 106 | 107 | Now here's the improved version of this program where we've handled this exception. 108 | ```python 109 | n, sum = 0, 0 110 | 111 | while n < 5: 112 | value = input('Enter Number %s: ' % (n + 1)) 113 | 114 | try: 115 | value = float(value) 116 | sum = sum + value 117 | n += 1 118 | except ValueError: 119 | print('Invalid Input. Please enter a numeric value.\n') 120 | 121 | print('\nSum = %.2f' % sum) 122 | ``` 123 | 124 | ### Possible Variations 125 | 126 | #### Multiple `except` blocks 127 | There could be any number of `except` clauses following a `try` statement. 128 | 129 | ```python 130 | try: 131 | STATEMENTS 132 | except SomeException: 133 | # Code to handle exception 134 | except SomeOtherException: 135 | # Code to handle exception 136 | except AndAnotherException: 137 | # Code to handle exception 138 | ``` 139 | 140 | #### Multiple exceptions in one `except` clause 141 | A single `except` clause can also accept multiple exceptions as parenthesized tuple. 142 | 143 | ```python 144 | try: 145 | STATEMENTS 146 | except (RuntimeError, TypeError, NameError): 147 | # Code to handle exception 148 | ``` 149 | 150 | #### The exception instance 151 | You can get the instance of the actual error or exception object using the following syntax. 152 | 153 | ```python 154 | try: 155 | STATEMENTS 156 | except SomeException as e: 157 | # Do something with this `e` 158 | ``` 159 | ## Raising Exceptions 160 | We might need to raise exceptions ourselves when something unexpected happens in our program. 161 | 162 | We can use the `raise` keyword to raise exceptions like this: 163 | ```python 164 | raise Exception('Hey, this was a test exception.') 165 | raise ValueError('Hey, this was another exception.') 166 | ``` 167 | 168 | The only argument required for the `raise` keyword is the exception itself. This could be either an exception instance or exception class(a class that derives from Exception). 169 | 170 | ## Built-in Exceptions 171 | There are various types of exceptions in python. Check [the official docs](https://docs.python.org/3/library/exceptions.html) to know about the Built-in Exceptions in python. 172 | 173 | ## Exercises 174 | 1. Improvements on the program to find the area of circle. 175 | - Move the logic to compute the area to a function 176 | - Handle runtime exceptions 177 | - Ability to try again in case of invalid input. 178 | 179 | 2. Improvements on the program we did to compute the age of the user by checking his date of birth. 180 | - Refactor it using functions. 181 | - Handle runtime exceptions. 182 | - Ability to try again in case of invalid input. 183 | 184 | 3. Improvements on the program to parse out the value of `m` and `c` from the equation of line `y = mx + c` 185 | - Refactor the logic for parsing the equation to a function 186 | - Take two user inputs: equation of two lines 187 | - Write a function to get the intersection of two lines 188 | - Write a function to get the angle between two lines 189 | - Print angle between two lines and the point of intersection 190 | - Print if they're parallel or perpendicular to each other 191 | - Handle runtime exceptions. 192 | - Ability to try again in case of invalid input. 193 | 194 | 4. Program to ask for a filename and read the contents of the file and print it on the screen. Ensure there are no unhandled exceptions. 195 | 196 | 197 | ## Read More? 198 | Want to read more? Go through these links. 199 | 1. https://docs.python.org/3/tutorial/errors.html 200 | 2. https://wiki.python.org/moin/HandlingExceptions 201 | 3. https://docs.python.org/3/library/exceptions.html 202 | 4. http://stackoverflow.com/questions/730764/try-except-in-python-how-do-you-properly-ignore-exceptions 203 | 5. https://www.tutorialspoint.com/python/python_exceptions.htm 204 | -------------------------------------------------------------------------------- /units/python/6/exercise_3.py: -------------------------------------------------------------------------------- 1 | 2 | import math 3 | 4 | 5 | def parse_line(equation): 6 | """ 7 | Parses the given equation of line in y = mx + c, and returns 8 | the values of m and c. 9 | """ 10 | # Split the equation with '=' into LHS and RHS. 11 | rhs = equation.split('=')[1] 12 | # Split the RHS into two parts 'mx' and 'c' with '+' operator. 13 | parts = rhs.split('+') 14 | # Get the value of 'm' from the first part, 'mx'. 15 | m = parts[0].replace('x', '').strip() 16 | # Get the value of 'c' from the second part. 17 | c = parts[1].strip() 18 | 19 | return (float(m), float(c)) 20 | 21 | 22 | def get_intersection(line1, line2): 23 | """ 24 | Calculates the intersection point of two lines given by their 25 | parsed tuples each containing slope & y-intercept. 26 | """ 27 | (m1, c1) = line1 28 | (m2, c2) = line2 29 | 30 | try: 31 | # Get the point of intersection 32 | x = (c1 - c2) / (m2 - m1) 33 | # And, as we have y = mx + c 34 | y = m1 * x + c1 35 | return (x, y) 36 | except ZeroDivisionError: 37 | # If we get the ZeroDivisionError 38 | # this means slope of the lines are equal 39 | # which means they're parallel and have no intersection point. 40 | return None 41 | 42 | 43 | def get_angle(line1, line2): 44 | """ 45 | Calculates the angle between two lines (in Degrees) using their 46 | parsed tuples each containing slope & y-intercept 47 | """ 48 | 49 | (m1, c1) = line1 50 | (m2, c2) = line2 51 | 52 | denominator = 1.0 + m1 * m2 53 | 54 | # If this part of the expression results to zero 55 | # then it implies the angle between the lines is 90 degrees. 56 | if denominator == 0: 57 | return 90.0 58 | 59 | angle_radian = math.atan((m1 - m2) / denominator) 60 | 61 | return angle_radian * (180 / math.pi) 62 | 63 | 64 | def get_lines_relation(angle): 65 | if angle == 0: 66 | return 'parallel' 67 | elif angle == 90: 68 | return 'perpendicular' 69 | 70 | 71 | def run(): 72 | """ 73 | The actual program that runs. 74 | """ 75 | print('Enter equations of lines in y = mx + c form:\n') 76 | 77 | try: 78 | # Get the equations of two lines from the user. 79 | equation1 = input('Line 1: ') 80 | equation2 = input('Line 2: ') 81 | 82 | # Parse the two equations of two lines. 83 | line1 = parse_line(equation1) 84 | line2 = parse_line(equation2) 85 | 86 | # Print the intersection point. 87 | point = get_intersection(line1, line2) 88 | print('\nIntersection Point = {}'.format(point)) 89 | 90 | # Angle between lines. 91 | angle = get_angle(line1, line2) 92 | print('Angle between lines = {} Degrees'.format(angle)) 93 | 94 | # Relation in between lines i.e parallel or perpendicular. 95 | relation = get_lines_relation(angle) 96 | if not relation is None: 97 | print('The lines are {}'.format(relation)) 98 | 99 | except (IndexError, ValueError): 100 | print( 101 | '\nError parsing the equation of lines. ' + 102 | 'Please provide the equation in `y = mx + c` form.' 103 | ) 104 | 105 | 106 | def main(): 107 | """ 108 | The main function that actually executes the program. 109 | """ 110 | 111 | while True: 112 | run() 113 | try_again = input('\nTry Again (Y/N)? ') 114 | 115 | # If the user doesn't wants to try again, exit. 116 | if try_again.upper() != 'Y': 117 | break 118 | 119 | 120 | # Run the program 121 | main() 122 | -------------------------------------------------------------------------------- /units/python/6/handling_exceptions.py: -------------------------------------------------------------------------------- 1 | a = int(input('First Number: ')) 2 | b = int(input('Second Number: ')) 3 | 4 | try: 5 | result = a / b 6 | except ZeroDivisionError: 7 | print('Error: Division by Zero') 8 | 9 | -------------------------------------------------------------------------------- /units/python/6/handling_exceptions_improved.py: -------------------------------------------------------------------------------- 1 | while True: 2 | a = float(input('First Number: ')) 3 | b = float(input('Second Number: ')) 4 | 5 | try: 6 | result = a / b 7 | print('Result = {}'.format(result)) 8 | 9 | except ZeroDivisionError: 10 | print('Error: Division by Zero') 11 | 12 | try_again = input('\nTry Again (Y/N)? ') 13 | 14 | # If the user doesn't want to try again exit the loop. 15 | if try_again.upper() != 'Y': 16 | break 17 | 18 | print() 19 | 20 | # Program will exit finally 21 | print('Good Bye!') 22 | 23 | -------------------------------------------------------------------------------- /units/python/7/Modules and Packages - Presentation.md: -------------------------------------------------------------------------------- 1 | 4 | ###### Python 5 | Modules and Packages 6 | ================== 7 | 8 | # ![](../../../python-logo-200x200.png) 9 | 10 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 11 | 12 | --- 13 | 16 | # Reflections 17 | --- 18 | ### So far, 19 | We've covered all these things 20 | 21 | 1. Python Basics, Conditionals and Loops 22 | 2. Functions and Exception Handling 23 | 24 | Note: If you're not aware of these. Read them at https://github.com/kabirbaidhya/learn-python-django-web 25 | 26 | --- 27 | # Modules 28 | --- 29 | 32 | ### What are Modules? 33 | 34 | Modules in Python are nothing just plain python files with `.py` extension that may contain and expose a set of definitions be it functions, classes, variables, etc. 35 | 36 | Definitions from one module can be imported to other modules and so on which helps in code reusability. 37 | 38 | You can use `import` statement to import a module or the definitions from a module in another module. 39 | 40 | --- 41 | 42 | ### What modules offer? 43 | - Namespacing - avoid naming colisions of definitions 44 | - Portability 45 | - Even better code reusability 46 | - Better Code Organization 47 | - Modularity - Of Course 48 | 49 | --- 50 | 53 | 54 | ###### Example 1 55 | This is a file (module) named `test.py`. 56 | ```python 57 | def factorial(n): 58 | if n == 0: 59 | return 1 60 | 61 | return n * factorial(n - 1) 62 | 63 | 64 | def fibo(n): 65 | result = [] 66 | a, b = 0, 1 67 | while b < n: 68 | result.append(b) 69 | a, b = b, a+b 70 | 71 | return result 72 | ``` 73 | 74 | --- 75 | ###### Example 1 76 | This is another file (module) `main.py` that uses functions from `test` module. 77 | 78 | ```python 79 | import test # Import the test module here 80 | 81 | 82 | def main(): 83 | n = input('Enter a Number: ') 84 | 85 | series = test.fibo(n).join(', ') 86 | print('Series upto {}: \n {}'.format(n, series)) 87 | print('Factorial of {}'.format(n, test.factorial(n))) 88 | 89 | 90 | main() 91 | ``` 92 | 93 | --- 94 | ### More on Modules 95 | 96 | You application generally is composed of several different modules. Modules may contain both executable and non-executable code (like function definitions, class definitions etc). 97 | 98 | But it's usually preferable to keep all your executable code only in your main module or the module that you're using as an entry point script and make all the other modules have only non-executable code. 99 | 100 | --- 101 | ### Module's `__name__` 102 | In every module you define, you can find a `__name__` variable whose value would be the name of the module. 103 | 104 | When you run a module directly as a script, the value of `__name__` inside that module is set to `__main__` otherwise it's value would be the module's name. 105 | 106 | --- 107 | ###### Example 2 108 | 109 | ```python 110 | # fib.py 111 | import sys 112 | 113 | def fib(n): 114 | a, b = 0, 1 115 | while b < n: 116 | print(b, end=' ') 117 | a, b = b, a+b 118 | print() 119 | 120 | 121 | if __name__ == '__main__': 122 | n = int(sys.argv[1]) 123 | fib(n) 124 | ``` 125 | 126 | You can use this file both as a script and an importable module. 127 | 128 | --- 129 | ###### Example 2 - Running it directly 130 | Run the script from command line 131 | 132 | ```bash 133 | $ python fib.py 100 134 | ``` 135 | 136 | This would take the value of `n` from the command line arguments and run the program. The code executes and prints the output since here the value of `__name__` will be `__main__`. 137 | 138 | 139 | --- 140 | ###### Example 2 - Importing as a module 141 | 142 | ```python 143 | import fib 144 | 145 | n = int(input('Enter N: ')) 146 | # Now execute that function. 147 | fib.fib(n) 148 | ``` 149 | Now if you're importing the module like this, the executable code under the `if __name__ == '__main__'` block won't be executed. 150 | 151 | Instead it will be executed when the function `fib` is called. 152 | 153 | 154 | --- 155 | # The `import` Syntax Variants 156 | --- 157 | ##### Syntax 1 158 | rts the module itself in it's own name. 159 | ```python 160 | import fib 161 | ``` 162 | So, to access the `fib` function defined inside the `fib` module you need to do 163 | ```python 164 | >>> fib.fib(50) 165 | ``` 166 | --- 167 | ##### Syntax 2 168 | Imports the function `fib` from the module `fib`. 169 | 170 | ```python 171 | from fib import fib 172 | ``` 173 | 174 | Now to call the `fib` function you can directly do 175 | ```python 176 | >>> fib(50) 177 | ``` 178 | 179 | You can also import multiple definitions from a module. 180 | ```python 181 | from foo import bar, baz, test, xyz 182 | ``` 183 | 184 | --- 185 | ##### Syntax 3 186 | Imports all the names that the module defines 187 | ```python 188 | from foo import * 189 | ``` 190 | 191 | **Note:** This is not considered a good practice and not recommended either. 192 | 193 | --- 194 | ### Built-in Modules 195 | Python provides it's standard library as a set of modules and packages. Let's look into this simple example. 196 | 197 | There are many built-in modules & packages available out of the box in python's standard library. You can check the full list [here](https://docs.python.org/3/library/). 198 | 199 | --- 200 | ###### Example 3 201 | Using python's built-in `math` module 202 | ```python 203 | import math 204 | 205 | value = 5.34 206 | 207 | print('value =', value) 208 | print('ceil =', math.ceil(value)) 209 | print('floor =', math.floor(value)) 210 | print('abs =', math.fabs(value)) 211 | ``` 212 | 213 | Here we're using the [`math`](https://docs.python.org/3/library/math.html) module which is one of the built-in modules that python has in it's [standard library](https://docs.python.org/3/library/). 214 | 215 | --- 216 | 219 | # Packages 220 | --- 221 | 224 | ### Packages in Python 225 | If you think of the modules as files having `.py` extension; then you can think of packages as directories that contains modules. 226 | 227 | Most importantly to be a package the directory, must contain a special file `__init__.py` which indicates python that it's a package that contains modules. 228 | 229 | --- 230 | 233 | ##### Example 4 234 | For instance, consider the following directory structure: 235 | 236 | ``` 237 | foo/ 238 | __init__.py 239 | bar 240 | __init__.py 241 | baz.py 242 | ``` 243 | 244 | Here `foo` is the main package, `bar` is the sub-package under `foo` and `baz.py` is a module inside `bar`. 245 | 246 | --- 247 | ##### Example 4 248 | Let's say `baz.py` has the following code: 249 | ```python 250 | def say_hello(to = 'World'): 251 | print('Hello', to) 252 | ``` 253 | 254 | --- 255 | ##### Example 4 256 | 257 | Now to reference the `baz` module from outside you would use the `import` statement with dotted names like this: 258 | ```python 259 | import foo.bar.baz 260 | 261 | # You can call the say_hello() using 262 | foo.bar.baz.say_hello() 263 | ``` 264 | 265 | Alternatively you can use the `import .. from` syntax like this: 266 | ```python 267 | form foo.bar.baz import say_hello 268 | 269 | say_hello('Again') 270 | ``` 271 | --- 272 | 275 | # Let's do some real coding :) 276 | --- 277 | 280 | ##### Building a Simple App 281 | ## User Information App 282 | #### Phase I 283 | --- 284 | ##### Please follow this link for the steps. 285 | ###### https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/python/7/modules-and-packages.md 286 | 287 | --- 288 | 291 | # Read More? 292 | --- 293 | 296 | ### Links 297 | Want to read more? Go through these links. 298 | 1. https://docs.python.org/3/tutorial/modules.html 299 | 2. https://python.swaroopch.com/modules.html 300 | 3. https://docs.python.org/3/library/ 301 | 4. https://docs.python.org/3/library/json.html#module-json 302 | 5. https://docs.python.org/3/library/functions.html#open 303 | 304 | --- 305 | 308 | ###### This slide was a part of course 309 | #### Python, Django & Web Development 310 | ###### [github.com/kabirbaidhya/learn-python-django-web](https://github.com/kabirbaidhya/learn-python-django-web) 311 | --- 312 | # Thank You 313 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 314 | ###### kabirbaidhya@gmail.com 315 | 316 | -------------------------------------------------------------------------------- /units/python/7/Modules and Packages.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/7/Modules and Packages.pdf -------------------------------------------------------------------------------- /units/python/7/examples/example_2.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | value = 5.34 4 | 5 | print('value =', value) 6 | print('ceil =', math.ceil(value)) 7 | print('floor =', math.floor(value)) 8 | print('abs =', math.fabs(value)) 9 | -------------------------------------------------------------------------------- /units/python/7/examples/example_3.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def fib(n): 4 | a, b = 0, 1 5 | while b < n: 6 | print(b, end=' ') 7 | a, b = b, a+b 8 | print() 9 | 10 | 11 | if __name__ == '__main__': 12 | fib(int(sys.argv[1])) 13 | -------------------------------------------------------------------------------- /units/python/7/examples/fib.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def fib(n): 4 | a, b = 0, 1 5 | while b < n: 6 | print(b, end=' ') 7 | a, b = b, a+b 8 | print() 9 | 10 | print('Command line arguments:', sys.argv) 11 | 12 | 13 | if __name__ == '__main__': 14 | n = int(sys.argv[1]) 15 | fib(n) 16 | -------------------------------------------------------------------------------- /units/python/7/examples/foo.py: -------------------------------------------------------------------------------- 1 | import test # Import the test module here 2 | 3 | 4 | def main(): 5 | n = int(input('Enter a Number: ')) 6 | 7 | series = test.fibo(n) 8 | print('Fibonacci Series up to {}: \n {}'.format(n, series)) 9 | print('Factorial of {}: {}'.format(n, test.factorial(n))) 10 | print(__name__) 11 | 12 | 13 | main() 14 | -------------------------------------------------------------------------------- /units/python/7/examples/foo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/7/examples/foo/__init__.py -------------------------------------------------------------------------------- /units/python/7/examples/foo/bar/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/units/python/7/examples/foo/bar/__init__.py -------------------------------------------------------------------------------- /units/python/7/examples/foo/bar/baz.py: -------------------------------------------------------------------------------- 1 | def say_hello(to = 'World'): 2 | print('Hello', to) 3 | 4 | -------------------------------------------------------------------------------- /units/python/7/examples/test.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | if n == 0: 3 | return 1 4 | 5 | return n * factorial(n - 1) 6 | 7 | 8 | def fibo(n): 9 | result = [] 10 | a, b = 0, 1 11 | 12 | while b < n: 13 | result.append(b) 14 | a, b = b, a+b 15 | 16 | return result 17 | 18 | 19 | print(__name__) 20 | -------------------------------------------------------------------------------- /units/python/7/examples/util.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | if n == 0: 3 | return 1 4 | 5 | return n * factorial(n - 1) 6 | 7 | 8 | def fibo(n): 9 | result = [] 10 | a, b = 0, 1 11 | while b < n: 12 | result.append(b) 13 | a, b = b, a+b 14 | 15 | return result 16 | -------------------------------------------------------------------------------- /units/python/8/examples/example_3.py: -------------------------------------------------------------------------------- 1 | class Employee: 2 | # This is a class variable. 3 | total_count = 0 4 | 5 | def __init__(self, name, started, company): 6 | self.name = name 7 | self.started = started 8 | self.company = company 9 | 10 | # Increment the total count 11 | Employee.total_count += 1 12 | 13 | def say_hi(self): 14 | print('Hi! I\'m {}, I have started working on {} since {}'.format( 15 | self.name, 16 | self.company, 17 | self.started 18 | )) 19 | 20 | @classmethod 21 | def print_count(cls): 22 | print('There are {:d} employees so far.'.format(cls.total_count)) 23 | 24 | emp1 = Employee('John Doe', '2013-01-02', 'Acme Corp.') 25 | emp2 = Employee('Mark Joe', '2014-12-05', 'Acme Corp.') 26 | 27 | emp1.say_hi() 28 | emp2.say_hi() 29 | Employee.print_count() 30 | -------------------------------------------------------------------------------- /units/python/8/examples/example_4.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | # This is a class variable. 3 | total_count = 0 4 | 5 | def __init__(self, name): 6 | self.name = name 7 | # Increment the total count 8 | Person.total_count += 1 9 | 10 | def greet(self): 11 | print('{}: Hello'.format(self.name)) 12 | 13 | @classmethod 14 | def print_count(cls): 15 | print('There are {:d} people so far.'.format(cls.total_count)) 16 | 17 | 18 | class Employee(Person): 19 | def __init__(self, name, started, company): 20 | Person.__init__(self, name) 21 | self.started = started 22 | self.company = company 23 | 24 | def introduce(self): 25 | Person.greet(self) 26 | print('I have started working on {} since {}'.format( 27 | self.company, 28 | self.started 29 | )) 30 | 31 | 32 | class Student(Person): 33 | def __init__(self, name, grade, school): 34 | Person.__init__(self, name) 35 | self.grade = grade 36 | self.school = school 37 | 38 | def introduce(self): 39 | Person.greet(self) 40 | print('I am a student studying in grade {:d} at {}'.format(self.grade, self.school)) 41 | 42 | 43 | def main(): 44 | person1 = Person('John Doe') 45 | employee1 = Employee('Mark Joe', '2014-12-05', 'Acme Corp.') 46 | student1 = Student('Jane Doe', 5, 'The Abc School') 47 | 48 | person1.greet() 49 | employee1.introduce() 50 | student1.introduce() 51 | 52 | main() 53 | 54 | -------------------------------------------------------------------------------- /units/python/8/examples/exercise_1.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | def __init__(self): 3 | self.__list = [] 4 | 5 | def push(self, item): 6 | self.__list.append(item) 7 | 8 | def pop(self): 9 | return self.__list.pop() 10 | 11 | def stack_top(self): 12 | return self.__list[-1] 13 | 14 | def size(self): 15 | return len(self.__list) 16 | 17 | def to_list(self): 18 | return self.__list 19 | 20 | -------------------------------------------------------------------------------- /units/web/1/web-basics-and-http.md: -------------------------------------------------------------------------------- 1 | Web Basics and HTTP 2 | =================== 3 | [Home](https://github.com/kabirbaidhya/learn-python-django-web) | [Slides](https://speakerdeck.com/kabirbaidhya/python-web-basics-and-http) | [← Prev](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/database/8/classes-and-objects.md) | [Next →]() 4 | 5 | This is a short introduction of the Web, the basics and the concepts about Web Development, Web Application Architecture and the HTTP. 6 | 7 | ## Web 8 | The World Wide Web (WWW) is a universe of interconnected network of information available via internet and which are accessible via the HTTP protocol. 9 | 10 | Information and resources are generally interlinked with each other across networks as hypertext documents or hypermedia. 11 | 12 | Today, the Web is not only limited to the hypertext documents and Web Pages but also includes the growing Cloud based applications and the mobile applications that are backed by Web services and applications on the cloud that are made possible due to web. 13 | 14 | The HTTP protocol and the internet are the ones that made possible the Web we have today. 15 | 16 | ## HTTP 17 | * HTTP(Hypertext Transfer Protocol) is an application layer protocol. 18 | * Request-Response Protocol 19 | * Client Sends the HTTP request requesting the resources 20 | * Server receives the request and responds with the resources 21 | 22 | For instance: 23 | An http request would look this: 24 | ``` 25 | GET / HTTP/1.1 26 | Accept: */* 27 | Accept-Encoding: gzip, deflate 28 | Connection: keep-alive 29 | Host: localhost 30 | User-Agent: HTTPie/0.9.2 31 | ``` 32 | 33 | And on receiving this request the server could respond with the following response: 34 | ``` 35 | HTTP/1.1 200 OK 36 | Connection: keep-alive 37 | Content-Encoding: gzip 38 | Content-Type: text/html 39 | Date: Sat, 08 Apr 2017 00:06:03 GMT 40 | ETag: W/"583bce74-264" 41 | Last-Modified: Mon, 28 Nov 2016 06:28:04 GMT 42 | Server: nginx/1.10.0 (Ubuntu) 43 | 44 | 45 | 46 | 47 | Welcome to nginx! 48 | 55 | 56 | 57 |

Welcome to nginx!

58 |

If you see this page, the nginx web server is successfully installed and 59 | working. Further configuration is required.

60 | 61 |

For online documentation and support please refer to 62 | nginx.org.
63 | Commercial support is available at 64 | nginx.com.

65 | 66 |

Thank you for using nginx.

67 | 68 | 69 | ``` 70 | ### HTTP Request 71 | The end which initiate a request to the server is the HTTP client. 72 | 73 | HTTP Request may contain the following things: 74 | * URIs (Uniform Resource Identifiers) 75 | * Methods/Verbs 76 | * Headers 77 | * Payload/Body 78 | 79 | #### URIs(Uniform Resource Identifiers) 80 | URIs are the ones that actually identify a resource on a remote server. 81 | 82 | URLs contain a the protocol, hostname followed by the path of the resource on the host at which the resource could be accessible. 83 | ``` 84 | protocol://hostname/path 85 | ``` 86 | 87 | For instance: 88 | ``` 89 | https://example.com/users/52/documents/xyz.pdf 90 | ``` 91 | This could be an example of URL. Here, the protocol used is `https`, hostname is `example.com` and the path to the resource is `/users/52/documents/xyz.pdf`. 92 | 93 | ##### Query Strings 94 | The URIs could also contain query strings. You probably have seen some thing like `?q=this+was+just+a+test&name=Foo` gets appended to some website url when you press some button like Search. This is the query string which might also come in the URI. 95 | 96 | Consider this url: 97 | ``` 98 | https://example.com/search?q=test&foo=bar 99 | ``` 100 | 101 | Here the part of the url followed by `?` is the query string which is `q=test&foo=bar`. Actually, query string includes some key value pairs that the client sends to server in urlencoded form via the urls. 102 | 103 | #### HTTP Methods (Verbs) 104 | The HTTP method should generally differentiate the type of the request on any resource. 105 | 106 | The most common HTTP methods used in web applications today are: 107 | 108 | 1. GET 109 | 2. POST 110 | 3. PUT 111 | 4. PATCH 112 | 4. DELETE 113 | 114 | #### Request Headers 115 | The request headers will contain meta information about the request. 116 | Request headers look like this: 117 | ``` 118 | Accept: */* 119 | Accept-Encoding: gzip, deflate 120 | Connection: keep-alive 121 | Host: localhost 122 | User-Agent: HTTPie/0.9.2 123 | ``` 124 | 125 | #### Request payload/data 126 | HTTP `POST`, `PUT`, `PATCH` requests do need to send data or payload along in request. Consider the case when you are submitting a form to the server. Generally you would just submit the form as a `POST` request. In these cases the form's data is sent along with the request as a payload. 127 | 128 | However, in other request methods, payload aren't necessary and are omitted. 129 | 130 | ## Client 131 | A slient in the Web usually means the software or a program which initiate the HTTP request. Generally these are: Browsers, Mobile Apps, Scripts, Web scrapers, automated scripts or even CLI tools if they rely on HTTP based services. 132 | 133 | ## Server 134 | In web, a server actually means the http server which is responding to the client's http requests. These could be Nginx Server, Apache HTTP Server, or any http servers made in any language like Python, NodeJs etc as long as they listen on certain port and respond to http requests. 135 | 136 | ## Testing everything 137 | We'll test how everything works with the http protocol and the web using python's simple http server and a lightweight command line http client tool `httpie`. 138 | 139 | ## Web Application Architecture 140 | A typical web application could be broken down into 3-tiers: 141 | 142 | 1. UI (Frontend) 143 | 2. Logic (Backend) 144 | 3. Data tier (Database) 145 | 146 | ### UI tier 147 | The UI (User Interface) is the front end of the application which the end user actually interacts with. For the web applications, we use technologies like HTML, CSS, JavaScript and multimedia to develop the UI. But generally this could be anything even mobile apps or CLI applications that communicate with backend Web services or Web APIs. 148 | 149 | When we talk about Frontend or Frontend Development we actually talk about developing this layer of the application. 150 | 151 | The UI tier (or the frontend) talks with the Logic tier (backend) using the HTTP protocol. 152 | 153 | ### Logic tier 154 | The UI tier (or the frontend) cannot directly communicate with the database, it needs a sort of middleman to do this work. This is what the Logic tier does, it communicates with the Data tier and also holds the main application logic. Actually, it communicates with the both the tiers and does the performs the business logic. The data might come from and go into the database as per the business logic. 155 | 156 | ### Data tier 157 | This is actually the layer in the application which holds the application's data. This is mostly the database. It stores the data received from the user (via the middle tier) and also holds the data that are displayed in the UI (via the middle tier). 158 | -------------------------------------------------------------------------------- /units/web/2/examples/anim/css/style.css: -------------------------------------------------------------------------------- 1 | #container { 2 | height: 500px; 3 | width: 800px; 4 | margin: 30px auto; 5 | background-color: #eaeaea; 6 | border: 1px solid #666; 7 | position: relative; 8 | } 9 | 10 | #box { 11 | height: 100px; 12 | width: 100px; 13 | background-color: #666; 14 | position: absolute; 15 | top: 10px; 16 | left: 100px; 17 | border-radius: 50%; 18 | } 19 | -------------------------------------------------------------------------------- /units/web/2/examples/anim/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Anim Test 5 | 6 | 7 | 8 | 9 |
10 |
11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /units/web/2/examples/anim/js/anim.js: -------------------------------------------------------------------------------- 1 | window.addEventListener('load', handleLoad); 2 | 3 | var x = 0; 4 | var y = 0; 5 | var dX = 1; 6 | var dY = 1; 7 | var colors = [ 8 | '#923102', 9 | '#ea66f2', 10 | '#222', 11 | '#333', 12 | '#5f4cd8', 13 | '#555', 14 | '#4549e0', 15 | '#777' 16 | ]; 17 | 18 | function handleLoad() { 19 | animate(); 20 | } 21 | 22 | function animate() { 23 | var duration = 5; 24 | 25 | setInterval(update, duration); 26 | } 27 | 28 | function update() { 29 | var container = document.querySelector('#container'); 30 | var box = document.querySelector('#box'); 31 | var boxRight = x + box.offsetWidth; 32 | var boxBottom = y + box.offsetHeight; 33 | var delta = 2; 34 | 35 | if (boxRight >= container.clientWidth) { 36 | dX = -1; 37 | changeBgColor(box) 38 | } else if (x <= 0) { 39 | dX = +1; 40 | changeBgColor(box) 41 | } 42 | 43 | if (boxBottom >= container.clientHeight) { 44 | dY = -1; 45 | changeBgColor(box) 46 | } else if (y <= 0) { 47 | dY = +1; 48 | changeBgColor(box) 49 | } 50 | 51 | x = x + dX * delta; 52 | y = y + dY * delta; 53 | 54 | // Update the box CSS. 55 | box.style.left = x + 'px'; 56 | box.style.top = y + 'px'; 57 | } 58 | 59 | function changeBgColor(box) { 60 | box.style.backgroundColor = randomColor(); 61 | } 62 | 63 | function randomColor() { 64 | var index = Math.floor(Math.random() * (colors.length - 1)) + 0; 65 | 66 | return colors[index]; 67 | } 68 | 69 | 70 | -------------------------------------------------------------------------------- /units/web/2/examples/calculator/css/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | background: #eaeaea; 5 | } 6 | 7 | body * { 8 | font-size: 16px; 9 | } 10 | 11 | h1 { 12 | margin-top: 20px; 13 | margin-bottom: 20px; 14 | text-align: center; 15 | font-weight: 500; 16 | color: #666; 17 | font-size: 30px; 18 | } 19 | 20 | #calculator { 21 | display: table; 22 | margin: 20px auto; 23 | } 24 | 25 | .input-group { 26 | margin-bottom: 15px; 27 | } 28 | .input-group input { 29 | width: 100px; 30 | padding: 5px; 31 | margin: 5px; 32 | font-size: 20px; 33 | text-align: right; 34 | } 35 | 36 | #output { 37 | font-size: 20px; 38 | display: inline-block; 39 | height: 24px; 40 | border: 1px solid #999; 41 | margin: 5px; 42 | padding: 5px; 43 | width: calc(100% - 24px); 44 | text-align: right; 45 | } 46 | 47 | .button-group { 48 | padding: 5px; 49 | } 50 | -------------------------------------------------------------------------------- /units/web/2/examples/calculator/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Calculator 5 | 6 | 7 | 8 | 9 |
10 |

Calculator

11 | 12 |
13 |
14 | 15 | + 16 | 17 |
18 |
19 | 20 |
21 |
22 | 23 |
24 | 25 | 26 |
27 |
28 | 29 | 30 |
31 |
32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /units/web/2/examples/calculator/js/calculator.js: -------------------------------------------------------------------------------- 1 | window.addEventListener('load', handleLoad); 2 | 3 | var op = '+'; // The calculation operator 4 | 5 | function handleLoad() { 6 | var calculateButton = document.querySelector('#calculate'); 7 | var clearButton = document.querySelector('#clear'); 8 | var minusButton = document.querySelector('#minus'); 9 | var plusButton = document.querySelector('#plus'); 10 | 11 | calculateButton.addEventListener('click', handleCalculateClick); 12 | clearButton.addEventListener('click', handleClearClick); 13 | minusButton.addEventListener('click', handleMinusClick); 14 | plusButton.addEventListener('click', handlePlusClick); 15 | } 16 | 17 | function handlePlusClick() { 18 | console.log('Plus button clicked.'); 19 | 20 | var operator = document.querySelector('#operator'); 21 | 22 | op = '+'; 23 | operator.innerText = '+'; 24 | } 25 | 26 | function handleMinusClick() { 27 | console.log('Minus button clicked.'); 28 | 29 | var operator = document.querySelector('#operator'); 30 | 31 | op = '-'; 32 | operator.innerText = '-'; 33 | } 34 | 35 | function handleCalculateClick() { 36 | console.log('Calculate Button Clicked.'); 37 | 38 | // Get the input & result elements 39 | var input1 = document.querySelector('#input1'); 40 | var input2 = document.querySelector('#input2'); 41 | var output = document.querySelector('#output'); 42 | 43 | // Get the values. 44 | var value1 = Number(input1.value); 45 | var value2 = Number(input2.value); 46 | 47 | // Just add those two values. 48 | var result = calculate(value1, value2); 49 | 50 | // Update the output element's content. 51 | output.innerHTML = result; 52 | } 53 | 54 | function calculate(value1, value2) { 55 | switch (op) { 56 | case '+': 57 | return value1 + value2; 58 | 59 | case '-': 60 | return value1 - value2; 61 | } 62 | } 63 | 64 | function handleClearClick() { 65 | console.log('Clear Button Clicked.'); 66 | 67 | // Get the input & result elements. 68 | var input1 = document.querySelector('#input1'); 69 | var input2 = document.querySelector('#input2'); 70 | var output = document.querySelector('#output'); 71 | 72 | // Clear the fields and output. 73 | input1.value = ''; 74 | input2.value = ''; 75 | output.innerHTML = ''; 76 | } 77 | -------------------------------------------------------------------------------- /units/web/2/examples/hello-world/css/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | background: #eaeaea; 5 | } 6 | 7 | h1 { 8 | margin-top: 20px; 9 | margin-bottom: 20px; 10 | text-align: center; 11 | font-weight: 500; 12 | color: #666; 13 | font-size: 30px; 14 | } 15 | 16 | p { 17 | text-align: center; 18 | font-size: 15px; 19 | color: #999; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /units/web/2/examples/hello-world/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Hello Web! 4 | 5 | 6 | 7 |

Hello World

8 |

I'm learning Web Development.

9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /units/web/2/examples/hello-world/js/hello.js: -------------------------------------------------------------------------------- 1 | window.addEventListener('load', handleLoad); 2 | 3 | function handleLoad() { 4 | // This will invoke the changeContent function after 3 seconds. 5 | setTimeout(changeContent, 3000); 6 | } 7 | 8 | function changeContent() { 9 | // This will change the content of the

tag. 10 | document.querySelector('p').innerHTML = "I'm learning Web Development with HTML, CSS and JavaScript."; 11 | } 12 | -------------------------------------------------------------------------------- /workshop/Presentation.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | Learning Python 4 | === 5 | 6 | # ![](python-logo-200x200.png) 7 | 8 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 9 | 10 | --- 11 | --- 12 | 15 | # Introduction 16 | --- 17 | 20 | # What is Python? 21 | --- 22 | > Python is a programming language that lets you work quickly and integrate systems more effectively. 23 | www.python.org 24 | 25 | 26 | --- 27 | ### Why Python? 28 | 1. Easy to learn yet very powerful 29 | 2. General purpose language that could be used almost everywhere 30 | 3. Flexibility and scalability 31 | 4. Multi-paradigm: object oriented, functional, procedural etc. 32 | 5. Popular language, big community 33 | 6. Fun to work with 34 | 7. Career Opportunities 35 | --- 36 | ### Python is everywhere 37 | * CLI applications 38 | * Web Apps backened / APIs 39 | * GUI applications 40 | * Network applications 41 | * System Administration / DevOps 42 | * Scientific Applications 43 | * Data Science Projects 44 | * Machine Learning / Deep learning 45 | * and much more 46 | --- 47 | # Getting Started 48 | --- 49 | ### Python 2 or 3? 50 | There are two versions of python currently in use python 2.7 & python 3. 51 | 52 | So, begineers often come up with question **“Should I choose Python 2 or Python 3”**? 53 | 54 | --- 55 | 56 | ### Current State 57 | 58 | 1. Most production applications today use Python 2.7. 59 | 2. Python 3 is ready for the production deployment of applications today. 60 | 3. Python 2.7 will only receive necessary security updates until 2020. 61 | 4. The brand name “Python” encapsulates both Python 3 and Python 2. 62 | 63 | --- 64 | 65 | ### So... 3? 66 | 67 | Yes, start with python 3.x but familiarizing yourself with Python 2.7 will be very useful. 68 | 69 | In case if you have to work with legacy projects in the future you might need to know 2.x too. 70 | 71 | --- 72 | ### Installation 73 | 74 | ###### Linux 75 | Python comes out of the box in most modern linux distros like Debian, Fedora, Centos etc. In case it's not preinstalled you can always download it from the official website. 76 | ###### Windows 77 | You can download the installer from the official website. https://www.python.org/downloads/ 78 | 79 | --- 80 | ### Code Editors 81 | 82 | You could use any code editors out there to write code in python as long as it supports syntax highlighting. 83 | 84 | Here are some recommended editors/IDEs: 85 | 86 | - Microsoft Vscode 87 | - Atom 88 | - Sublime 89 | - Vim 90 | - Jetbrains PyCharm IDE 91 | 92 | --- 93 | 96 | # Python Basics 97 | --- 98 | 101 | ### Hello World 102 | 103 | Hello World in python is just a one liner. 104 | 105 | ```python 106 | print "Hello, World!" 107 | ``` 108 | Pretty neat. Isn't it? 109 | 110 | --- 111 | ### Hello World: Python 3 112 | 113 | In `python3` it's 114 | ```python 115 | print("Hello, World!") 116 | ``` 117 | Mind the parenthesis. In python3 `print` is a function. 118 | 119 | --- 120 | # How'd you run it? 121 | --- 122 | ### 1. Directly in the Python shell. 123 | 124 | Run python shell first. 125 | ``` 126 | ➜ python 127 | Python 2.7.12 (default, Nov 19 2016, 06:48:10) 128 | [GCC 5.4.0 20160609] on linux2 129 | Type "help", "copyright", "credits" or "license" for more information. 130 | >>> 131 | ``` 132 | Then 133 | ``` 134 | >>> print "Hello World!" 135 | Hello World! 136 | ``` 137 | --- 138 | ### 2. Standard approach 139 | Create a file `hello_world.py` with the code. 140 | 141 | ```python 142 | print "Hello World!" 143 | ``` 144 | 145 | Now run it with python. 146 | 147 | ```bash 148 | ➜ python hello_world.py 149 | ``` 150 | ``` 151 | Hello World! 152 | ``` 153 | --- 154 | # How it works? 155 | --- 156 | ### Compilation & Interpretation 157 | Python is a dynamic language, and running it from the command line essentially triggers the following steps: 158 | 159 | 1. The source is compiled the first time it is encountered (e.g., imported as a module or directly executed). This step generates the binary file, with a pyc or pyo extension depending on your system. 160 | 161 | 2. The interpreter reads the binary file and executes the instructions (opcodes) one at a time. 162 | 163 | 164 | 165 | --- 166 | # Syntax and semantics 167 | 168 | 169 | --- 170 | ### Incase you're from a C-style language 171 | You need to be aware of few things in python. 172 | 173 | 1. No semicolon 174 | 2. No curly braces 175 | 3. Indentation is a part of syntax 176 | 4. Dynamically-typed language 177 | --- 178 | ### Pythonic code 179 | Looks something like this 180 | ```python 181 | 182 | """ 183 | Generates Fibonacci series upto n 184 | """ 185 | def fib(n): 186 | a, b = 0, 1 187 | 188 | while a < n: 189 | print a 190 | a, b = b, a+b 191 | 192 | 193 | fib(1000) 194 | ``` 195 | --- 196 | # Let's dive into the code 197 | --- 198 | #### Example 1: Printing and Comments 199 | ```python 200 | # This prints Hello World! 201 | print "Hello World!" 202 | 203 | # This is a comment; single line comment 204 | 205 | """ 206 | And this is a multiline comment. 207 | As this could take more than one line of comments. 208 | Like this. 209 | """ 210 | print "Hello Again." 211 | ``` 212 | Output: 213 | ```plain 214 | Hello World! 215 | Hello Again. 216 | ``` 217 | --- 218 | 219 | #### Example 2: Printing More 220 | ```python 221 | # Printing more texts 222 | print "Hello World!" 223 | print "Hello Again." 224 | print "We enjoy typing." 225 | print "Learning python is easy." 226 | print "And fun." 227 | print "Printing text is way easier." 228 | ``` 229 | Output: 230 | ```plain 231 | Hello World! 232 | Hello Again. 233 | We enjoy typing. 234 | Learning python is easy. 235 | And fun. 236 | Printing text is way easier. 237 | ``` 238 | --- 239 | #### Example 3: Printing more than just texts 240 | ```python 241 | print "One + One =", 1 + 1 242 | print "One - Two =", 1 - 2 243 | print "Two * Five =", 1 * 5 244 | print "Four / Two =", 4 / 2 245 | print "Expression (12 * 5) - (2 ^ 3) + (1 / 2) =", ((12 * 5) - (2 ** 3) + (1 / 2)) 246 | print "Seven is less than or equal to Six is", 7 <= 6 247 | ``` 248 | Output: 249 | ```plain 250 | One + One = 2 251 | One - Two = -1 252 | Two * Five = 5 253 | Four / Two = 2 254 | Expression (12 * 5) - (2 ^ 3) + (1 / 2) = 52 255 | Seven is less than or equal to Six is False 256 | ``` 257 | --- 258 | #### Example 4: Variables and Printing 259 | ```python 260 | first_name = "Kabir" 261 | last_name = "Baidhya" 262 | dob = "July 30, 1992" 263 | home_town = "Kathmandu, Nepal" 264 | 265 | print "Hi! I am", first_name, last_name, "." 266 | print "I was born on", dob, "." 267 | print "I'm from", home_town, "." 268 | ``` 269 | 270 | Output: 271 | ```plain 272 | Hi! I am Kabir Baidhya . 273 | I was born on July 30, 1992 . 274 | I'm from Kathmandu, Nepal . 275 | ``` 276 | --- 277 | #### Example 5: Proper Formatting 278 | ```python 279 | first_name = "Kabir" 280 | last_name = "Baidhya" 281 | dob_month = "July" 282 | dob_day = 30 283 | dob_year = 1992 284 | difficulty = "easy" 285 | 286 | print "Hi! I am %s %s." % (first_name, last_name) 287 | print "I was born on %s %d, %d." % (dob_month, dob_day, dob_year) 288 | print "Python is %s to learn." % difficulty 289 | ``` 290 | Output: 291 | ```plain 292 | Hi! I am Kabir Baidhya. 293 | I was born on July 30, 1992. 294 | Python is easy to learn. 295 | ``` 296 | 297 | --- 298 | #### Example 6: User Input 299 | ```python 300 | print "What is your name?", 301 | 302 | # This would take input from the user 303 | # and store it in a variable. 304 | name = raw_input() 305 | 306 | print "Hi! %s. \nIt's nice to meet you." % (name) 307 | print "Hope you're doing good." 308 | ``` 309 | 310 | Output: 311 | ```plain 312 | What is your name? Kabir 313 | Hi! Kabir. 314 | It's nice to meet you. 315 | Hope you're doing good. 316 | ``` 317 | 318 | --- 319 | # Data Types 320 | --- 321 | ### Buit-in Data types 322 | * **Numeric**: int, float, long 323 | * **Boolean**: bool 324 | * **Sequences**: str, list, tuple, bytes 325 | * **Mappings**: dict 326 | * **Sets**: set, frozen set 327 | 328 | Read more https://en.wikibooks.org/wiki/Python_Programming/Data_Types 329 | 330 | --- 331 | ### Immutable & Mutable types 332 | 333 | 1. Immutable types 334 | - int, float, long, tuple, byetes, frozen set, etc. 335 | 2. Mutable types 336 | - list, dict, set, etc. 337 | --- 338 | #### Example 7: Basic data types 339 | ```python 340 | an_integer = 6 341 | a_floating_point = 17.60 342 | a_boolean = True 343 | a_string = "Foo" 344 | 345 | print "Integer value = %d" % an_integer 346 | print "Float value = %f" % a_floating_point 347 | print "Boolean value = %r" % a_boolean 348 | print "String value = %s" % a_string 349 | ``` 350 | 351 | Output: 352 | ```plain 353 | Integer value = 6 354 | Float value = 17.600000 355 | Boolean value = True 356 | String value = Foo 357 | ``` 358 | 359 | --- 360 | #### Example 8: Lists 361 | 362 | ```python 363 | fruits = ['Banana', 'Apple', 'Lime'] 364 | numbers = [1, 2, 3, 4, 5, 6, 7, 8] 365 | 366 | # This is called list comprehension 367 | even_numbers = [x for x in numbers if x % 2 == 0] 368 | 369 | print "Numbers: %s" % numbers 370 | print "Even Numbers: %s" % even_numbers 371 | print "Fruits: %s, %s and %s" % (fruits[0], fruits[1], fruits[2]) 372 | ``` 373 | Output: 374 | ```plain 375 | Numbers: [1, 2, 3, 4, 5, 6, 7, 8] 376 | Even Numbers: [2, 4, 6, 8] 377 | Fruits: Banana, Apple and Lime 378 | ``` 379 | 380 | --- 381 | #### Example 9: Dictionaries 382 | 383 | ```python 384 | data = { 385 | "name": "Kabir Baidhya", 386 | "dob": "July 30, 1992", 387 | "home_town": "Kathmandu, Nepal" 388 | } 389 | 390 | print "Hi! I am %s." % data["name"] 391 | print "I was born on %s." % data["dob"] 392 | print "I'm from %s." % data["home_town"] 393 | ``` 394 | 395 | Output: 396 | ```plain 397 | Hi! I am Kabir Baidhya. 398 | I was born on July 30, 1992. 399 | I'm from Kathmandu, Nepal. 400 | ``` 401 | --- 402 | ### Read More? 403 | 1. http://docs.python-guide.org/en/latest 404 | 2. https://www.python.org 405 | 3. https://iluxonchik.github.io/why-you-should-learn-python/ 406 | 4. https://learnpythonthehardway.org/book/ 407 | 408 | --- 409 | 412 | # Any Questions? 413 | --- 414 | 417 | # Thank You 418 | ###### [@kabirbaidhya](https://github.com/kabirbaidhya) 419 | ###### kabirbaidhya@gmail.com 420 | 421 | -------------------------------------------------------------------------------- /workshop/Presentation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/workshop/Presentation.pdf -------------------------------------------------------------------------------- /workshop/python-logo-200x200.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kabirbaidhya/learn-python-django-web/3d301586807ef8178a3995b37011ed51f4b55dd2/workshop/python-logo-200x200.png --------------------------------------------------------------------------------