Learn pythong and create a simple app that takes in github username and returns the list of repositories sample: https://qasinow.pythonanywhere.com/
- Run the final app
- clone repo
cd pythonpip install flaskFLASK_APP=script.py flask run
- Python is a high-level, interpreted, interactive and object-oriented scripting language.
- Variables are containers for storing data values.
- Unlike other programming languages, Python has no command for declaring a variable.
x = 5
y = "John"
print(x)- Some of data types in Python
- Numbers `int, float, complex
- String
str - List
list - Tuple
tuple - Set
set - Dictionary
dict - Boolean
bool - None
NoneType
Numbers in python are are represented by int, float, complex
int: integer1, 2, 3, 4, 5float: floating point number1.0, 2.0, 3.0, 4.0, 5.0complex: complex number1+2j, 2+3j, 3+4j, 4+5j, 5+6jtype(5)->inttype(5.0)->floattype(5+6j)->complex
Strings are arrays of bytes representing unicode characters, str
str: string"hello", "world", "python", "programming"type("hello")->strtype('hello')->strtype("""hello""")->str
Lists are used to store multiple items in a single variable, list
list: list[1, 2, 3, 4, 5]type([1, 2, 3, 4, 5])->listtype([1, 2.0, 3+4j, "hello", [1, 2, 3]])->listtype([])->list
list -> [2,'qasim', 3, 4, 5]
len([2,'qasim', 3, 4, 5])->5list.append(6)->[2,'qasim', 3, 4, 5, 6]list.remove('qasim')->[2, 3, 4, 5, 6]list.pop()->[2, 3, 4, 5]list.insert(1, 'qasim')->[2, 'qasim', 3, 4, 5]list.sort()->[2, 3, 4, 5, 'qasim']list.reverse()->['qasim', 5, 4, 3, 2]list.clear()->[]list.copy()->[2, 'qasim', 3, 4, 5]list.count(2)->1
Tuples are used to store multiple items in a single variable, they are different from lists in the sense that they are immutable i.e they cannot be changed, tuple
tuple: tuple(1, 2, 3, 4, 5)type((1, 2, 3, 4, 5))->tupletype((1, 2.0, 3+4j, "hello", [1, 2, 3]))->tuple
tuple -> (2,'qasim', 3, 4, 5)
len((2,'qasim', 3, 4, 5))->5tuple.count(2)->1tuple.index(2)->0tuple[0]->2tuple[1]->qasim>tuple[2]->3
Sets are used to store multiple items in a single variable, they are unordered and unindexed, set, repeated items are not allowed
set: set{1, 2, 3, 4, 5}type({1, 2, 3, 4, 5})->settype({1, 2.0, 3+4j, "hello", [1, 2, 3]})->set
set -> {2,'qasim', 3, 4, 5}
len({2,'qasim', 3, 4, 5})->5set.add(6)->{2,'qasim', 3, 4, 5, 6}set.remove('qasim')->{2, 3, 4, 5, 6}set.pop()->{2, 3, 4, 5}set.clear()->set()set.copy()->{2, 'qasim', 3, 4, 5}set.discard(2)->{'qasim', 3, 4, 5}
Dictionaries are used to store data values in key:value pairs, dict
dict: dict{"name": "qasim", "age": 25, "city": "Ottawa"}type({"name": "qasim", "age": 25, "city": "Ottawa"})->dicttype({"name": "qasim", "age": 25, "city": "Ottawa", "hobbies": ["coding", "reading", "gaming"]})->dict
dict -> {"name": "qasim", "age": 25, "city": "Ottawa"}
len({"name": "qasim", "age": 25, "city": "Ottawa"})->3dict["name"]->qasimdict.get("name")->qasimdict.keys()->dict_keys(['name', 'age', 'city'])dict.values()->dict_values(['qasim', 25, 'Ottawa'])dict.items()->dict_items([('name', 'qasim'), ('age', 25), ('city', 'Ottawa')])dict.pop("name")->qasim
Booleans represent one of two values: True or False
bool: boolTrue, Falsetype(True)->booltype(False)->bool
bool(0)->Falsebool(1)->Truebool(2)->Truebool(3)->True
==: equal!=: not equal>: greater than<: less than>=: greater than or equal to<=: less than or equal to
and: andor: ornot: not&: and|: or~: not
if condition:
# code
elif condition:
# code
else:
# codefor i in range(5):
print(i)
for val in "string":
if val == "i":
break
print(val)i = 1
while i < 6:
print(i)
i += 1
while True:
print("hello")
breaklist comprehension is a way to create lists in python
new_list = [i for i in old_list]
new_list = [i.upper() for i in old_list]
new_list = [i for i in old_list if i != 0]functions are a block of code that only runs when it is called there are many ways to define a function
def my_function(name):
print(f"hello {name}")
def my_function(name="qasim"):
print(f"hello {name}")
def my_function(*args):
while args:
print(args.pop())
def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key} : {value}")lambda expressions are used to create anonymous functions and are used to create small functions
x = lambda a : a + 10
print(x(5))
my_function = lambda a : a + 10
print(my_function(5))
print((lambda a : a + 10)(5))map and filter are used to apply a function to a list of elements map will return a list of the results after applying the given function to each item of a given iterable filter will return a list of the elements of the iterable for which the function returns True
my_list = [1, 2, 3, 4, 5]
new_list = list(map(lambda x: x * 2, my_list))
new_list = list(filter(lambda x: x % 2 == 0, my_list))dir(): returns a list of all the methods and properties of the objecthelp(): returns the documentation of the objecttype(): returns the type of the objectid(): returns the unique id of the object
- LEGB Rule
- L : Local
- E : Enclosing
- G : Global
- B : Built-in the scope of a variable is the context in which it is defined.
x = 300
def my_function():
x = 200
print(x)
print(x) # 300
def my_function():
global x
x = 200
print(x) # 200to use files in python, you have to open them first, using the built-in open() function
f = open("demofile.txt", "r")
print(f.read())
f.close()- Read : read the user input
- Evaluate : evaluate the user input
- Print : print the result
- Loop : loop the above process until the user quits
- type()
- dir()
- help()
- len()
- lower()
- strip()
- split()
- append()
- remove()
- set()
- sort()
- join()
" * ".join(list)->a * b * cwhere list = [a, b, c]
new_list = [i.upper() for i in old_list]set_list = {i.upper() for i in old_list}dict_list = {i: i.upper() for i in old_list}
new_list = old_list# here the changes in new_list will reflect in old_listnew_list = old_list[:]# here the changes in new_list will not reflect in old_listnew_list = old_list.copy()# here the changes in new_list will not reflect in old_listnew_list = list(old_list)# here the changes in new_list will not reflect in old_list
zip([1, 2, 3], [4, 5, 6])->[(1, 4), (2, 5), (3, 6)]- zip combine the elements of two lists in a tuple
import randomimport mathimport osimport sysimport jsonfull list of standard library: https://docs.python.org/3/library/
- cerate folder
mkdir my_module - create file
touch my_module/my_module.py - create file
touch my_module/__init__.py from my_module import my_modulemy_module.my_function()
os.getcwd()gets current working directoryos.chdir('path')change directoryos.listdir()list all files and folders in current directory
-
sys.pathlist of all the directories where python looks for modules -
sys.argv is a list in Python, which contains the command-line arguments passed to the script.
-
sys.exit()exit from python
python3 my_script.py arg1 arg2 arg3
import sys
print('Number of arguments:', len(sys.argv), 'arguments.')- unit testing : testing individual units or components of a software
- integration testing : testing the combination of two or more units
- functional testing : testing the functionality of the software
- end-to-end testing : testing the complete flow of the software
assert 1 == 1# no outputassert 1 == 2# AssertionError
import unittestunittest.TestCaseis a class that allows us to create test cases
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())- assertEqual(a, b) checks a and b are equal
- assertNotEqual(a, b) checks a and b are not equal
- assertTrue(x) checks x is True
- assertFalse(x) checks x is False
- assertIs(a, b) checks a is b
- assertIsNot(a, b) checks a is not b
- assertIsNone(x) checks x is None
- assertIsNotNone(x) checks x is not None
- Django: high-level web framework
- Flask: micro web framework
- Pyramid: open source web framework
- Bottle: simple web framework
pip install flask- making a simple hello world with welcome animated message
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
flask runto run the server, it will look forapp.pyand run the server on port : 5000- if the file name is different then
FLASK_APP=script.py flask run
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
- we can pass arguments to the templates
render_template('index.html', name=name)- the template file should be in
templatesfolder - inorder to render the passed argument in the template file we use
{{ name }}
@app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name=user)<h1> welcome {{ name }} </h1>{{ variable }}: to print the variable{% for i in list %} {{ i }} {% endfor %}: for loop{% if condition %} {{ variable }} {% endif %}: if condition{% block content %} {% endblock %}: block of content{% extends "layout.html" %}: extending the layout file{% include "header.html" %}: including the header file
{% set name = "qasim" %}: setting the variable{% macro render_title(title) %} <title>{{ title }}</title> {% endmacro %}: creating a macro{{ render_title("Home") }}: using the macro- the diffrence between
{{ }}and{% %}is that{{ }}is used to print the variable and{% %}is used to write the logic
- requests module is used to make the http requests
pip install requests
import requests
@app.route('/repos/<username>')
def repos(username):
r = requests.get(f'https://api.github.com/users/{username}/repos')
return r.json()@app.route('/repos/<username>')
def repos(username):
r = requests.get(f'https://api.github.com/users/{username}/repos')
return render_template('repos.html', repos=r.json())<ul>
{% for repo in repos %}
<li>{{ repo.name }}</li>
{% endfor %}
</ul><form action="/repos" method="get">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>