Python 入门的60个基础练习

Python167

python 的语法逻辑完全靠缩进,建议缩进 4 个空格。 如果是顶级代码,那么必须顶格书写,哪怕只有一个空格也会有语法错误。 下面示例中,满足 if 条件要输出两行内容,这两行内容必须都缩进,而且具有相同的缩进级别。

print('hello world!')

if 3 > 0:
    print('OK')
    print('yes')

x = 3; y = 4
print(x + y)
print('hello world!')
print('hello', 'world!')
print('hello' + 'world!')
print('hello', 'world', sep='***')
print('#' * 50)
print('how are you?', end='')
  • 运算符可以分为:算术运算符、比较运算符和逻辑运算符。优先级是:算术运算符>比较运算符>逻辑运算符。最好使用括号,增加了代码的可读性。
print(5 / 2)
print(5 // 2)
print(5 % 2)
print(5 ** 3)
print(5 > 3)
print(3 > 5)
print(20 > 10 > 5)
print(20 > 10 and 10 > 5)
print(not 20 > 10)
number = input("请输入数字:")
print(number)
print(type(number))

print(number + 10)
print(int(number) + 10)
print(number + str(10))
username = input('username: ')
print('welcome', username)
print('welcome ' + username)

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 = """
hello
world
abcd"""
print(words)

py_str = 'python'
len(py_str)
py_str[0]
'python'[0]
py_str[-1]

py_str[2:4]
py_str[2:]
py_str[:2]
py_str[:]
py_str[::2]
py_str[1::2]
py_str[::-1]

py_str + ' is good'
py_str * 3

't' in py_str
'th' in py_str
'to' in py_str
'to' not in py_str

列表也是序列对象,但它是容器类型,列表中可以包含各种数据

alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
len(alist)
alist[-1]
alist[-1][-1]
[1,2,3][-1]
alist[-2][2]
alist[3:5]
10 in alist
'o' in alist
100 not in alist
alist[-1] = 100
alist.append(200)

元组与列表基本上是一样的,只是元组不可变,列表可变。

atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])
len(atuple)
10 in atuple
atuple[2]
atuple[3:5]


 adict = {'name': 'bob', 'age': 23}
 len(adict)
 'bob' in adict
 'name' in adict
 adict['email'] = 'bob@tedu.cn'
 adict['age'] = 25

单个的数据也可作为判断条件。 任何值为 0 的数字、空对象都是 False,任何非 0 数字、非空对象都是 True。

if 3 > 0:
    print('yes')
    print('ok')

if 10 in [10, 20, 30]:
    print('ok')

if -0.0:
    print('yes')

if [1, 2]:
    print('yes')

if ' ':
    print('yes')
a = 10
b = 20

if a < b:
    smaller = a
else:
    smaller = b
print(smaller)

s = a if a < b else b
print(s)
import getpass

username = input('username: ')

password = getpass.getpass('password: ')

if username == 'bob' and password == '123456':
    print('Login successful')
else:
    print('Login incorrect')
import random

num = random.randint(1, 10)
answer = int(input('guess a number: '))
if answer > num:
    print('猜大了')
elif answer < num:
    print('猜小了')
else:
    print('猜对了')

print('the number:', num)
score = int(input('分数:'))

if score >= 90:
    print('优秀')
elif score >= 80:
    print('好')
elif score >= 70:
    print('良')
elif score >= 60:
    print('及格')
else:
    print('你要努力了')
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('你要努力了')
import random

all_choices = ['石头', '剪刀', '布']
computer = random.choice(all_choices)
player = input('请出拳:')

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('平局')
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')
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
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:
    print('the number is:', num)

因为循环次数是已知的,实际使用时,建议用 for 循环

sum100 = 0
counter = 1

while counter < 101:
    sum100 += counter
    counter += 1

print(sum100)

break 是结束循环,break 之后、循环体内代码不再执行。

while True:
    yn = input('Continue(y/n): ')
    if yn in ['n', 'N']:
        break
    print('running...')

计算 100 以内偶数之和。
continue 是跳过本次循环剩余部分,回到循环条件处。

sum100 = 0
counter = 0

