Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

In biến đơn và nhiều biến trong Python (print)

Khác biệt lớn giữa Python 2 và Python 3: print là statement (Py2) vs function (Py3).

Python 2.7

# In biến đơn
print 27           # 27
print "Rahul"      # Rahul

# In biến đơn với ngoặc (được coi là tuple 1 phần tử)
print(27)          # 27
print("Rahul")     # Rahul

# In nhiều biến
print 27, 54, 81          # 27 54 81
print (27, 54, 81)        # (27, 54, 81) -> IN RA TUPLE!
print ("Rahul", "Raj")    # ('Rahul', 'Raj') -> TUPLE!

Python 3.x

# BẮT BUỘC dùng ngoặc
print(27)           # 27
print("Rahul")      # Rahul

# In nhiều biến
print(27, 54, 81)           # 27 54 81
print("Rahul", "Raj", "Rajesh")  # Rahul Raj Rajesh

# Tùy chỉnh separator và end
print(27, 54, 81, sep=' | ', end='\n\n')
# 27 | 54 | 81

# In không newline
print("Loading", end=' ')
print("...")  # Loading ...

So sánh nhanh

Đặc điểmPython 2Python 3
print xOKSyntaxError
print(x)OK (tuple nếu nhiều arg)OK (function)
print x, yOK (space separated)SyntaxError
print(x, y)In tuple (x, y)In x y (space separated)
sep/end paramKhôngCó
file paramKhông (dùng >>)Có (print(..., file=sys.stderr))

Best Practice (Python 3)

  • Luôn dùng print(...) với ngoặc.
  • Dùng sep, end, file để kiểm soát output.
  • Format string: print(f"{x} {y}") hoặc print("{} {}".format(x, y)).

Ví dụ nâng cao

import sys

# In ra stderr
print("Error!", file=sys.stderr)

# In không flush (buffered)
print("Processing...", end='', flush=True)

# In nhiều dòng
print("Line 1\nLine 2\nLine 3")

# Unpacking trong print
items = ['apple', 'banana', 'cherry']
print(*items, sep=', ')  # apple, banana, cherry