An article takes you to understand the input and output of Python

1, Why input and output?

Whether it's "hello world" from the beginning or the previous examples, they are basically "talking to themselves" to show the code fragments of the class. Only when it can receive user input, generate results according to the input code and output them to the screen can it be regarded as a relatively complete and simple program.

2, input function

Get user input and save it as a string. If it's important to say twice, the return value of the input function is a string type. Even if you enter a number 1, you will only be returned with the string "1", not the integer 1. Here are some simple examples:

#First example
>>> inp  = input("please input your name: ")
please input your name: jack
>>> inp
'jack'
>>> type(inp)
<class 'str'>

#Second example
age  = input("please input your age: ")
please input your age: 18
 print(age)
'18'

#The third example
>>> type(age)
<class 'str'>

#The fourth example

>>> a = input("Please enter a character:")
'Please enter a character: blank before and after' 
>>> a
'   Blank before and after   '

In the first example, inp = input("please input your name:"), and a string can be provided in the input function to prompt the user for input. After the return value of the input function is assigned to the variable inp, the value entered by the user is saved in inp.

Type is one of Python's built-in functions, which is very useful for viewing the data type of an object.

In the second example, age 18 is entered, but a string of "18" is saved in age.

The third example, without entering anything, returns an empty string.

In the fourth example, the space before and after valid input is retained in the returned string.

From the above example, it is not difficult to find that the input function returns the user's input to the variable as it is, and wraps it into a string. This will certainly not work and will bring many problems, so it is usually necessary to process and judge the user input.

  • Process empty inputs:
inp = input("Please enter your name:  ")

if inp == "":    
    inp = input("Name cannot be blank, please re-enter:  ")
  • Convert string to numeric type:
age = input("Please enter your age:")

age = int(age)   # Convert string to integer

if age > 18:
    print("You are an adult!")
else:
    print("Not weaned yet?")
  • Remove the blank lstrip at the beginning, the blank rstrip at the end and the blank strip at both ends
inp = input("Please enter your name:  ")

inp = inp.strip()  # The use of strip is described in string data types

print(inp)
  • Determine the type of character entered

The int() function is used to convert a string to an integer. This method is dangerous. See the following example:

s = "123"
a = int(s)
print(a)

s = "something"
a = int(s)

For strings such as "123" and "283242", the conversion is OK, but for strings containing characters and special characters, there is no way to convert, and an abnormal error will pop up. Therefore, before using the int function, you must first judge the input.

Modify the above example:

age = input("Please enter your age:")

if age.isdigit():   # Use the isdigit function to determine whether the input is all in digital format
    age = int(age)   # Convert string to integer
    print("Your age is:", age)
else:
    print("Illegal input!")
  • The input function can sometimes be cleverly used to block or pause a program
print("The previous part of the program has been executed......")

input("Please press enter to continue......")       # Here, the program will pause and wait for your carriage return

print("Continue with the rest of the procedure......")

At this time, the input function does not save the input, but is used to pause the program action.

3, print input function

The print function is used to format and display the content on the standard output, mainly referring to the screen display.

Print can accept multiple strings, string type variables or printable objects. Each string is separated by a comma "," and output in a string. Print will print each string in turn, and output a space every time a comma "," is encountered.

a = "i am"
b = "student"
print(a,"a", b)
# Automatically separated by spaces
print(a+"a"+b)

For a statement like print(a+"a"+b), the value of a+"a"+b is calculated first, and then printed through print. print() will automatically execute the internal statements and output the desired results. Take another example:

>>> a = 10
>>> b = 2
>>> print(sum((a, a*b)))        # First find a*b, then sum, and then print
30   #result

Take a look at the prototype of the print function: Print (self, * args, Sep = '', end = '\ n', file = none)

sep parameter: delimited symbol. It is a space by default;

End parameter: the end method after printing. The default is line break. \ n. If end = '' is set, the print can be printed continuously in one line without line break. Flexible printing control can be realized by making use of the parameters of print.

>>> a = "i am"
>>> b = "student"
>>> print(a,"a" , b, sep="*")
i am*a*student #Output results

4, print formatted output

After Python 2.6, there are two ways to format output.

One is the% percent formatted output of printf similar to C language, which is also the most basic and commonly used formatted output method of Python. The other is str.format().

Here we focus on the traditional% percent formatted output method,

Take the following statement as an example:

print ("My name is %s this year %d year!" % ('Xiao Ming', 10))

First, construct a string "my name is% s, this year is% d years old!", and replace the part that needs to be replaced by other variables or values with the% percentile plus a data type code, such as% s and% d. Then add a tuple of the same number of variables or values with% after the string.

That is, the number of% symbols in the front and the number of parameter values to be provided later. Each parameter value is separated by commas, and all parameters are enclosed in parentheses. Each parameter corresponds to the previous% one by one, and the data type must be able to correspond legally.

This is the basic usage. See the following figure for more formats, and then master the matching method of formats.

Formatting symbol: (the picture comes from Baidu, please contact to delete if it infringes)

Auxiliary instruction of formatting operator: (the picture comes from Baidu, please contact to delete if it infringes)

Classic case:

s = "i am %s" % "jack"
print(s)

s = "i am %s age %d" % ("jack", 18)
print(s)

s = "i am %(name)s age %(age)d" % {"name": "jack", "age": 18}
print(s)
s = "percent %.2f" % 99.97623
print(s)
s = "i am %(pp).2f" % {"pp": 123.425556, }
print(s)
s = "i am %.2f %%" % 123.425556
print(s)

It should be noted that if you want to print a% percentile in print, you need to use%%, two percentiles to escape a percentile, that is, print("%%").

If you have no love for the complex formatting control of print and no requirements for beauty, it is easy to use% s as a placeholder all the way. For example:

print("%s %s %s %s %s" % (a, b, c, d, e))

5, Summary

Based on Python, this paper introduces several common input and output methods. Through the actual operation of each project, we can better understand the usage of input and output statements. The difficulties encountered in the project practice and the points needing attention are explained in detail.

Posted on Thu, 02 Dec 2021 23:56:31 -0500 by KITTfan2K