컴퓨터 못만지는거/야금야금 Python

파이썬으로 연속된 정수의 합 구하기 Sum of Consecutive Integers python

김무명01 2020. 1. 9.

파이썬으로 연속된 정수의 합 구하기

반복문 연습 겸 간단하게 연속된 정수의 합을 더하는 프로그램을 만들었다. 

낯선 부분은 반복문 안에 콜론(:)을 넣는 것 ..

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
print('This is the program for adding up consecutive integers.\n')
n1 = input('The first number: \n')
n2 = input('The last number: \n')
 
n1 = int(n1)
n2 = int(n2)
= 0
 
for i in range(n1, n2 + 1):
 
    if i == n2:
        print(i, end='')
        print(" = ", end='')
 
    else:
        print(i, end='')
        print(" + ", end='')
 
    s = s + i
 
print(s)
 

 

  • input으로 입력받는 텍스트는 모두 문자열로 취급된다.
  • 연산을 하려면 int 명령어를 써서 정수 형태로 바꿔준다.
  • n1, n2를 받아서 list 생성을 해도 될 것 같다.
  • print(i, end='')
    파이썬은 print 명령어를 한 번 쓸 때마다 무조건 한 줄씩 띄어진다.
    print 명령어 한 번은 \n을 포함하고 있는 꼴.
    줄 넘김(?) 없이 한 줄에 줄줄이 입력하려면 end='' 이렇게 입력을 해줘야 한다.
  • 반복문이나 조건문에는 end 명령어가 필요없다.
    tab으로 구분한다.

 

print 형식을 약간 다르게 써 본 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
= 0
 
n1 = input('The first number? \n')
n2 = input('The last number? \n')
 
n1 = int(n1)
n2 = int(n2)+1
 
for i in range(n1, n2):
 
    if i == n2-1:
        print("%d"+end='', %(i))
 
    else:
        print(i, end='')
        print(" + ", end='')
 
    s = s + i
 
print(s)
 

 

print 안에서 "+"를 써서 line 15, 16의 두 줄로 썼던 걸 한 줄로 쓸 수 있다. 

당연히 출력되는 결과는 같다.

 

1 - 10까지 더하기

 

 

음수도 더하기

 

댓글