while counter < 100:
    counter += 1

    if counter % 2 == 1:
        continue
    sum100 += counter

print(sum100)
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]))

sum100 = 0

for i in range(1, 101):
    sum100 += i

print(sum100)

列表中先给定两个数字,后面的数字总是前两个数字之和。

fib = [0, 1]

for i in range(8):
    fib.append(fib[-1] + fib[-2])

print(fib)
for i in range(1, 10):
    for j in range(1, i + 1):
        print('%s*%s=%s' % (j, i, i * j), end=' ')
    print()

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()

[10 + 5]

[10 + 5 for i in range(10)]

[10 + i for i in range(10)]
[10 + i for i in range(1, 11)]

[10 + i for i in range(1, 11) if i % 2 == 1]
[10 + i for i in range(1, 11) if i % 2]

['192.168.1.%s' % i for i in range(1, 255)]
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')

f = open('/tmp/passwd')
data = f.read()
print(data)
data = f.read()

f.close()

f = open('/tmp/passwd')
data = f.read(4)
f.readline()
f.readlines()
f.close()

f = open('/tmp/passwd')
for line in f:
    print(line, end='')
f.close()

f = open('图片地址', 'rb')
f.read(4096)
f.close()

f = open('/tmp/myfile', '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)

f.tell()
f.close()

拷贝文件就是以 r 的方式打开源文件,以 w 的方式打开目标文件,将源文件数据读出后,写到目标文件。
以下是【不推荐】的方式,但是可以工作:

f1 = open('/bin/ls', 'rb')
f2 = open('/root/ls', 'wb')

data = f1.read()
f2.write(data)

f1.close()
f2.close()

每次读取 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:
        break
    dst_fobj.write(data)

src_fobj.close()
dst_fobj.close()

注意:位置参数中的数字是字符形式的

import sys

print(sys.argv)

def gen_fib(l):
    fib = [0, 1]

    for i in range(l - len(fib)):
        fib.append(fib[-1] + fib[-2])

    return fib

a = gen_fib(10)
print(a)
print('-' * 50)
n = int(input("length: "))
print(gen_fib(n))
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])

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)

每一个以 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)

此文件名为: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))
from random import randint

alist = list()
list('hello')
list((10, 20, 30))
astr = str()
str(10)
str(['h', 'e', 'l', 'l', 'o'])
atuple = tuple()
tuple('hello')
num_list = [randint(1, 100) for i in range(10)]
max(num_list)
min(num_list)
alist = [10, 'john']

for 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=',')
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')
py_str.count('lo')
py_str.endswith('!')
py_str.endswith('d!')
py_str.startswith('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'])
"%s is %s years old" % ('bob', 23)
"%s is %d years old" % ('bob', 23)
"%s is %d years old" % ('bob', 23.5)
"%s is %f years old" % ('bob', 23.5)
"%s is %5.2f years old" % ('bob', 23.5)
"97 is %c" % 97
"11 is %#o" % 11
"11 is %#x" % 11
"%10s%5s" % ('name', 'age')
"%10s%5s" % ('bob', 25)
"%10s%5s" % ('alice', 23)
"%-10s%-5s" % ('name', 'age')
"%-10s%-5s" % ('bob', 25)
"%10d" % 123
"%010d" % 123

"{} is {} years old".format('bob', 25)
"{1} is {0} years old".format(25, 'bob')
"{:.format('name', 'age')
import shutil

with open('/etc/passwd', 'rb') as sfobj:
    with open('/tmp/mima.txt', 'wb') as dfobj:
        shutil.copyfileobj(sfobj, dfobj)

shutil.copyfile('/etc/passwd', '/tmp/mima2.txt')
shutil.copy('/etc/shadow', '/tmp/')
shutil.copy2('/etc/shadow', '/tmp/')
shutil.move('/tmp/mima.txt', '/var/tmp/')
shutil.copytree('/etc/security', '/tmp/anquan')
shutil.rmtree('/tmp/anquan')

shutil.copymode('/etc/shadow', '/tmp/mima2.txt')

shutil.copystat('/etc/shadow', '/tmp/mima2.txt')
shutil.chown('/tmp/mima2.txt', user='zhangsan', group='zhangsan')
import os

