Python Basics (notes)

wordcloud

Types and Sequences


Use `type` to return the object's type.
In [1]:
type('This is a string')
Out[1]:
str
In [2]:
type(None)
Out[2]:
NoneType
In [3]:
type(1)
Out[3]:
int
In [4]:
type(1.0)
Out[4]:
float

Tuples are an immutable data structure (cannot be altered).
In [6]:
x = (1, 'a', 2, 'b')
type(x)
Out[6]:
tuple

Lists are a mutable data structure.
In [7]:
x = [1, 'a', 2, 'b']
type(x)
Out[7]:
list

Use `append` to append an object to a list.
In [8]:
x.append(3.3)
print(x)
[1, 'a', 2, 'b', 3.3]

This is an example of how to loop through each item in the list.
In [9]:
for item in x:
    print(item)
1
a
2
b
3.3

Or using the indexing operator:
In [10]:
i=0
while( i != len(x) ):
    print(x[i])
    i = i + 1
1
a
2
b
3.3

Use `+` to concatenate lists.
In [11]:
[1,2] + [3,4]
Out[11]:
[1, 2, 3, 4]

Use `*` to repeat lists.
In [12]:
[1]*3
Out[12]:
[1, 1, 1]

Use the `in` operator to check if something is inside a list.
In [13]:
1 in [1, 2, 3]
Out[13]:
True

Now let's look at strings. Use bracket notation to slice a string.
In [14]:
x = 'This is a string'
print(x[0]) #first character
print(x[0:1]) #first character, but we have explicitly set the end character
print(x[0:2]) #first two characters
T
T
Th

This will return the last element of the string.
In [15]:
x[-1]
Out[15]:
'g'

This will return the slice starting from the 4th element from the end and stopping before the 2nd element from the end.
In [16]:
x[-4:-2]
Out[16]:
'ri'

This is a slice from the beginning of the string and stopping before the 3rd element.
In [17]:
x[:3]
Out[17]:
'Thi'

And this is a slice starting from the 4th element of the string and going all the way to the end.
In [18]:
x[3:]
Out[18]:
's is a string'
In [19]:
firstname = 'Krishnakanth'
lastname = 'Allika'

print(firstname + ' ' + lastname)
print(firstname*3)
print('Krish' in firstname)
Krishnakanth Allika
KrishnakanthKrishnakanthKrishnakanth
True

`split` returns a list of all the words in a string, or a list split on a specific character.
In [20]:
firstname = 'Christopher Eric Hitchens'.split(' ')[0] # [0] selects the first element of the list
lastname = 'Christopher Eric Hitchens'.split(' ')[-1] # [-1] selects the last element of the list
print(firstname)
print(lastname)
Christopher
Hitchens

Make sure you convert objects to strings before concatenating.
In [21]:
'Chris' + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-9d01956b24db> in <module>
----> 1 'Chris' + 2

TypeError: can only concatenate str (not "int") to str
In [22]:
'Chris' + str(2)
Out[22]:
'Chris2'

Dictionaries associate keys with values.
In [23]:
x = {'Christopher Hitchens': 'The Missionary Position: Mother Teresa in Theory and Practice',
     'Richard Dawkins': 'The Selfish Gene',
     'Yuval Noah Harari':'Sapiens: A Brief History of Humankind',
     'Douglas Adams':"The Hitchhiker's Guide to the Galaxy"
    }

x['Christopher Hitchens'] # Retrieve a value by using the indexing operator
Out[23]:
'The Missionary Position: Mother Teresa in Theory and Practice'
In [24]:
x['Carl Sagan'] = None
x['Carl Sagan']

Iterate over all of the keys:
In [25]:
for name in x:
    print(x[name])
The Missionary Position: Mother Teresa in Theory and Practice
The Selfish Gene
Sapiens: A Brief History of Humankind
The Hitchhiker's Guide to the Galaxy
None

Iterate over all of the values:
In [26]:
for book in x.values():
    print(book)
The Missionary Position: Mother Teresa in Theory and Practice
The Selfish Gene
Sapiens: A Brief History of Humankind
The Hitchhiker's Guide to the Galaxy
None

Iterate over all of the items in the list:
In [27]:
for name, book in x.items():
    print(name)
    print(book)
Christopher Hitchens
The Missionary Position: Mother Teresa in Theory and Practice
Richard Dawkins
The Selfish Gene
Yuval Noah Harari
Sapiens: A Brief History of Humankind
Douglas Adams
The Hitchhiker's Guide to the Galaxy
Carl Sagan
None

You can unpack a sequence into different variables:
In [28]:
x = ('Richard','Dawkins','Evolutionary Biologist')
fname, lname, profession = x
In [29]:
fname
Out[29]:
'Richard'
In [30]:
lname
Out[30]:
'Dawkins'

