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")