Table of Contents
1. The syntax of the print() function is as follows:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush= False)" >print(*objects, sep=' ', end='\n', file=sys.stdout, flush= False)
2. Print() prints out text
3. How to use spaces in print()
4. Print() line break
6. Tab character\t
7. Output mathematical expressions
8. Print out backslashes\
9. Output of print() variables
10. Formatted output of print() data
11. Print() small example
11.1 Print characters
11.9 Use the letters word love to print a heart shape
11.10  用字符输出 I ❤ U (2款效果)
11.11 From Dear, I love you forever! Five words output five hearts
12. Print() Chinese input displays garbled characters
13. Print() writes to the file
Home Backend Development Python Tutorial Detailed explanation of examples of usage of Print() function in Python

Detailed explanation of examples of usage of Print() function in Python

Nov 14, 2022 pm 05:02 PM
python

This article brings you relevant knowledge about Python, which mainly introduces the relevant knowledge about the usage of print() function. The print() function is used to print output. One of the most common built-in functions in Python, let’s take a look at it, I hope it will be helpful to everyone.

Detailed explanation of examples of usage of Print() function in Python

[Related recommendations: Python3 video tutorial ]

print() function is used to print output and is the most common in python A built-in function.

1. The syntax of the print() function is as follows:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush= False)

Will print out "objects" to the text stream specified by the "file parameter", separated by the "sep parameter" and add the "end parameter" at the end. "sep", "end", "file" and "flush" must be given as keyword arguments. The flush keyword parameter was added after version 3.3 of Phthon.

All non-keyword parameters will be converted to strings as if str() were executed, and will be written to the stream with the "sep parameter" and the "end parameter" at the end . Both the "sep parameter" and the "end parameter" must be strings; they can also be "None", which means the default value is used. If no "objects parameter" is given, print() will only write the "end parameter".

 The "file parameter" must be an object with a write(string) method; if the parameter does not exist or is None, sys.stdout will be used. Because the arguments to be printed are converted to text strings, print() cannot be used with file objects in binary mode. For these objects, file.write(...) should be used instead. Whether the output is cached usually depends on the file, but if the flush keyword argument is True, the output stream is forced to be flushed.

The printed text content is not only Chinese text, but also English text or text containing special symbols. When printing text, you need to use quotation marks. The text content is quoted. The quotation marks can be single quotation marks (' '), double quotation marks (" "), triple quotation marks (""" """)

#Triple quotedA pair of triple quotes, quoting multiple lines of textMultilinetext="""must do as they can.

Usage method

Code

Running result

Single quotes

A pair of single quotes, double quotes can be used inside the single quotes, and the single quotes can be printed out

print('Where there is life, there is hope')

Where there is life, there is hope



##print('"Where there is life, there is hope"')

"Where there is life, there is hope"





#Double quotes

A pair of double quotes, single quotes can be used inside the double quotes, and the single quotes can be printed out

print("Never be discouraged!")

Never be discouraged!



print("'Never be discouraged! '")

'Never be discouraged! '





They who cannot do as they would,

must do as they can.

If you cannot do as you wish, you must do your best.

"""

print(Multilinetext)

hey who cannot do as they would,

If you can’t do what you want,

you must try your best.


3. How to use spaces in print()

#2Use commas between two adjacent items Intervalprint("It depends on people", "It depends on heaven", "If there is life, there is hope")It depends on people As long as there is success, there is hope in life##3##4comma Intervalprint ("It depends on people")If you plan things in people, you will succeed in heaven

The "end" parameter of the print() function specifies what symbol the print() function uses to indicate the end after printing the content. The default value is "\n" , indicating line break, that is, the print() function will automatically wrap the line after printing the specified content.

We can use other symbols to indicate the completion of print() output printing through the definition of the "end" parameter. For example: the "end" parameter of the print() function is specified as "|", that is, the print() function outputs "|" every time the output is completed.

Method

Code

Run result

##1

Put spaces directly in the quotation marks, there is no limit to the number of spaces

print("Planning depends on people, success depends on God, if there is life, there is hope")

Things depend on people, success depends on God. Where there is life, there is hope









Use a comma at the end of multiple lines

print ("It's up to people to make things happen",)
print ("It's up to heaven")

It's up to people to make things happen, it's up to heaven
(2 There is a space between the strings)





When printing two or more adjacent lines,

is not used

print("It depends on people"""It depends on heaven")

