본문 바로가기
Service/Coding

Google Python Automation Certification - Week 3

by 포항돼지 2022. 2. 2.

Loops

while loops,for loops, recursion(반복, 되풀이)

 

value 에 값 넣는거


x = 0
while x < 5:
    print("Not there yet, x=" + str(x))
    x = x + 1
print("x=" + str(x))

 

총 5번 , 0,1,2,3,4 반복함

def attempts(n):
    x = 1
    while x <= n:
        print("Attempting " + str(x))
        x = x + 1
    print("Done")

attempts(3)

 

variable 없으면 Name error 나옴

 

infinite loop = 끝나지 않는 loop

여기서 n+=1이 없으면, 1씩 증가를 하지 않으니까 계속 똑같은 1만 반복되서 무한 루프 걸리는거
break 쓰면 중간에 멈추는거 가능

1. 벨류 만들기 , initializing

2. 무한루프 아닌지 확인

 

for x in range(5) ,&amp;nbsp; 무조건 0 부터 시작

 

기본으로 변수가 정의 안되어 있는 for, while loop 에서는  0에서 부터 시작

 


values = [ 23, 52, 59, 37, 48]

sum = 0
length = 0
for value in values:
    sum += value
    length += 1

print("totalsum: " + str(sum) + " = Average: " + str(sum/length))
리스트 순서대로 sum에 가져와서 리스트 값을 순서값으로 더하는거 가능
그리고 length 올림으로 총 합계의 나누기 쌉가능
구글 시팔롬들 다 지들처럼 똑똑한줄아나, 왜 이런거 설명 하나도 안하고 그냥 돌려버리지

 

이런 스크립트 일 경우, 1부터 시작하는게 중요하다. 왜? 0부터 시작하면 무조건 output이 0이니까

 

 

def factorial(n):
    result = 1
    for i in range(1,n+1):   #n+1을 안해서 에러가 났었는데, n+1을 하는 이유는, n값까지 포함해서 해야되니까
        result = result * i
    
    return result

print(factorial(4)) # should return 24
print(factorial(5)) # should return 120
 
 

#1 == 시작점(및 끝점) , #2 == 끝점 , #3 == 시퀀스 넘버, 끊어 치기 하고 싶은 양

range function can get the 1,2,3 parameter

sequence generated won't contain the last element;

 

To quickly recap the range() function when passing one, two, or three parameters:

  • One parameter will create a sequence, one-by-one, from zero to one less than the parameter.
  • Two parameters will create a sequence, one-by-one, from the first parameter to one less than the second parameter.
  • Three parameters will create a sequence starting with the first parameter and stopping before the second parameter, but this time increasing each step by the third parameter.

 

Nested for Loops,

Loops inside of the Loops

Left Loop안에 Right Loop이 들어가 있음, 즉 Right Loop이 먼저 끝나고 Left Loop도 끝남

left loop 시작점이 0 부터 시작해서 right loop 7 끝날때까지 계속 저 string print 하는거임, 그래서 left 값이 0 이면 right 값이 7까지 다 돌때까지 나오는거고, 다음 left 값이 증가해서 1이면 , right 값은 1 -> 7까지 (0제외)

다음은 2->7  이렇게 계속 반복 되는 거. end = " " 는 문장 끝낼때 이거 넣겠다고 얘기 하는거

 

# ends the output with '@'
print("Python" , end = '@') 
print("GeeksforGeeks")

Output :

Python@GeeksforGeeks

 

team = ["Tottenham" , "Wolves" , "MU" , "MC"]

for home_team in team:
    for away_team in team:
        if home_team != away_team:
            print(home_team + " vs " + away_team)

 

home_team 이랑 home_team 같으면 그냥 ignore 하게 됨, 왜? 조건문에 같지 않다면만 걸어 놨으니까

Nested for loop is very useful

근데 조심히 써야됨, 프로세싱 처리하는데 거의 더블 되니까 시간 엄청 오래 걸릴수도 있음

 

Python 에서는 integer는 not iterable 하다 0 - 25까지 가려면

range(25)

list = 순서대로 , string 도 순서대로 감

 

존나 어렵누...시발 , 다시 보니까 그냥, for loop안에 user element를 리스트로 넣어서 비교하면 끝임 ㅋ 한번 더 보니까 쉽네

 

Loops Cheat Sheet

Loops Cheat Sheet

Check out below for a run down of the syntax for while loops and for loops.

While Loops

A while loop executes the body of the loop while the condition remains True.

Syntax:

 

Things to watch out for!

  • Failure to initialize variables. Make sure all the variables used in the loop’s condition  are initialized before the loop.
  • Unintended infinite loops. Make sure that the body of the loop modifies the variables used in the condition, so that the loop will eventually end for all possible values of the variables.

Typical use:

While loops are mostly used when there’s an unknown number of operations to be performed, and a condition needs to be checked at each iteration.

For Loops

A for loop iterates over a sequence of elements, executing the body of the loop for each element in the sequence.

Syntax:

 

The range() function:

range() generates a sequence of integer numbers. It can take one, two, or three parameters:

  • range(n): 0, 1, 2, ... n-1
  • range(x,y): x, x+1, x+2, ... y-1
  • range(p,q,r): p, p+r, p+2r, p+3r, ... q-1 (if it's a valid increment)

Common pitfalls:

  • Forgetting that the upper limit of a range() isn’t included.
  • Iterating over non-sequences. Integer numbers aren’t iterable. Strings are iterable letter by letter, but that might not be what you want.

Typical use:

For loops are mostly used when there's a pre-defined sequence or range of numbers to iterate.

Break & Continue

You can interrupt both while and for loops using the break keyword. We normally do this to interrupt a cycle due to a separate condition.

You can use the continue keyword to skip the current iteration and continue with the next one. This is typically used to jump ahead when some of the elements of the sequence aren’t relevant.

If you want to learn more, check out this wiki page on for loops.

 

Recursion (very common technic but not use much in automation)

def sum_positive_numbers(n):
  if n <= 1:
  return n
  return n + sum_positive_numbers(n-1)
   
  print(sum_positive_numbers(3)) # Should be 6
  print(sum_positive_numbers(5)) # Should be 15

 

 

 

 

factor = 인수 , 곱해서 나올수 있는 두가지 자연수

Prime Factor = 소인수 , 하나의 값만 가진 자연수,

pitfall = 눈에 잘안 띄는,, 위험

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

anatomy = 해부학

def attempts(n):
    x = 1
    while x <= n:
        print("Attempting " + str(x))
        x = x + 1
    print("Done")

attempts(3)