def get_fname():
    while True:
        fname = input('filename: ')
        if not os.path.exists(fname):
            break
        print('%s already exists. Try again' % fname)

    return fname

def get_content():
    content = []
    print('输入数据,输入 end 结束')
    while True:
        line = input('> ')
        if line == 'end':
            break
        content.append(line)

    return content

def wfile(fname, content):
    with open(fname, 'w') as fobj:
        fobj.writelines(content)

if __name__ == '__main__':
    fname = get_fname()
    content = get_content()
    content = ['%s\n' % line for line in content]
    wfile(fname, content)
alist = [1, 2, 3, 'bob', 'alice']
alist[0] = 10
alist[1:3] = [20, 30]
alist[2:2] = [22, 24, 26, 28]
alist.append(100)
alist.remove(24)
alist.index('bob')
blist = alist.copy()
alist.insert(1, 15)
alist.pop()
alist.pop(2)
alist.pop(alist.index('bob'))
alist.sort()
alist.reverse()
alist.count(20)
alist.clear()
alist.append('new')
alist.extend('new')
alist.extend(['hello', 'world', 'hehe'])
import sys
import keyword
import string

first_chs = string.ascii_letters + '_'
all_chs = first_chs + string.digits

def check_id(idt):
    if keyword.iskeyword(idt):
        return "%s is keyword" % idt

    if idt[0] not in first_chs:
        return "1st invalid"

    for ind, ch in enumerate(idt[1:]):
        if ch not in all_chs:
            return "char in postion #%s invalid" % (ind + 2)

    return "%s is valid" % idt

if __name__ == '__main__':
    print(check_id(sys.argv[1]))

randpass 模块参见《37-生成密码/验证码》

import subprocess
import sys
from randpass import gen_pass

def adduser(username, password, fname):
    data = """user information:
%s: %s
"""
    subprocess.call('useradd %s' % username, shell=True)
    subprocess.call(
        'echo %s | passwd --stdin %s' % (password, username),
        shell=True
    )
    with open(fname, 'a') as fobj:
        fobj.write(data % (username, password))

if __name__ == '__main__':
    username = sys.argv[1]
    password = gen_pass()
    adduser(username, password, '/tmp/user.txt')

stack = []

def push_it():
    item = input('item to push: ')
    stack.append(item)

def pop_it():
    if stack:
        print("from stack popped %s" % stack.pop())

def view_it():
    print(stack)

def show_menu():
    cmds = {'0': push_it, '1': pop_it, '2': view_it}
    prompt = """(0) push it
(1) pop it
(2) view it
(3) exit
Please input your choice(0/1/2/3): """

    while True:

        choice = input(prompt).strip()[0]
        if choice not in '0123':
            print('Invalid input. Try again.')
            continue

        if choice == '3':
            break

        cmds[choice]()

if __name__ == '__main__':
    show_menu()
import sys

def unix2dos(fname):
    dst_fname = fname + '.txt'

    with open(fname) as src_fobj:
        with open(dst_fname, 'w') as dst_fobj:
            for line in src_fobj:
                line = line.rstrip() + '\r\n'
                dst_fobj.write(line)

if __name__ == '__main__':
    unix2dos(sys.argv[1])

\r 是回车不换行

import time

length = 19
count = 0

while True:
    print('\r%s@%s' % ('#' * count, '#' * (length - count)), end='')
    try:
        time.sleep(0.3)
    except KeyboardInterrupt:
        print('\nBye-bye')
        break
    if count == length:
        count = 0
    count += 1
adict = dict()
dict(['ab', 'cd'])
bdict = dict([('name', 'bob'),('age', 25)])
{}.fromkeys(['zhangsan', 'lisi', 'wangwu'], 11)

for key in bdict:
    print('%s: %s' % (key, bdict[key]))

print("%(name)s: %(age)s" % bdict)

bdict['name'] = 'tom'
bdict['email'] = 'tom@tedu.cn'

del bdict['email']
bdict.pop('age')
bdict.clear()
adict = dict([('name', 'bob'),('age', 25)])
len(adict)
hash(10)
adict.keys()
adict.values()
adict.items()

