Python basic exercises, including answer analysis

Posted by mizz key_me on Mon, 03 Jan 2022 22:41:16 +0100

Hello, I'm spicy.  

Today, I'll sort out some Python exercises [including answer analysis]. You can try it yourself first, and then check with the answer analysis at the end of the text. I hope it can help you.

Exercises

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

==========My business card==========
full name: itheima   
QQ:xxxxxxx
 cell-phone number:185xxxxxx
 Company address:Beijing xxxx
===========================

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

==========My business card==========
full name: itheima   
QQ:xxxxxxx
 cell-phone number:185xxxxxx
 Company address:Beijing xxxx
===========================

3. Programming: the user inputs his name in the keyboard, such as "Zhang San", and the terminal prints "Hello, Zhang San"

4. Judge whether the following code is written correctly. If not, please modify the code and execute the code.

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

5. Write a program, get the user name and password from the keyboard, and then judge. If it is correct, output the following information: "welcome to erudite Valley!"

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

7. Question about examination results: prompt the user to enter the results, judge which level they belong to, and print the results to the console. Fail below 60, pass above 60, pass from 70 to 80, good from 80 to 90 and excellent above 90.

8. Use while to print the following graphics

9. Use the for loop to print each character in the string "abcdef" in turn.

10. Please invert the a string and output it. For example, the reverse of 'abc' is' cba '

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

12. Programming to add 1 to all even numbers in a list whose elements are all numbers

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

14. Title Description

Input three groups of personal information on the console. Each person has a name and age. Store the information in the dictionary and the dictionary in the list.

Traverse the list and print everyone's information in the following format:

1 sheet 3 20

2 Li Si 22

3 Wang Wu 23

15. Known string test = "aAsmr3idd4bgs7Dlsf9eAF", take out the number in the string and generate a new string

16. The existing string msg = "hel@#$lo pyt \nhon ni\t hao% $", remove all characters that are not English letters, and print the result: "please deal with the following result: hellopythonnihao"

17. CODE TITLE

Define the function findall and return the starting subscripts of all positions that meet the requirements, such as the string "HelloWorld hellopython helloc + + hellojava",

You need to find out the location of all "hello" in it. The returned format is a tuple, that is: (0,10,21,29)

18. Code questions

Define a function sum_test receives a parameter n and calculates 1 + 2 + 3 + in the function+ N and print the result.

19. CODE TITLE

Define a function max with an indefinite length parameter_ Min, the accepted parameter type is numeric, and finally returns the maximum and minimum of these numbers

20. Code questions

Copy the contents of one file to another.

21. Code questions

Use the os module to rename all files in the folder. For example, add new at the beginning of all file names in the current test directory_ This string.

22. Code questions

Define a fruit class, and then create Apple object, orange object and watermelon object through the fruit class, and add attributes: color and price respectively

23. Code questions

Define a computer class. Computers have brands, prices and can play movies. Create two objects "Lenovo computer" and "Apple Computer" respectively. Call the action of playing the movie, Lenovo computer plays the movie "huluwa", and apple computer plays "Sheriff black cat".

24. Code questions

Write a piece of code to complete the following requirements:

  1. Define a Person class. The class must have an initialization method, and the method must have the Person's name and age attributes

  2. The name in the class is a public attribute and the age is a private attribute

  3. Provides a public method get to get private properties_ Age method

  4. Provides a method set that can set private properties_ Age method. If the entered age is between 0 and 100, set the age. Otherwise, it will prompt that the input is incorrect

  5. When rewriting str to print the object, print out the name and age.

25. Code questions

[code question]

Write the code as follows:

-Define input_ The password function prompts the user for a password

-If the user input length is < 8, an exception is thrown

-If the length entered by the user is > = 8, the entered password is returned

Answer analysis

1. Answer analysis:

# You can basically use print at the beginning
print("==========My business card==========")
print("full name: itheima")
print("QQ:xxxxxxx")
print("cell-phone number:185xxxxxx")
print("Company address:Beijing xxxx")
print("===========================")

2. Answer analysis:

# Now that we have learned formatting, we mainly practice formatting
# There are four formats we want, one is the name, one is QQ, one is the mobile phone number, one is the address, and the upper and lower edges are fixed formats
​
#1. Define 4 variables to store 4 data to be formatted respectively
name = "itheima"
QQ = "12345678"
phone = "1388888888"
address = "Beijing xxxx"
​
# 2. Format output
# Print top border
print("==========My business card==========")
# Format 4 variables, in which the f-string format is used. 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 bottom border
print("===========================")
​
 

3. Answer analysis:

# Let's practice the input method here, so just use input to receive user input
# Receive input name
name = input("Please enter your name:")
# Print name
print(name)

4. Answer analysis:

# What we are looking at here is our perception of variables
# The built-in method in python is a variable. You can assign a value to it, but it can't be used as a method again after assignment
# The modification only needs to remove the first line of code
​
#int = 100  #The built-in method is incorrectly assigned, so that the following int methods cannot be used
a = "200"
b = int(a)
print(b)

