@TOC
preface
This paper materials all come from the free course MOOC Python programming (= = www.icourse163.org/course/BIT-… = =)
The basic Python notes tend to focus more on my own code implementation and discussion, so there will not be a comparison of inputs for the points, which will probably be summarized later in the series. If I summarize the knowledge points later, I will probably type them by hand, but it is true that the screenshot does not enhance the memory effect. If possible, I will try to make a list of knowledge points (refer to the course schedule).
An overview of the
This one contains code examples from the 0-3 week course, as well as examples from Python123’s homework section, and the results. The overall picture looks something like the following
The main body
1. Basic grammar elements
Example: temperature conversion
requirements
Convert Fahrenheit (F) to Celsius (C) automatically determine what type of temperature meter is input and convert according to the last symbol
Analysis of the
The problem requires conversion and identification between two units so we’re going to use a conversion formula between the two.
Celsius =5/9 (°F-32) Fahrenheit = ° C ×9/5+32
The recognition of units F and C is determined by the recognition of the last character.
Input setting variable [-1]
Code section
TempStr = input("Please enter a signed temperature value:")
if TempStr[-1] in ['F'.'f']:
C = (eval(TempStr[0: -1]) - 32) /1.8
print("The converted temperature is {:.2f}C".format(C))
elif TempStr[-1] in ['C'.'c']:
F = 1.8*eval(TempStr[0: -1]) + 32
print("The converted temperature is {:.2f}F".format(F))
else:
print("Input format error")
Copy the code
The results
It’s centigrade to Fahrenheit
Please enter a signed temperature value: 12C converted temperature is53.60F
Copy the code
Degrees Fahrenheit to Degrees Celsius
Please enter a signed temperature value: 53F converted temperature is11.67C
Copy the code
② Job: Hello World conditional output
requirements
Get an integer input from the user and print “Hello World” using this integer value:
If the input value is 0, Direct output “Hello World” = = If the input value is greater than 0, Print “Hello “as a two-character line World “(space characters) = = == If the input value is less than 0, print “Hello World”== vertically
Analysis of the
The requirement here is the conditional judgment to decide which branch to go, there are three in total, and the flow chart is as follows :(the basic diagram of UML modeling is not strictly drawn and described here)
code
n = eval(input())
if n == 0:
print("Hello World")
elif n > 0:
print("He\nll\no \nWo\nrl\nd")
else:
for c in "Hello World":
print(c)
Copy the code
The results
Enter >0 for a line break every two characters
1He ll o Wo rl d process has terminated, exit code0
Copy the code
Input 0, output directly
0Hello World process terminated, exit code0
Copy the code
Input <0, vertical output
-1H E L L O W o r L D The process has ended, exit the code0
Copy the code
③ Homework: numerical calculation
requirements
Get the user input a string, format is as follows:
M OP N among them, the M and N is any Numbers, OP represents an operation, which can be described as follows: The +, -, *, /) (addition, subtraction, multiplication, and division according to OP, Output the operation result of M OP N, save 2 decimal places uniformly. note: == Multiple Spaces can exist between M and OP and between OP and N, regardless of input errors. = =
Example:
The input | The output |
---|---|
10 + 100 | 110.00 |
1/20 | 0.05 |
Analysis of the
A simple calculation preserves two decimal places
{:.2f}
code
a=input(a)print("{:.2f}".format(eval(a)))
Copy the code
The results
10+100
110.00Process terminated, exit code0
Copy the code
1/20
0.05Process terminated, exit code0
Copy the code
2. Basic graph drawing
Example: Python drawing
requirements
Draw a python
Analysis of the
Use Python’s Turtle library for drawing
Step (Win10) : ①win+ R ② enter CMD to enter the command line interface ③ enter PIP install Turtle
= = can add parameters when using PIP -i pypi.tuna.tsinghua.edu.cn/simple== such as: PIP install -i pypi.tuna.tsinghua.edu.cn/simple library name, it will from tsinghua side mirror to install the library. PIP PIP PIP PIP PIP PIP PIP PIP PIP PIP C: Users\xx\ PIP, create a new file pip.ini, The following = = [global] index – url = pypi.tuna.tsinghua.edu.cn/simple== this solution is also from the CSDN post PIP install method is slow
code
import turtle
turtle.setup(650.350.200.200)
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
turtle.circle(40.80)
turtle.circle(-40.80)
turtle.circle(40.80/2)
turtle.fd(40)
turtle.circle(16.180)
turtle.fd(40*2/3)
turtle.done()
Copy the code
The results
This process is dynamic rather than instantaneous, showing us the whole process of drawing
② Homework: Turtle octagon drawing
requirements
Using the Turtle library, draw an octagon. Octagon effect is as follows:
Analysis of the
So if you look at this normal graph, you just have to calculate the degree of rotation, so in this case, 360/8 is 45, and you rotate it 45 degrees 8 times, and you go a certain distance, and you say 100
code
import turtle as t
t.pensize(2)
for i in range(8):
t.fd(100)
t.left(45)
Copy the code
The results
Turtle draws an 8-angle shape
requirements
Using the Turtle library, draw an octagonal figure.
code
import turtle as t
t.pensize(2)
for i in range(8):
t.fd(150)
t.left(135)
Copy the code
The product of cycles and angles should be an integer multiple of 360
The results
3. Basic data types
Example: The power to make progress every day – work hard
The problem
- At what level do you need to work hard in a weekday mode to be the same as working 1% a day?
- A: 1% A year, 365 days A year, non-stop
- B: 365 days a year, working 5 days a week and having 2 days off. 1% less days off. How hard do you work?
Analysis of the
We can calculate the final effect of AThe method given by the teacher is to use the computational power of the computer to directly trial and error
code
Trial-and-error code:
def dayUP(df) :
dayup = 1
for i in range(365) :if i % 7 in [6.0]:
dayup = dayup*(1 - 0.01)
else:
dayup = dayup*(1 + df)
return dayup
dayfactor = 0.01
while dayUP(dayfactor) < 37.78:
dayfactor += 0.001
print("The work day effort parameter is: {:.3f}".format(dayfactor))
Copy the code
The results
The effort parameters for working days are:0.019Process terminated, exit code0
Copy the code
② Example: Text progress bar – the beginning of a short answer
requirements
Simple progress bar simulation, no dynamic refresh using downward push
code
import time
scale = 10
print("------ Execution started ------")
for i in range(scale+1):
a = The '*' * i
b = '. ' * (scale - i)
c = (i/scale)*100
print("{: ^ 3.0 f} % [{} - > {}]".format(c,a,b))
time.sleep(0.1)
print("------ Execution completed ------")
Copy the code
The results
------ Start ------0% [] - >...10% [*] - >...20 %[**->........]
30* * * % [] - >...40%] [* * * * - >...50% [* * * * * - >...60% [* * * * * * - >...70% [* * * * * * * - >...80% [* * * * * * * * - >..]90% [* * * * * * * * * - >.]100%[**********->] ------ End ------ The process is complete. Exit the code0
Copy the code
③ Example: Text progress bar – full version
requirements
Dynamic refresh, with a series of refresh activities only in that row
Analysis of the
Based on the simple version you need to overwrite all parts of the text
code
import time
scale = 50
print("Execution begins".center(scale//2."-"))
start = time.perf_counter()
for i in range(scale+1):
a = The '*' * i
b = '. ' * (scale - i)
c = (i/scale)*100
dur = time.perf_counter() - start
print({: "\ r ^ 3.0 f} % [{} - > {}] {: 2 f} s".format(c,a,b,dur),end=' ')
time.sleep(0.1)
print("\n"+"End of execution".center(scale//2.The '-'))
Copy the code
The results
----------- Start ----------100% [* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - >]5.00S ----------- Execution complete ---------- The process is complete. Exit the code0
Copy the code
④ Homework: square root formatting
requirements
Take an integer a entered by the user, calculate the square root of A, save three decimal places, and print it.
The output is 30 characters wide, right-aligned output, and extra characters are padded with plus signs (+). if the results of more than 30 characters, is the width of the results shall prevail.
Analysis of the
Understand how to format output.
Note: If an ordinary root yields a complex number, since both the real and imaginary parts of the complex number are floating point numbers,.3f can take three decimal places for both the real and imaginary parts. = =
code
a = eval(input())
print("{: + > 30.3 f}".format(pow(a, 0.5)))
Copy the code
The results
232
++++++++++++++++++++++++15.232Process terminated, exit code0
Copy the code
-232
+++++++++++++++++0.000+15.232 j.Process terminated, exit code0
Copy the code
⑤ Operation: string piecewise combination
requirements
Get a string s of input, split s with character minus sign (-), and output the first and last two paragraphs combined with plus sign (+).
The input | The output |
---|---|
Alice-Bob-Charis-David-Eric-Flurry | Alice+Flurry |
Analysis of the
S. split(k) splits S with k as a tag to produce a list. Split (); split ();
code
s = input()
ls = s.split("-")
print("{} + {}".format(ls[0], ls[-1]))
Copy the code
The results
Alice-Bob-Charis-David-Eric-Flurry Alice+Flurry process has ended, exit the code0
Copy the code
After the injection
The difficulty of the code in these three chapters is not very, nor very long, but there are certain requirements for the use of some functions, perhaps not using the function is also written, but using the function will undoubtedly greatly reduce the amount of code. But sometimes I am confused, because I have heard before that using some functions may make the program take more time, and the program goes wrong without knowing why. It’s deadly. For example, the ==split() function == in the example of the split string, I looked up its source code. As follows:
public String[] split(String regex, int limit) {
/* fastpath if the regex is a
(1)one-char String and this character is not one of the
RegEx's meta characters ".$|()[{^?*+\\", or (2)two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter. */ char ch = 0; if (((regex.value.length == 1 && ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || (regex.length() == 2 && regex.charAt(0) == '\ \' && (((ch = regex.charAt(1))-'0') | ('9'-ch)) < 0 && ((ch-'a') | ('z'-ch)) < 0 && ((ch-'A') | ('Z'-ch)) < 0)) && (ch < Character.MIN_HIGH_SURROGATE || ch > Character.MAX_LOW_SURROGATE)) { int off = 0; int next = 0; boolean limited = limit > 0; ArrayList
list = new ArrayList<>(); while ((next = indexOf(ch, off)) ! = -1) { if (! limited || list.size() < limit - 1) { list.add(substring(off, next)); off = next + 1; } else { // last one //assert (list.size() == limit - 1); list.add(substring(off, value.length)); off = value.length; break; } } // If no match was found, return this if (off == 0) return new String[]{this}; // Add remaining segment if (! limited || list.size() < limit) list.add(substring(off, value.length)); // Construct result int resultSize = list.size(); if (limit == 0) { while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { resultSize--; } } String[] result = new String[resultSize]; return list.subList(0, resultSize).toArray(result); } return Pattern.compile(regex).split(this, limit); }
Copy the code
It can be said that I still do not understand the reading now, and I still need to read more and input understanding in the future. If the article is helpful to you, add it to your bookmark as a little note. If there is a problem in the text can also comment pointed out, convenient small to be modified. Thank you!