SoFunction
Updated on 2024-11-19

Python's Commonly Used print Output Functions and input Input Functions

Preface:

In every programming language, there are input and output streams, through which we can write programs to interact with the outside world. Of course, the purpose of writing a program is to process the data stream, and then either save it or release it. Today, we will learn about input/output streams in Python, and we will introduce standard input/output streams and file input/output streams.

I. Getting Command Line Parameters

in implementingPythonScripts can pass parameters to the script from the command line, then receive them within the script, and then separate each parameter.

The first step in the method of use:

import sys

Step 2 of the usage method:

temp=[1]

The following code will print the name of the Python file and the parameter you passed in (without passing a parameter, you will get an error).

import sys
n1=[0]
n2=[1]
print(n1,type(n1))
print(n2,type(n2))

This module parses command line arguments and generates help messages.PythonStandard Modules

Step 1 (guide package):

import argparse

Step 2 (Create ArgumentParser object):

margs=()

Step 3 (add information about the command line arguments to be parsed).

margs.add_argument(argument name, default value, type, hint statement)

Step 4 (Generate parameter list).

args=margs.parse_args()

II. Most commonly used inputs and outputs

Function [Output

①Print function prototype

Explain the parameter list.

*args for variable arguments
sep stands for spacing defaults to spaces
end represents a newline at the end of the output.
file represents whether to redirect the output stream to a file. It is a file descriptor
The pass at the end is a placeholder, since python is a syntactically strict formatting language.
Functions and loops are not allowed to leave blanks, and passes are generally used to take up space.

def print(self, *args, sep=' ', end='\n', file=None): 
    # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=, flush=False)
    
    Prints the values to a stream, or to  by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current .
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    pass

②Use the print function

The print function prints numbers, adds and subtracts.

You can output a string (the string must be enclosed in double or single quotes, otherwise the interpreter won't understand what's being typed).

print can direct the output to the file inside, open function to open the file

Create python scripts without importing headers, and import third-party packages only when you use a library.

# 1. Output Digital

print(888)
# 2. Output Operator
print(1+3)
# Output string
print('Hello World')
print('Hello World', "Hello Kity")
The # print function outputs the content directly into the file
# Open the file to get the file descriptor F and then output to the file.
F = open('', "a+")
print('Hello File', file=F)
()

Function [Input]

①input function prototype

  • input function is commonly used in Python input function, you can read the black window input data
def input(*args, **kwargs): # real signature unknown
    """
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
    """
    pass

②Use the input function

# input input
# Input function boxes are filled with prompt statements
# Input comes in as a string at first #
q=input('Please enter your name')
print(type(q))
print("My name is:",q)
# input (direct type conversion is possible)
q=int(input("Please enter your data:"))
print(type(q))

III. Inputs and outputs under the sys package

The name suggests that this package is about the system, if print and input do not satisfy your needs
It's not a bad idea to take a look with. print and input are both encapsulated in the latter.

More standard input than input, you can use his method readline() to read in one line at a time.
The line read in contains all special characters and subsequent newlines, if you don't want to read newlines into the
To do so, add strip() to the readline.

The code is as follows:

# First guide the package
import sys
# Read a line directly, including the line breaks at the end.
str1=()
# Read a line without the last newline character
str2=().strip()

This is a more official output than the print function, because print is wrapped on top of his implementation. For Python(“Hello World”+"\n")together withprint(“Hello World”)The effect is the same.Redirection of output is also supported. This is done by directly redirecting the standard output
object to the file descriptor, if you want to restore the standard output, just point the I/O object to the standard I/O object again.

The code is as follows:

import sys
# Create a file descriptor
f1=open("","w")
# Redirect standard output to within a file
=f1
# Write message
("Hello")
#Recover redirection
=sys.__stdout__

IV. Redirection of command-line scripts

In life, we may have such a need, is to write their own code for testing, testing if the amount of data is very large each time we enter the words is very troublesome, there is also a need to print the log, if each time the log will be printed to the screen if the amount of information is large, it may be refreshed down. Thus our input/output redirection. Input and output redirection is generally to print the data on the screen to a file, or need to read the data from the screen to read from the file.

1. Redirect standard output

Deliver the results of script execution directly into a file for permanent storage.
The syntax is.python file.py > store file eg: python >

The code is as follows:

import sys
num=int(input())
# num=int([1])

flag=True
for i in range(1,10):
    for j in range(0,10):
        temp=num-2*i-2*j
        if temp<10 and temp>=0:
            print(i*10000+j*1000+temp*100+j*10+i)
            flag=False
for i in range(1,10):
    for j in range(0,10):
        temp=num-2*i-2*j
        if temp>=0 and temp%2==0 and temp//2<10:
            print(i*100000+j*10000+temp//2*1000+temp//2*100+j*10+i)
            flag=False
if flag:
    print(-1)

The results are as follows:

2. Redirection of standard input

For input redirection the syntax is almost the same as for output

python <

Summary.
The use of Python for input and output redirection, you can sort the data through the code, filtering and other operations, you can play the role of a filter. In the brush of algorithmic problems we often need to understand more about input and output in order to comply with the algorithmic problems given by the sample input sample output. This shows that mastering Python input and output is very important to us.

This article on Python commonly used print output function and input input function is introduced to this article, more related Python input and output function content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!