5. Answer analysis:

# There are two knowledge points, one is input and the other is if judgment
# Get user name and password from keyboard
name = input("enter one user name:")
password = input("Please input a password:")
# and connects two judgment statements, indicating that both must be equal
if name=="MrSun" and password=="123456":
    print("Welcome to erudite Valley")

6. Answer analysis:

# What we examine here is our conditional judgment
# In reality, + - * / is selected by the user, so we execute the corresponding behavior according to the operation selected by the user
# Note that the input returns a string. Remember to convert the number to int
num1 = int(input("Please enter the first number: "))
opt = input("Please enter the action 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}")
else:
    print("The operation you are trying to perform is invalid!")

7. Answer analysis:

# Similar to the above calculator, it mainly focuses on input and multi branch judgment
# Get scores from the keyboard. input returns a string. Remember to convert it into int
score = int(input("Please enter your grade: "))
# Multi branch 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")
else:
    print("excellent")

8. Answer analysis:

# The asterisk increases by 5, and then decreases to 5
# Consider using a flag to control the increase and decrease of asterisks
# The string can be multiplied by '*' * 5 to indicate that the asterisk is repeated 5 times
​
​
#Number of asterisks to print initially
num = 1
# Set a flag. If true, it means to increase the asterisk
flag = True
​
# Exit the loop when the asterisk is less than 0
while num>0:
    # Print stars
    print("*"*num)
    # If the asterisk has reached 5, change the flag and start reducing the stars in the next cycle
    if num==5:
        flag = False
        
    # If the flag is true, the star number is incremented,
    if flag:
        num+=1
     
    # flag is false, indicating that the asterisk begins to decrease
    else:
        num-=1

9. Answer analysis:

# Investigate the usage of for range
pstr = "abcdef"
for s in pstr:
    print(s)

10. Answer analysis:

a = "abcd"
# Method 1 uses while reverse traversal
# Gets the maximum subscript of the string
index = len(a)-1
while lg>0:
    print(a[index])
    # Subscript decrement
    index-=1
​
# Method 2 use slice
a = [::-1]
print(a)

11. Answer analysis:

# Review list traversal, review integer to string, and consider string splicing
l = [1,2,3,4]
# Defines an empty string for splicing strings
result = ""
# Traverse list elements
for num in l:
    # Convert integers into strings and splice them into result
    result+=str(num) 
# Print results
print(result)

12. Answer analysis:

# Review list traversal and list tuple value modification
# for range or while can be used for traversal, but subscripts need to be used for modification, so the method of while plus subscripts is adopted
​
l = [1,2,3,4,5,6]
# Define subscript, initially 0
index = 0
​
# Loop through the list elements until you reach the last value
while index<len(l):
    # If it is an even number, add 1 to this element
    if l[index]%2==0:
        l[index]+=1
    # Move subscript backward
    index+=1

13. Answer analysis:

# Investigate tuple traversal, list element addition, 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)
    
    # The statistical results are spliced into a format like ('a',1)
    tmp = (s,cnt)
    
    # Judge whether this element has been counted. If it has been stated in the result, it will be counted. Continue to the next element
    if tmp in result:
        continue
    else:
        result.append(tmp)
# Print statistics 
print(result)

14. Answer analysis:

# Examine the input method, the enumerate method, string formatting, and the while loop
​
# Define a list to store all user information
users = []
# Define cycle factor
i = 0
while i<3:
    name = input("Please enter your name: ")
    # Remember to convert
    age = int(input("Please enter age"))
    # The user information is constructed into a dictionary and added to the list
    users.append({"name":name,'age':age})
​
# Traverse the print user information, because you want to print the number, you can consider using enumerate
# Note: the enumerate method returns elements. We need to receive two variables, one is the number and the other is the element
for thnum,user in enumerate(users,start=1):
    # Fast formatting with f-string
    print(f"{thnum} {user['name']} {user['age']}")
    
    
# If you haven't learned 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 1 to the serial number
    thnum+=1
 

15. Answer analysis:

# 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 is composed of characters in 0123456789. If the character is in this, does it mean that it is a number
# 3. Splice characters that are numbers together
​
test = "aAsmr3idd4bgs7Dlsf9eAF"
​
# Define a variable to receive numeric characters
result = ""
for s in test:
    # If s is in the following string, it indicates that this character is a numeric character
    if s in "0123456789":
        # Add and spell numeric characters to the result
        result+=s
# Print results
print(result)

16. Answer analysis:

# 1. Because you want to process each character, you need to traverse the characters
# 2. If we judge whether a character is an English letter, we have a method to judge the isalpha method
# 3. Splicing English words together is what we want
msg = "hel@#$lo pyt \nhon ni\t hao%$" 
# Save results
result = ""
# Loop traversal character
for s in msg:
    # Determines whether the current character is a letter
    if s.isalpha():
        # Add characters to results
        result+=s
# Print the final result
print(result)

17. Answer analysis:

