Python ステートメント知識 02

1. 単純な if ステートメント

if ステートメントでは、インデントは for ループと同じように機能します。テストに合格すると、if ステートメントに続くすべてのインデントされたコード行が実行されます。それ以外の場合は無視されます。

age = 19 
if age >= 18: 
	print("You are old enough to vote!")

1.1 if-else ステートメント

age=17
if age >=18:
	print("You are old enough to vote!")
else:
	print("Sorry, you are too young to vote.")

1.2 if-elif-else ステートメント

Python は、if-elif-else 構造内のコードのブロックを 1 つだけ実行し、合格する条件付きテストが見つかるまで、各条件付きテストを順番にチェックします。必要な数の elif ブロックを使用します。

age = 12 
if age < 4: 
	print("Your admission cost is $0.") 
elif age < 18: 
	print("Your admission cost is $5.") 
else: 
	print("Your admission cost is $10.")

出力:

Your admission cost is $5.

1.3 if文でリストを処理する

リストが空でないことを確認してください

requested_toppings = [] 
if requested_toppings: 
	for requested_topping in requested_toppings: 
		print("Adding " + requested_topping + ".") 
	print("\nFinished making your pizza!") 
else: 
	print("Are you sure you want a plain pizza?")

ここでは、リストは空で、出力は
次のとおりです。

2. ユーザー入力と for ループ

2.1 関数 input() の仕組み

関数 input() はプログラムを一時停止し、ユーザーがテキストを入力するのを待ちます。ユーザー入力を取得した後、Python は便宜上それを変数に格納します。

message = input("Tell me something, and I will repeat it back to you: ") 
print(message)

関数 input() は 1 つのパラメーターを受け入れます。ユーザーに表示されるプロンプトまたは指示です。これにより、ユーザーは何をすべきかを知ることができます。

2.2 int() を使用して数値入力を取得する

関数 input() を使用すると、Python はユーザー入力を文字列として解釈します。数値比較を行うとエラーが発生します. この問題を解決するには、関数 int() を使用して、Python に入力を数値として扱うように指示します.

height = input("How tall are you, in inches? ") 
height = int(height) 
if height >= 36: 
	print("\nYou're tall enough to ride!") 
else:
	print("\nYou'll be able to ride when you're a little older.")

2.3 while ループの紹介

while ループを使用してカウントします。たとえば、次の while ループは 1 から 5 までカウントします。

current_number = 1 
while current_number <= 5: 
	print(current_number) 
	current_number += 1

ユーザーが終了するタイミングを選択できるようにし、while ループを使用して、ユーザーが望む限りプログラムを実行し続ける

prompt = "\nTell me something, and I will repeat it back to you:" 
prompt += "\nEnter 'quit' to end the program. " 
message = "" 
while message != 'quit': 
	message = input(prompt) 
	print(message)

記号を使用
このフラグをアクティブと呼びましょう (任意の名前を付けることができます)。これは、プログラムの実行を継続するかどうかを決定するために使用されます。

2.3.1 while ループを使用してリストと辞書を処理する

新しく登録されたがまだ認証されていない Web サイト ユーザーのリストがあるとします。これらのユーザーを認証した後、それらのユーザーを認証済みユーザーの別のリストに移動するにはどうすればよいでしょうか? 1 つの方法は、while ループを使用して、ユーザーが認証されている間に認証されていないユーザーのリストからユーザーを抽出し、それを別の認証済みユーザーのリストに追加することです。

# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace'] 
confirmed_users = [] 
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
	current_user = unconfirmed_users.pop() 
	print("Verifying user: " + current_user.title()) 
	confirmed_users.append(current_user) 
 
# 显示所有已验证的用户
print("\nThe following users have been confirmed:") 
for confirmed_user in confirmed_users: 
	print(confirmed_user.title())

おすすめ

転載: blog.csdn.net/weixin_46111970/article/details/129496864