<jupyter_start><jupyter_text>Python Base Language Quick Reference Table of contents1. Imports2. Simple Data Types3. Math4. Comparisons and Boolean Operations5. Conditional Statements6. For Loops and While Loops7. Slicing8. With Statement9. DateTime  1. Imports<jupyter_code># 'generic import' of math module
import math
math.sqrt(25)
# import a function
from math import sqrt
sqrt(25)  # no longer have to reference the module
# import multiple functions at once
from math import cos, floor

# import all functions in a module (generally discouraged)
from csv import *

# define an alias
import datetime as dt<jupyter_output><empty_output><jupyter_text>2. Simple Data Types **Determine type of an object**<jupyter_code>print(type(2)) #int
type(2.0) #float
type("two") #string
type(True) # bool
type(None) #NoneType<jupyter_output><empty_output><jupyter_text>**Check if an object is of a given type**<jupyter_code>isinstance(2.0, float)
isinstance("two", (float, str))<jupyter_output><empty_output><jupyter_text>**Convert an object to a given type**<jupyter_code>float(2)
int(2.9)
str(2.9)<jupyter_output><empty_output><jupyter_text>**Zero, None and empty containers are converted to False:**<jupyter_code>bool(0)
bool(None)
bool('') # empty string
bool({}) # empty dictionary<jupyter_output><empty_output><jupyter_text>**Non-Empty containers and non-zeros are converted to True**<jupyter_code>bool(2) 
bool('two')
 bool([2])
bool({'key':'val'})<jupyter_output><empty_output><jupyter_text>3. Math<jupyter_code>10 ** 4 # exponent
5 % 4 # modulo
# previous versions of python did integer division
# python 3 coerces values into floats
10/4 
10 // 4 # floor division<jupyter_output><empty_output><jupyter_text>4. Comparisons and Boolean Operations<jupyter_code>x = 5
x != 3
x >= 5 and x < 10
x < 5 or x ==5<jupyter_output><empty_output><jupyter_text>5. Conditional Statements<jupyter_code>if x > 0:
    print('positive')
elif x == 0:
    print('zero')
else:
    print('negative')
#single-line if
if x > 0: print('positive')
#single line if/else statement (ternary operator)
'positive' if x > 0 else 'zero or negative'<jupyter_output><empty_output><jupyter_text>6. For Loops and While Loops **range returns a sequence of integers from 0 to n-1**<jupyter_code># includes the start value but not the stop value [start, end)
range(0,3) #[0, ,1, 2]
rng = range(0,3)
list(rng)
# default start is 0
rng = range(3)
list(rng)
#third argument is a step value
rng = range(0,5,2)
list(rng)<jupyter_output><empty_output><jupyter_text>**for loops:**<jupyter_code># not the recommended style
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
    print(fruits[i].upper())
# recommended style
for fruit in fruits:
    print(fruit.upper())
# iterate through two things at once (using tuple unpacking)
family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
    print( key,value)
# use enumerate if you need to access the index value within the loop
for index,fruit in enumerate(fruits):
    print(index,fruit)<jupyter_output>(0, 'apple')
(1, 'banana')
(2, 'cherry')<jupyter_text>**for/else loop:**<jupyter_code>for fruit in fruits:
    if fruit == 'banana':
        print('Found the banana!')
        break    # exit the loop and skip the 'else' block
else:
    # this block executes ONLY if the for loop completes without hitting 'break'
    print("Can't find the banana")<jupyter_output>Found the banana!<jupyter_text>**while loop:**<jupyter_code>count = 0
while count < 5:
    print('printing %s time(s)' % count)
    count += 1<jupyter_output>printing 0 time(s)
printing 1 time(s)
printing 2 time(s)
printing 3 time(s)
printing 4 time(s)<jupyter_text>7. Slicing<jupyter_code>weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']
weekdays[0]
# elements 0 (inclusive) to 3 (exclusive)
weekdays[0:3]
# starting point implied to be zero
weekdays[:3]
# elements 3 (inclusive) through implied end
weekdays[3:]
# last element
weekdays[-1]
# eveery second element (step by 2)
weekdays[::2]
# backwards (step by -1)
weekdays[::-1]<jupyter_output><empty_output><jupyter_text>8. With Statement<jupyter_code># the With statement (like using in C#) is used to issue cleanup code when a variable comes out of scope
class cleanup_thing:
        def __enter__(self):
            self.open=True
            return self
        def __exit__(self, type, value, traceback):
            self.open=False
        def isOpen(self):
            return self.open

with cleanup_thing() as thing:
    print(thing.isOpen())
print(thing.isOpen())<jupyter_output>True
False<jupyter_text>9. DateTime<jupyter_code>from datetime import datetime
from datetime import timedelta

#get now
datetime.today()
a = datetime(2012, 9, 23)
a
b = timedelta(days=2, hours=6)
a+b
a-b
d=b+timedelta(hours=4.5)
d.days
d.seconds
# total timedelta in seconds
d.total_seconds()<jupyter_output><empty_output><jupyter_text>**Converting to / from strings **<jupyter_code>text = '2012-09-20'
datetime.strptime(text, '%Y-%m-%d')
z = datetime(2012, 9, 23, 21, 37, 4, 177393)
datetime.strftime(z, '%A %B %d, %Y')<jupyter_output><empty_output><jupyter_text>** Time Zones **<jupyter_code>from pytz import timezone

d = datetime(2012, 12, 21, 9, 30, 0)

# localize the date for Chicago
central = timezone('US/Central')
loc_d = central.localize(d)
print(loc_d)
# Convert to Bangalore time
bang_d = loc_d.astimezone(timezone('Asia/Kolkata'))
print(bang_d)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13005143277002204, 'fraction_numerical': 0.026818515797207936, 'mean_word_length': 5.528776978417266, 'pattern_counts': {'":': 0, '<': 72, '<?xml version=': 0, '>': 73, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '18', 'dir': 'jupyter-structured-clean-dedup', 'id': '256609', 'license': 'MIT', 'n_tokens_mistral': 2042, 'n_tokens_neox': 1921, 'n_words': 559, 'path': 'Python Quick Reference/Base Language.ipynb', 'repo_name': 'eriksalt/jupyter', 'size': '5444'}