Python基礎(day2)

格式化輸出

現有一練習需求,問用戶的姓名、年齡、工作、愛好 ,然後打印成以下格式:

------------ info of wuli -----------
Name  : wuli
Age   : 22
job   : Engineer
Hobbie: code
------------- end -----------------

只需要把要打印的格式先準備好, 由於裏面的 一些信息是需要用戶輸入的,你沒辦法預設知道,因此可以先放置個佔位符,再把字符串裏的佔位符與外部的變量做個映射關係就好

name = input('請輸入姓名:')
age = input('請輸入年齡:')
job = input('請輸入工作:')
hobbie = input('你的愛好:')

msg = '''------------ info of %s -----------
Name  : %s
Age   : %d
job   : %s
Hobbie: %s
------------- end -----------------''' %(name,name,int(age),job,hobbie)
print(msg)

%s就是代表字符串佔位符,除此之外,還有%d,是數字佔位符, 上面的age後面使用%d,就代表必須只能輸入數字。

現在有這麼一行代碼:

msg = "我是%s,年齡%d,目前學習進度爲2%"%('武力',18)
print(msg)

這樣會報錯的,因爲在格式化輸出裏,你出現%默認爲就是佔位符的%,但是我想在上面一條語句中最後的2%就是表示2%而不是佔位符.

msg = "我是%s,年齡%d,目前學習進度爲2%%"%('武力',18)
print(msg)

這樣就可以了,第一個%是對第二個%的轉譯,告訴Python解釋器這只是一個單純的%,而不是佔位符。

while ... else ...

與其它語言else 一般只與if 搭配不同,在Python 中還有個while ...else 語句

while 後面的else 作用是指,當while 循環正常執行完,中間沒有被break 中止的話,就會執行else後面的語句.

count = 0
while count <= 5 :
    count += 1
    print("Loop",count)

else:
    print("循環正常執行完啦")
print("-----out of while loop ------")

結果輸出:

Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循環正常執行完啦
-----out of while loop ------

如果執行過程中被break啦,就不會執行else的語句了

count = 0
while count <= 5 :
    count += 1
    if count == 3:break
    print("Loop",count)

else:
    print("循環正常執行完啦")
print("-----out of while loop ------")

結果輸出:

Loop 1
Loop 2
-----out of while loop ------

邏輯運算

邏輯運算符:and、or、not

在沒有()的情況下not 優先級高於 and,and優先級高於or,即優先級關係爲( )>not>and>or,同一優先級從左往右計算。

例如:判斷如下邏輯語句的運算結果爲True,Flase。

1,3>4 or 4<3 and 1==1
2,1 < 2 and 3 < 4 or 1>2 
3,2 > 1 and 3 < 4 or 4 > 5 and 2 < 1
4,1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8
5,1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6
6,not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6

 如果是數字之間的邏輯運算:

  x or y , x爲真,值就是x,x爲假,值是y;

       x and y, x爲真,值是y,x爲假,值是x。

例如,求下列邏輯語句的值:

8 or 4
0 and 3
0 or 4 and 3 or 7 or 9 and 6

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章