Python基础知识学习_Day2

一、for循环

1.1功能及语法

 for循环是迭代循环机制(while是条件循环),语法如下:

1 for i in a b c:
2     print(i)

1.2典型例子:

1.2.1猜年龄循环

 1 realy_age = 30
 2 for i in range(3):
 3     age = int(input("pls input age:"))
 4     if age == realy_age:
 5         print("正确!")
 6         break
 7     elif age > realy_age:
 8         print("猜大了")
 9     else:
10         print("猜小了")
11 else:
12     print("次数太多了,退出程序")
猜年龄

1.2.2 for基于range用法

range(5)是指0-4顾头不顾尾,例子如下:

 1  for i in range(10):
 2     print(i)
 3 0
 4 1
 5 2
 6 3
 7 4
 8 5
 9 6
10 7
11 8
12 9
range用法

1.2.3 for嵌套使用

1 for i in range(10):
2     for j in range(10):
3         if j<6:
4             continue
5 
6         print(i,j)
for嵌套使用

 

二、while循环

2.1 while功能和语法

while条件循环,满足某一条件下,一直循环,直到不满足,终止。

2.2 while用法举例:

2.2.1 死循环

1 count = 0
2 while True:
3     print("你是风儿我是沙,缠缠绵绵到天涯...",count)
4     count +=1
死循环

2.2.2 猜年龄游戏(while用法)

 1 count = 0
 2 age = 56
 3 while count <3:
 4     guess_age = input("age:").strip()
 5     if guess_age.isdigit():
 6         guess_age = int(guess_age)
 7     else:
 8         continue
 9     if guess_age == age:
10         print("猜对了")
11         break
12     elif guess_age < age:
13         print("往大猜")
14     else:
15         print("往小猜")
16     count +=1
猜年龄

三、数据类型

数字类型包括:数字、字符串、列表、元组、字典

3.1 数字

3.1.1 整型

python中可用十进制、八进制、十六机制

3.1.2 布尔bool

True 和False

1和0

3.1.3 浮点float

 在python里面,浮点就是小数,整数和浮点在计算机内部存储方式是不同的,整数运算永远是精确的,浮点运算有四舍五入的误差。

3.1.4数字相关内置函数

 3.2字符串

3.2.1 字符串创建

msg = "Hello world"
print(msg,type(msg))

执行结果:Hello world <class 'str'>

3.2.2 字符串常用操作

分割、长度、索引、切片、移除空白

3.2.3 字符串常用举例

1 msg='Hello worll'
2 print(msg)
3 print(msg.center(30,"*"))  #居中,不够的用*填充
4 print(msg.upper()) #全部大写字母
5 print(msg.lower()) #全部小写字母
6 print(msg.count("l",2,5)) #统计下标从2-5中间l的个数
7 print(msg.ljust(30,"*"))  #左对齐,不够的用*填充
8 print(msg.rstrip()) #去掉右边的空格
9 print(msg.strip()) #去掉左右的空格
10
print(len(msg)) #计算长度

3.3列表

3.3.1 列表创建

name_list = ['alex''seven''eric']

name_list = list(['alex''seven''eric'])

3.3.2 常用操作

增删改查,代码如下:

 1 names = ['alex','liumj','jack','liumj','wangzy','yesky','tmg']
 2 names2 = ['alex','liumj','jack','liumj']
 3 name1 = names.copy() #copy names列表,不同的内存地址
 4 names.append('wangxy') #追加元素到列表里面
 5 print(names.insert(1,"oldboy")) #在第二个元素前插入oldboy元素
 6 print(names.count('liumj')) #统计列表中liumj元素的个数
 7 print(names.index('alex')) #获取alex元素的下标索引
 8 print(names.remove('jack')) #移除jack元素
 9 names.reverse() #反向排序
10 print(names)
11 names.sort() #列表元素排序
12 print(names)
13 names.pop(6) #删除下标为6的元素
14 print(names)
15 print(names.reverse(names2))
16 names.extend(names2) #把names2追加到names里面
17 print(names)
原文地址:https://www.cnblogs.com/liumj0305/p/5970616.html