Python/Fundamentals

Python Basics(1). (from Coursera)

metamong 2022. 4. 4.

1) Python Basics

# Types

e.g) 11 (int) / 12.32 (float) - can check the specifics of floats 'sys.float_info' / "I love Python" (str) / True, False (bool)

→ By using the data type, we can see the actual data type (type(11) = int)

→ type casting) change the type of the expression (float(2), int(2.2), string(1), int(True) = 1)

 

# Expressions & Variables

→ 

 

# String Operations

→ String = a sequence of characters contained within two quotes
→ 

 

 

 

→ e.g) name = 'lizz', print(name[0:2]) = 'li'

→ len command - len("Hello") = 5

→ concatenate) + - a = "apple", b = " is the best", a+b = "apple is the best"

→ replicate the string) - a = "apple", 2*a = "appleapple"

→ immutable - a[0] = "b" (x)

→ \n, \t, \\ (or put r in front of the string)

→ method) upper, replace, find(output is the first index of the sequence), 

# Lists & Tuples = 

 

 

* ex)  A = (1,2,3,4,5) A[1:4] results (2,3,4) (the last index is one larger than we want)

→ immutable = we can't change the elements (but we can assign variable to other tuple)

→ function) sorted(tuple): sorts the elements in a tuple

→ method) index: finding the index of an element

→ nesting

 

 

: can access strings in the second nested tuples using a third index (NT[2][1][0] = 'r')

 

* Lists = (also) an ordered sequence

→ a list is represented with square brackets e.g) [1, 3.14, "hello", 5]

→ mutable

→ the same convetions apply for nesting

→ each element of a list can be accssed via index (including negative index)

→ concatenate & slicing

→ extend, append(add only one more element in the list)

→ split: can use split function to separate strings on a specific character known, as a delimiter

 

* ex) "A,B,C,D".split(",") = [A,B,C,D]

→ aliasing: after B=A, when we change A[0], B[0] also changes

→ solution: B=A[:] (B references a new copy or clone of the original list)

→ del command - removing the element in the list (del(A[0]))

→ help command - get more info

 

# Dictionaries

 

→ Key) 

→ use {}

 

 

→ by using dict[key1], we can print the value of key1

→ by making a code 'dict[key6]', a new key-value pair is entered in a dictionary

→ del dict[key1]

→ we can check if the key we are looking for is in the dictionary by using in command ("key3" in dict - returns True or False)

→ dict.keys() - returns a list of keys

→ dict.values() - returns a list of values

 

# Sets = a type of collection

→ unlike lists and tuples, they are unordered (do not record element position)

→ only have unique elements (duplicate items will not be present)

→ use {}

→ type casting (list -> set by using set())

→ set.add, set.remove

→ check the item using in command

→ using a venn diagram is an easy way to understand sets

→ set1 & set2: find the intersection of two sets (common elements) ( = set1.intersection(set2))

→ set1.difference(set2): find all the elements that are only contained in set1

→ set1.union(set2): has all the elements in set1 and sets

→ set1.issubset(set2) / set1.issuperset(set2)

# Conditions & Branching

 

* Comparions Operators

→ compares some value or operand

→ based on some condition, they produce a Boolean

→ <, >, <=, >=, !=, == (case sensitive)

→ Inequality operation is also used to compare the letters/words/symbols according to the ASCII value of letters

→ when there are multiple letters, the first letter takes precedence in ordering

 

* Branching

→ allows us to run different statements for a different input

 

age = 18
if(age > 18):
	print("you can enter")
elif(age == 18):
	print("go see Pink Floyd")
else:
	print("go see Meat Loaf")
print("move on")

 

* Logic Operators

→ take Boolean values & produce Boolean values

→ not, or, and operator

 

album_year = 1979

if album_year < 1980 or album_year == 1991 or album_year == 1993:
	print("this album came out in year %d" %album_year)

 

# Loops

 

- range(N) = [0, 1, 2, ... N-1], range(N, N+3) - [N, N+1, N+2] (range function generates a list)

 

* for loops

 

# For Loop example

dates = [1982, 1980, 1973]
N = len(dates)

for i in range(N):
	print(dates[i])
    
"""

1982
1980
1973

"""
    
# Loop through the list and iterate on both index and element value

squares = ['red', 'yellow', 'green', 'purple', 'blue']

for i, square in enumerate(squares):
	print(i, square)

"""
0 red
1 yellow
2 green
3 purple
4 blue

"""

 

* while loops

- 

 

# While Loop Example

dates = [1982, 1980, 1973, 2000]

i = 0
year = dates[0]

while(year != 1973):    
    print(year)
    i = i + 1
    year = dates[i]
    

print("It took ", i ,"repetitions to get out of loop.")

