1. 程式人生 > >day1-字符串拼接、表達式、break和continue

day1-字符串拼接、表達式、break和continue

int pre small think range span guess mat lex

一 字符串拼接方式

1. 用加號(+)拼接

name = eason
age = 18

info = ‘‘‘---info:‘‘‘+ name +‘‘‘
age: ‘‘‘ + str(age)

print(info)

2. 用占位符(%)拼接

name = "eason"
age = 18

info = ‘‘‘-----info-----
name: %s
age: %d
 ‘‘‘ % (name,age)

print(info)

3. 用format方法拼接

1.關鍵字拼接(官方推薦)
name = "eason01"
age = 19

info = ‘‘‘-----info----
name: {_name}
age:: {_age}
‘‘‘.format(_name = name,_age = age) print(info) 2.占位符拼接 name = "eason02" age = 20 info = ‘‘‘-----info----- name: {0} age: {1} ‘‘‘.format(name,age) print(info)

二 表達式if...else...

場景一:用戶登錄驗證

name = input("請輸入用戶名:")
pwd = input("請輸入密碼:")

if name == "alex" and pwd == "cmd":
    print("歡迎,alex!")
else
: print("用戶名密碼錯誤!")

場景二:猜年齡遊戲

age_of_oldboy = 22

guess_age = int(input("guess age:"))

if guess_age == age_of_oldboy:
    print("yes,you got it !")
elif guess_age < age_of_oldboy:
    print("think bigger!")
else:
    print("think smaller!")

三 表達式for loop

最簡單的循環10次

for i in range(10):
    print
("loop:", i )

需求一,遇到小於5的循環次數就不走了,直接進入下一次循環

for i in range(0,10,2): #0 初始化值,10 序列長度, 2 步長
    if i < 5:
        continue #不往下走了,直接進入下一次loop
    print("loop",i)

需求二,遇到大於5的循環次數就不走了,直接退出

for i in range(10): #默認初始化值 0 ,步長為 1
    if i > 5:
        break # 不往下走了,直接跳出當前整個loop
    print("loop",i)

四 表達式while

count = 0
while True:
    print("11111",count)
    count += 1
    if count == 100:
        print("2222")
        break

如何實現讓用戶不斷的猜年齡,但只給最多3次機會,再猜不對就退出程序

my_age = 25

count = 0
while count < 3:
    user_input = int(input("input your guess num:"))
    if user_input == my_age:
        print("you got it!")
        break
    elif user_input < my_age:
        print("think bigger!")
    else:
        print("think smaller!")
    count += 1
else:
    print("you have tied too many times...")

註:當遇到不正常退出(break)時,則程序不執行循環(for,while)所對應的else下的代碼,只有當for循環體中代碼正常執行的時,才執行else中的代碼

更多python資料:猛擊這裏

day1-字符串拼接、表達式、break和continue