python刷题笔记(1)

2021/4/15 12:26:56

本文主要是介绍python刷题笔记(1),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目一

用字符串的格式化方法输出名片

print('==========我的名片==========')
print('姓名: {}'.format('itheima'))
print('QQ:{}'.format(12345678))
print('手机号:{}'.format(15315821234))
print('公司地址:{}'.format('北京市海淀区'))
print('===========================')

==========我的名片==========
姓名: itheima
QQ:12345678
手机号:15315821234
公司地址:北京市海淀区
===========================

可参考字符串的格式化方法

题目二

编写代码,设计简易计算器,完成加减乘除等操作

num1 = eval(input('请输入一个数'))
ops = input('请输入要进行的操作')
num2 = eval(input('请输入另一个数'))
if ops == '+':
    print('结果为{}'.format(num1+num2))
elif ops=='-':
    print('结果为{}'.format(num1 - num2))
elif ops == '*':
    print('结果为{}'.format(num1 * num2))
elif ops == '/':
    print('结果为{}'.format(num1 / num2))

请输入一个数2
请输入要进行的操作*
请输入另一个数3
结果为6

题目三

使用for循环,依次打印abcdef中的每个字符

str = 'abcdef'
for i in str:
    print(i,end=',')

a,b,c,d,e,f,

注意字符串可以直接遍历及求长度。

题目四

将字符串反转输出

str = 'abc'
for i in str[::-1]:
    print(i,end='')

cba

注意第二行的切片表示

题目五

字符串和列表的转换

  1. 字符串转换为列表,将‘1234’转换为[1,2,3,4]

  2. 将列表转换为字符串,将[1,2,3,4]转换为‘1234’

lis = [1,2,3,4]
st = ''
for i in lis:
    st+=str(i)
print(st)
print(type(st))

1234
<class 'str'>

题目六

现有字符串 msg = "hel@#$lo pyt \nhon ni\t hao%$" ,去掉所有不是英文字母的字符,打印结果:“请理以后的结果为:hellopythonnihao”

msg = "hel@#$lo pyt \nhon ni\t hao%$"
st = ''
for i in msg:
    if i in 'abcdefghijklmnopqrstuvwxyz':
        st +=i
print(st)

hellopythonnihao

与上题的思路相同,先定义一个空字符串,然后把符合条件的加入到里面。

题目七

定义 input_password 函数,提示用户输入密码,如果用户输入长度 < 8,抛出异常,如果用户输入长度 >=8,返回输入的密码

def input_password():
    password = input('请输入你的密码')
    if len(password)<8:
        raise Exception('密码长度至少8位')
    elif len(password)>=8:
        return password
input_password()

注意异常处理部分。

题目八

将一个文件中的内容复制到另一个文件中

f1 = open('a.txt','r')
f2 = open('abc.txt','w')
f2.write(f1.read())
f1.close()
f2.close()

可参考python文件的读写



这篇关于python刷题笔记(1)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程