Python introductory practice 100 questions (1)

first question

Topic: Find the combination of numbers, 1, 2, 3, 4 form 3 digits without repetition, how many are there in total?
answer:

total = 0
for i in range(1, 5):  # range(1, 5) 会产生: 1, 2, 3, 4
    for j in range(1, 5):
        for k in range(1, 5):
            if i != j and j != k and k != i:  # 为了避免某个数重复出现,如:1 2 1
                print(i, j, k)  # 输出排列
                total += 1

print('total:', total)

second question

Topic: Individual tax calculator, calculate the individual tax after deduction of five insurances and one housing fund
:

wages = float(input("please input your wages:"))                    #收入
benefit = float(input("please input Benefit deduction amount:"))    #五险一金扣除金额
profit = wages -benefit
bonus = 0
thresholds = [5000,3000,9000,13000,10000,20000,25000]
roles = [0,0.03,0.1,0.2,0.25,0.3,0.35,0.45]
for i in range(len(thresholds)):
	if profit <= thresholds[i]:
		bonus += profit * roles[i]
		profit = 0
		break
	else:
		bonus += thresholds[i]*roles[i]
		profit -= thresholds[i]

bonus += profit * roles[-1]
print("your bonus is : ",bonus)

third question

Topic: A number, plus 100 is a perfect square number, plus 168 is also a perfect square number, find the
solution of this number problem:

n= 0
while (n+1)**2 - n*n <=168:
	n+=1
for i in range((n+1)**2):
	if i**0.5 == int(i**0.5) and (i+168)**0.5 == int((i+168)**0.5):
		print("这个数可能是:%d" % (i-100)

fourth question

Topic : Enter the time and determine the day of the year

year = int(input("please input year:"))
month = int(input("please input month:"))
day =  int(input("please input day:"))
days = [31,28,31,30,31,30,31,31,30,31,30,31]
res =0
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):  //判断是否是闰年
	days[1] = 29
for i in range(month -1):
	res += days[i]
res += day
print("%d年%d月%d日是该年的第%d天." % (year,month,day,res))

fifth question

Topic: Input three numbers and output from small to large (sorting algorithm)
Problem solution:

num1 = input("please input num1:")
num2 = input("please input num2:")
num3 = input("please input num3:")
arr = [num1,num2,num3]
temp = 0
for i in range(len(arr)):
	for j in range (i+1,len(arr)):
		if arr[i] > arr[j]:
			temp = arr[i]
			arr[i] = arr[j]
			arr[j] = temp
print(arr)

Sixth question

Topic : Output the Fibonacci sequence of specified length Problem
solution:

arr = [0,1]
length = int(input("please input the array lenth:"))
for i in range(2,length):
	temp = arr[i-1]+arr[i-2]
	arr.append(temp)
print(arr)

Seventh question

Title: Use [:] to copy a list
Solution:

list1 = ['tom','Bob','Alise']
list2 = list1
list3 = list1[:]

print("变量(0x%x): %s" % (id(list1),str(list1)))
print("引用(0x%x): %s" % (id(list2),str(list2)))
print("复制(0x%x): %s" % (id(list3),str(list3)))

Question eight

Title: Output the 99 multiplication table and align
the solution:

for i in range(1,10):
	for j in range(1,i+1):
		if i*j < 10:
			print("%dx%d=%d " %(i,j,i*j),end='  ')
		else:
			print("%dx%d=%d " %(i,j,i*j),end=' ')
	print()

Question 9

Topic: Simulate system user login and provide registration function
Solution:

import os 
import json
choose = int(input("Please choose login or register,1-login,2-register,3-exit : "))
files = './passwd.json'  #用户名密码存储在json文件中
def login(num):
	if num  == 1:
		name = input("please input your Login name:")
		passwd  = input("please input your Login  passwd:")
		f = open(files,"r")
		data = json.load(f)
		for key in data:
			if name == data[key]['name'] and passwd == data[key]['pass']:   # 判断账号密码是否正确
				print("\nLogin is OK !!!!\n")
				return
		f.close()
		print("Username Or passwd is error,please retry !!!")
		return
	elif num  == 2:
		name = input("please input your name:")
		passwd  = input("please input your passwd:")
		user = {
    
    "name":name,"pass":passwd}
		if os.path.getsize(files):  #判断文件是否为空
			f = open(files,"r")
			data = json.load(f)
			for key in data:     
				if name == data[key]['name']:  #循环遍历字典,判断用户名是否已经注册
					print("Your name to be registered!!!,please login!!")
					login(1)
					return
			length = str(len(data)) 
			data['user'+length] = user        #追加账户信息到字典中
			f.close()
		else:
			data={
    
    'user0':user}
		f = open(files,"w")
		json.dump(data,f,ensure_ascii=False)   #向文件中写入账户信息
		print("Register is Ok !!!,please login!!!")
		f.close()
		login(1)
		return
	elif num  == 3:
		print("Exit!!!!!")
		return
	else:
		new = int(input("Input error,pleasr give me a now choose :"))
		login(new)
		return
login(choose)
os.system("pause")

Question ten

Title: Use * to output a chess board
Solution:

import os
for i in range(32):
	for j in range(48):    
		x = int(i/4)   #每个格子高4
		y = int(j/6)   #每个格子宽6
		if (x+y) % 2 ==1:
			print("*",end="")    
		else:
			print(" ",end="")
	print()

Guess you like

Origin blog.csdn.net/qq_45590334/article/details/128409083