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

วิธีเขียน inline if statement สำหรับ print ใน Python

Python มี 2 วิธีในการเขียน inline if statements:

  1. if condition: statement
  2. s1 if condition else s2

โปรดทราบว่า type ที่ 2 ไม่สามารถใช้โดยไม่มี else ได้ ตอนนี้คุณสามารถใช้ inline ใน print statement ได้ ตัวอย่างเช่น

a = True
if a: print("Hello")

จะได้ผลลัพธ์:

Hello
a = False
print("True" if a else "False")

จะได้ผลลัพธ์:

False