= "Hello" x
More Python
Functions, Methods & Modules
Functions
Problem: Write a function sum_of_squares
that takes two numbers as arguments and returns sum of their squares.
>>> sum_of_squares(3, 4)
25
>>> sum_of_squares(2, 5)
29
Methods
Methods of special kind of functions that work on a value or an object.
x.upper()
'HELLO'
"Python".upper()
'PYTHON'
= 1 x
# doesn't work x.upper()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[5], line 1 ----> 1 x.upper() # doesn't work AttributeError: 'int' object has no attribute 'upper'
Let’s see some more useful methods on strings.
"mathematics".count("mat")
2
"mathematics".replace("mat", "rat")
'ratheratics'
Spliting and Joining strings
= "Anything that can go wrong, will go wrong." sentence
sentence.split()
['Anything', 'that', 'can', 'go', 'wrong,', 'will', 'go', 'wrong.']
We can also specify a delimeter to split it differently.
",") sentence.split(
['Anything that can go wrong', ' will go wrong.']
Can we write a function to compute the number of words in a sentence?
def wordcount(sentence):
return len(sentence.split())
"one two three") wordcount(
3
Let’s also see how to join strings.
"-".join(["one", "two", "three"])
'one-two-three'
"".join(["a", "b", "c"])
'abc'
Reading Files
%%file three.txt
one
two three
Writing three.txt
ls
index.ipynb three.txt
open("three.txt").read()
'one\ntwo\nthree\n'
open("three.txt").readlines()
['one\n', 'two\n', 'three\n']
How to print the contents of three.txt
in upper case?
= open("three.txt").read()
contents print(contents.upper())
ONE
TWO
THREE
Modules
import time
time.asctime()
'Mon Oct 28 11:52:28 2024'
print(time.asctime())
Mon Oct 28 11:52:40 2024
%%file date.py
import time
print(time.asctime())
Writing date.py
!python date.py
Mon Oct 28 11:53:00 2024
There are mutliple ways to import things in Python.
import time
time.asctime()
'Mon Oct 28 11:57:40 2024'
from time import asctime
asctime()
'Mon Oct 28 11:58:04 2024'
from time import asctime as mytime
mytime()
'Mon Oct 28 11:59:05 2024'
Let’s look at some more useful modules.
import os
List all files in the current directory.
os.listdir()
['index.ipynb', 'three.txt', 'date.py']
# .. parent directory
"..") os.listdir(
['2024-08-19',
'2024-10-14',
'2024-10-21',
'02',
'2024-08-12',
'2024-10-28',
'2024-09-30',
'01',
'index.qmd']
You can also try giving whole path.
# works only on unix
"/home") os.listdir(
['anand']
You could try the following if you are on windows.
os.listdir("c:\\")
Reading Command-line arguments
Let’s see how to write programs that take command-line arguments.
In Python, the sys
module keeps tracks of the command-line arguments passed to the program in variable sys.argv
%%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']
Example: Square
Let’s write a script to compute square of a number.
%%file square.py
import sys
= int(sys.argv[1])
n print(n*n)
Writing square.py
!python square.py 5
25
Lists
= ["Alice", "Bob", "Charlie"] names
len(names)
3
0] names[
'Alice'
for name in names:
print("Hello", name)
Hello Alice
Hello Bob
Hello Charlie
= [1, 2, 3, 4, 5] numbers
sum(numbers)
15
Let’s see how to compute product of numbers.
def product(numbers):
= 1
result for n in numbers:
*= n
result return result
1, 2, 3, 4]) product([
24
We can add a new element to a list using append
method.
= [1, 2, 3, 4, 5]
numbers 6) numbers.append(
numbers
[1, 2, 3, 4, 5, 6]
How to computes squares of a list of numbers?
numbers
[1, 2, 3, 4, 5, 6]
+ numbers numbers
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
def squares(numbers):
= []
result for n in numbers:
*n)
result.append(nreturn result
1, 2, 3, 4, 5]) squares([
[1, 4, 9, 16, 25]
*n for n in numbers] [n
[1, 4, 9, 16, 25, 36]
*n for n in range(10) if n%2 == 0] [n
[0, 4, 16, 36, 64]
# sum of squares of all even numbers below one million
sum([n*n for n in range(1000000) if n%2 == 0])
166666166667000000
How to find all the python files in the current directory?
import os
for f in os.listdir() if f.endswith(".py")] [f
['args.py', 'date.py', 'square.py']
Example: sumfile
Write a program sumfile.py
that takes a filename as command-line argument and computes the sum of all numbers in a file.
%%file 5.txt
1
2
3
4
5
Writing 5.txt
%%file sumfile.py
import sys
= sys.argv[1]
filename = open(filename).readlines()
lines print(lines)
= [int(line) for line in lines]
numbers print(numbers)
print(sum(numbers))
Overwriting sumfile.py
!python sumfile.py 5.txt
['1\n', '2\n', '3\n', '4\n', '5\n']
[1, 2, 3, 4, 5]
15
List Indexing & Slicing
= ["a", "b", "c", "d", "e", "f", "g", "h"] x
0:2] # from index 0 to index 2 (end is not included) x[
['a', 'b']
2] # up to index 2 x[:
['a', 'b']
2:] # from index 2 onwards x[
['c', 'd', 'e', 'f', 'g', 'h']
1:7:3] # from index 1 to 7 in steps of 3 x[
['b', 'e']
-1] # reverse x[::
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
How to get the last element of a list?
x
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
len(x)-1] x[
'h'
-1] x[
'h'
= "one two three" sentence
# last word
-1] sentence.split()[
'three'
Numerical Computing
If you don’t have numpy
and matplotlib
installed, you can install them using:
!python -m pip install numpy matplotlib
import numpy as np
= np.array([1, 2, 3, 4, 5]) x
x
array([1, 2, 3, 4, 5])
x.dtype
dtype('int64')
x.shape
(5,)
x
array([1, 2, 3, 4, 5])
+ 10 x
array([11, 12, 13, 14, 15])
* x x
array([ 1, 4, 9, 16, 25])
1/x
array([1. , 0.5 , 0.33333333, 0.25 , 0.2 ])
Example: Euclidian distance between two points
Euclidian distance between two vectors is defined as:
\(E(p, q) = \sqrt{\Sigma_{i=1}^{n}(p_{i}-q_{i})^2}\)
= np.array([1, 2, 3, 4, 5])
P = np.array([10, 20, 30, 40, 50]) Q
= P-Q d
sum(d*d)) np.sqrt(np.
np.float64(66.74578638386096)
def euclidean_distance(P, Q):
= P-Q
d return np.sqrt(np.sum(d*d))
euclidean_distance(P, Q)
np.float64(66.74578638386096)
Plotting Graphs
Install matplotlib using:
!python -m pip install matplotlib
import numpy as np
import matplotlib.pyplot as plt
Let’s plot \(y = x^2\).
# divide [-10, 10] into 100 numbers
= np.linspace(-10, 10, 100)
x = x*x y
plt.plot(x, y)
plt.grid()"$y = x^2$") plt.title(
Text(0.5, 1.0, '$y = x^2$')
*x, label="$x^2$")
plt.plot(x, x2*x, label="$2 x$")
plt.plot(x,
plt.grid() plt.legend()