條件控制
if,如果條件成立則做,反之做...
if condition:
do something
else:
do something
多個條件判斷
if condition:
do something
elif condition:
do something
else:
循環(huán)
for
for item in iterable? do something
于,,,其中的每一個元素手负,做,凿掂,涣觉,事情
while
只要,烘豌,,條件成立看彼,就一直做廊佩,囚聚,,但時常是通過設(shè)置來停止循環(huán)
while condition
do something
在循環(huán)過程中制造某種可以使循環(huán)停下來的條件
練習(xí)題
實(shí)戰(zhàn)1:打印1到100以內(nèi)的偶數(shù)
def even_print():
for i in range(1,101):
if i%2==0:
print(i)
even_print()
實(shí)戰(zhàn)2:創(chuàng)建10個文件并保存以數(shù)字命名
def text_creation(): #創(chuàng)建文件函數(shù)
path='C:/Users/sharymo/Desktop/'#文件保存路徑
for name in range(1,11):
with open(path+str(name)+'.txt','w')as text:#文件名設(shè)置
text.write(str(name))#寫入字符數(shù)字當(dāng)內(nèi)容
text.close()
print('Done')
text_creation()
綜合練習(xí)搖骨游戲
第一部分實(shí)現(xiàn)搖骨子
import random#導(dǎo)入隨機(jī)庫
def roll_dice(numbers=3,points=None):#創(chuàng)建一個搖骨子的函數(shù)标锄,有骨子數(shù)量顽铸,三個篩子的點(diǎn)數(shù)
print ('<<<<<ROLL THE DICE! >>>>>')#提示搖骨子
if points is None:#如果骨子數(shù)是空則創(chuàng)建三個篩子的點(diǎn)數(shù)列表
points=[]
while numbers>0:#搖三次骨子,每搖一次骨子數(shù)少一料皇,直到?jīng)]有搖骨子的次數(shù)
point=random.randrange(1,7)
points.append(point)
numbers=numbers-1
return points
第二部分將搖骨子的結(jié)果翻譯成大小
def roll_result(total):#將點(diǎn)數(shù)轉(zhuǎn)換成大小函數(shù)跋破,骨子的總數(shù)
isBig = 11 <= total <=18#設(shè)定大與小評判的標(biāo)準(zhǔn)
isSmall = 3 <= total <=10
if isBig:#在不同的條件下返回不同的結(jié)果
return 'Big'
if isSmall:
return 'Small'
第三部分創(chuàng)建開始函數(shù)
def start_game():
money=1000
while money>0:
print('<<<<< GAME STARTS! >>>>>')#告知用戶游戲開始
choices = ['Big','Small']
your_choice = input('Big or Small :')#猜大猜小
if your_choice in choices:#如果符合輸入規(guī)范,就往下進(jìn)行瓶蝴,
your_bet=int(input('How much you wanna bet?-'))#input的輸入是字符串
points = roll_dice()#調(diào)用roll_dice函數(shù)毒返,返回points列表儲存著三個點(diǎn)數(shù)
total = sum(points)#求和
youWin = your_choice == roll_result(total)#判斷是否勝利
if youWin:#用條件判斷語句告知輸贏
print('The points are',points,'You win !')
money=money+your_bet
print("you have {}now".format(money))
else:
print('The points are',points,'You lose !')
money=money-your_bet
print("you have {}now".format(money))
else:
print('Invalid Words')#如果不符合,就告知用戶重新選擇
#start_game()
start_game()
這次呢舷手,以大家都用的方式寫的
萌新求多多支持_