kennpi
@kennpi (ぴ けん)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

python

12月、1月、2月が冬、3月、4月、5月が春、6月、7月、8月が夏、9月、10月、11月が冬を設定して

入力値
5
出力
月の数値を入力してください
5月は春です

を出したいんですが

n = int(input())
if n == 3,4,5 :
print("月の数値を入力してください")
print(n+ "月は春です")

ここで詰まってしまって、教えてくれませんか、、、

0

4Answer

初心者とのことなので、例外処理など難しいことは省きますね。

season.py
# input関数の引数に入力を促す文字列が入れられます。
month = int(input("月の数値を入力してください : "))

# 場合分けをします。
# 春の月は3, 4, 5の何れかなので、or演算子でつなげます。
if month == 3 or month == 4 or month == 5:
    # monthは数値なので、str関数で文字列にしてから連結します。
    print(str(month) + "月は春です。")

# in演算子を使うと楽です。
elif month in (6, 7, 8):
    print(str(month) + "月は夏です。")

elif month in (9, 10, 11):
    # formatメソッドを使うと、このように書けます。
    print("{}月は秋です。".format(month))

elif month in (12, 1, 2):
    # f文字列というformatメソッドを簡単にしたものを使うと、このように書けます。
    print(f"{month}月は冬です。")

else:
    print(f"{month}月は存在しません。")
2Like

Comments

  1. @kennpi

    Questioner

    ありがとうございます!!!!
    おかげで凄く理解できました!!
print(str(n)+ "月は春です")

or

print(n, "月は春です", sep="")

or

print("{0}月は春です".format(n))

これで良いと思いますが。

0Like

Comments

  1. @kennpi

    Questioner

    ありがとうございます、、おかげで出力出来ました!!

Python のコードをそのまま貼り付けるとインデントが消えて正しく読めなくなります。以下のようにコードの前後に空行を置いて ```py``` で囲んでください。

(空行)
```py
if x is not None:
    print(x)
```
(空行)

そうするとフォーマットされて読みやすくなります。

if x is not None:
    print(x)

また質問するときはどこで詰まったのか、何の書き方が分からないのか、どういうエラーが出ているかを具体的に書いてください。タイトルも「Python で○○したいが××エラーが出る」のように具体的に書くと回答が得られやすいです。

さて、ご質問のコードではまずこのようなエラーが出ると思います。

    if n == 3,4,5:
             ^
SyntaxError: invalid syntax

このような書き方はできません。 if n in (3, 4, 5):としてください。また print は @cloudsnow さんが回答されたように直してください。

0Like

Comments

  1. @kennpi

    Questioner

    なるほどですね、、、分かりました!!
    ご指摘ありがとうございます。次の質問から気を付けます!
    出力出来ました、、、本当にありがとうございます!
dict = {
    "" : [3, 4, 5],
    "" : [6, 7, 8],
    "" : [9, 10, 11],
    "" : [12, 1, 2]
}

print("月の数値を入力してください")
month = int(input())
for season, months in dict.items():
    if month in months:
        print(f"{month}月は{season}です。")
0Like

Your answer might help someone💌