四. Python基础(4)--语法

1 ● 比较几种实现循环的代码

i = 1

sum = 0

while i <= 10: # 循环10-1+1=10次

    sum += i

    i += 1

print(sum)

 

sum = 0

for i in range(1, 11): # 循环11-1=10次

    sum += i

print(sum)

 

i = 0

sum = 0

while True:

    i += 1

    if i <=10:

        sum += i

    else:

        break

print(sum)

试着对照C语言的代码:

#include <stdio.h>

 

void main()

{

    int sum=0;

    int i;

    for(i=1;i<=10;i++) # 循环10-1+1=10

        sum+=i;

    printf("%d", sum);

    getchar();

}

 

//等价于:

void main()

{

    int sum=0;    

    int i = 1;

        while(i<=10){

            sum+=i;

            i++;

        }

 

    printf("%d", sum);

    getchar();

}

 

2 ● while循环和for循环

for循环--一般用于有限循环

while循环一般用于无线循环

 

3 ● range()和xrange()

# py2:

# range(),用于生成连续的数字,列表类型

# xrange(),用于生成连续的数字,for循环时才能使用,返回一个生成器(generator, 也是一种数据类型)

 

# py3

# range() = py2xrange(), for循环时才能使用,返回一个生成器

for i in range(10):

    print(i, end = " ")

print("\n")

for i in range(1, 11): # 默认步长为1

    print(i, end = " ")

print("\n")

for i in range(10, 0, -1):

    print(i, end = " ")

print("\n")

for i in range(0, 11, 2):

    print(i, end = " ")

print("\n")

for i in range(10, 0, -2):

    print(i, end = " ")

0 1 2 3 4 5 6 7 8 9

 

1 2 3 4 5 6 7 8 9 10

 

10 9 8 7 6 5 4 3 2 1

 

0 2 4 6 8 10

 

10 8 6 4 2

 

4 ● 对于input()函数得到的字符串, 如果希望是数字, 一般要做如下检验和处理:

strip()

index = index.strip()

isdecimal

if index.isdecimal()

③根据实际需求判断index的范围

 

5 ● 可迭代对象

for循环的,就是可迭代对象

有关可迭代对象, 详见:

http://python.jobbole.com/87805/

 

6 ● 代码案例(flag = True/False)

# li = ['alex', 'eric' ,'rain']

# 利用下划线将列表的每一个元素拼接成字符串"alex_eric_rain"

li = ["alex", "eric", "rain"]

msg = ""

is_first = True

for item in li:

    if is_first:

        msg += item

        is_first = False

    else:

        msg += "_" + item

print(msg)

 

msg = ""

is_first = True

for item in li:

    if is_first:

        tmp = item

        is_first = False

    else:

        tmp = "_" + item

    msg += tmp # 这一步必然执行!!!!!

print(msg)

 

7 ● 字符串按每行三个字母显示, 并计算可显示多少行?

index = 0

content = input("请输入字符串:")

 

for i in content:

    index += 1

    if index % 3 == 0:

        print(i, end= "\n")

    else:

        print(i, end = " ")

print("\n")

if len(content) % 3 == 0:

    count = len(content) / 3

else:

    count = int(len(content)/3) + 1 # 也可以用len(content)//3

print(count)

 

8 ● 有关作用域

# 只要一个语句执行了, 那么这个语句内的变量就会放在内存, 即允许使用.

# if 1 == 1:

#     name = '123'

# print(name) # 123

 

# 上面的案例如果是在C/C++, Java中会报错, 因为name的作用域只在if语句内

 

# if 1!=1:

#     name = '123'

# print(name) # 报错

 

# 如果变量名未定义,则报错.

a = 0

while True:

    a = a + 1

    if a >= 10:

        break

print(a) # 10

 

 

9 ● split知识扩充

formula = input("请输入加法算式:")

a,b = formula.split("+")

print(int(a) + int(b))

请输入加法算式: 5 + 9

14

formula = input("请输入加法算式:")

tmp = formula.split("+", 1) # ['5', '8+9'], 1表示分割次数

# tmp = formula.split("+", 2) # 5+8+9

print(tmp)

 posted on 2018-01-31 17:22  Arroz  阅读(231)  评论(0编辑  收藏  举报