Session 1

Published

September 21, 2023

Topics Covered
  • Getting Started
  • Working with Command-line arguments

Welcome

 ____        _   _                 
|  _ \ _   _| |_| |__   ___  _ __  
| |_) | | | | __| '_ \ / _ \| '_ \ 
|  __/| |_| | |_| | | | (_) | | | |
|_|    \__, |\__|_| |_|\___/|_| |_|
       |___/                       
 _____                     _       _   _             
|  ___|__  _   _ _ __   __| | __ _| |_(_) ___  _ __  
| |_ / _ \| | | | '_ \ / _` |/ _` | __| |/ _ \| '_ \ 
|  _| (_) | |_| | | | | (_| | (_| | |_| | (_) | | | |
|_|  \___/ \__,_|_| |_|\__,_|\__,_|\__|_|\___/|_| |_|
                                                     
  ____                          
 / ___|___  _   _ _ __ ___  ___ 
| |   / _ \| | | | '__/ __|/ _ \
| |__| (_) | |_| | |  \__ \  __/
 \____\___/ \__,_|_|  |___/\___|

Quick Introduction to Juputer Notebook

Enter code and press Shift + Enter.

1 + 2
3

We can also run external commands.

!ls
assignment-01.qmd  index.qmd       references.bib  script.js
assignments.qmd    lab.qmd     references.qmd  session1.ipynb
_book          live-notes.qmd  schedule.ipynb  styles.css
course.qmd     _quarto.yml     schedule.qmd    syllabus.qmd
!figlet Python
 ____        _   _                 
|  _ \ _   _| |_| |__   ___  _ __  
| |_) | | | | __| '_ \ / _ \| '_ \ 
|  __/| |_| | |_| | | | (_) | | | |
|_|    \__, |\__|_| |_|\___/|_| |_|
       |___/                       
!python --version
Python 3.10.10

Jupyter notebooks allows writing notes in markdown.

We can also use bold and italic.

Or add headings using #.

heading 1

heading 2

heading 3

Let’s look at jupyter magic commands!

%time sum(range(1000000))
CPU times: user 25.4 ms, sys: 0 ns, total: 25.4 ms
Wall time: 25.6 ms
499999500000

The above one is a line magic command, where all the code in a single line.

There are also cell-magic commands.

%%time 
numbers = range(1000000)
sum(numbers)
CPU times: user 42.2 ms, sys: 0 ns, total: 42.2 ms
Wall time: 46.9 ms
499999500000

We can use %%file magic command to create a new file, without leaving jupyter notebook.

%%file hello.py
print("Hello, world!")
Writing hello.py
!python hello.py
Hello, world!

Custom Magic Commands for the training

The %load_problem magic command is used to load a program by its name.

%load_problem square
Problem: Square

Write a function square to compute the square of a number.

>>> square(4)
16

You can verify your solution using:

%verify_problem square

# your code here
def square(x):
    return x*x
square(4)
16

You can verify the solution using magic command %verify_problem.

%verify_problem square
✓ verify square(2)
✓ verify square(4)
🎉 Congratulations! You have successfully solved problem square!!

A Taste of Python

Python is Simple

Hello, world is a just a single line of code.

print("hello, world!")
hello, world!
1 + 2
3
%%file hello.py
print("hello, world!")
Overwriting hello.py
!python hello.py
hello, world!

Python is dynamically typed

x = 1
y = 2
print(x+y)
3
x = 1
print(x)

x = "python"
print(x)
1
python
1 + "2"
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Python is dynamically typed, but also strongly typed.

It does not allow operations on incompatible datatypes.

Python used indentation

x = 10
   y = 5
print(x+y)
IndentationError: unexpected indent (3665479488.py, line 2)
x = 10
y = 5
print(x+y)
15
marks = 5
if marks > 35:
    print("pass")
else:
    print("fail")
print("done")
fail
done

Python is expressive!

Python has elegant datastructures and built-in functions.

# sum of squares of all numbers below one million
sum([n*n for n in range(1000000)])
333332833333500000
[n*n for n in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
sum([n*n for n in range(10)])
285
sum([n*n for n in range(10) if n % 2 == 0])
120

Find the longest word in the dictionary.

All words in the dictionary are available at /usr/share/dict/words.

!head /usr/share/dict/words
A
AA
AAA
AA's
AB
ABC
ABC's
ABCs
ABM
ABM's
!wc -l /usr/share/dict/words
103494 /usr/share/dict/words
max([1, 5, 87, 32, 3])
87
max(open("/usr/share/dict/words"), key=len)
"electroencephalograph's\n"
max(open("/usr/share/dict/words"), key=len).strip()
"electroencephalograph's"

How to find the top-5 longest words?

sorted(open("/usr/share/dict/words"), key=len, reverse=True)[:5]
["electroencephalograph's\n",
 "Andrianampoinimerina's\n",
 'counterrevolutionaries\n',
 "counterrevolutionary's\n",
 "electroencephalogram's\n"]

Python is productive

Python has extensive standard library and many third-party libraries.

Let’s find the popular Python repositories on github.

import requests

url = "https://api.github.com/search/repositories"
params = {"q": "language:python flask", "sort": "stars"}

data = requests.get(url, params=params).json()
type(data)
dict
data.keys()
dict_keys(['total_count', 'incomplete_results', 'items'])
# data['items'][0]
for repo in data['items'][:10]:
    print(repo['full_name'])
    print(repo['description'])
    print(repo['stargazers_count'])
    print("---")
pallets/flask
The Python micro framework for building web applications.
64196
---
Asabeneh/30-Days-Of-Python
30 days of Python programming challenge is a step-by-step guide to learn the Python programming language in 30 days. This challenge may take more than100 days, follow your own pace.  These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
26222
---
plotly/dash
Data Apps & Dashboards for Python. No JavaScript Required.
19368
---
OpenEthan/SMSBoom
短信轰炸/短信测压/ | 一个健壮免费的python短信轰炸程序,专门炸坏蛋蛋,百万接口,多线程全自动添加有效接口,支持异步协程百万并发,全免费的短信轰炸工具!!hongkonger开发全网首发!!
14046
---
postmanlabs/httpbin
HTTP Request & Response Service, written in Python + Flask.
11965
---
Miserlou/Zappa
Serverless Python
11904
---
miguelgrinberg/flasky
Companion code to my O'Reilly book "Flask Web Development", second edition.
8258
---
benbusby/whoogle-search
A self-hosted, ad-free, privacy-respecting metasearch engine
7836
---
jofpin/trape
People tracker on the Internet: OSINT analysis and research tool by Jose Pino
7701
---
flask-restful/flask-restful
Simple framework for creating REST APIs
6659
---

Getting Started

1 + 2
3

Numbers, Strings and Lists

Python has many datatypes, but we’ll start with the most common ones - numbers, strings and lists.

Numbers

Python has integers.

2 + 5
7
2 ** 5
32
2 ** 100
1267650600228229401496703205376
2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Python has floating point numbers.

1.2 + 2.3
3.5
0.1 + 0.2
0.30000000000000004

checkout https://0.30000000000000004.com/ for explanation.

Pay attention to division of numbers.

7 / 2
3.5
6 / 2
3.0

The / operatoris a floating point division operator.

If you want integer division, use //.

7 // 2
3

Strings

In python, strings are enclosed in single quotes or double quotes. Both of them mean the same.

"hello"
'hello'
'hello'
'hello'
"hello" + "world"
'helloworld'
"hello" * 5
'hellohellohellohellohello'
print("=" * 40)
========================================

Python also supports multi-line strings. Multi-line strings are enclosed in three single or double quotes.

message = """
Hello everyone,

welcome to the python foundation course!
"""
message
'\nHello everyone,\n\nwelcome to the python foundation course!\n'
print(message)

Hello everyone,

welcome to the python foundation course!

Python strings support unicode characters.

print("అ ఆ ఇ ఈ") # Telugu
print("ಅ ಆ ಇ ಈ") # Kannada
print("அ ஆ இ ஈ") # Tamil
print("അ ആ ഇ ഈ") # Malayalam
print("अ आ इ ई") # Hindi
అ ఆ ఇ ఈ
ಅ ಆ ಇ ಈ
அ ஆ இ ஈ
അ ആ ഇ ഈ
अ आ इ ई

We can also specify the unicode characters using unicode code point.

print("\u0c05 \u0c06 \u0c07 \u0c08") # Telugu
print("\u0c85 \u0c86 \u0c87 \u0c88") # Kannada
print("\u0b85 \u0b86 \u0b87 \u0b88") # Tamil
print("\u0d05 \u0d06 \u0d07 \u0d08") # Malayalam
print("\u0905 \u0906 \u0907 \u0908") # Hindi
అ ఆ ఇ ఈ
ಅ ಆ ಇ ಈ
அ ஆ இ ஈ
അ ആ ഇ ഈ
अ आ इ ई
print("\U0001f638")
😸
n = 5
print(n * "😸")
😸😸😸😸😸

Lists

Python has lists to represent a collection of values.

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
x = [1, 2, 3, 4, 5]
x
[1, 2, 3, 4, 5]
print(x)
[1, 2, 3, 4, 5]

We can access individual elements of a list using [] operator.

names = ["Alice", "Bob", "Charlie", "Dave"]
names[0]
'Alice'
names[1]
'Bob'
names[2]
'Charlie'
len(names)
4
for name in names:
    print("Hello", name)
Hello Alice
Hello Bob
Hello Charlie
Hello Dave

A quick note about importing modules

import os
# curent working directory
os.getcwd()
'/home/jupyter-anand/book'
import sys
sys.version
'3.10.10 | packaged by conda-forge | (main, Mar 24 2023, 20:08:06) [GCC 11.3.0]'

Reading Command-line arguments

The most common way to provide inputs to a program is through command-line arguments.

!echo hello
hello
!wc -l *.py
1 hello.py

In Python, the sys.argv variable maintains the list of command-line arguments passed to the program.

By convention, the first entry is always the program name.

%%file args.py
import sys

print(sys.argv)
Writing args.py
!python args.py
['args.py']
!python args.py hello
['args.py', 'hello']
!python args.py hello world
['args.py', 'hello', 'world']
!python args.py 1 2 3 4 5
['args.py', '1', '2', '3', '4', '5']

Example: echo

Write a program to print the first command-line argument.

%%file echo.py
import sys

print(sys.argv[1])
Overwriting echo.py
!python echo.py hello
hello

Example: square

%%file square.py
import sys
# print(sys.argv)

n = int(sys.argv[1])
print(n*n)
Overwriting square.py
!python square.py 5
25
%load_problem add-two-numbers
Problem: Add Two Numbers

Write a program add.py that takes two numbers as command-line arguments and prints their sum.

$ python add.py 3 4
7
$ python add.py 10 20
30

You can verify your solution using:

%verify_problem add-two-numbers

# your code here