python入门的120个基础练习(一)
学习永远都是“理论”与“实践”相结合效果最好。
这里有python入门的120个基础练习(1~40),希望对你有用。
01-Hello World
python的语法逻辑完全靠缩进,建议缩进4个空格。 如果是顶级代码,那么必须顶格书写,哪怕只有一个空格也会有语法错误。 下面示例中,满足if条件要输出两行内容,这两行内容必须都缩进,而且具有相同的缩进级别。
print('hello world!')if 3 > 0:print('OK')print('yes')x = 3; y = 4 # 不推荐,还是应该写成两行print(x + y)
02-print
print('hello world!')print('hello', 'world!') # 逗号自动添加默认的分隔符:空格print('hello' + 'world!') # 加号表示字符拼接print('hello', 'world', sep='***') # 单词间用***分隔print('#' * 50) # *号表示重复50遍print('how are you?', end='') # 默认print会打印回车,end=''表示不要回车
03-基本运算
运算符可以分为:算术运算符、比较运算符和逻辑运算符。优先级是:算术运算符>比较运算符>逻辑运算符。最好使用括号,增加了代码的可读性。
print(5 / 2) # 2.5print(5 // 2) # 丢弃余数,只保留商print(5 % 2) # 求余数print(5 ** 3) # 5的3次方print(5 > 3) # 返回Trueprint(3 > 5) # 返回Falseprint(20 > 10 > 5) # python支持连续比较print(20 > 10 and 10 > 5) # 与上面相同含义print(not 20 > 10) # False
04-input
number = input("请输入数字: ") # input用于获取键盘输入print(number)print(type(number)) # input获得的数据是字符型print(number + 10) # 报错,不能把字符和数字做运算print(int(number) + 10) # int可将字符串10转换成数字10print(number + str(10)) # str将10转换为字符串后实现字符串拼接
05-输入输出基础练习
username = input('username: ')print('welcome', username) # print各项间默认以空格作为分隔符print('welcome ' + username) # 注意引号内最后的空格
06-字符串使用基础
python中,单双引号没有区别,表示一样的含义
sentence = 'tom\'s pet is a cat' # 单引号中间还有单引号,可以转义sentence2 = "tom's pet is a cat" # 也可以用双引号包含单引号sentence3 = "tom said:\"hello world!\""sentence4 = 'tom said:"hello world"'# 三个连续的单引号或双引号,可以保存输入格式,允许输入多行字符串words = """helloworldabcd"""print(words)py_str = 'python'len(py_str) # 取长度py_str[0] # 第一个字符'python'[0]py_str[-1] # 最后一个字符# py_str[6] # 错误,下标超出范围py_str[2:4] # 切片,起始下标包含,结束下标不包含py_str[2:] # 从下标为2的字符取到结尾py_str[:2] # 从开头取到下标是2之前的字符py_str[:] # 取全部py_str[::2] # 步长值为2,默认是1py_str[1::2] # 取出yhnpy_str[::-1] # 步长为负,表示自右向左取py_str + ' is good' # 简单的拼接到一起py_str * 3 # 把字符串重复3遍't' in py_str # True'th' in py_str # True'to' in py_str # False'to' not in py_str # True
07-列表基础
列表也是序列对象,但它是容器类型,列表中可以包含各种数据
**alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]len(alist)alist[-1] # 取出最后一项alist[-1][-1] # 因为最后一项是列表,列表还可以继续取下标[1,2,3][-1] # [1,2,3]是列表,[-1]表示列表最后一项alist[-2][2] # 列表倒数第2项是字符串,再取出字符下标为2的字符alist[3:5] # ['bob', 'alice']10 in alist # True'o' in alist # False100 not in alist # Truealist[-1] = 100 # 修改最后一项的值alist.append(200) # 向**列表中追加一项
08-元组基础
元组与列表基本上是一样的,只是元组不可变,列表可变。
atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])len(atuple)10 in atupleatuple[2]atuple[3:5]# atuple[-1] = 100 # 错误,元组是不可变的
09-字典基础
# 字典是key-value(键-值)对形式的,没有顺序,通过键取出值adict = {'name': 'bob', 'age': 23}len(adict)'bob' in adict # False'name' in adict # Trueadict['email'] = 'bob@tedu.cn' # 字典中没有key,则添加新项目adict['age'] = 25 # 字典中已有key,修改对应的value
10-基本判断
单个的数据也可作为判断条件。 任何值为0的数字、空对象都是False,任何非0数字、非空对象都是True。
if 3 > 0:print('yes')print('ok')if 10 in [10, 20, 30]:print('ok')if -0.0:print('yes') # 任何值为0的数字都是Falseif [1, 2]:print('yes') # 非空对象都是Trueif ' ':print('yes') # 空格字符也是字符,条件为True
11-条件表达式、三元运算符
a = 10b = 20if a < b:smaller = aelse:smaller = bprint(smaller)s = a if a < b else b # 和上面的if-else语句等价print(s)
12-判断练习:用户名和密码是否正确
import getpass # 导入模块username = input('username: ')# getpass模块中,有一个方法也叫getpasspassword = getpass.getpass('password: ')if username == 'bob' and password == '123456':print('Login successful')else:print('Login incorrect')
13-猜数:基础实现
import randomnum = random.randint(1, 10) # 随机生成1-10之间的数字answer = int(input('guess a number: ')) # 将用户输入的字符转成整数if answer > num:print('猜大了')elif answer < num:print('猜小了')else:print('猜对了')print('the number:', num)
14-成绩分类1
score = int(input('分数: '))if score >= 90:print('优秀')elif score >= 80:print('好')elif score >= 70:print('良')elif score >= 60:print('及格')else:print('你要努力了')
15-成绩分类2
score = int(input('分数: '))if score >= 60 and score < 70:print('及格')elif 70 <= score < 80:print('良')elif 80 <= score < 90:print('好')elif score >= 90:print('优秀')else:print('你要努力了')
16-石头剪刀布
import randomall_choices = ['石头', '剪刀', '布']computer = random.choice(all_choices)player = input('请出拳: ')# print('Your choice:', player, "Computer's choice:", computer)print("Your choice: %s, Computer's choice: %s" % (player, computer))if player == '石头':if computer == '石头':print('平局')elif computer == '剪刀':print('You WIN!!!')else:print('You LOSE!!!')elif player == '剪刀':if computer == '石头':print('You LOSE!!!')elif computer == '剪刀':print('平局')else:print('You WIN!!!')else:if computer == '石头':print('You WIN!!!')elif computer == '剪刀':print('You LOSE!!!')else:print('平局')
17-改进的石头剪刀布
import randomall_choices = ['石头', '剪刀', '布']win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]prompt = """(0) 石头(1) 剪刀(2) 布请选择(0/1/2): """computer = random.choice(all_choices)ind = int(input(prompt))player = all_choices[ind]print("Your choice: %s, Computer's choice: %s" % (player, computer))if player == computer:print('\033[32;1m平局\033[0m')elif [player, computer] in win_list:print('\033[31;1mYou WIN!!!\033[0m')else:print('\033[31;1mYou LOSE!!!\033[0m')
18-猜数,直到猜对
import randomnum = random.randint(1, 10)running = Truewhile running:answer = int(input('guess the number: '))if answer > num:print('猜大了')elif answer < num:print('猜小了')else:print('猜对了')running = False
19-猜数,5次机会
import randomnum = random.randint(1, 10)counter = 0while counter < 5:answer = int(input('guess the number: '))if answer > num:print('猜大了')elif answer < num:print('猜小了')else:print('猜对了')breakcounter += 1else: # 循环被break就不执行了,没有被break才执行print('the number is:', num)
20-while循环,累加至100
因为循环次数是已知的,实际使用时,建议用for循环
sum100 = 0counter = 1while counter < 101:sum100 += countercounter += 1print(sum100)
21-while-break
break是结束循环,break之后、循环体内代码不再执行。
while True:yn = input('Continue(y/n): ')if yn in ['n', 'N']:breakprint('running...')
22-while-continue
计算100以内偶数之和。
continue是跳过本次循环剩余部分,回到循环条件处。
sum100 = 0counter = 0while counter < 100:counter += 1# if counter % 2:if counter % 2 == 1:continuesum100 += counterprint(sum100)
23-for循环遍历数据对象
astr = 'hello'alist = [10, 20, 30]atuple = ('bob', 'tom', 'alice')adict = {'name': 'john', 'age': 23}for ch in astr:print(ch)for i in alist:print(i)for name in atuple:print(name)for key in adict:print('%s: %s' % (key, adict[key]))
24-range用法及数字累加
# range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# >>> list(range(10))# range(6, 11) # [6, 7, 8, 9, 10]# range(1, 10, 2) # [1, 3, 5, 7, 9]# range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]sum100 = 0for i in range(1, 101):sum100 += iprint(sum100)
25-列表实现斐波那契数列
列表中先给定两个数字,后面的数字总是前两个数字之和。
fib = [0, 1]for i in range(8):fib.append(fib[-1] + fib[-2])print(fib)
26-九九乘法表
for i in range(1, 10):for j in range(1, i + 1):print('%s*%s=%s' % (j, i, i * j), end=' ')print()# i=1 ->j: [1]# i=2 ->j: [1,2]# i=3 ->j: [1,2,3]#由用户指定相乘到多少n = int(input('number: '))for i in range(1, n + 1):for j in range(1, i + 1):print('%s*%s=%s' % (j, i, i * j), end=' ')print()
27-逐步实现列表解析
# 10+5的结果放到列表中[10 + 5]# 10+5这个表达式计算10次[10 + 5 for i in range(10)]# 10+i的i来自于循环[10 + i for i in range(10)][10 + i for i in range(1, 11)]# 通过if过滤,满足if条件的才参与10+i的运算[10 + i for i in range(1, 11) if i % 2 == 1][10 + i for i in range(1, 11) if i % 2]# 生成IP地址列表['192.168.1.%s' % i for i in range(1, 255)]
28-三局两胜的石头剪刀布
import randomall_choices = ['石头', '剪刀', '布']win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]prompt = """(0) 石头(1) 剪刀(2) 布请选择(0/1/2): """cwin = 0pwin = 0while cwin < 2 and pwin < 2:computer = random.choice(all_choices)ind = int(input(prompt))player = all_choices[ind]print("Your choice: %s, Computer's choice: %s" % (player, computer))if player == computer:print('\033[32;1m平局\033[0m')elif [player, computer] in win_list:pwin += 1print('\033[31;1mYou WIN!!!\033[0m')else:cwin += 1print('\033[31;1mYou LOSE!!!\033[0m')
29-文件对象基础操作
# 文件操作的三个步骤:打开、读写、关闭# cp /etc/passwd /tmpf = open('/tmp/passwd') # 默认以r的方式打开纯文本文件data = f.read() # read()把所有内容读取出来print(data)data = f.read() # 随着读写的进行,文件指针向后移动。# 因为第一个f.read()已经把文件指针移动到结尾了,所以再读就没有数据了# 所以data是空字符串f.close()f = open('/tmp/passwd')data = f.read(4) # 读4字节f.readline() # 读到换行符\n结束f.readlines() # 把每一行数据读出来放到列表中f.close()################################f = open('/tmp/passwd')for line in f:print(line, end='')f.close()##############################f = open('图片地址', 'rb') # 打开非文本文件要加参数bf.read(4096)f.close()##################################f = open('/tmp/myfile', 'w') # 'w'打开文件,如果文件不存在则创建f.write('hello world!\n')f.flush() # 立即将缓存中的数据同步到磁盘f.writelines(['2nd line.\n', 'new line.\n'])f.close() # 关闭文件的时候,数据保存到磁盘##############################with open('/tmp/passwd') as f:print(f.readline())#########################f = open('/tmp/passwd')f.tell() # 查看文件指针的位置f.readline()f.tell()f.seek(0, 0) # 第一个数字是偏移量,第2位是数字是相对位置。# 相对位置0表示开头,1表示当前,2表示结尾f.tell()f.close()
30-拷贝文件
拷贝文件就是以r的方式打开源文件,以w的方式打开目标文件,将源文件数据读出后,写到目标文件。
以下是【不推荐】的方式,但是可以工作:
f1 = open('/bin/ls', 'rb')f2 = open('/root/ls', 'wb')data = f1.read()f2.write(data)f1.close()f2.close()
31-拷贝文件
每次读取4K,读完为止:
src_fname = '/bin/ls'dst_fname = '/root/ls'src_fobj = open(src_fname, 'rb')dst_fobj = open(dst_fname, 'wb')while True:data = src_fobj.read(4096)if not data:breakdst_fobj.write(data)src_fobj.close()dst_fobj.close()
32-位置参数
注意:位置参数中的数字是字符形式的
import sysprint(sys.argv) # sys.argv是sys模块里的argv列表# python3 position_args.py# python3 position_args.py 10# python3 position_args.py 10 bob
33-函数应用-斐波那契数列
def gen_fib(l):fib = [0, 1]for i in range(l - len(fib)):fib.append(fib[-1] + fib[-2])return fib # 返回列表,不返回变量fiba = gen_fib(10)print(a)print('-' * 50)n = int(input("length: "))print(gen_fib(n)) # 不会把变量n传入,是把n代表的值赋值给形参
34-函数-拷贝文件
import sysdef copy(src_fname, dst_fname):src_fobj = open(src_fname, 'rb')dst_fobj = open(dst_fname, 'wb')while True:data = src_fobj.read(4096)if not data:breakdst_fobj.write(data)src_fobj.close()dst_fobj.close()copy(sys.argv[1], sys.argv[2])# 执行方式# cp_func.py /etc/hosts /tmp/zhuji.txt
35-函数-九九乘法表
def mtable(n):for i in range(1, n + 1):for j in range(1, i + 1):print('%s*%s=%s' % (j, i, i * j), end=' ')print()mtable(6)mtable(9)
36-模块基础
每一个以py作为扩展名的文件都是一个模块。
star.py:hi = 'hello world!'def pstar(n=50):print('*' * n)if __name__ == '__main__':pstar()pstar(30)在call_star.py中调用star模块:import starprint(star.hi)star.pstar()star.pstar(30)
37-生成密码/验证码
此文件名为:randpass.py
思路:
1、设置一个用于随机取出字符的基础字符串,本例使用大小写字母加数字
2、循环n次,每次随机取出一个字符
3、将各个字符拼接起来,保存到变量result中
from random import choiceimport stringall_chs = string.ascii_letters + string.digits # 大小写字母加数字def gen_pass(n=8):result = ''for i in range(n):ch = choice(all_chs)result += chreturn resultif __name__ == '__main__':print(gen_pass())print(gen_pass(4))print(gen_pass(10))
38-序列对象方法
from random import randintalist = list() # []list('hello') # ['h', 'e', 'l', 'l', 'o']list((10, 20, 30)) # [10, 20, 30] 元组转列表astr = str() # ''str(10) # '10'str(['h', 'e', 'l', 'l', 'o']) # 将列表转成字符串atuple = tuple() # ()tuple('hello') # ('h', 'e', 'l', 'l', 'o')num_list = [randint(1, 100) for i in range(10)]max(num_list)min(num_list)
39-序列对象方法2
alist = [10, 'john']# list(enumerate(alist)) # [(0, 10), (1, 'john')]# a, b = 0, 10 # a->0 ->10for ind in range(len(alist)):print('%s: %s' % (ind, alist[ind]))for item in enumerate(alist):print('%s: %s' % (item[0], item[1]))for ind, val in enumerate(alist):print('%s: %s' % (ind, val))atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90)sorted(atuple)sorted('hello')for i in reversed(atuple):print(i, end=',')
40-字符串方法
py_str = 'hello world!'py_str.capitalize()py_str.title()py_str.center(50)py_str.center(50, '#')py_str.ljust(50, '*')py_str.rjust(50, '*')py_str.count('l') # 统计l出现的次数py_str.count('lo')py_str.endswith('!') # 以!结尾吗?py_str.endswith('d!')py_str.startswith('a') # 以a开头吗?py_str.islower() # 字母都是小写的?其他字符不考虑py_str.isupper() # 字母都是大写的?其他字符不考虑'Hao123'.isdigit() # 所有字符都是数字吗?'Hao123'.isalnum() # 所有字符都是字母数字?' hello\t '.strip() # 去除两端空白字符,常用' hello\t '.lstrip()' hello\t '.rstrip()'how are you?'.split()'hello.tar.gz'.split('.')'.'.join(['hello', 'tar', 'gz'])'-'.join(['hello', 'tar', 'gz'])
41~120题见下篇
python入门的120个基础练习(一)相关推荐
- python入门的120个基础练习_python入门的120个基础练习(一),自学python必看!!...
学习永远都是"理论"与"实践"相结合效果最好. 这里有python入门的120个基础练习(1~40),希望对你有用. 01-Hello World python ...
- python入门基础代码图-适合Python入门的5本基础书籍
原标题:适合Python入门的5本基础书籍 Python 3标准库 对程序员而言,标准库与语言本身同样重要,它好比一个百宝箱,能为各种常见的任务提供完美的解决方案,所以本书是所有Python程序员都必 ...
- Python入门学习笔记1-Python基础
Python入门学习笔记1-Python基础 前言:本文介绍了Python学习的前导知识概念以及必记基础函数,如善用help方法查看帮助文档,以及内置对象类型的概念以及常用函数的详解. 一.Pytho ...
- 零基础学习python入门书_零基础学习Python不可错过的5本书籍
原标题:零基础学习Python不可错过的5本书籍 Python作为目前编程开发的主流语言之一,在企业中的应用范围越来越广,广阔的发展前景吸引了很多小伙伴想要入行Python,下面小U就为大家介绍一下零 ...
- 适合Python入门的5本基础书籍
Python 3标准库 对程序员而言,标准库与语言本身同样重要,它好比一个百宝箱,能为各种常见的任务提供完美的解决方案,所以本书是所有Python程序员都必备的工具书!全书以案例驱动的方式讲解了标准库 ...
- python 舍去小数_零基础小白Python入门必看——编程基础概念
1. 程序的构成 程序由模块组成,一个模块对应python的源文件 ,一般后缀为:.py 模块由语句构成 语句是python程序的构造单元,用于创建对象.变量赋值.调用函数.控制语句等. 2. 对象 ...
- python入门经典必备推荐基础教程
绝对是python初学者入门必备,比learning python写的好100倍,远超python基础教程n个数量级 下载地址 http://pan.baidu.com/s/1jGwzpeY 更多p ...
- python入门需要多久-零基础小白多久能学会python
学习任何一门编程语言,都是为了去实现一个个项目,来解决实际的问题.无论项目是大还是小,都关联着许多知识与技能. 例如要写一个「文件资源管理器」的应用,就需要MVC设计模式.组件化构建.对象集合及操作. ...
- 小猿学python_小猿圈python入门之转行零基础该如何学Python?
转行零基础学Python编程开发难度大吗?从哪学起?近期很多小伙伴问我,如果自己转行学习Python,完全0基础能否学会呢?Python的难度到底有多大?今天,小编就来为大家解决一下疑惑. 学习Pyt ...
最新文章
- 【跃迁之路】【605天】程序员高效学习方法论探索系列(实验阶段362-2018.10.09)...
- TCP/IP 详解卷一 - TCP CWR、ECE、URG、ACK、PSH、RST、SYN、FIN控制位
- 织梦channel标签currentstyle样式无效不起作用
- 1社会心理学---感知情境
- 如何正确的检测对象类型?
- Ubuntu14.04安装mysql
- erp服务器性能测试,浪潮PS-ERP压力测试报告--AMD单路服务器
- 什么是消息队列及消息队列原理和应用场景详解
- 2.3Java NIO
- .gitignore文件写法
- VOA Special English Facebook Stock Goes on Sale (中英文对照)
- Visio画出的图,裁剪成固定大小再添加马赛克的方法
- 小甲鱼C++快速入门学习笔记
- 小程序封装请求工具http.js
- vivo S16/S15/S12/S10 PRO卡刷线刷系统升级降级推荐成功解决屏幕锁不记得开机锁成功刷好的有效方案
- Java序列中如果有些字段不想被序列化,怎么办
- Unity官方案例噩梦射手开发总结<一> 角色的攻击功能实现
- linux DRM/KMS 测试工具 modetest、kmscude、igt-gpu-tools (一)
- 双网卡“在 TCP 网络上检测出有重复名称”错误
- 托里拆利小号:有关于其的证明