python基础题

文章目录

  • for 、if-else、while、应用
  • 字符串、列表与元组应用

for 、if-else、while、应用

一:求1-100偶数和

sum=0 #0+2+4... 从0开始
for i in range(1,101):
   if i%2==0:  
      sum+=i
print(sum)

效果:
在这里插入图片描述
二:记录用户输入的次数

try_count=0 #循环未开始,count=0
while try_count < 3 :
   num=input('please input number:')
   try_count +=1 #用户输入一次,count加一,count计数完显示用户输入的次数
   print('用户输入了%d次' %(try_count))

效果:
python基础题_第1张图片
三:随机生成年份并判断是否为闰年

import random
year=random.randint(1900,2000)
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
   print(year,'is 闰年')
else:
        print(year,'is not 闰年')
    

效果:
在这里插入图片描述
四:打印九九乘法表

 '''
九九乘法表中,第一行一列,第二行2列...第九行9列
每一行都固定相应的列,用嵌套循环取值
i=1 j=1
i=2 j=1,2
i=3 j=1,2,3
i=4 j=1,2,3,4
i=5 j=1,2,3,4,5
i=6 j=1,2,3,4,5,6 #j从1开始到i结束

#循环一次不换行打印一行,打印完一行后换行(i先遍历第一个值,j遍历完1-i个值再换行,接着i去遍历下一个值) 下三角
  for i in range (1,10)
   for j in range (1,i+1)
      print('%d*%d=%d'%(j,i,j*i),end='')
   print()
'''
#打印上三角
for i in range (9,0,-1):
        for j in range (1,i+1):
                print('%d*%d=%d'%(j,i,j*i),end='')
        print()


      

       

效果:
python基础题_第2张图片
五:三元运算符判断奇偶数

a=int(input('a:'))
print('%d is even'%(a) if a%2==0 else '%d is odd'%(a))

效果:
在这里插入图片描述
六:求解一元二次方程

import math
a=int(input('a:'))
b=int(input('b:'))
c=int(input('c:'))
s=b**2-4*a*c
if s==0:
   print('方程的解只有一个: x1 = ',(-1*b)/(2*a))
elif s>0 :
   x1=((-1*b)+math.sqrt(s))/(2*a)
   x2=((-1*b)-math.sqrt(s))/(2*a)
   print('方程的解为:%.3f 和 %.3f'%(x1,x2))
else:
   print('方程无解')

效果:
python基础题_第3张图片
七:防黑客暴力破解用户登录系统

count=0
while count < 3:
   count+=1
   print('第%d次登陆:'%(count))
   name=input('name:')
   passwd=input('passwd:')
   if name=='root':
      if passwd=='redhat':
         print('%s登陆成功'%(name))
         break
      else:
         print('%s登陆失败,密码不正确' % (name))

   else:
      print('身份不正确')
   
else:
   print('超过登陆次数')
   

字符串、列表与元组应用

一:编写一个检查 Python 有效标识符的小脚本,名字是 idcheck.py。
要求:Python 标识符必须以字母或下划线开头
1). 只检查长度大于等于 2 的标识符
2). 以字母或者下划线开始
3). 后面要跟字母,下划线或者或数字

while True :
      import string
      name=input('input name: ')
      if name=='exit':
         print('退出')
         exit(0)
      if len(name) > 2 :
         if name[0] in string.ascii_letters+'_':
            for i in name[1:]:
 #遍历一个letter检测一遍,只要检测到错误的letter就退出,因此只显示一遍letter is wrong就退出,如果全部正确,只显示一遍正确str。如果if下条件为判断正确,由于i遍历name,因此会一直print
               if not ( i in string.digits+string.ascii_letters+'_'):
                  print('after letter is wrong')
                  break
#else对应for,表示for遍历结束后执行的语句。
            else:
               print(' right str') 
                  
         else:
            print('first letter is wrong')
      else:
         print('length is too short')

效果:
python基础题_第4张图片
二:判断回文串:

  1. 只考虑字母或者数字字符: 删除非字母或数字
  2. 忽略字母的大小写: 统一转成大写或者小写
##忽略大小写:统一转换成大写或者小写 
#转换成小写:  字符.lower()
##只考虑字母或者数字:删除非字母数字的字符
string1=input('string: ')
string2=''
for item in string1:
   if item.isalnum():
      string2+=item
string3=string2.lower()
print(string3==string3[::-1])   

效果:
在这里插入图片描述
三:打印/var/log/目录中所有的日志文件名称(以.log结尾)

import os
filename=os.listdir('/var/log')#列出/var/log内所有文件名组成列表存入filename中
for item in filename:
   if item.endswith('.log'):#判断文件名是否以.log结尾
      print(item)
#url='hello'
#url.startswith('hel')  判断url是否以hel为开头,返回值为True

四:编写一个函数来验证输入的字符串是否是有效的 IPv4 ?
1). IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。
比如,172.16.253.1;
2). IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的
#ip = ‘172.25.254.100’

ip=input('ip: ')
ip1=ip.split('.')
if len(ip1)==4:
   for item in ip1:
      if not(0 <= int(item) <= 255):
         print('too long')
         break
      if len(item)>1 and item.startswith('0'):
         print('error: has 0')
         break        
   else:
      print('ok')
         
else:
   print('error')
'''
写法:
1:先满足大条件下:长度为4
在大条件下写满足的小条件
2:一旦监测到错误就退出,检测正确后面也有可能是错误的没有监测到,无法下结论,因此用反向思维,而且print也只要求打印一遍。
'''

效果:
在这里插入图片描述
五:检测大写字母

word=input('input a word: ')    
if word.isupper() or word.istitle() or word.islower(): 
   print('correct')
