python基础语法

** 因为基本逻辑语句其实各个编程语言都是大同小异,语法上小有差别实际上都差不多,但是不写出来又感觉不完整,所以就简简单单整理一下。

1.if语句:

      (1)if语句的几种形式:

if...else语句:

定义compare()函数,比较两个参数的大小,根据比较结果给出不同的返回值

def compare(a, b):
    if a > b:
        return 1
    else:
        return -1

调用函数

c = compare(5, 6)
print(c)
if...elif...else语句:

定义compare()函数,比较两个参数的大小,根据比较结果给出不同的返回值

def compare(a, b):
    if a > b:
        return 1
    elif a == b:
        return 0
    else:
        return -1

调用函数

c = compare(5, 6)
print(c)
if...elif...elif...语句:

定义compare()函数,比较两个参数的大小,根据比较结果给出不同的返回值

def compare(a, b):
    if a > b:
        return 1
    elif a == b:
        return 0
    elif a < b:
        return -1

调用函数

c = compare(5, 6)
print(c)
(2)if语句处理列表:

检查特定值是否包含在列表内:                    

创建列表numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

用in关键字判断num是否包含在列表中

num = 6
if num in numbers:
    print('num is in numbers')
else:
    print('num is not in numbers')

用not in关键字判断num1是否不包含在列表中

num1 = 11
if num1 not in numbers:
    print('num1 is not in numbers')
else:
print('num1 is in numbers')
function(){ //外汇基本面分析 http://www.kaifx.cn/question/...
检查列表是否为空:   

创建空列表

numbers = []

判断列表是否为空

if numbers:
    # 当列表不为空,返回True
    print('numbers is not empty')
else:
    # 当列表为空,返回False
print('numbers is empty')
2.while循环:
      (1)while语句的几种形式:
             1)使用判断条件退出的while语句:    

【1】判断条件为a<=5,当a>5时退出循环

a = 1
while a <= 5:
    print(a)
    # 去掉本句会变成死循环无法跳出while循环
    a += 1

【2】判断条件为用户输入数值是否>0,当input<=0时退出循环

b = True
while b:
    c = int(input('please input a number'))
    if c > 0:
        b = True
    else:
        b = False

【3】判断条件为用户输入数值是否不等于3,当input==3时退出循环

d = 0
while d != 3:
    d = int(input('please input a number'))
    print(d)
    2)强制退出的while语句:    
                   a.break语句:

执行break语句立即退出当前while循环

运行结果为,当输入非正数时,代码运行结束

b = True
while b:
    c = int(input('please input a number'))
    if c > 0:
        b = True
        print(c)
    else:
        Break
          b.continue语句:

执行continue语句跳出当前次循环的剩余代码,直接执行下次循环

运行结果为,只打印输入的所有正数

b = True
while b:
    c = int(input('please input a number'))
    if c > 0:
        b = True
        print(c)
    else:
        Continue
  (2)while循环处理列表:
                1)转移列表的元素:

创建两个列表

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = []

将a列表的元素弹出,并添加到列表b中,直到a成为空列表

while a:
    c = a.pop()
    b.append(c)

输出运行结果

print(a)
print(b)
  2)删除列表内所有指定元素:
a = [3, 4, 5, 6, 7, 8, 9, 5, 33, 44, 2, 5, 6, 5, 4, 5]

移除列表中所有5

while 5 in a:
    a.remove(5)

print(a)
3.for 循环语句:
      (1)for语句的基本格式:        

保存结果的变量

result = 0

获取从1到100的数值,并执行累加操作

range()函数用于生成一系列连续的整数

for i in range(101):
  result += i
print(result)
    2)for遍历列表和字典:
                      在3.2和3.3字典和列表的章节中已经用到了遍历列表和字典的代码,在此处不再赘述。
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

遍历列表,输出各个元素

for a1 in a:
  print(a1)**

评论

暂无评论