Python basic exercises, including answer analysis

Five packs of spicy strips! 2021-09-15 12:36:47
python basic exercises including answer

Hello everyone , I'm spicy . 

Today I'll tidy up some Python Exercises 【 With answer analysis 】, You can try it yourself first , Then check with the answer at the end of the text , I hope I can help you .


1. Use the formatted output of the string to complete the display of the following business cards

========== My business card ==========
full name : itheima  
cell-phone number :185xxxxxx
The company address : The Beijing municipal xxxx

2. Use the formatted output of the string to complete the display of the following business cards

========== My business card ==========
full name : itheima  
cell-phone number :185xxxxxx
The company address : The Beijing municipal xxxx

3. Programming to realize : The user enters his name on the keyboard , for example “ Zhang San ”, Terminal printing “ Hello , Zhang San ”

4. Determine whether the following code is written correctly , If not , Please modify the code , Then execute the code .

int = 100
a = "200"
b = int(a)

5. Programming , Get the user name and password from the keyboard , And then determine , If it is correct, output the following information : " Welcome to erudite Valley !"

6. Write code to design a simple calculator , You can perform basic addition, subtraction, multiplication and division .

7. The question of test scores : Prompt the user to enter the score , Judge which level it belongs to , Print the results to the console .60 Fail below ,60 A score of above is a pass ,70 Points to the 80 Classified as qualified ,80 Points to the 90 Divided into good ,90 The above points are excellent .

8. Use while Print as follows

9. Use for loop , Print the string in sequence "abcdef" Each character in .

10. Please put a Invert the string and output . for example :'abc' The reverse of this is 'cba' 

11. hold [1,2,3,4] convert to "1234"

12. Programming to realize Add... To all even numbers in a list whose elements are all numbers 1

13. test = ("a","b","c","a","c") , Count the number of occurrences of each element in Yuanzu and save the final result in the list , for example [('a',1),('b',3),('c',5)].

14. Title Description

Input at the console 3 Group profile , Everyone has a name and age , Store information in a dictionary , Store the dictionary in the list .

Traverse the list , Print everyone's information , The print format is as follows :

1 Zhang San 20

2 Li Si 22

3 Wang Wu 23

15. Known string test = "aAsmr3idd4bgs7Dlsf9eAF", Take the number from the string , Generate a new string

16. Existing string msg = "hel@#$lo pyt \nhon ni\t hao%$" , Remove all characters that are not English letters , Print the results :" Please make sure that the result is :hellopythonnihao"

17. Code Title

Defined function findall, It is required to return the starting subscript of all positions that meet the requirements , Such as a string "helloworldhellopythonhelloc++hellojava",

We need to find out all the "hello" The location of , The returned format is a tuple , namely :(0,10,21,29)

18. Code question

Define a function sum_test Receive a parameter n , Calculate... In a function 1 + 2 + 3 + ... + n Value , And print the results .

19. Code Title

Define a function with an indefinite length parameter max_min, The accepted parameter type is numeric , Finally, the maximum and minimum of these numbers are returned

20. Code question

Put the contents of a file , Copy to another file .

21. Code question

Use os modular , Rename all the files in the folder . for example , At present test Add... At the beginning of all file names in the directory new_ This string .

22. Code question

Define a fruit class , Then through fruit , Create an apple object 、 Orange object 、 Watermelon object and add attributes : Color and price

23. Code question

Define a computer class , Computers have brands , There is a price , Can play movies . Create separate 2 Objects " Lenovo computer " and " Apple computer ". Call the action of playing the movie , Lenovo computer plays The movie " Huluwa ", Apple computer plays " Sheriff black cat ".

24. Code question

Write a piece of code to complete the following requirements :

  1. Define a Person class , Class should have initialization methods , The name and age attributes of the person should be included in the method

  2. The name in the class is a public attribute , Age is a private property .

  3. Provides a public method for obtaining private properties get_age Method .

  4. Provide methods that can set private properties set_age Method , It is required if the age entered is 0 -- 100 Between , Set the age , otherwise , Prompt input incorrect ,.

  5. rewrite str When printing objects is required , hold Name and age are printed .

25. Code question

【 Code question 】

Write the code as follows :

