Python開発環境の概要
PythonはPython2とPython3の2つの主要バージョンがあり、現在はPython3への移行が主流となっています。開発にはPyCharmなどの統合開発環境がよく使用されます。
基本的なデータ型
Pythonでは以下の基本的なデータ型が使用されます:
- 整数型(int)
- 文字列型(str)
- リスト型(list)
- 辞書型(dict)
変数の命名規則
変数名は以下の規則に従う必要があります:
- 英字、アンダースコア、数字のみ使用可能
- 先頭は英字で始まる必要がある
- 大文字の使用は推奨されない
条件分岐の実装例
以下のコードはメニュー選択システムの実装例です:
menu_text = """
10086コールセンターへようこそ
1. 通話料金照会
2. データ通信量照会
3. オペレーター対応
"""
print(menu_text)
selected_option = input("機能番号を入力してください:")
if selected_option == "1":
print("1. 自回線照会, 2. 他回線照会, 3. 固定電話照会")
query_type = input("照会タイプを入力してください:")
if query_type == "1":
print("自回線を照会します")
elif query_type == "2":
print("他回線を照会します")
elif query_type == "3":
print("固定電話を照会します")
elif selected_option == "2":
print("データ通信量を照会します")
elif selected_option == "3":
print("オペレーターに接続します")
else:
print("入力が無効です")
ループ処理の実装
様々なループ処理の例を以下に示します:
# 1から100までの合計を計算
# total = 0
# num = 1
# while num <= 100:
# total += num
# num += 1
# print(total)
# 1から100までの奇数を表示
# num = 1
# while num <= 100:
# if num % 2 != 0:
# print(num)
# num += 1
# 1から100までの偶数を表示
# num = 1
# while num <= 100:
# if num % 2 == 0:
# print(num)
# num += 1
# 1-2+3-4+5...+99の合計を計算
# num = 1
# result = 0
# while num < 100:
# if num % 2 == 0:
# result -= num
# else:
# result += num
# num += 1
# print(result)
ユーザー認証システムの実装
以下はユーザー認証システムの実装例です:
user_database = [
{'user_id': 'alex', 'passcode': '123456', 'attempts': 0},
{'user_id': 'wu', 'passcode': '12345', 'attempts': 0},
{'user_id': 'haha', 'passcode': '12345', 'attempts': 0},
{'user_id': 'hk', 'passcode': '12345', 'attempts': 0},
]
max_attempts = 3
status = 0
while True:
remaining_attempts = 3
input_user = input("ユーザー名を入力:")
input_pass = input("パスワードを入力:")
for user_record in user_database:
if user_record['user_id'] == input_user and user_record['passcode'] == input_pass:
user_record['attempts'] = 0
print(f'{input_user}さん、ログイン成功')
status = 2
break
elif user_record['user_id'] == input_user and user_record['passcode'] != input_pass:
status = 2
user_record['attempts'] += 1
if user_record['attempts'] >= max_attempts:
print(f"ユーザー{input_user}はロックされました。管理者に連絡するか、別のユーザーでログインしてください")
status = 1
break
else:
remaining_attempts -= user_record['attempts']
retry_input = input('ユーザー名またはパスワードが間違っています。再試行するには任意キーを、終了するにはqを入力:')
if retry_input == "q":
status = 4
break
status = 1
break
else:
status = 3
if status == 1:
continue
elif status == 2:
print('システムへアクセスします')
break
elif status == 4:
break
exit_input = input("ユーザー名またはパスワードが間違っています。再試行するには任意キーを、終了するにはqを入力:")
if exit_input == "q":
break
continue