Python basic P1 variable advanced exercise

Posted by gromer on Sat, 12 Feb 2022 20:36:00 +0100

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:")

b = input("please enter a number:")

If you want to enter and get numbers, you can use int() for type conversion

a = input("Please enter a string:")

b = int(input("please enter a number:"))

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 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


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

%yDouble digit year0~99
%YFour digit year000~9999
%dOne day in the month0~31
%H24-hour system0~24
%I12 hour system hours01~12
%aLocal simplified week name
%ALocal full week name
%bLocal simplified month name
%BLocal full month name
%cLocal corresponding date and time
%jOne day of the year1~366
%pEquivalent of local A.M. or P.M
%UNumber of weeks in a year0~53
%wStart on Sunday0~6
%WNumber of weeks in a year0~53
%xLocal corresponding date
%XLocal corresponding time
%zThe 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")

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")
time_str = time.strftime("%Y--%m--%d", date)

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 namedescribe
datetime.dateIndicates the date. The commonly used attributes are: year,month and day
datetime.timeRepresents time. Common attributes are: hour,minute,second,microsecond
datetime.datetimeRepresents the date and time
datetime.timedeltaRepresents two dates, time and datetime, with a resolution of microseconds
datetime.tzinfoAbstract base classes of time zone related information objects, which are used by datetime and time classes to provide custom time adjustment
datetime.timezoneA 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")
date = datetime.datetime(date[0], date[1], date[2], date[3], date[4], date[5])


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

    # Judge whether there are abnormal sentences
    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):")    
        time.strptime(time_str, "%Y-%m-%d")        
        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

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

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:

characternumerical value

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)

Topics: Python Back-end