Writing Python basis functions

Writing Python basis functions

1. Enter his characters, statistics on the number of words, separated by a space between each word, and character input by the first letter capitalized center, capitalize the first letter of each word left, all lower, all upper right-aligned outputs manner.

If the input:? This is a c ++ program????.?

输出:There?are?5?words?in?the?line.??

Enter the code:

a = input ( "Enter a string line in English:")

b=a.capitalize()

print (b.center (60)) # layout intermediate

c = a.title () # capitalize the first letter

print (c.ljust (len (a))) # filled specified length

d=a.lower()

print(d)

e = a.upper () # all caps

print(e.rjust(60))

print(“There are”,b.count(" ")+1,“words in the line”)

operation result:
Here Insert Picture Description

2. Write the code, the following variables, as required to implement each function name = "aleX" ?:

. A removal space on both sides of the value corresponding to the variable name, and the input content after removal of?;

. B Please name the output variable corresponding to the first three characters of the value of?;

. C The variable name corresponding to variable values ​​of uppercase and lowercase, and outputs the result;

. D Please outputs a second character corresponding to the variable name values;

. Please output value e corresponding to the variable name "e" where the position of the index;

Enter the code:

from operator import index

name=" aleX "

print(name.strip())

name1=name.strip()

print(name1[0:3])

print(name.upper())

print(name.lower())

print(name1[0:2])

print(name.index(‘e’))

operation result:

Here Insert Picture Description

3. Enter the two string, the second string to delete all characters in the first string. For example, enter "They? Are? Students." And "aeiou", the first string after deleting become "Thy? R? Stdnts."

- Input Description: Each test contains two input strings?

- Output Description: The output string deleted?

Enter the code:

a = input ( "Enter a string line A:")

b = input ( "Please enter the characters you want to replace B:")

c=" "

for i in a:

if i not in b or i==" ":

c+=i;

print ( "The output is:", c)

operation result:

Here Insert Picture Description

  1. Complete the following menu functions using the function: requires each function menu to be realized.

Adding student information saved student information

Delete modify student information student information

drop out

Enter code: #_ 04

stuinfo = []

def main():

while True:

printMenu()

key = int (input ( 'Enter a number corresponding to the function:'))

if key == 1:

addinfo()

Elif key == 2:

deleteinfo()

Elif key == 3:

modifyindo()

Elif key == 4:

showinfo()

Elif key == 5:

saveToFile()

Elif key == 0:

quitConfirm = input ( 'Do you really want to quit it (Yes o No):?')

if quitConfirm == ‘Yes’:

            break

else:

            print('输入有误,请重新输入')

Print features tips

def printMenu():

print(’=’ * 30)

print ( 'Student Information Management System V1.0')

print ( '1. Adding student information')

print ( '2. delete student information')

print ( '3. Modify Student Information')

print ( '4. Show all student information')

print('5.保存数据')

print ( '0. exits the system')

print(’=’ * 30)

Add Student Information

def addinfo():

newname = input ( 'Enter the new name of the student:')

newsex = input ( 'Enter the new students of gender:')

newphone = input ( 'Enter the new number of students:')

newInfo = {}

newInfo[‘name’] = newname

newInfo[‘sex’] = newsex

newInfo[‘phone’] = newphone

stuinfo.append(newInfo)

删除学生信息

def deleteinfo():

delNum = int(input('请输入要删除的序号: ')) - 1

del stuinfo[delNum]

修改学生信息

def modifyindo():

stuId = int(input('请输入要修改的学生序号: ')) - 1

newname = input(‘输入修改后学生的姓名:’)

newsex = input(‘输入修改后学生的性别:’)

newphone = input(‘输入修改后学生的电话:’)

stuinfo[stuId][‘name’] = newname

stuinfo[stuId][‘sex’] = newsex

stuinfo[stuId][‘phone’] = newphone

查询学生信息

def showinfo():

print(’=’ * 30)

print('学生信息如下:')

print(’=’ * 30)

i

= 1

for tempInfo in stuinfo:

print(’%d %s %s %s’
% (i, tempInfo[‘name’], tempInfo[‘sex’], tempInfo[‘phone’]))

i += 1

保存学生信息

def saveToFile():

f

= open(‘backup.data’, ‘w’)

f.write(str(stuinfo))

f.close()

main()

运行结果:

Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

