Python Interactive

Programming Concept

เริ่มเขียนโปรแกรม

ให้มีการโต้ตอบกับผู้ใช้

  • input()

  • print()

myName = input("Please enter your name: ")
myAge = input("What about your age: ")

print ("Hello World, my name is", myName, "and I am", myAge, "years old.")

เมื่อรันโปรแกรม โปรแกรมจะถามชื่อของคุณ

Please enter your name:

สมมติ ให้ผู้ใช้งานพิมพ์ชื่อตนเองว่า กฤษณ์ จากนั้นกดปุ่ม Enter โปรแกรมจะถามข้อมูลอายุของคุณต่อ

What about your age:

ผู้ใช้งานกรอกเลขอายุ 20 โปรแกรมจะแสดงข้อความ

Hello World, my name is กฤษณ์ and I am 20 years old.

myName

myAge

input()

คำสั่ง - ฟังก์ชั่น

  1. รับค่าข้อมูลจากแป้นพิมพ์ มาเก็บในตัวแปรที่ระบุ

  2. ค่าข้อมูลที่รับเข้ามาเป็นประเภทข้อมูลอักขระ (String) โดยอัตโนมัติ

  3. จากตัวอย่างแรก

myAge = input("Hi %s, what about your age: " %(myName))

% formatter

myAge = input("Hi {}, what about your age: ".format(myName))

format()

print()

คำสั่ง - ฟังก์ชั่น

  1. ใช้สำหรับแสดงข้อมูลไปยังผู้ใช้งาน

  2. ผู้ใช้งานสามารถระบุข้อมูลที่ต้องการสื่อสาร (arguments) ได้ตั้งแต่ 1 ข้อมูลขึ้นไป โดยใช้เครื่องหมาย , เป็นตัวกำหนด

     

  3. จาก ตย. โค้ด พบว่ามีการส่งผ่านข้อมูลจำนวน 5 ข้อมูลผ่านคำสั่งฟังก์ชั่น print() ลองบอกว่ามีอะไรบ้าง ?

print ("Hello World, my name is", myName, "and I am", myAge, "years old.")
print ("Hello World, my name is %s and I am %s years old." %(myName, myAge))

% formatter

%s ข้อความ

%d เลขจำนวนเต็ม

%f เลขจำนวนทศนิยม

print ("Hello World, my name is {} and I am {} years old".format(myName, myAge))

format()

print (f"Hello World, my name is {myName} and I am {myAge} years old")

F String

''' หรือ """

สำหรับการแสดงผลข้อความที่ยาว

print ('''Hello World.
My name is James and
I am 20 years old.''')
Hello World.
My name is James and
I am 20 years old.

ผลการรัน...

\ (Escape Character)

การใช้สัญญลักษณ์ \ พิเศษ

  • \t

print ('ข้อมูลส่วนตัวของท่าน')
print ('ชื่อ\tกฤษณ์ ท.')
print ('ที่ทำงาน\tวท.ศรีวรการ')
ข้อมูลส่วนตัวของท่าน
ชื่อ	กฤษณ์ ท.
ที่ทำงาน	วท.ศรีวรการ

\ (Escape Character)

การใช้สัญญลักษณ์ \ พิเศษ

  • \n

print ('ข้อมูลส่วนตัวของท่าน')
print ('ชื่อ\tกฤษณ์ ท.\nที่ทำงาน\tวท.ศรีวรการ')
ข้อมูลส่วนตัวของท่าน
ชื่อ	กฤษณ์ ท.
ที่ทำงาน	วท.ศรีวรการ

\ (Escape Character)

การใช้สัญญลักษณ์ \ พิเศษ

  • \\

print ('\\ข้อมูลส่วนตัวของท่าน\\')
\ข้อมูลส่วนตัวของท่าน\

\ (Escape Character)

การใช้สัญญลักษณ์ \ พิเศษ

  • \"


     

  • \'

print ("I am 5'9\" tall")
I am 5'9" tall
print ('I am 5\'9" tall')
I am 5'9" tall

\ (Escape Character)

การใช้สัญญลักษณ์ \ พิเศษ

  • \t

  • \n

  • \\

  • \"

  • \'

Aj. Krit Th.

https://www.kritth.com

20204-2107 Python Inteactive

By Krit Th.

20204-2107 Python Inteactive

  • 45