print ("It depends on God")

print ("It depends on people") In the sky")

If you plan things in people, you will succeed in heaven





#5

No spaces between strings

print ("It depends on people" "It depends on God")

It’s up to people to make things happen

(There is no space between the two strings)

##Run resultThere is life##No line breaks after printing, Use the end parameter to set the ending symbol you want Code##Operation resultscodeprint("Everything depends on God", end ="|")Operation results##1 2 3 4 5#5. The separator sep

Force newline

##Code

print("There is life\nThere is hope")

There is hope


print("It depends on the person", end =" ")
print("Success depends on God", end =" ")

print("If there is life, there is hope", end =" ")

If you plan for things to happen, it depends on God. If you have life, you will have hope.



print("It depends on the person" ,end ="|")

print("If there is life, there is hope", end ="|")

It’s up to people to make things happen|It’s up to God to make things happen|Where there is life there is hope|



##Code
for x in range(0, 6):

print(x, end=' ')
for x in range(0, 6):

print(x , end=',')

Run result

0 1 2 3 4 5 0,1,2,3,4,5,



##Code

for x in range(1, 6):

print( x, end=' ')

print()

for x in range(1, 6):

print(x, end=',')

print()

Run result

1,2,3,4,5,



Use the sep parameter to constrain the number of print brackets Separator between items Code##Operation results

print("It depends on the person", "Everything depends on God", "Where there is life, there is hope", sep ="&")

Planning is up to people & success is up to Heaven & as long as there is life, there is hope



#Code
print("www", "csdn", "net", sep=".")

Run results
www.csdn.net

6. Tab character\t

##Codefor i in range (1, 11):Running result1 2 3 4name = 'Adversity awake'print(name.title() " once said" ": " '\n\t"' saying '"')#Code##Run result##Codeprint("Student ID\t\tName\t\t\t\t\tSubject\t\tScore") print("100000102\tCameron Cameron\t\t\tChinese\t\t85")Run resultprint("%-10s\t %-30s\t %-10s\t %-10s"%("Student Number","Name"," Subject","score")) print("%-10s\t %-32s\t %-10s\t %-12s"%("100000101","Avatar","Chinese","80" )) print("%-10s\t %-26s\t %-10s\t %-12s"%("100000103","Monica Belluca Melon","Chinese","85 "))

Tab character\t controls the horizontal spacing. It functions like the tab key and controls the spacing distance when printing output

\t means empty 8 characters,
If the element occupies less than 8 characters, each column can be perfectly aligned, and everyone is happy;
If the character element occupies more than or equal to 8 characters, the alignment will appear Deviation, you can insert N pieces of \t to join them together, so that the elements can be aligned

or use formatted output. For details, please see the example

Code

print("You must try your best if you can't do what you want\t")

# #Running result

If you can’t do what you want, you must try your best



print(i,' \t',i*2,'\t',i*3,'\t',i*4)

2 4 6 8

##3 6 9 12

##4 8 12 16

5 10 15 20

6 12 18 24

##7 14 21 28

8 16 24 32

9 18 27 36

10 20 30 40


Code

saying="Man proposes, god disposes Man proposes, God disposes"

Running result

Adversity Awake once said:

“Man proposes, god disposes Man proposes, God disposes.”





#Error print() effect distance:

print("Student ID \tName\tSubject\tScore")

print("100000101\tAvatar\tChinese\t80")
print("100000102\tCameron Cameron\tChinese\t85")
print("100000103\tMonica Bellu Cameron\tChinese\t85")

# Alignment deviation



print(" 100000101\tAvatar\t\t\t\t\tChinese\t\t80") print("100000103\tMonica Bellu Cameron\t\tChinese\t\t85")


#Use multiple tabs and keep the alignment intact



##Code
print("%-10s\t %-30s\t %-10s\t %-12s"%("100000102","Cameron Cameron","中文","82") )


Running result
#Alignment intact

Extra: Sometimes you need to align output, you can also use format() to achieve this:

##

7. Output mathematical expressions

