모듈?

변수, 함수, 클래스 등을 모아 놓은 파일. 모듈에 함수나 정보등을 정의해두고 가져다 쓰는 식



calculator.py 파일 생성


#합

def sum(x, y):

return x + y


# 차이

def difference(x, y):

return x + y


# 곱

def product(x, y):

return x * y


# 제곱

def square(x):

return x * x



이후 이 모듈을 쓸 파이썬 문서에서


from calculaotr import sum, square #difference, product도 가능, from calculator import * < 전부 임포트할 경우


print(sum(3, 5)) # 이런식으로 불러 쓸 수 있다.


i = 1

j = 1


while i <= 9:

    j = 1

    while j <= 9:

        sol = i * j

        print("%d * %d = %d" % (i, j, sol))

        j = j + 1

    i = i + 1

def fibonacci(number):

    previous = 0

    current = 1

    i = 1

    

    while i <= number:

        print(current)

        temp = previous                 #temp는 임시저장 공간

        previous = current

        current = current + temp

        i = i + 1 #i += i

        

fibonacci(20)        

        

x의 n승을 구하고 싶으면

pow(x, n)

def calculate(number):

i = 1

count = 0

while i <= number:

if number % i == 0:

print(i)

count = count + 1

i = i + 1

print("%d의 약수는 총 %d개입니다" % (number, count))

#print(str(number) + "의 약수는 총 " + str(count) + "개입니다.")


calculate(120)

calculate(240)


def calculate():

i = 1

sum = 0

while i < 1000:

if i % 2 == 0 or i % 3 == 0:

sum = sum + i

i = i + 1

return sum


print(calculate())



100이하의 8의 배수이지만 12의 배수는 아닌 숫자를 출력하라



i = 1

while i <= 100:

if i % 8 == 0 and i % 12 != 0:

print(i)

i = i + 1




def notify_grade(midterm, finalterm): #함수 정의

    score = midterm + finalterm # 점수는 중간 + 기말

    if 90 <= score:

        print("A학점입니다.") # 90점 이상 A학점

    elif 80 <= score:

        print("B학점입니다.") # 80점 이상 90점 미만 B학점

    elif 70 <= score:

        print("C학점입니다.") # 70점 이상 80점 미만 C학점

    elif 60 <= score:

        print("D학점입니다.") # 60점 이상 70점 미만 D학점

    else:

        print("낙제입니다.")   # 60점 미만 낙제


notify_grade(100,20) # A학점

notify_grade(40,23)  # D학점

notify_grade(80,80)  # A학점

1. if

a = 10

b = 84

if a < b:
print("b가 a보다 크다")

2. else 

a = 10

b = 84

if a < b:
print("b가 a보다 크다")
else:
print("a가 b보다 크다")

3. elif

a = 10

b = 84

if a < b:
print("b가 a보다 크다")
elif a == b:
print("a랑 b랑 같다")
else:
print("a가 b보다 크다")


i = 100 # 특정값

while i % 27 != 0: #i를 27로 나눴을 때 나머지가 0이 될 때까지 = 27의 배수일 때까지

i = i + 1

print(i)


#특정 값을 초과하는 배수기 때문에 처음부터 while 반복 문 안에 i = 특정값을 설정해주고, n의 배수표현을 i % n 으로 해주는 것

+ Recent posts