day 5-6 python (Fizz Buzz)

2023. 2. 27. 19:11개인적인 공부/Python

규칙 369 랑 비슷한 게임인것 같다.

 

3으로 나누어 떨어지는 경우에는 Fizz 5로 나누어 떨어질 경우에는 Buzz

둘다 해당하면 Fizz Buzz

 

숫자의 범위는 1부터 100까지

 

Instructions

You are going to write a program that automatically prints the solution to the FizzBuzz game.

Your program should print each number from 1 to 100 in turn.

When the number is divisible by 3 then instead of printing the number it should print "Fizz".

When the number is divisible by 5, then instead of printing the number it should print "Buzz".`

  And if the number is divisible by both 3 and 5 e.g. 15 then instead of the number it should print "FizzBuzz"

e.g. it might start off like this:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

.... etc.

 

1 부터 100 까지의 숫자로

나의 코드 

## Fizz Buzz

## 3으로 나누어 떨어질때 Fizz

## 5로 나누어 떨어질때 Buzz

## 둘다 포함되면 Buzz


for number in range(1,101):
    if number % 3 == 0 and number % 5 !=0:
        print("Fizz")
    elif number % 5 == 0 and number % 3 !=0:
        print("Buzz")
    elif number % 3 == 0 and number % 5 ==0:
        print("FizzBuzz")
    else:
        print(number)

 

 

더 좋은 방법

## 더 좋은 방법

for number in range(1,101):
    if number % 3 == 0 and number % 5 ==0: ## 여기를 먼저 시행한다음 elif 을 시행하기 때문에 코드를 짧게 할수 있다.
        print("FizzBuzz")
    elif number % 3 == 0:
        print("Fizz")
    elif number % 5 == 0:
        print("Buzz")
    else:
        print(number)

 

'개인적인 공부 > Python' 카테고리의 다른 글

day 6-2 python (반복문)  (0) 2023.03.01
day 6-1 python 함수 (Functions)  (0) 2023.02.28
day 5-5 python (짝수 더하기)  (0) 2023.02.27
day 5-4 for 반복문 과 range()  (0) 2023.02.27
day 5-2 python (평균 키 구하기)  (0) 2023.02.27