0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonのWhile文の書き方が冗長になる話。

Posted at

PythonのWhile文の書き方がどうしても冗長になってしまう気がして、しょんぼりしてしまうのは私だけだろうか。

例えば、こんな問題。

問題概要
ユーザーが数字を入力し続け、0が入力されたら入力を終了します。入力された数字のうち、偶数のみを合計に追加し、奇数はスキップ(無視)してください。While文でループを繰り返し、Continue文を使って奇数をスキップします。最終的に、偶数の合計を表示します。

要件

  • While文を使って、無限ループ(while True:)でユーザーの入力を繰り返します。
  • 各入力でnum == 0ならbreakでループを終了。
  • num % 2 == 1(奇数)ならcontinueでその入力をスキップ(合計に追加せず、次の入力へ)。
  • それ以外(偶数)なら合計に追加。
  • 入力はinput()int()を使い、プロンプトは「Input the number: 」で。
  • 終了時に「偶数の合計: [合計値]」の形式で表示。
  • 関数は不要(メインスクリプトでOK)。合計変数は初期値0で。

入力例

4
3
6
1
8
0

出力例

偶数の合計: 18

(4 + 6 + 8 = 18。3と1は奇数でスキップ)

私の解答

qiita.py
def skip_odd():
   total = 0
   while True:
       num = int(input("Input number: "))
       if num == 0:
           print("It's 0, Finish","total add is ",total)
           break
       elif num % 2 == 1:
           continue
           pass
       
       elif num % 2 == 0:
           total += num
           continue
   return total
       

print(skip_odd())

一応要件は満たしているんだけどムダが多いな💦
おそらく、continueの有効範囲(言い方あってる?)がまだ理解し切れていないのだろう。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?