アプリ版:「スタンプのみでお礼する」機能のリリースについて

プログラミングを学び始めたばかりのものです。pythonでif,for, whileを習い、100点満点のテストの点数を入力してその合計点、平均点を出し、その後の選択肢にyと入力するとまた繰り返す、というプログラムを書いています。複数のテスト結果を入力した後にendと入力すると、それまでの結果の合計を平均を計算するようにしています。0以下、あるいは100以上の数字を入力すると、数字は0から100ですよ、と警告を出すようにしています。
以下が私が書いたコードなのですが、これだとend以外の文字列を入力したときに、
if int(score)>=0 and int(score) <=100:
の処理をするときに、scoreがintじゃなきゃダメだよ、というエラーが出ます。
end以外の文字を入れたときに、0以下、または100以上の数字を入れた時と同じ処理、つまり警告を出したいのですが、どのようにすればいいでしょうか。
よろしくお願いします。

print("The Test Score program\n")
print ("Enter test scores")
print ('enter"end"to end the input')
print ("==========================")
total = 0
counter = 0

while True:
score = input ("Enter test score: ")
if score != "end":
if int(score)>=0 and int(score)<=100:
total = total + int(score)
counter+=1
else:
print ("Test score must be a number from 0 through 100. try again.")
else:
print ("==========================")
ave = total / counter
print ("total score:",total)
print ("avaerage score: ",ave)
total = 0
ave = 0
score = 0
counter = 0
enter = input ("Enter more sets of tests? (y/n)")
if enter.lower() == "y":
continue
else:
break

A 回答 (2件)

str(文字列)型の組み込みメソッドを使用します。



if "111".isdecimal():
print("decimal")
else:
print("not decimal")

参考:https://docs.python.jp/3/library/stdtypes.html#t …
    • good
    • 0
この回答へのお礼

ありがとうございます。
ためしたのですが、この場合中に入っている文字列そのものではなく、変数名をつかって判定をしたいのです。
この場合だと
score.isdecimal():
としたいところなのですが、どうもそうはいかないようです。
変数scoreがintなのかstrなのかを判別して、それぞれ別の処理を行うにはどうしたらいいでしょうか。

お礼日時:2018/09/11 06:10

No.1です。



> score.isdecimal():
> としたいところなのですが、どうもそうはいかないようです。
> 変数scoreがintなのかstrなのかを判別して

何か誤解なさっていると思います。
変数scoreに入力されているのは「文字列」(str)です。
その文字列が、10進数として読み取れ、intに変換できるかを判断するのが score.isdecimal() です。

こちらで確認しましたが以下サンプルでは問題なく判断が行われています。

-----test.py
while True:
score = input ("Enter test score: ")
print(score.isdecimal())
------------

> python test.py
Enter test score: 123
True
Enter test score: 12a
False
Enter test score: abc
False


これをif文の判断に組み込んで、score.isdecimal()がTrueなら通常処理を、Falseならエラー処理を行えば良いだけですね。
    • good
    • 0
この回答へのお礼

おっしゃる通り、勘違いしておりました。
ありがとうございました!

お礼日時:2018/09/11 08:30

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!