preface
After learning the basic part of python, the rest is only practice. For many people who are proficient in Python, there is no shortcut and only hands are familiar. Once there is no lasting practice, you will selectively forget many knowledge points. Although you can find the answer from Baidu, the author suggests that you should not go to Baidu every time, but learn to solve problems by yourself. The exercises will be explained from some classic exercises or interview questions.
practice
The world's martial arts, only fast not broken. Why? Because the enemy could not respond in time, he had already lost. Then the only way to develop is to practice hard. But it also needs a little skill, not blindly.
Calculator
Calculator for selling oranges: write a code to prompt the user to enter the price of oranges, then randomly generate the number of catties to buy (between 5 and 10 catties), and finally calculate the amount that should be paid!
analysis
This involves the application of several basic knowledge, such as input, random number generation, calculation and expansion, as well as exception and condition judgment
- In the processing of input function, the type after receiving data can only be string, so what is required in arithmetic operation is int or float
import random try: price = float(input("Please enter the price of oranges:")) except: print("Input data error") raise weight = random.randint(5,10) money = round(price * weight,2) print("User purchase{}Jin orange, deal with{}Yuan.".format(weight,money))
- Thinking point 1: why is the input price float instead of int?
- Thinking point 2: why use the round() function for the last calculated amount? Or is there any other use instead?
Guess the number
The program will randomly generate a value between 1 and 9 to prompt the user to guess the number, guess wrong and continue to guess (the prompt size needs to be given to allow the user to continue to input). If you guess right, exit the program. Add a condition, the user has only 3 opportunities, and can't input unlimited times, because he will always guess right.
analysis
Extract the key information of the topic Description: random number, loop while, break keyword and limited number of times
- The use of the break keyword. In the loop body, the break program will be interrupted and exited after execution, and the following code will not be executed
import random guess = random.randint(1,9) i = 0 while i < 3: guest=int(input("Please enter 1-9 Integer in range, cannot be decimal(Only 3 opportunities):")) if guest > guess: print("The value entered by the user is too large, please re-enter:") elif guest < guess: print("The user output value is small, please re-enter:") else: print("Congratulations, the user guessed right.") break i += 1
the finger-guessing game
This game is similar to guessing numbers, but it has a little more calculation. Let's see what the requirements are: prompt the user to input the fist to be given: Stone (1) / scissors (2) / cloth (3) / exit (4) the computer randomly gives a fist to compare the victory and defeat, showing whether the user wins, loses or draws; Note: the user has the right to choose to quit the game, and the computer should be random every time when guessing boxing, unlike the last time when guessing numbers, the computer will only generate randomly once in the current operation; So there is no limit to the number of times.
analysis
Therefore, the computer punches should be in the circular body category to ensure that the computer punches at random every time the user punches; According to the requirements, there must be a variable to store stone, scissors and cloth.
- Analyze the characteristics of data, including numbers and Chinese, so what is the way to store data? Two schemes: one is dictionary, the other is random function; The following will demonstrate a case for both schemes:
Scheme 1: store guessing data in dictionary
import random guess_dic = {1:"stone",2:"scissors",3:"cloth"} while True: guest = int(input("Please enter 1-4 Integer of, sub table represents:Stone (1)/Scissors (2)/Cloth (3)/Exit (4) and start guessing:")) com_guess = random.randint(1,3) if guest == 4: print("Select a game or enter a number that is not within the range to exit the game!!!") break elif (guest==1 and com_guess==3) or (guest==2 and com_guess==1) or (guest==3 and com_guess==2): print("User punches:{},The computer also punches:{},The computer won!".format(guess_dic.get(guest),guess_dic.get(com_guess))) elif guest == com_guess: print("User punches:{},The computer also punches:{},it ends in a draw!".format(guess_dic.get(guest),guess_dic.get(com_guess))) else: print("User punches:{},The computer also punches:{},The user won!".format(guess_dic.get(guest),guess_dic.get(com_guess)))
- Tip: list all the combinations and draws won by the computer, and the rest is won by the user. At the same time, the author is also testing while writing,
Scheme 2: list storage and random selection
import random guess_lis = ["stone","scissors","cloth"] while True: guest = int(input("Please enter 1-4 Integer of, sub table represents:Stone (1)/Scissors (2)/Cloth (3)/Exit (4) and start guessing:")) com_guess = guess_lis.index(random.choice(guess_lis)) + 1 if guest == 4: print("Select a game or enter a number that is not within the range to exit the game!!!") break elif (guest==1 and com_guess==3) or (guest==2 and com_guess==1) or (guest==3 and com_guess==2): print("User punches:{},The computer also punches:{},The computer won!".format(guess_lis[guest-1],guess_lis[com_guess-1])) elif guest == com_guess: print("User punches:{},The computer also punches:{},it ends in a draw!".format(guess_lis[guest-1],guess_lis[com_guess-1])) else: print("User punches:{},The computer also punches:{},The user won!".format(guess_lis[guest-1],guess_lis[com_guess-1]))
- Disadvantages: the complexity is much higher. The random punch of the computer is to randomly select the list first, then get the index, and finally add 1 to compare with the user, otherwise the user will win a lot.
multiplication table
As a classic interview question, practice is essential. Tip: Master nested loops
Nested for loop
for i in range(1,10): for j in range(1,i+1): print("{} * {} = {}".format(i,j,i*j),end=" ") print(" ")
Nested while loop
i = 1 while i <= 9: j = 1 while j <= i: print("{} * {} = {}".format(i, j, i * j), end=" ") j += 1 i += 1 print("")
- Comments: in comparison, the implementation of the for loop is relatively simple and not error prone. The operation position of the while variable may lead to errors. For example, j is initialized in the outermost layer. It is possible that only 1-9 multiplication results are obtained
summary
This exercise is more comprehensive. It reviews the basic grammar of data type, operation, loop, condition control and so on; The next article will review from these aspects. Only through more practice to consolidate the knowledge learned, the author has the right to review.