- Definition input_password function , Prompt user for password

- If the user enters the length < 8, Throw an exception

- If the user enters the length >=8, Return the password entered

Analysis of the answer

1. Analysis of the answer :

# At first, I can basically use print that will do
print("========== My business card ==========")
print(" full name : itheima")
print(" cell-phone number :185xxxxxx")
print(" The company address : The Beijing municipal xxxx")

2. Analysis of the answer :

# Now learn to format , We do exercises mainly to practice formatting
# The format we want is 4 One is the name One is QQ One is the cell phone number One is the address Up and down 2 The first edge is a fixed format
#1. Definition 4 Variables are stored separately 4 Data to format
name = "itheima"
QQ = "12345678"
phone = "1388888888"
address = " The Beijing municipal xxxx"
# 2. Format the output
# Print top border
print("========== My business card ==========")
# format 4 A variable , It uses f-string Format by , Students can also use other formatting methods
print(f" full name : {name}")
print(f"QQ: {QQ}")
print(f" cell-phone number : {phone}")
print(f" Address : {address}")
# Print the bottom border

3. Analysis of the answer :

# Let's practice here input Method So use input Just receive user input
# Receive input name
name = input(" Please enter your name :")
# Print the name

4. Analysis of the answer :

# What we're looking at here is our perception of variables
# python The built-in method in is a variable that you can assign a value to , But after assignment, it can't be used as a method again
# The modification only needs to remove the first line of code
#int = 100 # error The built-in method is assigned , Cause the back int Method cannot be used
a = "200"
b = int(a)

5. Analysis of the answer :

# There's a lot of research going on here 2 A knowledge One is input One is if Judge
# Get the user name and password from the keyboard
name = input(" Please enter a user name :")
password = input(" Please input a password :")
# and Connect 2 A judgment statement Express 2 All must be equal
if name=="MrSun" and password=="123456":
   print(" Welcome to erudite Valley ")

6. Analysis of the answer :

# What we examine here is our conditional judgment
# In our reality +-*/ It's for users to choose , Then we can operate according to the user's choice Perform the corresponding action
# Be careful input All the returned are strings. Remember to turn the number to int type
num1 = int(input(" Please enter the first number : "))
opt = input(" Please enter the operation you want to perform (+ - * /): ")
num2 = int(input(" Please enter the second number : "))
# Pay attention to the double equal sign when judging
if opt=="+":
   # Use f-string format , effect : 1 + 2 = 3
   print(f"{num1} {opt} {num2} = {num1+num2}")
elif opt=="-":
   print(f"{num1} {opt} {num2} = {num1-num2}")
elif opt=="*":
   print(f"{num1} {opt} {num2} = {num1*num2}")
elif opt=="/":  
   print(f"{num1} {opt} {num2} = {num1/num2}")
   print(" The operation you are trying to perform is invalid !")

7. Analysis of the answer :

# Similar to the calculator above Main investigation input as well as Multi branch judgment
# Get points from the keyboard ,input The returned string is a string. Remember to convert it into int
score = int(input(" Please enter your score : "))
# Multiple branches judge which grade the score belongs to
if score<60:
   print(" fail, ")
elif 60<=score<70:
   print(" pass ")
elif 70<=score<80:
   print(" qualified ")
elif 80<=score<90:
   print(" good ")
   print(" good ")

8. Analysis of the answer :

# The asterisk is passed first 5 individual , Then decrease to 5 individual
# Consider using a flag to control the increase and decrease of asterisks
# Strings can be multiplied '*'*5 Express The asterisk repeats 5 Time
# Number of asterisks to be printed initially
num = 1
# Set a flag , If true It means to increase the asterisk
flag = True
# The asterisk is less than 0 When you exit the loop
while num>0:
   # Print the stars
   # If the asterisk has arrived 5, change flag, The next cycle starts to reduce the number of stars
   if num==5:
       flag = False
   # If flag by true Say the star is increasing ,
   if flag:
   # flag by false Said the star began to decline

9. Analysis of the answer :

# Investigate for range Usage of
pstr = "abcdef"
for s in pstr:

10. Analysis of the answer :

