본문으로 이동

프로그래머가 아닌 이들을 위한 파이썬 3 자습서/결정

위키책, 위키책

If 구문(조건문)

[+/-]

내가 항상 믿는 것처럼 가볍게 실습을 하면서 이번 장도 시작합시다, 이번 프로그램은 정수의 절대값을 구하는 것입니다:

n = int(input("숫자? "))
if n < 0:
   print(n, "의 절대값은", -n, "입니다.")
else:
   print(n, "의 절대값은", n, "입니다.")

Here is the output from the two times that I ran this program:

숫자? -34
-34 의 절대값은 34 입니다.
숫자? 1
1 의 절대값은 1 입니다.

So what does the computer do when it sees this piece of code? First it prompts the user for a number with the statement "n = int(input("Number? "))". Next it reads the line "if n < 0:". If n is less than zero Python runs the line "print("The absolute value of", n, "is", -n)". Otherwise it runs the line "print("The absolute value of", n, "is", n)".

More formally Python looks at whether the expression n < 0 is true or false. An if statement is followed by an indented block of statements that are run when the expression is true. Optionally after the if statement is an else statement and another indented block of statements. This second block of statements is run if the expression is false.

There are a number of different tests that an expression can have. Here is a table of all of them:

연산자 기능
< 미만(보다 작다)
<= 이하(보다 작거나 같다)
> 초과(보다 크다)
>= 이상(보다 크거나 같다)
== 같다
!= 같지 않다

Another feature of the if command is the elif statement. It stands for else if and means if the original if statement is false but the elif part is true, then do the elif part. And if neither the if or elif expressions are true, then do what's in the else block. Here's an example:

a = 0
while a < 10:
    a = a + 1
    if a > 5:
        print(a, ">", 5)
    elif a <= 3:
        print(a, "<=", 3)
    else:
        print("두 가지 모두 참이 아닙니다.")

and the output:

1 <= 3
2 <= 3
3 <= 3
두 가지 모두 참이 아닙니다.
두 가지 모두 참이 아닙니다.
6 > 5
7 > 5
8 > 5
9 > 5
10 > 5

Notice how the elif a <= 3 is only tested when the if statement fails to be true. There can be more than one elif expression, allowing multiple tests to be done in a single if statement.

Examples

[+/-]
# This Program Demonstrates the use of the == operator
# using numbers
print(5 == 6)
# Using variables
x = 5
y = 8
print(x == y)

And the output

False
False

high_low.py

# 숫자 맞추기 게임을 합시다

# 사실 뭔가 마지막 자리수가 바뀌는 등의 무작위의 요소가 있어야 하는데,
# 그런 것은 차후에 살필 때까지 기다려 주세요
# (모듈을 다루는 장에서 무작위가 되도록 수정할 겁니다)
number = 7
guess = -1

print("숫자를 맞춰 보세요!")
while guess != number:
    guess = int(input("  아마... "))

    if guess == number:
        print("와아! 맞췄어요!")
    elif guess < number:
        print("제 생각보다 좀 큰데요...")
    elif guess > number:
        print("그렇게 크지는 않은데요.")

Sample run:

숫자를 맞춰 보세요!
  아마... 2
제 생각보다 좀 큰데요...
  아마... 5
제 생각보다 좀 큰데요...
  아마... 10
그렇게 크지는 않은데요.
  아마... 7
와아! 맞췄어요!

even.py

# 숫자를 물어본 후.
# 짝수인지 홀수인지를 출력한다
 
number = float(input("숫자를 말해봐: "))
if number % 2 == 0:
    print(int(number), "? 짝수이다.")
elif number % 2 == 1:
    print(int(number), "? 홀수이다.")
else:
    print(number, "... 뭔가 잘못됐다.")

Sample runs:

숫자를 말해봐: 3
3 ? 짝수이다.
숫자를 말해봐: 2
2 ? 짝수이다.
숫자를 말해봐: 3.4895
3.4895 ... 뭔가 잘못됐다.

average1.py

# 0이 입력되기 전까지 숫자를 입력받는다.
# 평균값을 출력한다.

count = 0
sum = 0.0
number = 1 # 루프가 즉시 종료되지 않도록 어떤 값이든 입력한다.

print("0을 입력하면 루프가 종료됩니다.")

while number != 0:
    number = float(input("숫자를 입력하시오: "))
    if number != 0:
        count = count + 1
        sum = sum + number
    if number == 0:
        print("입력된 평균값:", sum / count)

틀:Solution average2.py

# keeps asking for numbers until count numbers have been entered.
# Prints the average value.

#Notice that we use an integer to keep track of how many numbers, 
# but floating point numbers for the input of each number
sum = 0.0

print("This program will take several numbers then average them")
count = int(input("How many numbers would you like to average: "))
current_count = 0

while current_count < count:
    current_count = current_count + 1
    print("Number", current_count)
    number = float(input("Enter a number: "))
    sum = sum + number
    
print("The average was:", sum / count)

Sample runs:

This program will take several numbers then average them
How many numbers would you like to average: 2
Number 1
Enter a number: 3
Number 2
Enter a number: 5
The average was: 4.0
This program will take several numbers then average them
How many numbers would you like to average: 3
Number 1
Enter a number: 1
Number 2
Enter a number: 4
Number 3
Enter a number: 3
The average was: 2.66666666667

실습

[+/-]

Write a program that asks the user their name, if they enter your name say "That is a nice name", if they enter "John Cleese" or "Michael Palin", tell them how you feel about them ;), otherwise tell them "You have a nice name."

틀:Solution

Modify the higher or lower program from this section to keep track of how many times the user has entered the wrong number. If it is more than 3 times, print "That must have been complicated." at the end, otherwise print "Good job!"

틀:Solution

Write a program that asks for two numbers. If the sum of the numbers is greater than 100, print "That is a big number."

틀:Solution

틀:Navigation 스크립트 오류: "TScope" 모듈이 없습니다.