#1. Because you want to find the location, you need to traverse the string
#2. Because you want to find multiple characters, you need to use trimming to extract fixed characters
#3. Save the found location to the result list
#4. The topic is required to be a tuple, so it is transformed into a meta group
​
# src: original string, dst: string to find
def findall(src,dst):
    # Get the character length and use it to intercept characters
    lg = len(dst)
    # Save the index of the lookup
    res = []
    #Traversal character through subscript
    for index in range(lg):
        # Intercept the same characters as dst. If they are equal, the position is ok
        if src[index:index+lg]==dst:
            # Adds the current location to the result set
            res.append(index)
            
    # Convert the result into a meta group and return 
    return tuple(res)
​
s = "helloworldhellopythonhelloc++hellojava"
print(findall(s))

18. Answer analysis:

def sum_test(n):
    # Save results
    sum = 0
    # Circulation factor
    i = 1
    #Cyclic accumulation
    while i<=n:
        # Cumulative result
        sum+=i
        # Increase circulation factor
        i+=1
    print(sum)
    
num = 10
sun_test(num)

19. Answer analysis:

# Investigate the definition, transfer and traversal of indefinite length parameters
def max_min(*args):
    # Define the maximum and minimum values, take the first value of the element as the maximum and minimum values, and then compare it with other subsequent values
    max = args[0]
    min = args[0]
    for num in args:
        # If max is less than num, then max is updated to num
        if max<num:
            max = num
        # If min is greater than num, it means num is small, then min is updated
        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. Answer analysis:

# src source file path, dst target file path
def copy(src,dst):
    # Open src file
    # Open src by reading
    fr = open(src,'r')
    # Open dst by writing
    fw = open(dst,'w')
    # Write the contents of src to dst
    fw.write(fr.read())
    # Close file
    fr.close()
    fw.close()
    print('File copy complete')
    
copy("1.txt",'2.txt')

21. Answer analysis:

# Files are divided into two categories: one is a file and the other is a directory
# When processing, it is necessary to judge whether the file is still a directory
​
import os
#file_dir to rename the files under that folder
def rename(file_dir):
    # Obtain all files under the current file [including directory and file]
    files = os.listdir(file_dir)
   
    # Traverse to get all files and directories
    for file in files: 
        # Splice to get the full file path 
        filename = os.path.join(file_dir,file)
        # Determine if it is a file, rename it
        if os.path.isfile(filename):
            # Get the new file path name of the completed
            new_name = os.path.join(file_dir,"new_"+file)
            os.rename(filename,new_name)
        else: # If it's not a file, it's a directory
           #If it is a directory, the recursive call continues to rename the files in the subdirectory
           rename(filename) 
# test
rename('D:\test')

22. Answer analysis:

#  1. If we want to distinguish between fruits, we need a fruit type
#  2. Color and price are object attributes
#  3. Magic method__ str__  Easy to format print objects
class Fruit():
    def __init__(self, fruit_type):
        # Specify what type of fruit to create when creating
        self.type = fruit_type
        self.color = None
        self.price = None
    # Set 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!"
        else:
            return f'{self.type}: color--{self.color} price--{self.price}element '
​
# Create apple
apple = Fruit("Apple")
apple.Set_color('red')
apple.Set_price(5)
print(apple)
​
# ....  Other self created

23. Answer analysis:

# 1. Computers. In order to distinguish types, we need a computer type
# 2. Computers can play movies. There is a play method. Because movies do not belong to computers, we can pass movies as parameters
​
class Computer():
    def __init__(self,ctype):
        # Initialize the type of computer, such as Lenovo
        self.type = ctype
    # The act of playing a movie 
    def play(self,film):
        print(f"{self.type} Played {film}!")
    
    
levoe = Computer("association")
levoe.play("Tom and Jerry")
​
# Other computers create their own

24. Answer analysis:

class Person():
    def __init__(self, name,age):
        # Specify what type of fruit to create when creating
        self.name = name
        # Private property
        self.__age = age
        
    # Get the 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 age. Because age is a private property, you need to provide methods for modifying the object
    def Set_age(self,age):
        self.__age = age
        
    # Re__ str__  Easy to print and format
    def __str__(self):
        return f'name: {self.name}, age:{self.__age}'
​
# Test code
laowang = Person('laowang',50)
print(laowang)
laowang.Set_age(60)
print(laowang.Get_age())
print(laowang)

25. Answer analysis

# No parameter, return the face after user verification
def input_password():
    password = input("Please input a password: ")
    if len(password)<8:
        # If the password length is less than 8 bits, an exception is thrown
        raise Exception("The password must be at least 8 digits long")
    else:
        return password
    
input_password()

Previous wonderful push

I modified ban Hua's boot password in Python and found her secret after logging in again!

I collected Banhua's spatial data set in Python. In addition to meizhao, I found her other secrets again!

My roommate failed to fall in love with ban Hua. I climbed a website and sent it to him for instant cure. Men's happiness is so simple [once a day, forget their first love]

Topics: Python Programmer list