If there is a mathematical expression in the brackets after print, the printed result will be the result of the final operation of the expression

Code

products=[["iphone",6888],["MacPro",14800],["coffee",32],["abc",2499],["Book",60],["Nike",699 ],["MacPro",45600],["coffee",432],["abc",244499],["Book",6230],["Nike",61299],["MacPro",14800], ["coffee",32],["abc",2499],["Book",60],["Nike",699]]

print("-"*10 "Product List" " -"*10)

i=0

for product in products:

print('{:<6}\t{:<10}\t {:<10}'.format(str(i), product[0], str(product[1])))

i = i 1
Run result


##print(8/1)Running results8.0##CodeRun results##CodeRun Result8

Print prints the value of the expression

Code

Print(1 2 3 4 5)

Run results

15



##Code



print(2*4)

8



print(18-10)

8



##Code
print(2 6)

##Run result


#

9. Output of print() variables

No matter what type of data, including but not limited to: numerical type, Boolean type, list variable, dictionary variable...all can be passed through print() Direct output.

Print backslashes, put 2 backslashes together

Code

Print("If you can't do what you want\\you must do your best")

Operation results

If you can’t do what you want, you must try your best



##Code#Output tuple variableRun results(1, 2, 3, 4, 5, 'a', 'b', 'c')##Codeoperation result

Output of print() variable

Code

#Output numeric variable

num = 91682

print(num)

Running result

91682



##Code

#Output string variable

name = 'Sober in adversity'

print(name)

Running results

Sobering up in adversity



Code

#Output list variable

list = [1,2, 3,4,5,'a','b','c']

print(list)

Running result

[1, 2, 3, 4, 5, 'a', 'b', 'c']



tuple = (1,2,3,4,5,'a','b','c')

print(tuple)



#Output dictionary variable
dict ={'a':1, 'b':2,'c':3}

print(dict)

{'a': 1, 'b': 2, 'c': 3}



10. Formatted output of print() data

##3Decimal variablei = 2670.5The number is 2670.500000% dot (.) followed by the field width; i = 2.671455738-bit reserved field width 2.671456##i = 2.67145573#4s='Sober in adversity'The length of the sober name in adversity is 4

Insert into the string

Code

Run result

1

String variable

name = "Sober in adversity"

print("My name is %s " % name)

My name is Awake in Adversity





##2

Integer variable

age = 100

print("My age is %d"%(age) "years old")

My age He is 100 years old





print("The number is %f" %i)




% dot (.) Followed by the precision value; in the field width, the decimal point also occupies one place


