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

Python SyntaxError: Missing parentheses in call to 'print' - แก้ไข Python 3

ใน Python 3 ต้องล้อม print statements ด้วย parentheses ทุกครั้ง ถ้าพยายามพิมพ์ string ออกคอนโซลโดยไม่ล้อม string ใน parentheses จะเจอ error SyntaxError: Missing parentheses in call to 'print'

คู่มือนี้อธิบาย error นี้หมายถึงอะไร และการใช้ print statement ใน Python พร้อมตัวอย่าง ช่วยเรียนรู้วิธีแก้

SyntaxError: Missing parentheses in call to 'print'

Python 3 เป็น major update คนที่ 3 ของภาษา ในช่วงไม่กี่ปีมา กลายเป็น preferred version ของ Python

Python 3 เปลี่ยนวิธีเขียน print statements Standalone print statement ทำงานใน Python 2 พิมพ์ statement ไปคอนโซล

ใน Python 3 print เป็น function หมายถึงต้องล้อมเนื้อหา string ที่ต้องการพิมพ์คอนโซลใน parentheses เหมือน function call ทั่วไป

ตัวอย่างสถานการณ์ (An Example Scenario)

เขียนโปรแกรมพิมพ์ชื่อนักเรียนชั้นประถม 4 ที่ชื่อขึ้นต้นด้วย "A" เริ่มกำหนดลิสต์ชื่อนักเรียนในชั้น:

students = ["Alex", "Alexander", "Piper", "Molly", "Hannah"]

เขียน for loop วนทุก item ในลิสต์ ใน for loop ใช้ if statement เช็คว่าแต่ละชื่อขึ้นต้น "A" ไหม:

for s in students:
    if s.startswith("A") == True:
        print s

startswith() method เช็คว่า string เริ่มต้นด้วย character หรือชุด characters เฉพาะ โค้ดเช็คว่าแต่ละชื่อใน "students" เริ่มต้น "A" ไหม

เพิ่ม print statement ท้ายโค้ด บอกว่าโปรแกรมรันเสร็จ:

print "Above are all the students whose names begin with A."

พร้อมรันโปรแกรม:

File "main.py", line 5
print s
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(s)?

โค้ดแจ้ง syntax error

วิธีแก้ (The Solution)

Python เองเสนอ solution ใน error message แล้ว

เพราะใน Python 3 versions ก่อน ลืมใส่ parentheses รอบ print statement raise error แค่ "invalid syntax" ข้อความนี้ ambiguous เพราะ invalid syntax เกิดจากหลายปัญหา Python จึง introduce "missing parenthesis" error message ช่วย users

แก้: ล้อมค่าที่ต้องการพิมพ์คอนโซลด้วย parentheses ทุกค่า:

for s in students:
    if s.startswith("A") == True:
        print(s)
print("Above are all the students whose names begin with A.")

ล้อม "s" บน print line ด้วย parentheses ล้อม string ท้ายที่พิมพ์คอนโซลด้วย parentheses รันโปรแกรมดู:

Alex
Alexander
Above are all the students whose names begin with A.

โค้ดแสดงว่ามี 2 นักเรียนชื่อขึ้นต้น A หลังวนลิสต์นักเรียนเสร็จ โปรแกรมพิมพ์ข้อความอธิบาย output

สรุป

Python SyntaxError: Missing parentheses in call to 'print' error เกิดเมื่อพยายามพิมพ์ค่าคอนโซลโดยไม่ล้อมค่านั้นใน parentheses

วิธีแก้: เพิ่ม parentheses รอบ statements ที่ต้องการพิมพ์คอนโซล เพราะใน Python 3 print ไม่ใช่ statement คือ function ต้องเรียก function ด้วย parentheses ถ้าอยากรันมัน

ตอนนี้คุณมีความรู้แก้ Python error พบบ่อยนี้อย่าง pro แล้ว!