본문 바로가기
Service/Coding

Google Python Automation Certification - Week 2

by 포항돼지 2022. 2. 1.

Syntax = 그냥 코드 쓰는거, 컴퓨터한테 뭐 할지 알려주는거

 

Data Type

String = 문자열 (str)

integer = 정수형 (int)

Float = 소수형

 

다른 data type 끼리는 합치기 및 연산 불가능

 

type()하면 무슨 타입인지 확인 가능

 

variables = container of data

length = 10 , width = 2 가 assignment
length * width 가 expression
Must start with a letter or an underscore !

 

lowercase and upercase are different value.

int -> float 으로 바뀜
str() 써서 int 를 스트링으로 바꾸기

 

function

def greeting(name) = parameter

    print("Hi " + name)

 

 

2 Parameter

즉 function쓸때, pamameter (== arguments) 대로 쓰면 그 function이 발생함

 

return

returning value 하려면, 예를 들어서 function 돌려서 나온 결과값을 나중에 쓰려고 저장 하려면 return function 을 써야한다

 

예를 들어서, 2개의 삼각형의 넓이를 더하고 싶을때 => 삼각형 더하는 function 만들어서 return 하면 그 value 안에 function이 return 되어서 저장 되기때문에 추후에 더하기 가능.

 

이렇게 return 이 들어간 function 만들고, 다른 value에 function 돌리고 그 저장된 값 더하기 쌉가능
// 몫 integer로 표현

def convert_seconds(seconds):
    hours = seconds // 3600
    minutes = (seconds - hours * 3600) // 60
    remaining_seconds = seconds - hours * 3600 - minutes * 60
    return hours, minutes, remaining_seconds

a = convert_seconds(222258)
print(a)

return 을 안쓰면, 이렇게 result에 None이라는 값이 나옴, 왜 ?? function에 Christine이라는 value가 return 안됬으니까

Function이랑 Return 잘 쓸때까지 계속 연습 해야됨

첫번째 코드 보면 뭘 하는지 잘 모르니까, 두번째 function으로 refactoring 한 거임

Reader Understandable로 만드는게 제일 좋음 = Good naming or Comment 해야함

 

 

# 1) Complete the function to return the result of the conversion
def convert_distance(miles):
    km = miles * 1.6  # approximately 1.6 km in 1 mile
    return km

my_trip_miles = 55

# 2) Convert my_trip_miles to kilometers by calling the function above
my_trip_km = convert_distance(my_trip_miles)

# 3) Fill in the blank to print the result of the conversion
print("The distance in kilometers is " + str(my_trip_km))

# 4) Calculate the round-trip in kilometers by doubling the result,
#    and fill in the blank to print the result
print("The round-trip in kilometers is " + str(my_trip_km * 2))

 

def lucky_number(name):
    number = len(name) * 9
    string = "Hello" + name + ". Your lucky number is " + str(number)
    return string

print(lucky_number("Wayne"))
print(lucky_number("Jia"))

 

 

 

def order_numbers(number1, number2):

   if number2 > number1:

       return number1, number2

   else:

       return number2, number1

 

(smaller, bigger) = order_numbers(100, 99)

print(smaller, bigger)

 

 

As you can see in the end we are printing (smaller,bigger) but its not defined anywhere else in the program. This gives the idea that, it must filled those blank spaces.

Multiple 하게 return 할 수 있는거 보여주는 거.

 

Etiher true or false
Python doesnt know how to check between number and string smaller or greater
This case, Python totally know int(1)and str(1) is dif
and == 둘다 결과값 만족 해야 실행
둘중에 하나만 맞아도 ok
true == false , false == true 로 만들어줌

ex) print(not 42 == "Answer") 

True

 

execution sequence!

def hint_username(username):
    if len(username) < 3:
        print("Invalid username. Must be at least 3 ch")

 

username letter 3개

otherwise, it skips