a = "abcd"
# Method 1 Use while Backward Traversal
# Gets the maximum subscript of the string
index = len(a)-1
while lg>0:
   # Subscript decrement
# Method 2 uses slicing
a = [::-1]

11. Analysis of the answer :

# Review list traversal , Look at integer to string , Consider string splicing
l = [1,2,3,4]
# Define an empty string to splice strings
result = ""
# Traversal list elements
for num in l:
   # Convert an integer into a string and splice it to result
# Print the results

12. Analysis of the answer :

# Review list traversal , And list tuple value modification
# Traversal can use for range perhaps while, But when it comes to modification, you need to use subscripts , So using while How to add subscripts
l = [1,2,3,4,5,6]
# Define subscripts , For the initial 0
index = 0
# Loop through list elements , Until the last value
while index<len(l):
   # Judge if it is even , Add... To this element 1
   if l[index]%2==0:
   # The subscript moves backward

13. Analysis of the answer :

# Look at tuple traversal , List elements add , List element judgment , Tuple element statistics
test = ("a","b","c","a","c")
# Define a list to store statistical results
result = []
for s in test:
   # Number of statistical elements
cnt = test.count(s)
   # Splice the statistical results into ('a',1) This format
   tmp = (s,cnt)
   # Determine whether this element has been counted , If it has been stated in the result, this element has been counted Move on to the next element
   if tmp in result:
# Print Statistics

14. Analysis of the answer :

# Investigate input Method , Investigate enumerate Method , And string formatting , Investigate while loop
# Define a list to store all user information
users = []
# Define the cycle factor
i = 0
while i<3:
   name = input(" Please enter a name : ")
   # age Remember to convert integers
   age = int(input(" Please enter age "))
   # Construct user information into a dictionary , Add to list
# Traverse and print user information , Because you want to print the number , Consider using enumerate
# Be careful : enumerate Method returns the element , We need to use 2 Variables receive , One is the number , One is the element
for thnum,user in enumerate(users,start=1):
   # Use f-string Quick format
   print(f"{thnum} {user['name']} {user['age']}")
# If you haven't learned yet enumerate, You can use a variable to represent the sequence number
# The definition sequence number starts with 1
thnum = 1
for user in users:
print(f"{thnum} {user['name']} {user['age']}")
   # Remember to add the serial number 1

15. Analysis of the answer :

# 1. To extract numeric characters , We need to traverse the string
# 2. You need to know how to judge whether a character is a number , The number has 0123456789 The characters in , If the character is in this, does it mean that this is a number
# 3. Put together characters that are numbers
test = "aAsmr3idd4bgs7Dlsf9eAF"
# Define a variable to receive numeric characters
result = ""
for s in test:
   # If s In the following string, it indicates that this character is a numeric character
   if s in "0123456789":
       # Add numeric characters to the result
# Print the results

16. Analysis of the answer :

# 1. Because you have to process every character , So you need to traverse characters
# 2. If you judge whether a character is an English letter , We have a way to judge the string itself isalpha Method
# 3. Putting English words together is what we want
msg = "hel@#$lo pyt \nhon ni\t hao%$"
# Save results
result = ""
# Loop through characters
for s in msg:
   # Determine whether the current character is a letter
   if s.isalpha():
       # Add characters to the result
# Print the final result      

17. Analysis of the answer :

#1. Because to find the location , So you have to traverse the string
#2. Because you have to find multiple characters , So you need to use trimming to extract fixed characters
#3. Save the found location to the result list
#4. The title requires a tuple, so it is transformed into a meta group
# src: Original string ,dst: String to find
def findall(src,dst):
   # Get character length , Use to intercept characters
   lg = len(dst)
   # Save the index of the search
   res = []
   # Traversal characters through subscripts
   for index in range(lg):
       # Interception and dst If the same characters are equal, it means Location ok
       if src[index:index+lg]==dst:
           # Add the current location to the result set
   # Convert the result into a meta group and return      
   return tuple(res)
s = "helloworldhellopythonhelloc++hellojava"

18. Analysis of the answer :

def sum_test(n):
   # Save results
   sum = 0
   # Circulation factor
   i = 1
   # Cycle accumulation
   while i<=n:
       # Cumulative results
       # Increase the circulation factor
num = 10

