前提・実現したいこと
Pythonで複数のinput()を定義して途中のinput()でエラーが起きた際一番最初のinput()にもどってしまいます。解決策はありますでしょうか?例えばとして適当ですがじゃんけんゲームを例として書いてみました。勝負回数のところで文字列や4以上の数字を打つと最初から戻るので問題ないのですがじゃんけん中に3以上の数字や文字列を入力してしまうと最初からになってしまいます。改善策はありますでしょうか。
該当のソースコード
python3
1 2import random 3import time 4 5win = 0 6lose = 0 7draw = 0 8 9print('==じゃんけんしましょう!==') 10 11while True: 12 try: 13 count = int(input('何回勝負する?\ 14 \n1:1回\n2:3回\n3:5回\n4:それ以上')) 15 16 if count == 4: 17 num = int(input('何回勝負する?')) 18 else: 19 num = 0 20 21 count_dic = {1:1, 2:3, 3:5, 4:num} 22 hand_dic = {1:'グー', 2:'チョキ', 3:'パー'} 23 play_count = count_dic[count] 24 25 for i in range(play_count): 26 27 print(f'あなたの手はなに?({i+1}回目)\ 28 \n1:グー\n2:チョキ\n3:パー') 29 30 my_num = int(input('1から3の数字を入力してね。')) 31 32 com_num = random.randint(1,3) 33 34 my_hand = hand_dic[my_num] 35 com_hand = hand_dic[com_num] 36 37 if my_hand == com_hand: 38 print('あいこ!') 39 draw += 1 40 print(f'現在戦績 {win}勝{lose}敗{draw}引き分け') 41 time.sleep(0.5) 42 43 elif my_hand == 'グー': 44 if com_hand == 'パー': 45 print(f'君が{my_hand},相手が{com_hand}で君の負け') 46 lose += 1 47 elif com_hand == 'チョキ': 48 print(f'君が{my_hand},相手が{com_hand}で君の勝ち') 49 win += 1 50 print(f'現在戦績 {win}勝{lose}敗{draw}引き分け') 51 time.sleep(0.5) 52 53 elif my_hand == 'チョキ': 54 if com_hand == 'グー': 55 print(f'君が{my_hand},相手が{com_hand}で君の負け') 56 lose += 1 57 elif com_hand == 'パー': 58 print(f'君が{my_hand},相手が{com_hand}で君の勝ち') 59 win += 1 60 print(f'現在戦績 {win}勝{lose}敗{draw}引き分け') 61 time.sleep(0.5) 62 63 elif my_hand == 'パー': 64 if com_hand == 'チョキ': 65 print(f'君が{my_hand},相手が{com_hand}で君の負け') 66 lose += 1 67 elif com_hand == 'グー': 68 print(f'君が{my_hand},相手が{com_hand}で君の勝ち') 69 win += 1 70 print(f'現在戦績 {win}勝{lose}敗{draw}引き分け') 71 time.sleep(0.5) 72 73 except (KeyError, ValueError): 74 print('正しい数字を入力してね。') 75 76 77 78print('結果発表!!!') 79time.sleep(2) 80print(f'現在戦績 {win}勝{lose}敗{draw}引き分け') 81print(f'勝率 {(win/play_count)*100}%')
試したこと
ここに問題に対して試したことを記載してください。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/07/02 10:00
2020/07/02 10:01
2020/07/02 11:04