5.随机生成20个学生的成绩(1100);判断这20个学生成绩的等级(90100为A,80~90为B,其它为C)

输入代码:#_05

import random

p=[]

for i in range (1,21):

a=random.randint(1,100)

print(a,end=" ")

if(a>90):

print(“A”)

elif(a>80):

print(“B”)

else :

print(“C”)

运行结果:

Here Insert Picture Description

  1. 现有两个数组:A=[11,22,33]?B={“aa”:1,“bb”:2,“cc”:4}
    按上课内容完成不定长参数函数的定义及三种不同调用方式(非解包,只解包A,同时解包A、B)

输入代码:

A=[11,22,33]

B={“aa”:1,“bb”:2,“cc”:4}

def test(*arg1,**arg2):

print(arg1,end="   ")

print(arg2)

test()

test(A)

test(A,arg2=B)

test(arge=B)

运行结果:

Here Insert Picture Description

  1. 使用时间函数获取当前时间,按格式“%Y-%m-%d?%H:%M:%S”输出。

输入代码:

from time import strftime, localtime

print(strftime(’%Y-%m-%d %H:%M:%S’,localtime()))

运行结果:

Here Insert Picture Description

  1. 获取2019年6月?第一个星期一,第二个星期二,第三个星期三,第四个星期五的日期。打印结果如下图所示:?

输入代码:

#_08

import calendar

year =int(input(“请输入年”))

month =int(input(“请输入月”))

t=calendar.monthcalendar(year,month)

print(“第一个星期一是
6月”,t[1][0],“日”)

print(“第二个星期二是
6月”,t[2][1],“日”)

print(“第三个星期三是
6月”,t[3][2],“日”)

print(“第四个星期五是
6月”,t[4][4],“日”)

运行结果:

Here Insert Picture Description

  1. 使用time函数获取当前时间的年份,月份及当天属于当前的第几天,属于当月的第几天,打印结果如下图所示:

输入代码:

#_09

import time

t=time.localtime()

print("当前年份
",t[0])

print("当前月份
",t[1])

month =[31,28,31,30,31,30,31,31,30,31,30,31]

num=0

temp_mon=int(t[1]) #当前月份

temp_day=int(t[2]) #当前天数

for i in range(0,temp_mon-1) :

num=num+month[i]

num=num+temp_day

print(“今天为今年的第”,num,“天”)

print(“今天为这月的第”,temp_day,“天”)

运行结果:

Here Insert Picture Description

10.将日期"Sat?Mar?28?22:24:24?2016"字符串转换为“2016-03-28?22:24:24”形式显示

?

输入代码:

#_10

import time

import datetime

time=‘Sat Mar 28 22:24:24 2016’

time_format=datetime.datetime.strptime(time,’%a
%b %d %H:%M:%S %Y’)

print(time_format)

运行结果:

Here Insert Picture Description

11.打印出所有1998~2019年之间所有闰年的年日历,年份之间以‘-’分割线分割,分割线宽度需要与日历宽度保持一致,且每个年份日历打印之前居中打印年份信息,具体如下图:

输入代码:

#_11

import calendar

def check(year_num):#判断是不是闰年

if year_num % 100 == 0:

if year_num % 400 == 0:

return True

else:

return False

else:

if year_num % 4 == 0:

return True

else:

return False

for t
in range (1998,2019) :

if check(t) :

print ( "------------------------------", t, "in the calendar ---------- --------------------- ")

    print(calendar.calendar(t,w=2,l=1,c=6))

print("-------------------------------------------------------------------------")

:( leap year operating results: 2000,2004,2008,2012,2016)

Here Insert Picture Description
Here Insert Picture Description

12. a coach to play each village, each through a village petrol consumption to the remaining half of the gasoline further rise. After this he left the village after seven two liters of oil, and asked him how much oil added a total departure? After each between two villages consume much oil? (Required to use a recursive function)

Enter the code:

#_12

def f(gas ,cnt,record,test) :

if cnt==0:

return gas

test.append((gas+1)*2)

if(len(record)==0):

record.append(((gas+1)*2))

else:

index = len (record) -1

record.append((gas+1)*2-test[index])

return f((gas+1)*2,cnt-1,record,test)

record=[]

test=[]

print(f(2,7,record,test))

record.reverse()

print(record)

operation result:

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_43306493/article/details/92762929