Startup Data scientist Blog

データ分析系のテック情報を発信します

break と elseを使ったpythonコード

 

pythonコード

import random

roll = 0
count = 0

print('First person to roll a 5 win!')
while roll != 5:
    name = input('Enter a name, or \'q\' to quit: ')
    if name == 'q':
        break
   
    count = count + 1
    roll = random.randint(1, 5)
    print(f'{name} rolled {roll}')
else:
    print(f'{name} Winds!!!')
   
print(f'You rolled the dice {count} times.')

 

説明

a==b aとbが同じ場合

a!=b aとbが異なっている場合

break ブロック内での処理をスキップ(飛ばす)

 

Output

First person to roll a 5 win!
Enter a name, or 'q' to quit: A
A rolled 3
Enter a name, or 'q' to quit: B
B rolled 2
Enter a name, or 'q' to quit: 1
1 rolled 5
1 Winds!!!
You rolled the dice 3 times.

 

「q」を押すとゲームが終了。

 

if関数を使ってnameが空欄だった場合の条件を付け足した場合

import random

roll = 0
count = 0

print('First person to roll a 5 win!')
while roll != 5:
    name = input('Enter a name, or \'q\' to quit: ')
   
    if name.strip() == '':
        continue
       
    if name.strip() == 'q':
        break
   
    count = count + 1
    roll = random.randint(1, 5)
    print(f'{name} rolled {roll}')
else:
    print(f'{name} Winds!!!')
   
print(f'You rolled the dice {count} times.')

 

Output

irst person to roll a 5 win!
Enter a name, or 'q' to quit:  
Enter a name, or 'q' to quit: a
a rolled 1
Enter a name, or 'q' to quit: a
a rolled 2
Enter a name, or 'q' to quit: a
a rolled 5
a Winds!!!
You rolled the dice 3 times.

 

 

continueを使用することで空欄状態でEnterを押しても再度入力を求められます。