<jupyter_start><jupyter_text>Numbers<jupyter_code>type(2)
type(2.0)
2 + 2  # addition
2 - 2  # subtraction
2 * 2  # multiplication
2 / 2  # float division
2 // 2  # integer division
2 ** 3  # exponents
2 ** 0.5  # square root
5 % 2  # modulo operator (calculates the remainder)
int(2.0)  # conversion to an integer
int(2.1)  # this rounds down
round(2.11)  # rounds to the nearest integer
round(2.11, ndigits=1)  # round to the nearest 0.1
float(2)  # conversion to float
import math
math.pi
math.lcm(2, 3, 5)  # least common multiple<jupyter_output><empty_output><jupyter_text>Strings<jupyter_code>'a string'
"a string"
print("""
multi-
line
string
""")
'a' + 'string'  # concatenate strings
'a' * 2  # repeat strings
str(2)  # convert a number to a string
# raw string -- the last backslash must be escaped with another backslash if it is at the end
r'C:\Users\Me\A folder\\'
r'C:\Users\Me\A folder\a file.txt'<jupyter_output><empty_output><jupyter_text>String indexing<jupyter_code>'a string'[0]  # first character of a string
'a string'[-1]  # last character of a string
'a string'[0:4]  # index a string to get first 4 characters
'a string'[:4]  # index a string to get first 4 characters
'a string'[::2]  # get every other letter
'a string'[::-1]  # reverse the string
'a string'[:5:2]  # every other letter in the first 5 characters<jupyter_output><empty_output><jupyter_text>Built-in string methods<jupyter_code>'-'.join(['this', 'is', 'a', 'test'])
'this is a test'.split()
'\t\n   - remove left'.lstrip()  # remove whitespace on the left
'\t\n   - remove left'.rstrip()  # remove whitespace on the right
'testtest - remove left'.lstrip('test')  # remove all instances of 'test' from the left of the sting
'testtest - remove left'.lstrip('tes')  # remove all instances of 'tes' characters from the left of the sting
'testtest - remove left'.removeprefix('test')  # remove one instance of 'test' from the left of the string
'testtest - remove left'.removesuffix('left')
f'string formatting {2 + 2}'
print('tabs\tand\nnewlines')
print(r'tabs\tand newlines\n')
print('\t\n   - tabs and newlines')  # tab and newline at the beginning of a string, along with some spaces<jupyter_output>- tabs and newlines<jupyter_text>Variables<jupyter_code>books = 1
books  # print out our variable
books = books + 1
books
books += 1
books
books -= 1
books
books *= 2
books
books /= 2
books
books **= 2
books
books %= 2
books
# concatenate two string variables
a = 'string 1'
b = 'another string'
a + b
# check variable type
type(a)
# don't do this!
# type = 'test'
# type(a)  # if you try this, the type() function will no longer work<jupyter_output><empty_output><jupyter_text>Lists, Tuples, Sets, and Dictionaries<jupyter_code># a basic list
[1, 2, 3]
# lists can contain different data types
[1, 'a', 3]
# lists can contain other lists
[1, [1, 2, 3], 3]
# join lists
[1, 2, 3] + [4, 5]
# repeat a list
[1, 2, 3] * 2
# get the length of a list
len([1, 2, 3])
# make a blank list and add the element '1' to it
a_list = []
a_list.append(1)
a_list
# sort in-place
a_list = [1, 3, 2]
a_list.sort()
a_list
# sort
a_list = [1, 3, 2]
sorted(a_list)
# indexing: [start:stop:step]
a_list = [1, 2, 3, 4, 5]
a_list[0]
a_list[-1]
a_list[0:3]
a_list[:3]
a_list[::2]
a_list[0:3:2]
# reverse a list
a_list[::-1]<jupyter_output><empty_output><jupyter_text>Tuples<jupyter_code>a_tuple = (2, 3)
a_tuple
tuple(a_list)<jupyter_output><empty_output><jupyter_text>Sets<jupyter_code>set(a_list)
a_set = {1, 2, 3, 3}
a_set
set_1 = {1, 2, 3}
set_2 = {2, 3, 4}
set_1.union(set_2)
set_1 | set_2
set_1.difference(set_2)
# shorthand for different operator
set_1 - set_2<jupyter_output><empty_output><jupyter_text>Dictionaries<jupyter_code>a_dict = {'books': 1, 'magazines': 2, 'articles': 7}
a_dict
a_dict['books']
another_dict = {'movies': 4}
a_dict | another_dict
a_dict['shows'] = 12
a_dict<jupyter_output><empty_output><jupyter_text>Loops and Comprehensions<jupyter_code>a_list = [1, 2, 3]
for element in a_list:
    print(element)
