Python : คำสั่งเบื้องต้น print/input

<< Python

คำสั่งเบื้องต้น เริ่มต้นที่คำสั่งแสดงผลเลยครับกับ print

1. คำสั่ง print เป็นคำสั่งสำหรับใช้แสดงผลบนคอมมาไลน์ มีไวยากรณ์ดังนี้

เป็นคำสั่งใช้ในการแสดงผล แสดงข้อมูลบนคอมมาไลน์

print(ตัวแปรหรือข้อมูล)

ตัวอย่างเช่น

print(1,2,3)

ผลลัพธ์ 1 2 3

print("python")

ผลลัพธ์ Hello

a = "python"
print(a)

ผลลัพธ์ python

คำสั่ง input เป็นคำสั่งสำหรับรับข้อมูลจากแป้นพิมพ์ โดยรับทางคอมมาไลน์มีไวยากรณ์ดังนี้

input(ข้อความชนิดstring)

ตัวอย่างเช่น

a = input("Text :")
Text :Hello
print(a)

ผลลัพธ์ Hello

คำสั่ง round เป็นคำสั่งสำหรับใช้ปัดตัวเลข  มีไวยากรณ์ดังนี้

round(ตัวเลขจำนวนจริง)

ตัวอย่างเช่น

round(9)

ผลลัพธ์ 9

round(9.5)

ผลลัพธ์ 9

round(1.6)

ผลลัพธ์ 2

round(-0.1)

ผลลัพธ์ 0

round(-0.7)

ผลลัพธ์ -1

คำสั่ง sum เป็นคำสั่งสำหรับใช้หาผลรวม มีไวยากรณ์ดังนี้

sum(ข้อมูลตัวเลข)
sum(ข้อมูลตัวเลข, ค่าเริ่มต้น)

ตัวอย่างเช่น

sum([5,5,2])
ผลลัพธ์ 12
sum([1,1,1],20)
ผลลัพธ์ 23

คำสั่ง  print (ปริ้น) หลายๆบรรทัด ในภาษาไพธอน

โดยปกติแล้วเวลาเราจะแสดงข้อความอะไรออกหน้าจอเรามักจะพิมพ์คำสั่งให้จบภายในบรรทัดเดียว

ตัวอย่าง

print("When tomorrow comes I'll be on my own Feeling frightened of The things that I don't know When tomorrow comes Tomorrow comes Tomorrow comes")

ดังตัวอย่างข้างบนเราจะเห็นว่าถ้าเราเขียนให้จบภายในบรรทัดเดียวจะยากแก่การอ่านเราสามารถแบ่งข้อความแต่ยังอยู่ในคำสั่งเดียวกันได้เราสามารถเขียนได้ดังนี้

print("""When tomorrow comes
I'll be on my own
Feeling frightened of
The things that I don't know
When tomorrow comes
Tomorrow comes
Tomorrow comes""")

 

ผลการรัน

When tomorrow comes
I'll be on my own
Feeling frightened of
The things that I don't know
When tomorrow comes
Tomorrow comes
Tomorrow comes


ที่มา :

https://www.mindphp.com/developer/tips-python/4299-basic-commands-in-python-part-1-print-input-sum-type.html

https://arnondora.in.th/printing-python-from-zero-to-hero/