Python basic P1 variable advanced exercise
1. Variable helper (input and print)
input function
Read the string from standard input (with line break), and the prompt string will be printed to standard output (without line break) before reading the input
input standard format
input(prompt=None, /) # prompt=None input prompt string
The input function returns a string. Even if the user enters a number, the content output to the variable will be a string
Take a chestnut
a = input("Please enter a string:") print(type(a)) b = input("please enter a number:") print(type(b))
If you want to enter and get numbers, you can use int() for type conversion
a = input("Please enter a string:") print(type(a)) b = int(input("please enter a number:")) print(type(b))
print function
print prints the value to the stream or system, which is stdout by default
print standard format
print(*objects, sep=' ', end='\n', file=sys.stdout) # Objects: indicates the output objects. When outputting multiple objects, they need to be separated by commas # sep: used to space multiple objects # End: used to set what to end with. The default value is newline character \ n, we can replace it with other characters # File: file object to write
print can output variables in different forms, including but not limited to: numeric, Boolean, list variables, dictionary variables, etc
print direct output
print("hello cage")
print variable output
a = "hello cage" print(a)
print combined output
print("hello cage " + str(5))
print formatted output
a = 5.3425 print("%.2f" % a)
Advanced practice
1. Two methods are used to realize digital content input
2. Calculate the results of their addition, subtraction, multiplication and division respectively
3. Use four methods to output the results of addition, subtraction, multiplication and division respectively (the division results retain 2 decimal places)
Realization effect
Source code (see Annex)
2. Time difference calculation
strptime/strftime
The strptime function parses a time string into a time ancestor according to the specified format. The format of the parsing is determined by the format
Basic format of strptime
import time time.strptime(string[, format]) # String: time string # Format: format string
Before using this function, first get familiar with the symbols of the formatted string, that is, the contents of format
Date formatting symbol table
Symbol | function | Range |
---|---|---|
%y | Double digit year | 0~99 |
%Y | Four digit year | 000~9999 |
%m | month | 01~12 |
%d | One day in the month | 0~31 |
%H | 24-hour system | 0~24 |
%I | 12 hour system hours | 01~12 |
%M | Minutes | 00~59 |
%S | Seconds | 0~59 |
%a | Local simplified week name | |
%A | Local full week name | |
%b | Local simplified month name | |
%B | Local full month name | |
%c | Local corresponding date and time | |
%j | One day of the year | 1~366 |
%p | Equivalent of local A.M. or P.M | |
%U | Number of weeks in a year | 0~53 |
%w | Start on Sunday | 0~6 |
%W | Number of weeks in a year | 0~53 |
%x | Local corresponding date | |
%X | Local corresponding time | |
%z | The name of the current time zone |
Take a chestnut
import time str_time = input("Please enter a date( XXXX-XX-XX):") date = time.strptime(str_time, "%Y-%m-%d") print(date)
The strftime function, on the contrary, receives a time tuple and returns the current time in a readable string (the format is determined by format)
Basic format of strftime
import time time.strftime(format[, t]) # Format: format string # t: The optional parameter is a struct_time
Take a chestnut
import time str_time = input("Please enter a date( XXXX-XX-XX):") date = time.strptime(str_time, "%Y-%m-%d") print(date) time_str = time.strftime("%Y--%m--%d", date) print(time_str)
datetime module
datetime module: provides classes for processing date and time, both simple and complex; It supports date and time algorithms, but its implementation focuses on providing efficient attribute extraction function for output formatting and operation.
Common classes in datetime module:
Class name | describe |
---|---|
datetime.date | Indicates the date. The commonly used attributes are: year,month and day |
datetime.time | Represents time. Common attributes are: hour,minute,second,microsecond |
datetime.datetime | Represents the date and time |
datetime.timedelta | Represents two dates, time and datetime, with a resolution of microseconds |
datetime.tzinfo | Abstract base classes of time zone related information objects, which are used by datetime and time classes to provide custom time adjustment |
datetime.timezone | A class that implements the tzinfo abstract base class and represents a fixed offset from UTC |
Here we mainly introduce datetime Datetime, which will be used in later exercises
Basic usage of datetime
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None) # Year: year (0 ~ 9999) # Month: month (1 ~ 12) # day: date (1 ~ 31) # Hour: hour (0 ~ 23) # minute: minutes (0 ~ 59) # Second: second (0 ~ 59) # microsecond: microseconds (0 ~ 1000000) # Tzinfo: subclass object of tzinfo, such as the instance of timezone class
If a parameter exceeds these ranges, it will cause a ValueError exception (which is useful in later exercises)
Take a chestnut
import time import datetime time_str = input("Please enter the end date (Format: XXXX-XX-XX XX:XX:XX):") date = time.strptime(time_str, "%Y-%m-%d %H:%M:%S") print(date) date = datetime.datetime(date[0], date[1], date[2], date[3], date[4], date[5]) print(date)
try/expect
try/expect is used for exception handling. A special section will be used later to explain exception handling. Here, you only need to know how to use it
Basic format
try: # Judge whether there are abnormal sentences expect: print("Throw exception prompt")
Take a chestnut
import time import datetime while True: time_str = input("Please enter the start date (Format: XXXX-XX-XX):") try: time.strptime(time_str, "%Y-%m-%d") break except: print("Please enter the correct date! Please re-enter!") print("Date entered correctly")
Advanced practice
Use date and datetime modules to calculate the time difference
requirement:
1. Input two groups of month, year and day, and calculate the time difference between them
2. Days of output time difference
Realization effect
However, there are still some small problems in the current program. For example, if the input content is not within the correct date range, the program will report an error and cannot be executed correctly; try/expect comes in handy at this time
Let's look at the effect of the program first:
The effect of abnormal judgment through try:
If the input content is incorrect, it will be required to re input until the input content is correct before entering the next step
Source code (see Annex)
Now you can realize the time difference processing of dates, and later you can also realize the processing including time
requirement:
1. Input two groups of time, minutes and seconds, and calculate the time difference between them
2. Output time difference
3. Be able to judge whether the input date is reasonable
Effect achieved:
Source code (see Annex)
3. Roman numeral to integer
brief introduction
Let's first understand the composition principle of Roman numerals
Roman numerals include the following seven characters:
character | numerical value |
---|---|
I | 1 |
V | 5 |
X | 10 |
L | 50 |
C | 100 |
D | 500 |
M | 1000 |
For example: III represents 3, XV represents 15; Of course, there are also some special cases. For example, IV represents 4, and the small symbol in front of the large symbol is V - I, that is, 5-1 = 4. There are six kinds of cases:
I can be placed to the left of V (5) and X (10) to represent 4 and 9
X can be placed to the left of L (50) and C (100) to represent 40 and 90
C can be placed to the left of D (500) and M (1000) to represent 400 and 900
Now analyze the relationship between Roman numerals and decimal integers and convert the input Roman numerals into decimal integers
Advanced practice
Main implementation ideas:
1. First map the symbols and values of Roman numerals
2. Then traverse the Roman numeral string (from left to right)
3. If the Roman symbol on the left is larger or equal than that on the right, add this value
4. If the Roman symbol on the left is smaller than that on the right, subtract the small value
5. The final calculation result is the result of Roman numeral conversion
Effect achieved:
Source code (see Annex)