Make sure the number of values you are unpacking matches the number of variables being assigned.
In [31]:
x = ('Richard','Dawkins','Evolutionary Biologist','Author')
fname, lname, profession = x
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-31-4d9d585aa37c> in <module>
      1 x = ('Richard','Dawkins','Evolutionary Biologist','Author')
----> 2 fname, lname, profession = x

ValueError: too many values to unpack (expected 3)

Python has a built in method for convenient string formatting.
In [34]:
sales_record = {
'price': 22.50,
'num_items': 3,
'person': 'John'}

sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'

print(sales_statement.format(sales_record['person'],
                             sales_record['num_items'],
                             sales_record['price'],
                             sales_record['num_items']*sales_record['price']))
John bought 3 item(s) at a price of 22.5 each for a total of 67.5

Dates and Times

In [35]:
import datetime as dt
import time as tm

`time` returns the current time in seconds since the Epoch. (January 1st, 1970)
In [36]:
tm.time()
Out[36]:
1606902428.0856857

Convert the timestamp to datetime.
In [37]:
dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow
Out[37]:
datetime.datetime(2020, 12, 2, 15, 17, 10, 873519)

Handy datetime attributes:
In [38]:
# get year, month, day, etc.from a datetime
dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second 
Out[38]:
(2020, 12, 2, 15, 17, 10)

`timedelta` is a duration expressing the difference between two dates.
In [39]:
delta = dt.timedelta(days = 100) # create a timedelta of 100 days
delta
Out[39]:
datetime.timedelta(days=100)

`date.today` returns the current local date.
In [40]:
today = dt.date.today()
In [41]:
today - delta # the date 100 days ago
Out[41]:
datetime.date(2020, 8, 24)
In [42]:
today > today-delta # compare dates
Out[42]:
True

Functions

In [43]:
x = 1
y = 2
x + y
Out[43]:
3
In [44]:
y
Out[44]:
2

`add_numbers` is a function that takes two numbers and adds them together.
In [45]:
def add_numbers(x, y):
    return x + y

add_numbers(1, 2)
Out[45]:
3

'add_numbers' updated to take an optional 3rd parameter. Using `print` allows printing of multiple expressions within a single cell.
In [46]:
def add_numbers(x,y,z=None):
    if (z==None):
        return x+y
    else:
        return x+y+z

print(add_numbers(1, 2))
print(add_numbers(1, 2, 3))
3
6

`add_numbers` updated to take an optional flag parameter.
In [47]:
def add_numbers(x, y, z=None, flag=False):
    if (flag):
        print('Flag is true!')
    if (z==None):
        return x + y
    else:
        return x + y + z
    
print(add_numbers(1, 2, flag=True))
Flag is true!
3

Assign function `add_numbers` to variable `a`.
In [48]:
def add_numbers(x,y):
    return x+y

a = add_numbers
a(1,2)
Out[48]:
3

Objects and map()


An example of a class in python:
In [61]:
class Person:
    course = 'Python programming' #a class variable

    def set_name(self, new_name): #a method
        self.name = new_name
    def set_location(self, new_location):
        self.location = new_location
In [63]:
person = Person()
person.set_name('Krishnakanth Allika')
person.set_location('Hyderabad, India')
print('{} lives in {} and is learning {}.'.format(person.name, person.location, person.course))
Krishnakanth Allika lives in Hyderabad, India and is learning Python programming.

Here's an example of mapping the `min` function between two lists.
In [67]:
store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2)
cheapest
Out[67]:
<map at 0x1ee30f809d0>

Now let's iterate through the map object to see the values.
In [68]:
for item in cheapest:
    print(item)
9.0
11.0
12.34
2.01

Lambda and List Comprehensions


Here's an example of lambda that takes in three parameters and adds the first two.
In [69]:
my_function = lambda a, b, c : a + b
In [70]:
my_function(1, 2, 3)
Out[70]:
3

Let's iterate from 0 to 999 and return the even numbers.
In [72]:
my_list = []
for number in range(0, 1000):
    if number % 2 == 0:
        my_list.append(number)
