Python Basics Flashcards
Syntax used to concatenate strings
‘a’ + ‘b’
Finding the type of a value
type([val])
Syntax to define a function
def [function_name](param1, param2): code return val1, val2
Syntax to insert values into a string in order
“France is in {} and China is in {}”.format(“Europe”, “Asia”)
Insert values into a string by position
“{0} times {0} equals {1}”.format(3, 9)
Insert values into a string by name
“{name}’s population is {pop} million”.format(name=”Brazil, pop=209)
Format specification for 2 decimal places
“I own {:.2f}% of the company”.format(32.5548)
Format specification for 2 decimal places and comma separator
“Your bank balance is {:,.2f}”.format(12345.678)
Define an init function in a class to assign an attribute at instantiation
class class_name:
def_init_(self, param1):
self.attribute1 = param1
mc_2 = MyClass(“arg_1”)
Import datetime module
import datetime as dt
Create datetime.datetime string given a month, year and day
[var] = dt.datetime(1985, 3, 13)
Create datetime.datetime object from string
[var] = dt.datetime.strptime(“24/12/1984”, “%d/%m/%Y”)
Convert datetime.datetime object to string
dt_object = dt.datetime(1984, 12, 24) dt_string = dt_object.strftime("%d/%m/%Y")
Instantiate a datetime.time object
[var] = datetime.time(hour=0, minute=0, second=0, microsecond=0)
Retrieve part of a date stored in the datetime.datetime object
[var].day
Create a date from a datetime.datetime object
d2_dt = dt.datetime(1946, 9, 10) d2 = d2_dt.date()
Create a datetime.date object from a string
d3_str = "17 February 1963" d3_dt = dt.datetime.strptime(d3_str, "%d %B %Y") d3 = d3_dt.date
Instantiate a datetime.timedelta object
eg_4 = dt.timedelta(weeks=3)
Add a time period to datetime.datetime object
d1 = dt.date(1963, 2, 26) d1_plus_1wk = d1 + dt.timedelta(weeks=1)