print("8-bit reserved field Width %(i))



print("The output with two decimal places is %.2f"%(i))

The output with two decimal places is 2.67


#i= 2.6714563467

print( "a" ' .3f'%i)

print("a" '%f'%i)

a 2.671

a2 .671456

(The precision is 3, so only .671 is displayed, and the specified width is 10, so 5 spaces are added to the left to reach a field width of 10 digits. In the field width, the decimal point also occupies one digit)






x=len( s)

print('The length of %s's name is %d' %(s,x))

##'{1, 2, 3}'#% c#%e, %Eprint('%e'%k)Binary integerprint(bin(50))0b110010%hu, %u, %luOutput integers of types short, int, and long in decimal and unsigned formprint('%u'P50#%ho, %o, %lo#%#ho, %#o, %#lo%hX, %X, %lXprint('%x'P)32# Outputs integers of types short, int, and long in hexadecimal, prefixed, and unsigned form. If x is lowercase, the output hexadecimal numbers and prefix are both lowercase; if X is uppercase, the output hexadecimal numbers and prefix are both uppercase. print('%#x'P)0x32#%f, %lf, %F# %g, %lg, %G, %lGprint('%g'%i)

Format output

Code

Run result

%s

Output a string, characters The string is displayed using str()

i= 2.6714563467

print('%s'%i)

2.6714563467





#%r

Display of string (repr())

print('%r '%repr(set([1,1,2,3])))





Output a single character

print('%c'�)

Z





Index (base e)

k= 2671.4563467284

print('%E'%k)

##2.671456e 03

2.671456E 03




#%b





#%hd, %d, %ld

Output integers of types short, int, and long in decimal and signed form

print('%d'P)

50










In octal, without prefix, Outputs integers of types short, int, and long in unsigned form

print('%o'P)

62






Output short in octal, prefixed, unsigned form , int, long type integer

##print('%#o'P)

0o62





#%hx, %x, %lx,

In hexadecimal , output short, int, long type integers in unprefixed and unsigned form. If x is lowercase, then the output hexadecimal numbers are also lowercase; if X is uppercase, then the output hexadecimal numbers are also uppercase.





#%#hx、%#x、%#lx、

%#hX、%#X、%#lX

print('%#X'P)

0X32





Output floating point numbers of type float and double in decimal form

i= 2.6714563467
print('%f'%i)

2.67146





outputs float or double type decimals in the shorter form of decimal or exponent, and the decimal part is No extra 0's are added at the end. If g is lowercase, e is also lowercase when output in exponential form; if G is uppercase, E is also uppercase when output in exponential form.

i= 2.6714563467

2.67146

##Run resultDecimal format 2671#CodeRunning result##Codeprint('Hexadecimal form''{:x}'.format(int(k)) )Run resultNumber form 2671.46##Codek= 2671.4563467284

print('Percent form''{:%}'.format(k))

#Code k= 2671.4563467284Run resultCodeRun result##Codeprint('Decimal floating point number''{:f}'.format(k))Run resultCodek= 2671.4563467284Output octal numberprint(oct(int(k)))0o5157

Some other format output methods

Code

k= 2671.4563467284

print('Binary form''{0:b}'.format(int(k)))

Run result

Binary form 101001101111



##Code

k= 2671.4563467284

print('Decimal form''{:d}'. format(int(k)))



k= 2671.4563467284
print('Otal form''{:o}'.format(int(k)))

Octal form 5157



k= 2671.4563467284

Hexadecimal form a6f



##Code
k= 2671.4563467284

print('Number form''{:n}'.format(k))

##Running results



##Running results

Percent form 267145.634673%



print('Power exponential form''{:e}'.format(k))

##Power exponent form 2.671456e 03



k= 2671.4563467284
print('Shorter decimal form Output''{:g}'.format(k))

In decimal and exponent The shorter form outputs 2671.46



k= 2671.4563467284

Decimal floating point number 2671.456347



Output binary number

print( bin(int(k)))

##Run result
0b101001101111


##Code

k= 2671.4563467284

Run result



#Code

Output hexadecimal number

k= 2671.4563467284

print(hex(int(k)))

Run results

0xa6f



Codename = 'Adversity awake'Run resultAdversity Awake#Code##Running result
## English case conversion (the first letter of title() is capitalized, upper() All uppercase, lower() all lowercase)

print(name.title())



name = 'Adversity awake'
print(name.upper())

ADVERSITY AWAKE



#Code
name = 'Adversity awake'

print(name.lower())

Run Result
adversity awake


##

11.2

Print characters

Code

for u in range(1, 100):

Print('{:c}'.format(int( u)),end =" | ")

##Run result

| | | | | | | | |

| | | | | | | | | | | | | | | | | | !
| " | # | $ | % | & | ' | ( | ) | * | | , | - | . | / | 0 | 1 | 2 | 3 | 4 | 5
| 6 | 7 | 8 | 9 | : | ; | < | = | > | ? | @ | A | B | C | D | E | F | G | H | I
| J | K | L | M | N | O | P | Q | R | S | T | U | V | W | [ | \ | ]
| ^ | _ | ` | a | b | c | 0b10



Multiplication table

Codefor i in range (1, 10):Run result1 *1=1##

11.3 Print solid diamond

Multiplication table

for j in range(1, i 1):

print("{}*{}={}".format(j, i, i* j), end=" ")

print()

1*2=2 2*2=4

1*3=3 2*3=6 3*3=9

1*4 =4 2*4=8 3*4=12 4*4=16

1*5=5 2*5=10 3*5=15 4*5=20 5*5=25

1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36

1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49

1*8=8 2*8=16 3*8=24 4*8= 32 5*8=40 6*8=48 7*8=56 8*8=64

1*9=9 2*9=18 3*9=27 4*9=36 5*9 =45 6*9=54 7*9=63 8*9=72 9*9=81



##n=5Run result *#11.4 Print hollow diamond

##Print solid diamond

Code

for i in range(1,n 1):

print(" "*(n-i) "*"*(2*i-1))

for i in range(1,n):

print(" "*i "*"*( 2*(n-i)-1))

** *

*****

*******

**********

**** ***

*****

***

*



Print hollow diamond##Codeprint(" "*(n-1) "*")operation result * *

n=5

for i in range(1, n):

print(" "*(n-1-i) "*" " "*(2*i-1) "*")

for i in range(1, n-1):

print(" "*i "*" " "*((n-1-i)*2-1) "*")

print(" "*(n-1) "*")

*

* *

* * *

* * *

* *

* *

* *

*

*



11.5 Print hollow triangle

#11.6

##Print hollow triangle

Code

n=5

print(" "*(n-1) "*")

for i in range(2, n):

print(" "*(n-i) "*" " "*(2*(i-1)-1) "*")

print("* "*n)

Run result

*

* *

* * *

* * *

* * * * *



Print solid triangle

Coden =5Run result *#

11.7 Print side triangle (6 types)

Print solid triangle

m = 8

for i in range(0, n):

for j in range(0, m):

print (end=" ")

m = m - 1

for j in range(0, i 1):

print("* ", end=' ' )

print(" ")

* * *

* * * *

* * * *

* * * * *



## Method 2: ##Run results

##Print side triangle 1

Code

Method 1:

i = 5

while 0 < i < ;= 5:

j = 1

while j <= i:

print("* ", end = '')

j = 1

print(" ")

i -= 1


for i in range(0,5):

tx="◆"

print()

for k in range( 0,5):

if i>k:

continue

print(tx,end="")

◆◆◆◆◆
◆◆◆◆

◆◆◆

◆◆



# Method 2: n = 5◆◆◆◆◆◆◆◆◆◆

Print side triangle 2

Code

Method 1:

i = 1

while i <= 5:

j = 1

while j <= i:

                                                                                                                                                                                                                    .



print('\n'.join('◆' * i for i in range(1, n 1)))

Run results

##◆

◆◆◆◆


Print side triangle 3

Code tx1=' ' ◆◆◆ ◆◆#
for i in range(0,5):

tx='◆'
print()

for j in range(0,5):
print(tx if i<=j else tx1,end="")

Run results

##◆◆◆◆◆

◆◆◆◆

Print triangle 4

code

for i in range(0,5):

tx='◆'

tx1=' '

print()

for j in range( 0,5):

Print(tx if i<=j else tx1,end="")

Run result

◆◆◆◆◆

◆◆◆◆

◆◆◆

◆◆



##◆◆◆◆◆◆◆◆◆##
#Print triangle 5

Code

l= 5

for i in range(l):

for j in range(i):

print(end=' ')

for k in range(2*(l-i)-1):

print(end='◆')

print()

Run results

 ◆◆◆◆◆◆◆

 ◆◆◆◆◆

 ◆◆◆

 ◆



#11.8 Printing parallelogram

Print triangle 6

Code

i = 1

while i <= 9:

if i <= 5:

print('◆ '*i)

else:

Print ('◆'*(10 -i))

i = 1

#◆

◆ ◆

◆ ◆ ◆

◆ ◆ ◆ ◆

◆ ◆ ◆ ◆ ◆

◆ ◆ ◆ ◆

◆ ◆ ◆

◆ ◆



Print parallelogramCodefor i in range(l): Running results

l = 5

for j in range(l-i):

print(end=' ')

for k in range(l):

print(end='◆')

print()

## ◆◆◆◆◆

◆◆◆◆◆
◆◆◆◆◆

◆◆◆ ◆◆

◆◆◆◆◆


##

11.9 Use the letters word love to print a heart shape

#

11.10  用字符输出 I ❤ U (2款效果)

Use the letters word love to print a heart shape

Code

print('\n'.join([''.join([('Love'[(x-y) % len('Love')] if ( (x*0.05)**2 (y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0 else ' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))

Running result



用字符输出 I 爱 U (2款效果)

import time

y = 2.5

while y>=-1.6:

    x = -3.0

    while x<=4.0:

        if (x*x y*y-1)**3<=3.6*x*x*y*y*y or (x>-2.4 and x<-2.1 and y<1.5 and y>-1) or (((x<2.5 and x>2.2)or(x>3.4 and x<3.7)) and y>-1 and y<1.5) or (y>-1 and y<-0.6 and x<3.7 and x>2.2):

            print(' ',end="")

        else:

            print('*',end="")

        x = 0.1

    print()

    time.sleep(0.25)

    y -= 0.2


import time

y = 2.5

while y>=-1.6:

    x = -3.0

    while x<=4.0:

        if (x*x y*y-1)**3<=3.6*x*x*y*y*y or (x>-2.4 and x<-2.1 and y<1.5 and y>-1) or (((x<2.5 and x>2.2)or(x>3.4 and x<3.7)) and y>-1 and y<1.5) or (y>-1 and y<-0.6 and x<3.7 and x>2.2):

            print('*',end="")

        else:

            print(' ',end="")

        x = 0.1

    print()

    time.sleep(0.25)

    y -= 0.2



11.11 From Dear, I love you forever! Five words output five hearts

import time##

If there are Chinese characters in the code, python will report an error when running, and the Chinese cannot be input normally in python, garbled characters, etc.:

Compilation tip: SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0x*** in position 0: ...

Mainly caused by encoding problems.

Affected by different development systems and environments, the solutions will be different, but generally the solution can be solved by following the following methods. If necessary, please try the solution that suits your own system: (Remember, the following You don’t need to add all the methods to the python file, just choose one or two of them to try, which can solve the problem)

In the first line of your python file (.py)

1. Add

ba90b8924b2bc48cb6a17bf2c15503f8

When developing python, please note:

1. If you use pycharm Compile and write python code, pycharm will automatically save it in UTF-8 format by default. If you have modified it accidentally, please right-click on the pycharm work interface-File-Encoding-select UTF-8 encoding----reload- ----reload anyway. If that still doesn't work, try changing the path to all English.

 2. If you use other compilation and writing code tools, please click

Document>>Set File Encoding>>Unicode>>Unicode(UTF -8)

 3.If you use visual studio to compile and write python code,

 Python programming under visual studio 2022, an error will be reported: SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte

 Solution:

Save the Visual studio file Encoding changed to UTF-8:

##---->Unicode (UTF-8 with signature) - code page 65001

For other versions of visual studio, select "Advanced Save Options" in the file menu option

---->Unicode (UTF-8 with signature)- Code page 65001

Set the project character set to utf-8, select the project----right-click----Properties----add character set encoding

Visual Studio Community 2022 - UTF-8 codec issue #6784, please refer to reading:

https://github.com/microsoft /PTVS/issues/6784

## Digression: When making charts with matplotlib (pyplot), the title and axis The Chinese display will be abnormal and a small box will appear, which cannot be displayed normally. In this case, just add the following code to the header of the file:

Output five hearts, respectively from Dear I love you forever! Filled with five words.






sentence = "Dear, I love you forever!"

for char in sentence.split( ):

allChar = []

for y in range(12, -12, -1):

lst = []

lst_con = ''

for x in range(-30, 30):

formula = ((x*0.05)**2 (y*0.1)**2-1)**3 -(x*0.05)**2*(y*0.1)**3

if formula <= 0:

lst_con = char[(x) % len(char)]

else:

lst_con = ' '

lst.append(lst_con)

allChar = lst

print('\n '.join(allChar))

time.sleep(1)




#-*- coding: UTF-8 -*-

import matplotlib.pyplot as plt

import matplotlib as mpl

mpl.rcParams["font.sans-serif"]=["SimHei"]

mpl.rcParams["axes.unicode_minus"]=False

Write the print content to the file.

Sometimes, we will encounter situations where we want to print content not only on the screen, but also saved in a file. Then, we can try to write the print content to the file as follows:

Create the test.py file and enter:

#

Write Input file

code

# coding=utf-8

print("Hello, World!", file=open('file.txt', 'w'))


##Running result

After running, a file.txt file appears in the directory where the test.py file is located. Open the file.txt file and you will find that the content inside is:

Hello, World!

means that our print() writes the file successfully.




#【Related recommendations:

Write file

Code

for i in range (1, 11):

print(i,'\t',i*2,'\t',i*3,'\t',i*4,end='\ n',file=open('file.txt',mode ='a',encoding='utf-8'), flush=False)

Running results

After running, open the file.txt file and you will find that the content inside is:


##1 2 3 4

2 4 6 8

3 6 9 12

4 8 12 16

5 10 15 20

6 12 18 24

7 14 21 28

8 16 24 32

9 18 27 36

10 20 30 40


Indicates that our print() writes the file successfully.




Python3 video tutorial


The above is the detailed content of Detailed explanation of examples of usage of Print() function in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to handle API authentication in Python How to handle API authentication in Python Jul 13, 2025 am 02:22 AM

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

How to parse large JSON files in Python? How to parse large JSON files in Python? Jul 13, 2025 am 01:46 AM

How to efficiently handle large JSON files in Python? 1. Use the ijson library to stream and avoid memory overflow through item-by-item parsing; 2. If it is in JSONLines format, you can read it line by line and process it with json.loads(); 3. Or split the large file into small pieces and then process it separately. These methods effectively solve the memory limitation problem and are suitable for different scenarios.

Python for loop over a tuple Python for loop over a tuple Jul 13, 2025 am 02:55 AM

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

How to make asynchronous API calls in Python How to make asynchronous API calls in Python Jul 13, 2025 am 02:01 AM

Python implements asynchronous API calls with async/await with aiohttp. Use async to define coroutine functions and execute them through asyncio.run driver, for example: asyncdeffetch_data(): awaitasyncio.sleep(1); initiate asynchronous HTTP requests through aiohttp, and use asyncwith to create ClientSession and await response result; use asyncio.gather to package the task list; precautions include: avoiding blocking operations, not mixing synchronization code, and Jupyter needs to handle event loops specially. Master eventl

What is a pure function in Python What is a pure function in Python Jul 14, 2025 am 12:18 AM

Pure functions in Python refer to functions that always return the same output with no side effects given the same input. Its characteristics include: 1. Determinism, that is, the same input always produces the same output; 2. No side effects, that is, no external variables, no input data, and no interaction with the outside world. For example, defadd(a,b):returna b is a pure function because no matter how many times add(2,3) is called, it always returns 5 without changing other content in the program. In contrast, functions that modify global variables or change input parameters are non-pure functions. The advantages of pure functions are: easier to test, more suitable for concurrent execution, cache results to improve performance, and can be well matched with functional programming tools such as map() and filter().

Can a Python class have multiple constructors? Can a Python class have multiple constructors? Jul 15, 2025 am 02:54 AM

Yes,aPythonclasscanhavemultipleconstructorsthroughalternativetechniques.1.Usedefaultargumentsinthe__init__methodtoallowflexibleinitializationwithvaryingnumbersofparameters.2.Defineclassmethodsasalternativeconstructorsforclearerandscalableobjectcreati

what is if else in python what is if else in python Jul 13, 2025 am 02:48 AM

ifelse is the infrastructure used in Python for conditional judgment, and different code blocks are executed through the authenticity of the condition. It supports the use of elif to add branches when multi-condition judgment, and indentation is the syntax key; if num=15, the program outputs "this number is greater than 10"; if the assignment logic is required, ternary operators such as status="adult"ifage>=18else"minor" can be used. 1. Ifelse selects the execution path according to the true or false conditions; 2. Elif can add multiple condition branches; 3. Indentation determines the code's ownership, errors will lead to exceptions; 4. The ternary operator is suitable for simple assignment scenarios.

How to prevent a method from being overridden in Python? How to prevent a method from being overridden in Python? Jul 13, 2025 am 02:56 AM

In Python, although there is no built-in final keyword, it can simulate unsurpassable methods through name rewriting, runtime exceptions, decorators, etc. 1. Use double underscore prefix to trigger name rewriting, making it difficult for subclasses to overwrite methods; 2. judge the caller type in the method and throw an exception to prevent subclass redefinition; 3. Use a custom decorator to mark the method as final, and check it in combination with metaclass or class decorator; 4. The behavior can be encapsulated as property attributes to reduce the possibility of being modified. These methods provide varying degrees of protection, but none of them completely restrict the coverage behavior.

See all articles