Python基础语法与控制语句

在这里简单总结下Python中的一些基础语法及一些控制语句,包括Python中的四则运算及常见函数、if条件语句,for循环语句等。

1.  Python中的运算及常见函数。

(1) 四则运算:直接附上四则运算的代码,另外在计算机中的四则运算规则也跟数学中学过的一样。

2+6      >>> 8
5-3      >>> 2
9/3      >>> 3
5*4      >>> 20
10/5+2   >>> 4
2*3-4    >>> 2

(2) 常见函数(如果不清楚某个函数的用法,可以在Python中通过help(function)来查看function的具体用法说明)

绝对值函数: abs(-10)   >>> 10

四舍五入函数:round(1.24)   >>> 1.0

幂函数:pow(3, 2)   >>> 9

此外,Python中还有个关于数学运算的模块:math模块。简单用法如下

import math                               # 引入math模块

math.floor(30.8)   >>> 30.0        # 取整操作   

math.sqrt(9)        >>>  3.0          # 开方运算   

2.  Python中的控制语句

(1) if语句:

if condition1:

    operation1 (when condition1 = True)

elif condition2: (when condition1 = False)

    operation2 (when condition2 = True)

else:

    operation3

(2) for语句: 用法为for x in [一个可迭代的对象(如列表,字典,集合等)]。 此外for语句和if语句可结合使用。

words = ['dog', 'window', 'ubuntu']

for w in words:

    print(w, len(w))

>>> dog 3

>>> window 6

>>> ubuntu 6

(3) range()函数:用于循环生成一个序列,注意首尾索引值(不包含尾索引)。

for i in range(5):   # 生成0-5(不包含5)的序列

    print(i)

>>> 0 1 2 3 4

(4) continue语句:表示继续循环执行下一次的迭代。

for num in range(2, 5):

    if num%2 == 0:

        print("found an even number", num)

        continue

    print("found a number", num)

>>> found an even number 2

        found a number3

        found an even number 4

(5) break语句:执行循环时,执行的条件为False时,break语句将跳出当前的循环。

for n in range(2, 5):

    for x in range(2, n):

        if n%x == 0 :

            print(n, 'equals', x, '*', n//x)

            break

    else:

        print(n, 'is a prime number')

>>> 2 is a prime number

        3 is a prime number

        4 equals 2*2


以上是Python中的一些基本的操作和语句总结。当然这不是全部,仅供大家参考学习,更多内容可以查看Python教程。

发布了31 篇原创文章 · 获赞 30 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/linchunmian/article/details/79438793
今日推荐