๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Python

[Python] ์—ฐ์Šต๋ฌธ์ œ 3

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 3. 18.
๋ฐ˜์‘ํ˜•

Q1. ๋‹ค์Œ ์ฝ”๋“œ์˜ ๊ฒฐ๊ด๊ฐ’์€ ๋ฌด์—‡์ผ๊นŒ?

a = "Life is too short, you need python"

if "wife" in a: print("wife")
elif "python" in a and "you" not in a: print("python")
elif "shirt" not in a: print("shirt")
elif "need" in a: print("need")
else: print("none")

 

A) shirt

 

 

 

Q2. while๋ฌธ์„ ์‚ฌ์šฉํ•ด 1๋ถ€ํ„ฐ 1000๊นŒ์ง€์˜ ์ž์—ฐ์ˆ˜ ์ค‘ 3์˜ ๋ฐฐ์ˆ˜์˜ ํ•ฉ์„ ๊ตฌํ•ด ๋ณด์ž.

A)

result = 0
i = 1
while i <= 1000:
    if i % 3 == 0  # 3์œผ๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋Š” ์ˆ˜๋Š” 3์˜ ๋ฐฐ์ˆ˜
    result += i
    i += i
    
print(result)  # 166833 ์ถœ๋ ฅ

 

 

Q3. while๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ณ„(*)์„ ํ‘œ์‹œํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•ด ๋ณด์ž.

*
**
***
****
*****

 

A)

i = 0
while True:
    i += 1           # while๋ฌธ ์ˆ˜ํ–‰ ์‹œ 1์”ฉ ์ฆ๊ฐ€
    if i > 5: break  # i ๊ฐ’์ด 5 ์ด์ƒ์ด๋ฉด while๋ฌธ์„ ๋ฒ—์–ด๋‚œ๋‹ค
    print('*' * i)   # i ๊ฐ’ ๊ฐœ์ˆ˜๋งŒํผ *๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค

 

 

Q4. for๋ฌธ์„ ์‚ฌ์šฉํ•ด 1๋ถ€ํ„ฐ 100๊นŒ์ง€์˜ ์ˆซ์ž๋ฅผ ์ถœ๋ ฅํ•ด ๋ณด์ž.

A)

>>> for i in range(1, 101):
...     print(i)
...
1
2
3
4
5
6
7
8
9
10
... ์ƒ๋žต ...

 

 

Q5. A ํ•™๊ธ‰์— ์ด 10๋ช…์˜ ํ•™์ƒ์ด ์žˆ๋‹ค. ์ด ํ•™์ƒ๋“ค์˜ ์ค‘๊ฐ„๊ณ ์‚ฌ ์ ์ˆ˜๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

[70, 60, 55, 75, 95, 90, 80, 80, 85, 100]

for๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ A ํ•™๊ธ‰์˜ ํ‰๊ท  ์ ์ˆ˜๋ฅผ ๊ตฌํ•ด ๋ณด์ž.

 

A)

A = [70, 60, 55, 75, 95, 90, 80, 80, 85, 100]
total = 0
for score in A:
    total += score        # Aํ•™๊ธ‰์˜ ์ ์ˆ˜๋ฅผ ๋ชจ๋‘ ๋”ํ•œ๋‹ค
average = total / len(A)  # ํ‰๊ท ์„ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด ์ด ์ ์ˆ˜๋ฅผ ์ด ํ•™์ƒ์ˆ˜๋กœ ๋‚˜๋ˆˆ๋‹ค
print(average)            # ํ‰๊ท  79.0์ด ์ถœ๋ ฅ๋œ๋‹ค

 

 

Q6. ๋ฆฌ์ŠคํŠธ ์ค‘์—์„œ ํ™€์ˆ˜์—๋งŒ 2๋ฅผ ๊ณฑํ•˜์—ฌ ์ €์žฅํ•˜๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฝ”๋“œ๊ฐ€ ์žˆ๋‹ค.

numbers = [1, 2, 3, 4, 5]

result = []
for n in numbers:
    if n % 2 == 1:
         result.append(n*2)

์œ„ ์ฝ”๋“œ๋ฅผ ๋ฆฌ์ŠคํŠธ ๋‚ดํฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ‘œํ˜„ํ•ด ๋ณด์ž.

 

A)

numbers = [1, 2, 3, 4, 5]
result = [n*2 for n in numbers if n%2==1]
print(result)
[2, 6, 10]
๋ฐ˜์‘ํ˜•

'Python' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Python] ํ•จ์ˆ˜ - ๋งค๊ฐœ ๋ณ€์ˆ˜์™€ ์ธ์ˆ˜  (0) 2021.03.19
[Python] ํ•จ์ˆ˜  (0) 2021.03.19
[Python] for๋ฌธ  (0) 2021.03.18
[Python] while๋ฌธ  (0) 2021.02.11
[Python] if๋ฌธ  (0) 2021.02.11

๋Œ“๊ธ€