19. Analysis of the answer :

# Consider the definition of indefinite length parameters , And transmission , And traverse to find the size value
def max_min(*args):
   # Define the maximum 、 minimum value , Take the first value of the element as the maximum and minimum , Then compare with other values later
   max = args[0]
   min = args[0]
   for num in args:
       # If max Less than num that max Updated to num
       if max<num:
           max = num
       # If min Greater than num explain num Small , Update min
       if min>num:
           min = num
   return max,min
max,min = max_min(5,2,7,1,7,8,9,10)
print(f'max = {max},min = {min}')

20. Analysis of the answer :

# src Source file path ,dst The destination file path
def copy(src,dst):
   # open src file
   # Open by reading src
   fr = open(src,'r')
   # Open by writing dst
   fw = open(dst,'w')
   # hold src The contents of are written to dst in
   # Close file
   print(' File copy complete ')

21. Analysis of the answer :

# The documents are divided into 2 Class is a file and a directory
# When processing, you need to judge whether the file will still be in the directory
import os
#file_dir To rename the files under that folder
def rename(file_dir):
   # Get all files under the current file 【 Contains directories and files 】
   files = os.listdir(file_dir)
   # Traverse to get all files and directories
   for file in files:
       # Splice to get the complete file path
       filename = os.path.join(file_dir,file)
       # Determine if it is a file, rename
       if os.path.isfile(filename):
           # Get the completed new file path name
           new_name = os.path.join(file_dir,"new_"+file)
       else: # If it's not a file, it's a directory
          # If it is a directory, the recursive call continues Rename the files in the subdirectory
# test

22. Analysis of the answer :

# 1. We have to distinguish between fruit , Need to have a fruit type
# 2. Color and price are object attributes
# 3. Magic methods __str__ Easy to format and print objects
class Fruit():
   def __init__(self, fruit_type):
       # When creating, specify what type of fruit to create
       self.type = fruit_type
       self.color = None
       self.price = None
   # Set the color  
   def Set_color(self,color):
       self.color = color
   # Set price
   def Set_price(self,price):
       self.price = price
   def __str__(self):
       if self.color is None or  self.price is None:
           return " Fruit price and color are not set !"
           return f'{self.type}: color--{self.color} price--{self.price} element '
# Create an apple
apple = Fruit(" Apple ")
# .... Others create their own 

23. Analysis of the answer :

# 1. Computer , In order to distinguish the species, we need to have a Computer type type
# 2. Computers can play movies , Yes play Method , Because movies don't belong to computers , So we can pass the movie as a parameter
class Computer():
   def __init__(self,ctype):
       # Initialize the type of computer , For example, Lenovo
       self.type = ctype
   # The act of playing a movie  
   def play(self,film):
       print(f"{self.type} It's on {film}!")
levoe = Computer(" lenovo ")" Tom and Jerry ")
# Other computers create their own 

24. Analysis of the answer :

class Person():
   def __init__(self, name,age):
       # When creating, specify what type of fruit to create = name
       # Private property
       self.__age = age
   # For age , Because age is a private property, you need to provide a method to get the object
   def Get_age(self):
       return self.__age
   # Set the age , Because age is a private property, you need to provide methods to modify the object
   def Set_age(self,age):
       self.__age = age
   # again __str__ Easy to print and format
   def __str__(self):
       return f'name: {}, age:{self.__age}'
# Test code
laowang = Person('laowang',50)

25. Analysis of the answer

# No parameter , Returns the face verified by the user
def input_password():
   password = input(" Please input a password : ")
   if len(password)<8:
       # If the password length is less than 8 position Throw an exception
       raise Exception(" The password length is at least 8 position ")
       return password

Previous wonderful push

I use Python Changed ban Hua's boot password , After logging in again, I found her secret !

I use Python Collected the spatial data set of Banhua , In addition to meizhao, she found her other secret again !

Roommate single love class flower failed , I climbed a website and sent it to him for instant cure , Men's happiness is so simple 【 Once a day , Forget first love 】

