循序漸進-python-03

來源:互聯網
上載者:User

標籤:python

運算子是一些符號,它告訴 Python 解譯器去做一些數學或邏輯操作。一些基本的數學操作符如下所示:

>>> a=8+9>>> a17>>> b=1/3>>> b0.3333333333333333>>> c=3*5>>> c15>>> 4%31

下面是一個計算天數的指令碼

#/usr/bin/env python3#coding:utf8days = int(input("please enter days:"))mouth = days // 30day0 = days %30print "You enter %s days"%daysprint("Total is {} mouths and  {} days".format(mouth,day0))
[email protected]:~/file/1# python days.pythonplease enter days:1000You enter 1000 daysTotal is 33 Mouths and  10 Days

也可以用divmod函數實現,divmod(num1, num2) 返回一個元組,這個元組包含兩個值,第一個是 num1 和 num2 相整除得到的值,第二個是 num1 和 num2 求餘得到的值,然後我們用 * 運算子拆封這個元組,得到這兩個值。

>>> import sys>>> c=divmod(100,30)>>> c(3, 10)
#!/usr/bin/env python3days = int(input("Enter Days:"))print("Total  is {} mouths and {} days".format(*divmod(days,30)))[email protected]:~/file/1# python3  daysv2.py Enter Days:100Total  is 3 mouths and 10 days

效果是一樣的

關係運算子
Operator Meaning
< Is less than #小於
<= Is less than or equal to #小於等於
> Is greater than#大於
>= Is greater than or equal to#大於等於
== Is equal to #等於
!= Is not equal to#不等於
>>> 1 == 1True>>> 2 > 3False>>> 23 == 24False>>> 34 != 35True
邏輯運算子

對於邏輯 與,或,非,我們使用 and,or,not 這幾個關鍵字。

邏輯運算子 and 和 or 也稱作短路運算子:它們的參數從左向右解析,一旦結果可以確定就停止。例如,如果 A 和 C 為真而 B 為假,A and B and C 不會解析 C 。作用於一個普通的非邏輯值時,短路運算子的傳回值通常是能夠最先確定結果的那個運算元。

關係運算可以通過邏輯運算子 and 和 or 組合,比較的結果可以用 not 來取反意。邏輯運算子的優先順序又低於關係運算子,在它們之中,not 具有最高的優先順序,or 優先順序最低,所以 A and not B or C 等於 (A and (notB)) or C。當然,括弧也可以用於比較運算式。

>>> 4 and 33>>> 0 and 20>>> False or 4 or 54>>> 2 > 1 and not 3 > 5 or 4True>>> False and 3False>>> False and 4False
簡寫運算子

x op= expression 為簡寫運算的文法形式。其等價於 x = x op expression 

>>> a = 3>>> a += 20>>> a23>>> a /= 1>>> a23.0>>> a /= 2>>> a11.5




本文出自 “有志者,事竟成” 部落格,請務必保留此出處http://wuxinglai.blog.51cto.com/9136815/1882009

循序漸進-python-03

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.