"""

1982
1980
It took  2 repetitions to get out of loop.

"""

 

PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
Rating = PlayListRatings[0]
i = 0

while(i < len(PlayListRatings) and Rating >= 6):
    print(Rating)
    i = i+1
    Rating = PlayListRatings[i]
    
"""
10
9.5
10
8
7.5
"""

 

squares = ['orange', 'orange', 'purple', 'blue ', 'orange']
new_squares = []

i = 0
while(i < (len(squares)-1) and squares[i] == 'orange'):
    new_squares.append(squares[i])
    i = i+1
print(new_squares)

"""

['orange', 'orange']

"""

 

# Functions

 

* Built-in functions

→ len)  

→ sum) 

 

 

album_ratings = [10.0,8.5,9.5,7.0,7.0,9.5,9.0,9.5]
sorted_album_rating = sorted(album_ratings)

# album_ratings: unchanged
# sorted_album_rating: [7.0,7.0,8.5,9.0,9.5,9.5,9.5,10.0]

 

→ function sorted returns a new sorted list or tuple
(

 

album_ratings = [10.0,8.5,9.5,7.0,7.0,9.5,9.0,9.5]
album_ratings.sort()

# album_ratings:[7.0,7.0,8.5,9.0,9.5,9.5,10.0] 

 

 

* making a function

 

→ documentation is surrounded by triple quotes

→ help command - to display the documentation

→ scope) global(keyword global), local variables

 

→ Function blocks begin def followed by the function name and parentheses ()

→ There are input parameters or arguments that should be placed within these parentheses.

→ You can also define parameters inside these parentheses

→ There is a body within every function that starts with a colon (:) and is indented.

→ You can also place documentation before the body.

→ The statement return exits a function, optionally passing back a value.

 

 

* Collections & Functions

 

→ tuple example

 

def printAll(*args): # All the arguments are 'packed' into args which can be treated like a tuple
    print("No of arguments:", len(args)) 
    for argument in args:
        print(argument)
#printAll with 3 arguments

printAll('Horsefeather','Adonis','Bone')
#printAll with 4 arguments

printAll('Sidecar','Long Island','Mudslide','Carriage')

"""

No of arguments: 3
Horsefeather
Adonis
Bone
No of arguments: 4
Sidecar
Long Island
Mudslide
Carriage

"""

 

→ dictionary example

 

def printDictionary(**args):
    for key in args:
        print(key + " : " + args[key])

printDictionary(Country='Canada',Province='Ontario',City='Toronto')

"""

Country : Canada
Province : Ontario
City : Toronto

"""

 

# Exception Handling

 

try:
	getfile = open("myfile", "r")
	getfile.write("My file for exception handling.")
except IOError:
	print("Unable to open or read the date in the file.")
else:
	print("The file was written successfully")
finally:
	getfile.close()
    print("File is now closed.")
    

 

→ A try except will allow you to execute code that might raise an exception and in the case of any exception or a specific one we can handle or catch the exception and execute specific code. This will allow us to continue the execution of our program even if there is an exception

→ Python tries to execute the code in the try block. In this case if there is any exception raised by the code in the try block it will be caught and the code block in the except block will be executed. After the code that comes after the try except will be executed

→ else allows one to check if there was no exception when executing the try block. This is useful when we want to execute something only if there were no errors.

→ finally allows us to always execute something even if there is an exception or not. This is usually used to signify the end of the try except.

 

 

# Objects & Classes

 

→ an instance of an object: the realisation of a class

→ methods give you a way to change or interact with the object

 

* ex) creating a class Circle

 

# Create a class Circle

class Circle(object):
    
    # Constructor
    def __init__(self, radius=3, color='blue'):
        self.radius = radius
        self.color = color 
    
    # Method
    def add_radius(self, r):
        self.radius = self.radius + r
        return(self.radius)
    
    # Method
    def drawCircle(self):
        plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
        plt.axis('scaled')
        plt.show()  

 

→ creating an instance of a class Cricle & using the method

 

# Create an object RedCircle

RedCircle = Circle(10, 'red')
# Find out the methods can be used on the object RedCircle

dir(RedCircle)
# Print the object attribute radius

RedCircle.radius
# Print the object attribute color

RedCircle.color
# Set the object attribute radius

RedCircle.radius = 1
RedCircle.radius
# Call the method drawCircle

RedCircle.drawCircle()

 

 

* source) 'Python for DS, AI & Development' by Coursera

'Python > Fundamentals' 카테고리의 다른 글

python OOP  (0) 2022.07.07
Python Basics(2). (from Coursera)  (0) 2022.04.13
시계열 데이터 - datetime  (0) 2022.03.24
list comprehension  (0) 2022.03.20
Module & Package  (0) 2022.03.19

댓글