adict.get('name')
print(adict.get('qq'))
print(adict.get('qq', 'not found'))
print(adict.get('age', 'not found'))
adict.update({'phone': '13455667788'})

myset = set('hello')
len(myset)
for ch in myset:
    print(ch)

aset = set('abc')
bset = set('cde')
aset & bset
aset.intersection(bset)
aset | bset
aset.union(bset)
aset - bset
aset.difference(bset)
aset.add('new')
aset.update(['aaa', 'bbb'])
aset.remove('bbb')
cset = set('abcde')
dset = set('bcd')
cset.issuperset(dset)
cset.issubset(dset)

with open('passwd') as fobj:
    aset = set(fobj)

with open('mima') as fobj:
    bset = set(fobj)

with open('diff.txt', 'w') as fobj:
    fobj.writelines(bset - aset)
import getpass

userdb = {}

def register():
    username = input('username: ')
    if username in userdb:
        print('%s already exists.' % username)
    else:
        password = input('password: ')
        userdb[username] = password

def login():
    username = input('username: ')
    password = getpass.getpass("password: ")
    if userdb.get(username) != password:
        print('login failed')
    else:
        print('login successful')

def show_menu():
    cmds = {'0': register, '1': login}
    prompt = """(0) register
(1) login
(2) exit
Please input your choice(0/1/2): """

    while True:
             choice = input(prompt).strip()[0]
             if choice not in '012':
                 print('Invalid inupt. Try again.')
                 continue
             if choice == '2':
                 break

             cmds[choice]()

if __name__ == '__main__':
    show_menu()
import time

result = 0
start = time.time()
for i in range(10000000):
    result += i
end = time.time()
print(result)
print(end - start)
import time

t = time.localtime()
time.gmtime()
time.time()
time.mktime(t)
time.sleep(1)
time.asctime()
time.ctime()
time.strftime("%Y-%m-%d")
time.strptime('2018-07-20', "%Y-%m-%d")
time.strftime('%H:%M:%S')

from datetime import datetime
from datetime import timedelta
datetime.today()
datetime.now()
datetime.strptime('2018/06/30', '%Y/%m/%d')
dt = datetime.today()
datetime.ctime(dt)
datetime.strftime(dt, "%Y%m%d")

days = timedelta(days=90, hours=3)
dt2 = dt + days
dt2.year
dt2.month
dt2.day
dt2.hour
import os

os.getcwd()
os.listdir()
os.listdir('/tmp')
os.mkdir('/tmp/mydemo')
os.chdir('/tmp/mydemo')
os.listdir()
os.mknod('test.txt')
os.symlink('/etc/hosts', 'zhuji')
os.path.isfile('test.txt')
os.path.islink('zhuji')
os.path.isdir('/etc')
os.path.exists('/tmp')
os.path.basename('/tmp/abc/aaa.txt')
os.path.dirname('/tmp/abc/aaa.txt')
os.path.split('/tmp/abc/aaa.txt')
os.path.join('/home/tom', 'xyz.txt')
os.path.abspath('test.txt')
import pickle
"""以前的文件写入,只能写入字符串,如果希望把任意数据对象(数字、列表等)写入文件,
取出来的时候数据类型不变,就用到 pickle 了
"""

with open('/tmp/shop.data', 'rb') as fobj:
    mylist = pickle.load(fobj)

print(mylist[0], mylist[1], mylist[2])
try:
    n = int(input("number: "))
    result = 100 / n
    print(result)
except ValueError:
    print('invalid number')
except ZeroDivisionError:
    print('0 not allowed')
except KeyboardInterrupt:
    print('Bye-bye')
except EOFError:
    print('Bye-bye')

print('Done')
try:
    n = int(input("number: "))
    result = 100 / n
except (ValueError, ZeroDivisionError):
    print('invalid number')
except (KeyboardInterrupt, EOFError):
    print('\nBye-bye')
else:
    print(result)
finally:
    print('Done')

Original: https://blog.csdn.net/zea408497299/article/details/125238327
Author: taotaotao7777777
Title: Python 入门的60个基础练习