a_list = [1, 2, 3]
for index in range(len(a_list)):
    print(index)<jupyter_output>0
1
2<jupyter_text>This brings up the documentation for a function.<jupyter_code>?range
a_list = [1, 2, 3]
for index, element in enumerate(a_list):
    print(index, element)
a_list = []
for i in range(3):
    a_list.append(i)

a_list
# a list comprehension
a_list = [i for i in range(3)]
a_list
a_dict = {'books': 1, 'magazines': 2, 'articles': 7}
for key, value in a_dict.items():
    print(f'{key}:{value}')
# a dictionary comprehension
a_dict = {i: i ** 2 for i in range(1, 4)}
a_dict<jupyter_output><empty_output><jupyter_text>Booleans and Conditionals<jupyter_code>books_read = 11
books_read > 10
none_var = None
none_var is None
books_read = 12
if books_read < 10:
    print("You have only read a few books.")
elif books_read >= 12:
    print("You've read lots of books!")
else:
    print("You've read 10 or 11 books.")
a = 'test'
type(a) is str
type(a) is not str
'st' in 'a string'  # check for a substring in a string
a_set = {1, 2, 3}
1 in a_set
a_list = [1, 2, 3]
1 in a_list
a_dict = {1: 'val1', 2: 'val2', 3: 'val3'}
1 in a_dict
if 1 in a_set:
    print('1 is in there')
condition = False
if condition != False:
    print('not false')
elif condition == False:
    print('is false')<jupyter_output>is false<jupyter_text>Libraries and Imports<jupyter_code>import time
time.time()
import time as t
t.time()
import urllib.request
urllib.request.urlopen('https://www.pypi.org')
from urllib.request import urlopen
urlopen('https://www.pypi.org')
# importing a function from a subpackage of a library, and aliasing it
from urllib.request import urlopen as uo
uo('https://www.pypi.org')<jupyter_output><empty_output><jupyter_text>Functions<jupyter_code>def test_function(doPrint, printAdd='more'):
    """
    A demo function.
    """
    if doPrint:
        print('test' + printAdd)
    return printAdd
value = test_function(True)
print(value)
# brings up documentation for sorted()
?sorted
a_list = [2, 4, 1]
sorted(a_list, reverse=True)
def test_function():
    """
    A demo function.
    """
    func_var = 'testing'
    print(func_var)
test_function()
func_var
add10 = lambda x, y: x + y + 10
add10(10, 3)<jupyter_output><empty_output><jupyter_text>Classes<jupyter_code>class testObject:
    def __init__(self, attr):
        self.test_attribute = attr
    
    
    def test_function(self):
        print('testing123')
        print(f'testing{self.test_attribute}')
to = testObject(123)
to.test_attribute
to.test_function()<jupyter_output>testing123
testing123<jupyter_text>Here is another module from core Python.<jupyter_code>import calendar
# creates a new instance of a Calendar object
c = calendar.Calendar()
type(c)
# an attribute
c.firstweekday
# a method/function
list(c.iterweekdays())<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1338709677419355, 'fraction_numerical': 0.030791788856304986, 'mean_word_length': 4.731932773109244, 'pattern_counts': {'":': 0, '<': 62, '<?xml version=': 0, '>': 63, 'https://': 3, 'lorem ipsum': 0, 'www.': 3, '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': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '667438', 'license': 'MIT', 'n_tokens_mistral': 2716, 'n_tokens_neox': 2564, 'n_words': 772, 'path': '2-Chapter-2/Python Basics.ipynb', 'repo_name': 'DiegoMerino28/Practical-Data-Science-with-Python', 'size': '6820'}