Python Basics (notes)

Types and Sequences¶
Use `type` to return the object's type.
type('This is a string')
type(None)
type(1)
type(1.0)
Tuples are an immutable data structure (cannot be altered).
x = (1, 'a', 2, 'b')
type(x)
Lists are a mutable data structure.
x = [1, 'a', 2, 'b']
type(x)
Use `append` to append an object to a list.
x.append(3.3)
print(x)
This is an example of how to loop through each item in the list.
for item in x:
print(item)
Or using the indexing operator:
i=0
while( i != len(x) ):
print(x[i])
i = i + 1
Use `+` to concatenate lists.
[1,2] + [3,4]
Use `*` to repeat lists.
[1]*3
Use the `in` operator to check if something is inside a list.
1 in [1, 2, 3]
Now let's look at strings. Use bracket notation to slice a string.
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.
x[-1]
This will return the slice starting from the 4th element from the end and stopping before the 2nd element from the end.
x[-4:-2]
This is a slice from the beginning of the string and stopping before the 3rd element.
x[:3]
And this is a slice starting from the 4th element of the string and going all the way to the end.
x[3:]
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.
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.
'Chris' + 2
'Chris' + str(2)
Dictionaries associate keys with values.
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
x['Carl Sagan'] = None
x['Carl Sagan']
Iterate over all of the keys:
for name in x:
print(x[name])
Iterate over all of the values:
for book in x.values():
print(book)
Iterate over all of the items in the list:
for name, book in x.items():
print(name)
print(book)
You can unpack a sequence into different variables:
x = ('Richard','Dawkins','Evolutionary Biologist')
fname, lname, profession = x
fname
lname
Make sure the number of values you are unpacking matches the number of variables being assigned.
x = ('Richard','Dawkins','Evolutionary Biologist','Author')
fname, lname, profession = x
Python has a built in method for convenient string formatting.
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¶
import datetime as dt
import time as tm
`time` returns the current time in seconds since the Epoch. (January 1st, 1970)
tm.time()
Convert the timestamp to datetime.
dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow
Handy datetime attributes:
# get year, month, day, etc.from a datetime
dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second
`timedelta` is a duration expressing the difference between two dates.
delta = dt.timedelta(days = 100) # create a timedelta of 100 days
delta
`date.today` returns the current local date.
today = dt.date.today()
today - delta # the date 100 days ago
today > today-delta # compare dates
Functions¶
x = 1
y = 2
x + y
y
`add_numbers` is a function that takes two numbers and adds them together.
def add_numbers(x, y):
return x + y
add_numbers(1, 2)
'add_numbers' updated to take an optional 3rd parameter. Using `print` allows printing of multiple expressions within a single cell.
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.
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`.
def add_numbers(x,y):
return x+y
a = add_numbers
a(1,2)
Objects and map()¶
An example of a class in python:
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
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.
store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2)
cheapest
Now let's iterate through the map object to see the values.
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.
my_function = lambda a, b, c : a + b
my_function(1, 2, 3)
Let's iterate from 0 to 999 and return the even numbers.
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.
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