SoFunction
Updated on 2024-10-30

An article that takes you through input and output in Python

Python input

In Python, the user's keyboard input can be received using the built-in function input()

The basic usage of the input() function is as follows:variable = input()

The parameters are described below:

  • variable: is a variable that holds the results of the input

The text in double brackets is used to indicate what is to be entered

  • an actual example: Receive the result of user input and save it to the demo variable
demo = input("Please enter content:")

✅ In the, input () to receive user keyboard input type defaults to the string type, if you want to use input () function to receive other data types of data (such as int type) you need to carry out the strong conversion data type

number = int(input("Please enter an integer:"))

Addendum: Command line input

x = input("Please input x:")
y = raw_input("Please input x:")

utilizationinputcap (a poem)raw_inputBoth can read console input, but there is a difference between input and raw_input when dealing with numbers.raw_input() treats all input as a string and returns the string type; whereas theinput() has its own characteristics when dealing with purely numeric input, it returns the type of the number entered (int, float).input() Accepts legal python expressions.

Looking at the documentation for python input, you can see that theinput() It is still essentially the use ofraw_input() to achieve this, just after calling theraw_input() After that, call theeval() function, so you can even use the expression as ainput() parameter, and it will compute the value of the expression and return it.

def input(prompt):
return (eval(raw_input(prompt)))

financial penaltyinput() There is a special need, otherwise we generally recommend the use of theraw_input() to interact with the user.

Python Output

print() output

In Python, you can use the print() function to output the results to the console

Print() function syntax format:print(output)

where the output can be a number, a string, or an expression containing an operator

a = 7
b = 10
print(7)  # Output numbers
print(a if a > b else b)  # Output the result of the conditional expression
print("Life is short I use Python.")  # Output string

format() formatting output

✅ Simple to understand will be explained in detail later when talking about strings

utilization.format()Formatted output

name = "hacker"
age = 20
print("My name is {} and I am {} years old.".format(name, age))

In addition to using.format()In addition to thefor cleaner, more readable output.

name = "hacker"
age = 20
print(f"My name is {name} and I am {age} years old.")

summarize

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