本文为[Five packs of spicy strips!]所创,转载请带上原文链接,感谢

  1. Python - Programmation orientée objet - pratique (6)
  2. Python - Programmation orientée objet - réflexion hasattr, GetAttr, GetAttr, delattr
  3. Python - Programmation orientée objet - _Dict
  4. Python - pydantic (2) Modèle imbriqué
  5. Non-ASCII character ‘\xe5‘ in file on line 4, but no encoding declared; see http://python.or
  6. python笔记(一)
  7. Non - ASCII character 'xe5' in file on Line 4, but no Encoding declared;Voirhttp://python.or
  8. Notes Python (1)
  9. Talk about how JMeter executes Python scripts concurrently
  10. In Beijing, you can't see the moon in the Mid Autumn Festival. Draw a blood red moon in Python
  11. Un des pandas crée un objet
  12. Machine learning | unitary regression model Python practical case
  13. Draw a "Lollipop chart" with Excel and python
  14. Python uses scikit learn to calculate TF-IDF
  15. Getting started with Python Basics_ 3 conditional statements and iterative loops
  16. Python dynamic properties and features
  17. 云计算开发:Python内置函数-min()函数详解
  18. [Python skill] how to speed up loop operation and numpy array operation
  19. 雲計算開發:Python內置函數-min()函數詳解
  20. Développement de l'informatique en nuage: explication détaillée de la fonction intégrée python - min ()
  21. 从0起步学Python(附程序实例讲解)第1讲
  22. 从0起步学Python(附程序实例讲解)第1讲
  23. Apprendre Python à partir de 0 (avec des exemples de programme) leçon 1
  24. Apprendre Python à partir de 0 (avec des exemples de programme) leçon 1
  25. With Python, I'll take you to enjoy it for a month when the Mid Autumn Festival is coming
  26. You can't write interface software in Python! Which software on sale has no UI?
  27. Python国内外原题解析及源码1~15
  28. Python实现长篇英文自动纠错~
  29. Python implémente la correction automatique des erreurs en anglais long
  30. Analyse des problèmes originaux et code source de Python au pays et à l'étranger 1 ~ 15
  31. 一张思维导图学Python之表白
  32. Python教学中课程思政建设的研究探索2
  33. Recherche sur la construction idéologique et politique du Programme d'études dans l'enseignement Python 2
  34. Une présentation de la cartographie mentale Python
  35. Python高级用法总结(8)-函数式编程
  36. Python + Mirai development QQ robot starting tutorial (2021.9.9 test is valid)
  37. Python Advanced use Summary (8) - functional Programming
  38. How to get started with Python and share learning methods for free. All you want to know is here
  39. Python + Mirai development QQ robot starting tutorial (2021.9.9 test is valid)
  40. Python趣味编程中(PPT适合青少儿和零基础学习Python)
  41. Python基础第1讲(含代码、Python最新安装包、父与子的编程之旅:与小卡特一起学Python中文版)
  42. 用 Python 增强 Git
  43. Python基礎第1講(含代碼、Python最新安裝包、父與子的編程之旅:與小卡特一起學Python中文版)
  44. Base Python leçon 1 (y compris le Code, le dernier paquet d'installation Python, le voyage de programmation parent - enfant: apprendre la version chinoise de python avec le petit Carter)
  45. Dans la programmation amusante Python (ppt pour les jeunes enfants et l'apprentissage de base zéro Python)
  46. 非常好的题目详解Python字典的用法
  47. Python teaches you to build wechat push live Betta reminder from 0 (single room simplified version)
  48. Python 协程与 JavaScript 协程的对比
  49. 手把手带你用Python实现一个量化炒股策略
  50. Main dans la main pour mettre en œuvre une stratégie quantitative de spéculation boursière en python
  51. Comparaison des coproductions Python et JavaScript
  52. 【python种子项目ppc】一行代码生成项目与开发详细指导
  53. Docker 部署一个用 Python 编写的 Web 应用
  54. Python - poetry(4)管理环境
  55. Python - poetry(2)命令介绍
  56. [Python Seed Project PPC] a line of Code Generation Project and Development detailed guidance
  57. Introduction à la commande python - Poetry (2)
  58. Python - Poetry (4) Management Environment
  59. I collected Banhua's spatial data set in Python. In addition to meizhao, I found her other secrets again!
  60. I modified ban Hua's boot password in Python and found her secret after logging in again!