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

วิธีใช้ if-else statement ที่ command line ใน Python

มีหลายวิธีในการใช้ if-else construct ใน command line ของ Python ตัวอย่างเช่น bash รองรับ multiline statements ซึ่งใช้ได้ดังนี้:

$ python -c '
> a = True
> if a:
> print("a is true")
> '

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

a is true

หากต้องการให้คำสั่ง Python อยู่บรรทัดเดียว สามารถใช้ \n newline ระหว่างคำสั่งได้ ตัวอย่างเช่น

$ python -c $'a = True\nif a: print("a is true");'

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

a is true