else:
   print('wrong')

效果:
在这里插入图片描述
六:机器人能否返回原点

moves=input('>>')
print(moves.count('l')==moves.count('r') and moves.count('u')==moves.count('o'))
'''
用户输入lruo,只要向左向右向上向下次数相同,就会返回原点,代码意义上为:输入字符串中的字母次数相同即可
'''

效果:
在这里插入图片描述
七:学生出勤记录,有连续的两次迟到则为false

a=input('>>')
print(a.count('A')<=1 and a.count('LLL')<1)
'''
不超过2个连续的LL('LL'出现只有一个,不可以连续出现):LL<=1的话LLL也表示连续的LL不超过2个,LLL中的LL只有1个
'LLL')<1表示LLL以及LLLL...出现都为False,LL、L均为True。LL、L可以满足条件。
'''

效果:
在这里插入图片描述
八:设计一个程序,用来实现帮助小学生进行算术运算练习,它具有以下功能:提供基本算术运算
(加减乘)的题目,每道题中的操作数是随机产生的,练习者根据显示的题目输入自己的答案,程
序自动判断输入的答案是否正确并显示出相应的信息。最后显示正确率。

思路:
l 运行程序, 输入测试数字的大小范围
l 输入测试题目数量
l 任意键进入测试
l 系统进行测试并判断对错
l 系统根据得分情况进行总结,退出程序

步骤:
l 显示输入测试题数字的大小范围
l 显示输入测试题目数量
l 显示任意键进入测试
l 系统对用户输入的三个值分析如果均为空,使用默认值,否则转为int型
l 随机生成两个在用户给定范围的值,以及对两个值进行运算的操作符
l 用户输入答案
l 系统求解
l 系统检测并判断对错
l 系统根据正确个数百分比显示正确率,退出程序
l 根据用户输入的题目数量值count对系统出题次数进行循环
l 用户每做对一道题记录一次,用于求正确率
start=’’
bool(start)=False
if 后返回bool值
if not start #表示start为空时用默认值0
start=0

import random
start = input('输入测试数字的开始范围,默认为0>>')
end = input('输入测试数字的结束范围,默认为10>>')
count = input('输入测试题目数量,默认为10>>')
input('******任意键进入测试****')
start=0 if not start else int(start)
end=10 if not end else int(end)
count=10 if not count else int(count)
right_count=0
for item in range(count) :#出题数量
   num1=random.randint(start,end) #随机生成题目数字并限定出题数字范围
   num2=random.randint(start,end)
   operator=random.choice('+-*')
   usr_result=int(input('%s %s %s ='%(num1,operator,num2))) #用户答案转为int才可以与系统求解值check(int型)比较
   check=eval('%s%s%s'%(num1,operator,num2)) #check为int型
   if usr_result==check:
      print('correct')
      right_count+=1
   else:
      print('wrong')
print('正确率为%.2f %%'%((right_count/count)*100))

效果:
python基础题_第5张图片
九:建立一个命名元组
#命名元组:给里面的元素起名
collections.namedtuple(typename, field_names)
typename:类名称
field_names: 元组中元素的名称

from collections import namedtuple
user=namedtuple('user','name passwd')#定义名称为user,元素为name passwd
#user=namedtuple('user',['name','passwd'])#定义元素的2种方法:列表或字符串,定义名称为user,元素为name passwd
user1=user('scq','redhat') #给name passwd 传真实数据
print(user1.name,user1.passwd,user1)

效果:
在这里插入图片描述
十: 设置云主机系统
云主机的属性信息:
id: 递增,主机id
IPv4: 主机IP
disk: 主机硬盘大小
memory: 主机内存大小
name: 主机别名

from collections import namedtuple

from prettytable import PrettyTable

promt=""" 
        ******************************************
        ***************云主机管理系统 ****************
        ******************************************
                1). 添加云主机
                2). 删除云主机
                3). 修改云主机
                4). 查看云主机
                0). 退出系统
        用户请选择操作: 
        ******************************************
        """
id=0
information1=[]
user=namedtuple('user',['id','IPv4','disk','memory','name']) #定一个名为user的命名元组
while True:
    choice=input(promt)
    if choice == '1':
        id+=1 #id自动加一当作用户的id
        IPv4=input('主机IP:')
        disk=input('主机硬盘大小')
        memory=input('主机内存大小')
        name=input('主机别名')
        user1=user(id,IPv4,disk,memory,name)#给命名元组传入参数,user1形式为user(id=1, IPv4='1', disk='1', memory='1', name='1')
        information1.append(user1)#,将元组追加到列表中,作为列表的一项
        print(information1) #存入形式为:[user(id=1, IPv4='1', disk='1', memory='1', name='1')]
        print("添加主机%s成功" %(name))
    elif choice == '2':
        print("删除云主机".center(40, '*'))
        dele_id=int(input('输入要删除的ip:'))
        for host in information1:#查找信息,让host=列表中的元组
            if dele_id==host.id : #用户输入的id与命名元组中的id匹配时
                information1.remove(host)#删除信息中的一个元组,元组存储一个用户的所有信息
                print('%d删除成功'%(dele_id))
                break
        else:
            print('没有找到指定ip')

    elif choice=='3':
        pass
    elif choice=='4':
        print("查看云主机".center(40, '*'))
        table=PrettyTable(field_names=['id','IPv4','disk','memory','name'])
        for i in information1:
            table.add_row(i) #按行存入信息到表中
        print(table)
    elif choice=='0':
        exit(0)
    else:
        print('请输入正确的数字:')

效果:
python基础题_第6张图片

你可能感兴趣的:(python)