python入門基礎2 if語句 while迴圈 for迴圈
阿新 • • 發佈:2018-11-26
if語句
判斷使用者名稱和密碼是否正確:
_username="liulu"
_password="123456"
username=input("username:")
password=input("password:")
if username==_username and password==_password:
print("welcome {name} login...".format(name=username))
else:
print("invalid username and password!")
猜年齡:
my_age=23
guess_age=int(input("please guess my age:")) #因為input預設的是字串,所以需要int
if guess_age==my_age:
print("you got it!")
elif guess_age>my_age:
print("think smaller...")
else:
print("think bigger...")
while迴圈
猜年齡,最多猜三次,猜不中不能再猜
my_age=23
count=0
while True: #True要大寫 #可以簡化為while count <3:
if count==3:
break
#break 可結束執行本次迴圈。continue是跳出本次迴圈。
guess_age=int(input("guess age:"))
if guess_age==my_age:
print("you got it")
break
elif guess_age>my_age:
print("think smaller...")
else:
print("think bigger...")
count+=1
else:
print("you have no more chance to guess...")
for迴圈
猜年齡,最多猜三次,猜不中不能再猜
my_age=23
for i in range(3)
guess_age=int(input("guess age:"))
if guess_age==my_age:
print("you got it")
break
elif guess_age>my_age:
print("think smaller...")
else:
print("think bigger...")
else:
print("you have no more chance to guess...")
步長
# 從0到10
for i in range(10):
print("loop",i)
# 只打02468
for i in range(0,10,2):
print("loop",i)
if 與 while 混合使用案例:
猜年齡,最多猜三次,猜不中詢問是否繼續猜,輸入n後不再猜。
my_age=23
count=0
while count<3:
guess_age=int(input("guess age:"))
if guess_age==my_age:
print("you got it")
break
elif guess_age>my_age:
print("think smaller...")
else:
print("think bigger...")
count+=1
if count==3:
continue_confirm=input("would you like to keep guessing?")
if continue_confirm!="n":
count=0
for迴圈巢狀
for i in range(10):
print("------",i)
for j in range(10):
print(j)
if j>5:
break