Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Print Single และ Multiple Variables ใน Python (Python 2 vs 3)

การ Print ใน Python 2 และ Python 3 แตกต่างกันอย่างมาก

Python 2.7 (Legacy)

Print Single Variable

>>> print 27
27
>>> print "Rahul"
Rahul
>>> print(27)      # กำลังทำงาน (ถือเป็น Tuple 1 Element)
27
>>> print("Rahul")
Rahul

Print Multiple Variables

>>> print 27, 54, 81
27 54 81
>>> print (27, 54, 81)    # ถือเป็น Tuple!
(27, 54, 81)
>>> print ("Rahul", "Raj", "Rajesh")  # Tuple
('Rahul', 'Raj', 'Rajesh')

ใน Python 2 print เป็น Statement ไม่ใช่ Function การใส่ Parentheses ทำให้กลายเป็น Tuple

Python 3.x (Current Standard)

Print Single Variable

>>> print 27
SyntaxError: Missing parentheses in call to 'print'
>>> print(27)
27
>>> print("Rahul")
Rahul

ใน Python 3 print() เป็น Function ต้องมี Parentheses เสมอ

Print Multiple Variables

>>> print(27, 54, 81)
27 54 81
>>> print("Rahul", "Raj", "Rajesh")
Rahul Raj Rajesh

ควบคุม Separator และ End Character

>>> print("A", "B", "C", sep=" | ")
A | B | C
>>> print("Line 1", end=" --- ")
>>> print("Line 2")
Line 1 --- Line 2

ความแตกต่างสรุป

FeaturePython 2Python 3
Print TypeStatementFunction
ParenthesesOptionalRequired
Multiple Argsprint a, bprint(a, b)
Tuple with ()print (a, b) → Tupleprint((a, b)) → Tuple
sep/end paramsไม่รองรับรองรับ
UnicodeASCII DefaultUnicode Default

Best Practices สำหรับ Python 3

# Basic
print(value)

# Multiple with custom separator
print(a, b, c, sep=', ')

# No newline
print("Loading...", end=' ', flush=True)

# Format Strings (f-strings - Python 3.6+)
name = "John"
age = 30
print(f"Name: {name}, Age: {age}")

# Print to file
with open('log.txt', 'w') as f:
    print("Log entry", file=f)

Migration จาก Python 2 → 3

  • เพิ่ม Parentheses ทุก print
  • ใช้ from __future__ import print_function ใน Python 2.6+ เพื่อทดสอบ
  • เครื่องมือ 2to3 ช่วย Convert อัตโนมัติ