Preface#
Since the start of the semester a month ago, I have been busy with my studies and haven't had much time to think about many things. I often read books, but I haven't read Python books very frequently; instead, I've been reading more literature. The day before the holiday, after finishing an exam, I flipped through my Python book and learned some new things for me. I then improved and upgraded the project I was working on before the semester started and wrote a program for coordinate movement.
Output Preview#
The parts marked with # are my explanations and will not appear in the actual run.
Tell me your X position:
10 # The value I entered
Tell me your Y position:
0 # The value I entered
Original X position is 10.0
Original Y position is 0.0.
Original position is (10.0,0.0).
New X position is 12.0
New Y position is -1.0
New position is ((12.0, -1.0))
Introduction rules
There are four cases in total
Speed: slow
Add 1 X position and reduce 2 Y position
Speed: medium
Add 2 X position and reduce 1 Y position
Speed: fast
Add 3 X position and add 3 Y position
Speed: veryfast
Add 4 X position and add 6 Y position
Complete Code#
############################
### Date 2021 October 1 ###
### Author Magneto ###
### Name Coordinate Movement <——>
### Random True ###
### Language Python ###
############################
# Import random module
import random
# Define speed content and process randomly
speed_0 = ['slow', 'medium', 'fast', 'veryfast']
speed_random = random.choice(speed_0)
# User input for X coordinate
print("\nTell me your X position:")
your_x_position = input()
# User input for Y coordinate
print("Tell me your Y position:")
your_y_position = input()
# Convert X coordinate
x_position = float(your_x_position)
# Convert Y coordinate (+1 for initial position)
y_position = float(your_y_position)
# Output initial coordinate values
print(f"\nOriginal X position is {x_position}"
f"\nOriginal Y position is {y_position}."
f"\nOriginal position is ({x_position},{y_position}).")
# if-elif-else statement
# Define slow
if speed_random == 'slow':
# Algorithm
x_increment = x_position + 1
y_increment = y_position - 2
# Define medium
elif speed_random == 'medium':
# Algorithm
x_increment = x_position + 2
y_increment = y_position - 1
# Define fast
elif speed_random == 'fast':
# Algorithm
x_increment = x_position + 3
y_increment = y_position + 3
# Define other content, assuming other content speed is very fast, reaching the display limit
else:
# Algorithm
x_increment = x_position + 4
y_increment = y_position + 6
# Output moved coordinates
print(f"New X position is {x_increment}"
f"\nNew Y position is {y_increment}"
f"\nNew position is ({x_increment,y_increment})")
# Content introduction definition
alien = {
'slow': 'Add 1 X position and reduce 2 Y position',
'medium': 'Add 2 X position and reduce 1 Y position',
'fast': 'Add 3 X position and add 3 Y position',
'veryfast': 'Add 4 X position and add 6 Y position'
}
print("\nIntroduction rules")
# Character replacement and total number of introduction types
if len(alien) == 4:
# Character replacement
The_number = 'four'
# Total number of introduction types
print(f"There are {The_number} cases in total")
# Other types
else:
# Output null value
print("NULL")
# for statement output
for speed_1, position in alien.items():
print(f"Speed: {speed_1}")
print(f"{position}")
Code Analysis#
Analysis Explanation#
The code analysis will specifically describe the purpose of each line of code, including the lines occupied by comments.
random Module#
The code in line 9, import random
, imports the random module into this program, and the purpose of random is to randomly process the content in the dictionary, which can be seen in line 12. I wrote the dictionary content in line 11 and then used random for random processing. If we output it at this point:
# Import random module
import random
# Define speed content and process randomly
speed_0 = ['slow', 'medium', 'fast', 'veryfast']
speed_random = random.choice(speed_0)
# Output value
print(f"Current speed is {speed_random}")
It will randomly extract any value from speed_0
and output it, rather than outputting the first value.
Output Content
eg:
Current speed is medium
Before improving the code, the program made extensive use of random (see "Python Learning Diary – The Story of the Outlaw"). After the improvement, the random value was changed to manual input, making it more random (not really).
However, the speed is still processed randomly, as this is convenient for calculations rather than input.
Manual Input#
Using input to enter values:
# User input for X coordinate
print("\nTell me your X position:")
your_x_position = input()
# User input for Y coordinate
print("Tell me your Y position:")
your_y_position = input()
Here, your_coordinate_type_position
corresponds to the next group of conversion logic. It is worth noting that I did not use similar code like:
a = input("Tell me your X position:")
Output Content
eg:
Tell me your X position:0 # 0 is the value I entered
This is because using such code would make the output look less elegant. Excellent programs typically balance logic and aesthetics.
Solving Calculation Issues#
When using input for input, the originally outputted value cannot be calculated normally, and it will throw an error.
Error Code Example
a = input("Number is ")
b = a + 3
print(f"Now your number is {b}")
Error Content
b = a + 3
TypeError: can only concatenate str (not "int") to str
What to do? I directly used CV (not really). I looked through some small things written by my friend and found that I could use float() to process the input value, making it calculable. Thus, it became:
a = input("Number is ")
b= float(a)
c = b + 3
print(f"Now your number is {c}")
Output Content
eg:
Number is 1
4.0
This processing method I wrote for both X and Y coordinate inputs:
# Convert X coordinate
x_position = float(your_x_position)
# Convert Y coordinate (+1 for initial position)
y_position = float(your_y_position)
At this point, the input value has changed from the floating value of your_coordinate_type_position
to the fixed value of coordinate_type_position
, allowing for subsequent calculations.
Output Initial Coordinates#
In the original code, it was written as:
print(f"\nOriginal X position is {x_position}"
f"\nOriginal Y position is {y_position}."
f"\nOriginal position is ({x_position},{y_position}).")
Here, {coordinate_type_position}
is the value we input. At this step, since we did not perform calculations, {coordinate_type_position}
can be replaced with your_coordinate_type_position
and it would display normally. However, to reduce bytes (since I have nothing better to do), I recommend using {coordinate_type_position}
to reference the value.
In print()
, we do not need to write \n
to break lines; we can simply press Enter to create a new line. Of course, the \n
format also works.
Oh, by the way, in print()
, if we only want to output text, we can use print()
to output:
print("This is a piece of text")
Output Content
eg:
This is a piece of text
If you want to reference a certain value, you must add an f at the end, which stands for format, and it looks like this:
message = text
print(f"This is a piece of {message}")
Output Content
eg:
This is a piece of text
Of course, this is the most basic part, and I don't need to elaborate further; this is a problem discussed in the second chapter of a certain book.
if-elif-else Statement#
First, look at the original code:
# if-elif-else statement
# Define slow
if speed_random == 'slow':
# Algorithm
x_increment = x_position + 1
y_increment = y_position - 2
# Define medium
elif speed_random == 'medium':
# Algorithm
x_increment = x_position + 2
y_increment = y_position - 1
# Define fast
elif speed_random == 'fast':
# Algorithm
x_increment = x_position + 3
y_increment = y_position + 3
# Define other content, assuming other content speed is very fast, reaching the display limit
else:
# Algorithm
x_increment = x_position + 4
y_increment = y_position + 6
This involves calculations, so I must reference the float()
I wrote above before performing calculations.
The values here can be written arbitrarily; I ensured that the minimum number is not negative. However, in actual testing, it turns out it doesn't matter whether it is negative or not; no bugs will occur...
The most technical part here is the if-elif-else
statement, which can't really be called technical; it should be called logic.
I can translate the meaning of this entire segment of code, so I don't need to elaborate too much.
# if-elif-else statement #
# Define slow #
if speed_random == 'slow': # If the value of speed_random is slow, then
# Algorithm #
x_increment = x_position + 1 # The value of x_increment (new variable) is the value of x_position + 1
y_increment = y_position - 2 # The value of y_increment (new variable) is the value of y_position - 2
# Define medium #
elif speed_random == 'medium': # If it is not the previous ones but the value of speed_random is medium, then
# Algorithm #
x_increment = x_position + 2 # The value of x_increment is the value of x_position + 2
y_increment = y_position - 1 # The value of y_increment is the value of y_position - 1
# Define fast #
elif speed_random == 'fast': # If it is not the previous ones but the value of speed_random is fast, then
# Algorithm #
x_increment = x_position + 3 # The value of x_increment is the value of x_position + 3
y_increment = y_position + 3 # The value of y_increment is the value of y_position + 3
# Define other content, assuming other content speed is very fast, reaching the display limit
else: # Other cases
# Algorithm #
x_increment = x_position + 4 # The value of x_increment is the value of x_position + 4
y_increment = y_position + 6 # The value of y_increment is the value of y_position + 6
That's it. Here, the else
is deemed by me to be the speed of veryfast
, but logically speaking, it means that any value other than slow
, medium
, or fast
will execute such logic. This means that if the current speed is veryslow
, its algorithm will still be X+4, Y+6. However, due to the dictionary limitation, there are only four cases in total, so this problem will not occur.
Output Moved Coordinates#
print(f"New X position is {x_increment}"
f"\nNew Y position is {y_increment}"
f"\nNew position is ({x_increment,y_increment})")
At this point, the referenced coordinate values are the results calculated after processing through if-elif-else
, so there's no need to elaborate further.
Content Introduction#
First, let's look at the code:
# Content introduction definition
alien = {
'slow': 'Add 1 X position and reduce 2 Y position',
'medium': 'Add 2 X position and reduce 1 Y position',
'fast': 'Add 3 X position and add 3 Y position',
'veryfast': 'Add 4 X position and add 6 Y position'
}
print("\nIntroduction rules")
# Character replacement and total number of introduction types
if len(alien) == 4:
# Character replacement
The_number = 'four'
# Total number of introduction types
print(f"There are {The_number} cases in total")
# Other types
else:
# Output null value
print("NULL")
# for statement output
for speed_1, position in alien.items():
print(f"Speed: {speed_1}")
print(f"{position}")
This contains a lot of information.
First, the alien = {……}
part is a dictionary, where the first column is speed and the second column is the introduction. The values in the first column are called key
, and the values in the second column are called value
.
Each key
corresponds to a value
, and they correspond horizontally.
The subsequent print()
is the simplest print
statement, no need to elaborate.
Starting from if
, it is another logic:
# Character replacement and total number of introduction types
if len(alien) == 4:
# Character replacement
The_number = 'four'
# Total number of introduction types
print(f"There are {The_number} cases in total")
# Other types
else:
# Output null value
print("NULL")
If the total number of types in the alien dictionary is 4, then a new value will be generated, namely The_number = 'four'
, and it will output a sentence There are four cases in total
.
If not, it will directly output a single word NULL
.
This may not be easy to understand, but that is its logic.
Finally, the values in the alien
dictionary are output:
# for statement output
for speed_1, position in alien.items():
print(f"Speed: {speed_1}")
print(f"{position}")
speed_1
corresponds to key
, and position
corresponds to value
, reading the key
and value
and assigning them to speed_1
and position
, respectively.
Finally, it uses print
to output.
The for
loop will continue to output until all values are completely output.
Conclusion#
So, is this the end? This might be the most technical article I've written in nearly a year...
This article is synchronized and updated to xLog by Mix Space. The original link is https://fmcf.cc/posts/technology/Python_Notes_2