視頻位置:80:55
開始講循環了。感覺大學c語言學的還剩數組了吧。
還記得有的題是循環裏面讓變量減1,然後讓填會運行多少次。。。。。。
i = 8
while i <= 10:
print(i)
i += 1
print("bye")
輸出:
8
9
10
bye
一個小花樣:
i = 1
while i <= 5:
print('*' * i) # *重複i次
i += 1
print("bye")
輸出:
*
**
***
****
*****
bye
一個猜數遊戲:
請猜一猜這個數是幾,你有三次機會哦!猜對有獎哦!
這是我寫的:
i = 5 #答案
n = 3 #猜的次數
a = int(input("請輸入0-9中任意一個數: "))
while n > 0:
if a == i:
print(f"恭喜你猜對啦!這個數就是{i}!")
break
else:
n = n - 1
if n == 0:
print(f"機會用盡了,這是數是{i}")
break
a = int(input("猜錯了,再猜一次吧! "))
print("bye")
在pycharm裏有個小功能,選中一個變量,如i,右鍵,refactor—rename,此功能可以批量重命名我們的變量。
視頻主這樣寫的:
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input("Gusess: "))
guess_count += 1
if guess_count == secret_number:
print("you win")
break
else: # while的else
print("sorry you fail")
下面,我們來做一個遊戲,雖然沒有界面…但這算是遊戲的引擎了…視頻時間:91:10
小遊戲設計如下:
輸入help,則輸出 start stop quit三個說明
輸入其他的則輸出: 你說什麼?我看不懂
輸入start ,輸出:繫好安全帶,準備出發
輸入stop ,輸出:車一下子就停住了。
輸入 quit,退出遊戲
下面是我的代碼:
i = 1
while i !=0:
commd = input()
if commd == 'help':
print("start car start"
"stop car stop"
"quit quit game") #此處輸出並沒有換行
elif commd == 'start':
print("car start")
elif commd == 'stop':
print("car sotp")
elif commd == 'quit':
print('bye')
break
else:
print("I don't understand what you say")
輸出測試:
help
start car startstop car stopquit quit game
stop
car sotp
start
car start
ds
I don't understand what you say
quit
bye
視頻主是這麼寫的:
command = ""
while True: #也可以寫while command != "quit",但和下面的break重複了,故簡化。
command = input(">").lower() #此處確保輸入自動小寫化
if command == "start":
print("car started ....")
elif command == "stop":
print("car sotped ...")
elif command == "quit":
break
elif command == "help":
print("""
start - to start the car #此處的內容隨便寫,所以前面的空格(縮進)都可以去掉,這樣就頂個顯示。
stop - to stop the car
quit - to quit game
""")
else:
print("sorry i don't understand that")
升級遊戲功能:
輸入start後再次輸入,會提示車已啓動
輸入stop後再次輸入,,會提示車已停止
車未啓動就輸入stop,會提示車未啓動
在視頻主的基礎上,我的修改如下:
command = ""
car_status = "stop"
while True: #也可以寫while command != "quit",但和下面的break重複了,故簡化。
command = input(">").lower() #此處確保輸入自動小寫化
if command == "start":
if car_status == "stop":
print("car started ....")
car_status = "start"
else:
print("car is already started.")
elif command == "stop":
if car_status == "start":
print("car stoped ....")
car_status = "stop"
else:
print("car is already stoped.")
elif command == "quit":
break
elif command == "help":
print("""
start - to start the car
stop - to stop the car
quit - to quit game
""")
else:
print("sorry i don't understand that")
我添加了一個車的狀態變量,每次輸入命令後更新車的狀態。
>sta
sorry i don't understand that
>start
car started ....
>start
car is already started.
>stop
car stoped ....
>stop
car is already stoped.
>start
car started ....
>quit
視頻主是添加了一個布爾值,started = Fales,思路一致。
視頻時間位置102:00,下一節是for循環。今天到這裏。