if 문 다음에 : 콜론 와야됨, 아니면 intended 한 error (들쑥날쑥, 아무때나 imply 되있는거) 남

 

Modulus = %

def is_even(number):
    if number % 2 == 0:
        return True
    return False

is_even(2)

이런 코드 있을때, 참고로 (% == Modulus , 나머지 값 보여주는거 , // == 몫 , ** == 제곱) if state 가 조건을 충족하면 True 로 가서 함수가 종료되고, 만약 if statement 가 충족이 안되면 다음, return False 로 가서 False 를 출력 하게 된다. Else 문 써도 되긴 하는데, 상황에 따라 다르므로 둘다 알 고 있어야 함

 

Odd == 홀수 , Even == 짝수

 

Elif Statement (else if)

 

def hint_username(username):
    if len(username) < 3:
        print("Invalid username. Must be at least 3 ch")
    elif len(username) > 15:
        print("It is way too long!")
    else:
        print("Valid username")
   
hint_username("Wayne1231242351235")

if, elif, else

 

Comparison operators

  • a == b: a is equal to b
  • a != b: a is different than b
  • a < b: a is smaller than b
  • a <= b: a is smaller or equal to b
  • a > b: a is bigger than b
  • a >= b: a is bigger or equal to b

 

def calculate_storage(filesize):
    block_size = 4096
    # Use floor division to calculate how many blocks are fully occupied
    full_blocks = filesize // 4096
    # Use the modulo operator to check whether there's any remainder
    partial_block_remainder = filesize%4096
    # Depending on whether there's a remainder or not, return
    # the total number of bytes required to allocate enough blocks
    # to store your data.
    if partial_block_remainder > 0:
        return 4096*(full_blocks+1)
    return full_blocks*4096

print(calculate_storage(1))    # Should be 4096
print(calculate_storage(4096)) # Should be 4096
print(calculate_storage(4097)) # Should be 8192
print(calculate_storage(6000)) # Should be 8192

def calculate_storage(filesize):

    block_size = 4096
    full_block = filesize // block_size
    partial_block_remainder = filesize % block_size

    if partial_block_remainder > 0:
        return block_size*(full_block+1)
    else:
        return full_block*block_size

print(calculate_storage(1))
print(calculate_storage(4097))
 

filesize 받아오는거 , block size정해놓고,

full_block , block size comparison을 filesize에 comparison 해서 몫 구해서 몇번 곱해야 하는지 정하기 //

partial_block = 남은 나머지 값이 있으면 더블 해야되니까 나머지값 filesize값에 blocksize값 % comparison으로 구하기

 

 

Question 6

Complete the body of the format_name function. This function receives the first_name and last_name parameters and then returns a properly formatted string.

def format_name(first_name, last_name):
    # code goes here
    string = ("Name : " + last_name + "," + first_name)
    if first_name == "":
        return ("Name : " + last_name)
    elif last_name == "":
        return ("Name : " + first_name)
    elif first_name == "" and last_name == "":
        return ""
    else:
        return string 

 

print(format_name("Ernest""Hemingway"))
# Should return the string "Name: Hemingway, Ernest"
print(format_name("""Madonna"))
# Should return the string "Name: Madonna"
print(format_name("Voltaire"""))
# Should return the string "Name: Voltaire"
print(format_name(""""))
# Should return an empty string

 

 

def fractional_part(numerator, denominator):

 

   if denominator >0:

         return (numerator%denominator)/denominator

   return 0

 

 *********(numerator%denominator)/denominator

 

indented = 들쑥 날쑥한

refactoring = 결과의 변경 없이 코드를 재구성 하는 것

manipulate = 조종하다

tangle = 얽히다

fraction = 부분, 일부

neat = 정돈된

explicit = 분명한, 명쾌한

implict = 암시된, 내포된

contrast = 대조

parameter = 한도

flesh out = 구체화 하다 , 살을 채우다

indentation = 자국

denominator = 분모

numerator = 분자