Python基础入门练习,小白一定要多练啊!!!
Posted yunyun云芸
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基础入门练习,小白一定要多练啊!!!相关的知识,希望对你有一定的参考价值。
要想你的Python达到大神级别的,不管你是小白还是已经入门的,必须达到理论和实践相结合,现在不管学什么专业,都要有这两点,理论与实践的重要性。在这里小编准备了Python入门的26个基础练习,希望对你有用。
1-字典基础
字典是key-value(键-值)对形式的,没有顺序,通过键取出值
adict = {'name': 'bob', 'age': 23}
len(adict)
'bob' in adict # False
'name' in adict # True
adict['email'] = 'bob@tedu.cn' # 字典中没有key,则添加新项目
adict['age'] = 25 # 字典中已有key,修改对应的value
2-基本判断
单个的数据也可作为判断条件。 任何值为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的数字都是False
if [1, 2]:
print('yes') # 非空对象都是True
if ' ':
print('yes') # 空格字符也是字符,条件为True
3-条件表达式、三元运算符
a = 10
b = 20
if a < b:
smaller = a
else:
smaller = b
print(smaller)
s = a if a < b else b # 和上面的if-else语句等价
print(s)
4-判断练习:用户名和密码是否正确
import getpass # 导入模块
username = input('username: ')
#getpass模块中,有一个方法也叫getpass
password = getpass.getpass('password: ')
if username == 'bob' and password == '123456':
print('Login successful')
else:
print('Login incorrect')
5-猜数:基础实现
import random
num = 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)
6-成绩分类1
score = int(input('分数: '))
if score >= 90:
print('优秀')
elif score >= 80:
print('好')
elif score >= 70:
print('良')
elif score >= 60:
print('及格')
else:
print('你要努力了')
关注本人公众号,更多精彩内容,免费学习资料
7-成绩分类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('你要努力了')
8-石头剪刀布
import random
all_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('平局')
9-改进的石头剪刀布
import random
all_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')
10-猜数,直到猜对
import random
num = random.randint(1, 10)
running = True
while running:
answer = int(input('guess the number: '))
if answer > num:
print('猜大了')
elif answer < num:
print('猜小了')
else:
print('猜对了')
running = False
11-猜数,5次机会
import random
num = random.randint(1, 10)
counter = 0
while counter < 5:
answer = int(input('guess the number: '))
if answer > num:
print('猜大了')
elif answer < num:
print('猜小了')
else:
print('猜对了')
break
counter += 1
else: # 循环被break就不执行了,没有被break才执行
print('the number is:', num)
12-while循环,累加至100
因为循环次数是已知的,实际使用时,建议用for循环
sum100 = 0
counter = 1
while counter < 101:
sum100 += counter
counter += 1
print(sum100)
13-while-break
break是结束循环,break之后、循环体内代码不再执行。
while True:
yn = input('Continue(y/n): ')
if yn in ['n', 'N']:
break
print('running...')
14-while-continue
计算100以内偶数之和。
continue是跳过本次循环剩余部分,回到循环条件处。
sum100 = 0
counter = 0
while counter < 100:
counter += 1
# if counter % 2:
if counter % 2 == 1:
continue
sum100 += counter
print(sum100)
15-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]))
16-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 = 0
for i in range(1, 101):
sum100 += i
print(sum100)
17-列表实现斐波那契数列
列表中先给定两个数字,后面的数字总是前两个数字之和。
fib = [0, 1]
for i in range(8):
fib.append(fib[-1] + fib[-2])
print(fib)
18-九九乘法表
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()
19-逐步实现列表解析
# 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)]
20-三局两胜的石头剪刀布
import random
all_choices = ['石头', '剪刀', '布']
win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
prompt = """(0) 石头
(1) 剪刀
(2) 布
请选择(0/1/2): """
cwin = 0
pwin = 0
while 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 += 1
print('\\033[31;1mYou WIN!!!\\033[0m')
else:
cwin += 1
print('\\033[31;1mYou LOSE!!!\\033[0m')
21-函数应用-斐波那契数列
def gen_fib(l):
fib = [0, 1]
for i in range(l - len(fib)):
fib.append(fib[-1] + fib[-2])
return fib # 返回列表,不返回变量fib
a = gen_fib(10)
print(a)
print('-' * 50)
n = int(input("length: "))
print(gen_fib(n)) # 不会把变量n传入,是把n代表的值赋值给形参
22-函数-拷贝文件
import sys
def 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:
break
dst_fobj.write(data)
src_fobj.close()
dst_fobj.close()
copy(sys.argv[1], sys.argv[2])
# 执行方式
# cp_func.py /etc/hosts /tmp/zhuji.txt
23-函数-九九乘法表
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)
24-模块基础
每一个以py作为扩展名的文件都是一个模块。
star.py:
hi = 'hello world!'
def pstar(n=50):
print('*' * n)
if __name__ == '__main__':
pstar()
pstar(30)
在call_star.py中调用star模块:
import star
print(star.hi)
star.pstar()
star.pstar(30)
25-生成密码/验证码
此文件名为:randpass.py
思路:
1、设置一个用于随机取出字符的基础字符串,本例使用大小写字母加数字
2、循环n次,每次随机取出一个字符
3、将各个字符拼接起来,保存到变量result中
from random import choice
import string
all_chs = string.ascii_letters + string.digits # 大小写字母加数字
def gen_pass(n=8):
result = ''
for i in range(n):
ch = choice(all_chs)
result += ch
return result
if __name__ == '__main__':
print(gen_pass())
print(gen_pass(4))
print(gen_pass(10))
26-序列对象方法
from random import randint
alist = 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)
到这里结束啦~整理的这些题目希望给你们带来学习上的帮助,想了解更多Python,可以关注我私聊我啦。
以上是关于Python基础入门练习,小白一定要多练啊!!!的主要内容,如果未能解决你的问题,请参考以下文章
保姆级Java入门练习教程,附代码讲解,小白零基础入门必备(建议收藏)