002-用python設計第一個遊戲
阿新 • • 發佈:2018-12-04
第一個遊戲
示例1:
#/usr/bin/env python3
# -*-coding:utf-8 -*-
print("-----我是自戀狂-----")
temp = input("請問骰子有幾個面:")
guess = int(temp)
if guess == 6:
print("你猜對了")
else:
print("猜錯了")
print("遊戲結束")
示例2:
為上例增加異常捕捉
#/usr/bin/env python3 # -*-coding:utf-8 -*- print("-----我是自戀狂-----") temp = input("請問骰子有幾個面:") try: guess = int(temp) if guess == 6: print("你猜對了") else: print("猜錯了") except ValueError as e: print("你的輸入值是:%s"%temp) print("此處要求輸入純數字,請重新執行") finally: print("遊戲結束")
內建函式
內建函式為built in function,建成BIF。
#/usr/bin/env python3
# -*-coding:utf-8 -*-
#BIF 內建函式,檢視內建函式dir(__builtins),小寫的是內建函式,通過help可以檢視當前方法的使用
print(dir(__builtins__))
#檢視方法介紹
help(str)
FAQ
print使用 ‘+’連線,兩邊值的型別必須一致,否則會提示TypeError。
#/usr/bin/env python3 # -*-coding:utf-8 -*- a = 7 print("'hello',a: ",'hello',a) print("'hello %s'%a: ",'hello %s'%a) # +號兩邊轉為相同型別即可 print("'hello '+str(a)",'hello '+str(a))