Python Basics (notes)
Types and Sequences¶
Use `type` to return the object's type.
In [1]:
type('This is a string')
Out[1]:
In [2]:
type(None)
Out[2]:
In [3]:
type(1)
Out[3]:
In [4]:
type(1.0)
Out[4]:
Tuples are an immutable data structure (cannot be altered).
In [6]:
x = (1, 'a', 2, 'b')
type(x)
Out[6]:
Lists are a mutable data structure.
In [7]:
x = [1, 'a', 2, 'b']
type(x)
Out[7]:
Use `append` to append an object to a list.
In [8]:
x.append(3.3)
print(x)
This is an example of how to loop through each item in the list.
In [9]:
for item in x:
print(item)
Or using the indexing operator:
In [10]:
i=0
while( i != len(x) ):
print(x[i])
i = i + 1
Use `+` to concatenate lists.
In [11]:
[1,2] + [3,4]
Out[11]:
Use `*` to repeat lists.
In [12]:
[1]*3
Out[12]:
Use the `in` operator to check if something is inside a list.
In [13]:
1 in [1, 2, 3]
Out[13]:
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
This will return the last element of the string.
In [15]:
x[-1]
Out[15]:
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]:
This is a slice from the beginning of the string and stopping before the 3rd element.
In [17]:
x[:3]
Out[17]:
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]:
In [19]:
firstname = 'Krishnakanth'
lastname = 'Allika'
print(firstname + ' ' + lastname)
print(firstname*3)
print('Krish' in firstname)
`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)
Make sure you convert objects to strings before concatenating.
In [21]:
'Chris' + 2
In [22]:
'Chris' + str(2)
Out[22]:
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]:
In [24]:
x['Carl Sagan'] = None
x['Carl Sagan']
Iterate over all of the keys:
In [25]:
for name in x:
print(x[name])
Iterate over all of the values:
In [26]:
for book in x.values():
print(book)
Iterate over all of the items in the list:
In [27]:
for name, book in x.items():
print(name)
print(book)
You can unpack a sequence into different variables:
In [28]:
x = ('Richard','Dawkins','Evolutionary Biologist')
fname, lname, profession = x
In [29]:
fname
Out[29]:
In [30]:
lname
Out[30]:
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
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']))
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]:
Convert the timestamp to datetime.
In [37]:
dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow
Out[37]:
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]:
`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]:
`date.today` returns the current local date.
In [40]:
today = dt.date.today()
In [41]:
today - delta # the date 100 days ago
Out[41]:
In [42]:
today > today-delta # compare dates
Out[42]:
Functions¶
In [43]:
x = 1
y = 2
x + y
Out[43]:
In [44]:
y
Out[44]:
`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]:
'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))
`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))
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]:
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))
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]:
Now let's iterate through the map object to see the values.
In [68]:
for item in cheapest:
print(item)
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]:
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)
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)
Last updated 2020-12-02 15:48:33.869841 IST
Comments