print(my_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 256, 258, 260, 262, 264, 266, 268, 270, 272, 274, 276, 278, 280, 282, 284, 286, 288, 290, 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312, 314, 316, 318, 320, 322, 324, 326, 328, 330, 332, 334, 336, 338, 340, 342, 344, 346, 348, 350, 352, 354, 356, 358, 360, 362, 364, 366, 368, 370, 372, 374, 376, 378, 380, 382, 384, 386, 388, 390, 392, 394, 396, 398, 400, 402, 404, 406, 408, 410, 412, 414, 416, 418, 420, 422, 424, 426, 428, 430, 432, 434, 436, 438, 440, 442, 444, 446, 448, 450, 452, 454, 456, 458, 460, 462, 464, 466, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 488, 490, 492, 494, 496, 498, 500, 502, 504, 506, 508, 510, 512, 514, 516, 518, 520, 522, 524, 526, 528, 530, 532, 534, 536, 538, 540, 542, 544, 546, 548, 550, 552, 554, 556, 558, 560, 562, 564, 566, 568, 570, 572, 574, 576, 578, 580, 582, 584, 586, 588, 590, 592, 594, 596, 598, 600, 602, 604, 606, 608, 610, 612, 614, 616, 618, 620, 622, 624, 626, 628, 630, 632, 634, 636, 638, 640, 642, 644, 646, 648, 650, 652, 654, 656, 658, 660, 662, 664, 666, 668, 670, 672, 674, 676, 678, 680, 682, 684, 686, 688, 690, 692, 694, 696, 698, 700, 702, 704, 706, 708, 710, 712, 714, 716, 718, 720, 722, 724, 726, 728, 730, 732, 734, 736, 738, 740, 742, 744, 746, 748, 750, 752, 754, 756, 758, 760, 762, 764, 766, 768, 770, 772, 774, 776, 778, 780, 782, 784, 786, 788, 790, 792, 794, 796, 798, 800, 802, 804, 806, 808, 810, 812, 814, 816, 818, 820, 822, 824, 826, 828, 830, 832, 834, 836, 838, 840, 842, 844, 846, 848, 850, 852, 854, 856, 858, 860, 862, 864, 866, 868, 870, 872, 874, 876, 878, 880, 882, 884, 886, 888, 890, 892, 894, 896, 898, 900, 902, 904, 906, 908, 910, 912, 914, 916, 918, 920, 922, 924, 926, 928, 930, 932, 934, 936, 938, 940, 942, 944, 946, 948, 950, 952, 954, 956, 958, 960, 962, 964, 966, 968, 970, 972, 974, 976, 978, 980, 982, 984, 986, 988, 990, 992, 994, 996, 998]

Now the same thing but with list comprehension.
In [73]:
my_list = [number for number in range(0,1000) if number % 2 == 0]
print(my_list)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 256, 258, 260, 262, 264, 266, 268, 270, 272, 274, 276, 278, 280, 282, 284, 286, 288, 290, 292, 294, 296, 298, 300, 302, 304, 306, 308, 310, 312, 314, 316, 318, 320, 322, 324, 326, 328, 330, 332, 334, 336, 338, 340, 342, 344, 346, 348, 350, 352, 354, 356, 358, 360, 362, 364, 366, 368, 370, 372, 374, 376, 378, 380, 382, 384, 386, 388, 390, 392, 394, 396, 398, 400, 402, 404, 406, 408, 410, 412, 414, 416, 418, 420, 422, 424, 426, 428, 430, 432, 434, 436, 438, 440, 442, 444, 446, 448, 450, 452, 454, 456, 458, 460, 462, 464, 466, 468, 470, 472, 474, 476, 478, 480, 482, 484, 486, 488, 490, 492, 494, 496, 498, 500, 502, 504, 506, 508, 510, 512, 514, 516, 518, 520, 522, 524, 526, 528, 530, 532, 534, 536, 538, 540, 542, 544, 546, 548, 550, 552, 554, 556, 558, 560, 562, 564, 566, 568, 570, 572, 574, 576, 578, 580, 582, 584, 586, 588, 590, 592, 594, 596, 598, 600, 602, 604, 606, 608, 610, 612, 614, 616, 618, 620, 622, 624, 626, 628, 630, 632, 634, 636, 638, 640, 642, 644, 646, 648, 650, 652, 654, 656, 658, 660, 662, 664, 666, 668, 670, 672, 674, 676, 678, 680, 682, 684, 686, 688, 690, 692, 694, 696, 698, 700, 702, 704, 706, 708, 710, 712, 714, 716, 718, 720, 722, 724, 726, 728, 730, 732, 734, 736, 738, 740, 742, 744, 746, 748, 750, 752, 754, 756, 758, 760, 762, 764, 766, 768, 770, 772, 774, 776, 778, 780, 782, 784, 786, 788, 790, 792, 794, 796, 798, 800, 802, 804, 806, 808, 810, 812, 814, 816, 818, 820, 822, 824, 826, 828, 830, 832, 834, 836, 838, 840, 842, 844, 846, 848, 850, 852, 854, 856, 858, 860, 862, 864, 866, 868, 870, 872, 874, 876, 878, 880, 882, 884, 886, 888, 890, 892, 894, 896, 898, 900, 902, 904, 906, 908, 910, 912, 914, 916, 918, 920, 922, 924, 926, 928, 930, 932, 934, 936, 938, 940, 942, 944, 946, 948, 950, 952, 954, 956, 958, 960, 962, 964, 966, 968, 970, 972, 974, 976, 978, 980, 982, 984, 986, 988, 990, 992, 994, 996, 998]

Last updated 2020-12-02 15:48:33.869841 IST

Comments