Python - Week 1

·

8 min read

Last Monday, I started to watch pre-recorded online lectures about Python. Starting this week, I will write a weekly development blog about what I've learned, what I felt during the process, and what I can do with the things I've learned.

Week 1

Print

print('text')
print("text")
print('''text''')
print("""text""")

Separators

print('P', 'Y', 'T', 'H', 'O', 'N', sep=' ')
print('010', '1234', '5678', sep=' - ')
print('google', 'gmail.com', sep='@')

End Option

print('Welcome to', end=' ')
print('My Website') # prints Welcome to My Website

Format

print('%s %s' % ('one, two')) # prints one, two
print('%d %d' % (1, 2)) # prints 1, 2
print('{} {}'.format('one, two')) # prints one, two
print('{1} {0}'.format('one, two)) # prints two, one (python counts from zero)

%s

print('%10s' % ('s')) # prints          s
print('{:>10}'.format('string')) # prints          s
print('%-10s' % ('string')) # prints s         (has nine spaces after s)
print('{:10}'.format('string')) # prints s         (has nine spaces after s)
print('{:_<10}'.format('s')) # prints _________s (replaces space with _)
print('{:^10}'.format('s')) # prints     s     (places s in the middle)
print('%.5' % ('pythonstudy')) # prints pytho (. cuts the remainders)
print('{:.5}'.format('pythonstudy')) # prints pytho (. cuts the remainders)
print('{:10.5}'.format('pythonstudy')) # prints pytho (. cuts the remainders)

%d

print('%4d' % (42)) # prints   42
print('{:4d}'.format(42)) # prints   42

%f

print('%f' % (3.141592653589793)) # prints 3.141593 (rounds to the 6th digit)
print('{:f}'.format(3.141592653589793)) # prints 3.141593
print('%06.2f' % (3.141592653589793)) # prints 003.14
print('{:06.2f}'.format(3.141592653589793) # prints 003.14

Variables

Python declaration

Camel case (pythonLearning) : used for naming methods

Pascal case (PythonLearning) : used for naming classes

Snake case (python_learning) : used for naming varibles

n = 700
print(n) # prints 700
print(type(n)) # prints <class 'int'>
n = 7
print(n) # prints 7
m = n
print(m, n) # prints 7, 7
print(id(m)) # prints its very own identity value (ex. 2602841763088)
print(id(m) ==  id(n)) # prints True

Python Data Types

str = 'sequence' # letters
int = '4' # integer
float = '2.17' # real number
complex = '3, 1' # complex number
bool = 'True' # booleans (True, False)
list = [1, 2, 3] 
tuple = (1, 2, 3)
dict = {'name': 'Eric'}
set = {1, 2, 3}

Operators

+
-
*
/
// : remainder
abs(x) : absolute value
pow(x, y) x ** y -> 2 ** 3

Casting

print(bool(0)) # prints False
print(int(3.12)) # prints 3
print(float(2)) # prints 2.0
print(complex(1)) # prints (1 + 0j)
print(complex(0)) # prints 0j

Escape(backslash)

print(tab \t here) # prints tab (tab) here
print(new \n line) # prints 'line' on a new line
raw_string = r'D:\tpython\ntest
print(raw_string) # prints D:\tpython\ntest (r' makes str raw)
multi_str = \
"""
this
is how
you write 
in multiline
for variables
"""

Str Calculation

str_01 = "python"
str_02 = "Apple"
str_03 = "How are you doing"
str_04 = "Seoul Deajeon Busan Jinju"

print(str_01 * 3) 
print(str_01 +str_02)
print('y' in str_01) # True (y is in python)
print('z' in str_01) # False (z is not in python)
print('P' not in str_02)

Str Functions

print("Capitalize: ", str_01.capitalize())
print("endswith?: ", str_02.endswith("e")) # True (Apple ends with e)
print("replace", str_01.replace("thon", "good")) # prints pygood
print("sorted: ", sorted(str_01)) # sorts python in alphabetical order
print("split: ", str_04.split(' ')) # splits str according to spaces

Slicing

str_sl = 'Nice Python'

print(str_sl[0:3]) # prints Nic
print(str_sl[5:]) # prints from the 5th letter
print(str_sl[:len(str_sl)]) # str_sl[:11]
print(str_sl[:len(str_sl)-1])
print(str_sl[1:9:2]) # prints from 1st to 9th with 2 between each
print(str_sl[-5:]) # from the 5th from the right to the end
print(str_sl[1:-2])
print(str_sl[::2]) # beginning to end, with 2 between each
print(str_sl[::-1])

ASCII Values

# Every word, letter, functions, has its own ASCII value
print(ord(a)) # prints the ASCII value of a
print(chr(122)) # prints the letter of an ASCII value 122 (z)

Python Data Structures

Python List

a = [1, 2, 3, 'eric', 'shin', [10, 20 , 30]] # declaration
print(a[1]) # indexing (pulling a particular value out from the list) prints 2
print(a[5][1]) # pulls 20
print(a[0:3]) # slicing (prints the first three values)
print(a * 3) # list calculation
print('Test' + str(a[0])) # casts 1 to str for errors
print(a == a[:3] + a[3:]) # prints True

Editing Lists

a = [1, 2, 3, 'eric', 'shin', [10, 20 , 30]] # declaration
a[0] = 4 # editing
del a[0] # deleting
a.append(500) # adds 500 at the end of list a
a.sort()
a.reverse()
a.insert(2, 7) # replaces 3 with 7
a.remove(10) # removes value 10
print(a.pop()) # prints the very last value of list a, and removes it
extend_ex = [1, 2, 3]
a.extend(ex) # adds [1, 2, 3] at the end of list a

Python Tuples

a = (1, 2, 3) # tuple values cannot be edited nor deleted
print(a.index(2)) # prints the position where 2 is placed

# Packing (grouping values into a tuple)
packing = ('a', 'b', 'c', 1, 2, 3)

# Unpacking (distributing values into separate variables)
x1, x2, x3, x4, x5, x6 = packing
print(x1) = prints a

Python Dictionaries

dic = {'name': 'Eric', 'city': 'Pangyo', 'age' = 15}
multiline = {
    'Name': 'Eric',
    'City': 'Pangyo',
    'Age': 15,
    'Grade': 8,
    'Status': True
}
easier_way = (
    Name='Eric',
    City='Pangyo',
    Age=15,
    Grade=8,
    Status=True
)
print(dic.get('name')) # prints Eric
print(dic['name']) # does the same thing
print(dic.keys()) # lists keys ONLY
print(dic.values()) # lists values ONLY
print(list(dic.items())) # groups keys with corresponding values
dic['name'] = 'Duke' # editing
dic.update(name='Dorothy') # function for editing
dic_update = (
name='Erick'
)
dic.update(dic_update)

Python Set

# declaration
a = set([1, 2, 3])
b = set([1, 2, 3, 'a', 'b', 'c'])
c = {1, 2, 3}
d = {1, 2, 3, (1, 2, 3), [1, 2, 3]}

# cast to tuple
t = tuple(a)

# Set functions

print(a.intersection(b))
print(a.union(b))
print(a.difference(b))
print(a.isdisjoint(b)) # looks for values that exist both in a and b
print(a.issubet(b))
print(a.issuperset(b))

# Editing Sets

a.add(100)
a.discard(1)
a.remove(1)
a.clear # applicable to lists

Control Statements

If Statements

# Booleans (True, False)
# Operators
x = 15
y = 10

print(x == y) # False
print(x != y) # True
print(x > y) # True
print(x < y) # False
print(x >= y) # True
print(x <= y) # False

# Logic Operators
# and, or, not
a = 75
b = 40
c = 10

print('and:', a > b and b > c) # a > b > c
print('or:', a > b or b > c) # a > b or b > c 
print('not:', not a > b) # a <= b
print('not:', not b > c) # b <= c

# Priorities
# Calculation(+, -, *, /, ...) > Relations(>, <, <=, >=, ...) > Logic Operators(and, or, not)

# elifs (else if) and elses
num = 90

if num >= 90:
    print('Grade : A')
elif num >= 90:
    print('Grade : B')
elif num >= 70:
    print('Grade : C')
else:
    print('Fail')

Python Loops

For Loops

# for in <collection>
#   <loop body>

# range (from 0 - (n-1))
for v1 in range(10): # 0 ~ 9
    print('v1 is :', v1)

for v3 in range(1, 11, 2): # 1, 3, 5, 7, 9
    print('v3 is :', v3)

# sum functions
print(sum(range(1, 100)))

# Applications
lotto_numbers = [11, 19, 21, 12, 24, 35]

for n in lotto_numbers:
    print('Current number : ', n)

name = 'FineAppLE'

for n in name:
    if n.isupper():
        print(n)
    else:
        print(n.upper()) 
# prints
F
I
N
E
A
P
P
L
E

# break
# Stops when the code is executed

numbers = [14, 3, 4, 7, 10, 17, 21, 33, 77, 38, 37]

for num in numbers:
    if num == 33:
        print('Found : 33!')
        break # when the code is run, it stops immediately
    else:
        print('Not Found : 33')

# continue
# ignores the code below and continues on to the next loop

lt = ["1", 2, 4, True, 4.3, complex(4)]

for v in lt:
    if type(v) is bool:
        continue
    print("current type :", type(v))

# for - else

numbers = [14, 3, 4, 7, 10, 17, 21, 33, 77, 38, 37]

for num in numbers:
    if num == 21:
        print("Found : 24")
        break
else:
    print('Not found : 24')

# Application 2 (Times Table)

for i in range(2, 10):
    for j in range(1, 10):
        print('{:4d}'.format(i * j), end=' ')
    print()

While Loops

# Be careful because while loops often cause infinite loops, which makes the computer crash

# while <expr>:
#    <statement(s)>

# break, continue

n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)
print('Loop ended')

m = 5
while m > 0:
    m -= 1
    if m == 2:
        continue
    print(m)
print('Loop ended')

# While - else statements

a = ['foo', 'bar', 'baz', 'qux']
s = 'kim'

i = 0

while i < len(a):
    if a[i] == s:
        break
    i += 1
else:
    print(s, 'not found in list')

Thoughts

It was really fun learning how to code, and seeing how the computer works as I coded. Even when it was not working, it was still fun figuring out the reason and fixing them. I think I will generally enjoy learning this particular coding language. In difficulty wise, it is very easy, there are some hard concepts like packages, ifs, if-elses, that some people might not be familiar with, but if you keep using them, you will understand how they work easily.