Module 3b

Input / Output and f-string

วันนี้เราจะเรียนรู้ 🚀

  1. Input / Outputinput(), print()
  2. การแปลงชนิดข้อมูลจาก input()
  3. input().split() — รับหลายค่าพร้อมกัน
  4. f-string — จัดรูปแบบการแสดงผล
name = input("What's your name? ")
gpa = float(input("Your GPA? "))
print(f"Hi {name}, your GPA is {gpa:.2f}")

Note

ต่อจาก Module 3a — Variables, Operators, Math 👈

Input / Output ⌨️

รับข้อมูลจาก user — แสดงผลออกจอ

input() — รับข้อมูลจาก user

a = input()
  • ข้อมูลจาก input() เป็น str เสมอ
  • ต้องแปลงชนิดเอง ถ้าต้องการ number
# รับ string
name = input()

# รับ int
age = int(input())

# รับ float
gpa = float(input())

Warning

int(input()) การเขียนแบบนี้ = assume ว่าสิ่งที่ผู้ใช้พิมพ์เข้ามา แปลงเป็น int ได้

Important

⚠️ input() จะไม่ทำงานบนสไลด์ — ดังนั้นในช่อง Live Code เราจะจำลองค่าด้วย string แทนการรับจาก user จริง (เช่น x = '5') ถ้านำไปรันบนเครื่องจริงให้เปลี่ยนกลับเป็น input() ได้เลย

input() พร้อมข้อความแจ้ง user

แสดงข้อความถาม user ขณะรอรับข้อมูล

name = input('Please enter your name: ')
print('My name is', name)
Please enter your name: Somchai
My name is Somchai

โจทย์ #33

รับค่าตัวเลขจาก user เก็บในตัวแปร x — ตรวจสอบ type ของ x

จากนั้นคำนวณ \(y = x^3\) โดยให้ y เป็น float

x = input()
print(type(x))         # ได้อะไร?
<class 'str'>

input() ได้ string เสมอ — ต้องแปลงก่อนคำนวณ!

x = float(x)
y = x ** 3
print(y, type(y))

โจทย์ #34

รับชื่อเล่นจาก user แล้วแสดงผลว่า Hello, (ชื่อเล่น). Nice to meet you!

เงื่อนไข: ใช้ operator +

nkname = input('Please enter your nickname: ')
print('Hello, ' + nkname + '. Nice to meet you!')
Please enter your nickname: Ploy
Hello, Ploy. Nice to meet you!

input().split() — รับหลายค่าพร้อมกัน

ถ้าต้องการรับข้อมูลหลายค่าพร้อมกัน (คั่นด้วยช่องว่าง)?

fname, lname = input('Enter your name: ').split()
  • .split() ตัดข้อความด้วย ช่องว่าง (space)
  • 'John Doe''John' กับ 'Doe'

Warning

จำนวนตัวแปรต้องพอดี กับจำนวนคำที่ split ได้!

ถ้าพิมพ์ 3 คำ แต่มีแค่ 2 ตัวแปร → ValueError

Note

คำสั่ง .split() ถ้าตามหลัง string จะแยก string ที่คั่นด้วย whitespace ออกจากกัน เช่น

'John Doe'.split()'John' กับ 'Doe'
'Happy New\tYear'.split()'Happy' กับ 'New' กับ 'Year'

โจทย์ #35

รับ ชื่อ และ นามสกุล จาก user (คั่นด้วยช่องว่าง)

ก่อนที่จะรับค่า ให้แสดงข้อความว่า

Please enter your name and last name (separate with one space):

แล้วแสดงผล Hello,(name). Your Last Name is (lastname)

เงื่อนไข: ใช้เครื่องหมาย + ในการเชื่อม string

name, lastname = input(
    'Please enter your name and last name (separate with one space): '
).split()
print('Hello,' + name + '. Your Last Name is ' + lastname)
Enter your name and last name: Somchai Jaidee
Hello,Somchai. Your Last Name is Jaidee

โจทย์ #36: ชวนคิด

ถ้าใช้ input() โดยไม่มี .split() แล้วป้อน John Doe

จะได้ผลเหมือน input().split() หรือไม่?

👉 คลิกเพื่อดูเฉลย

ไม่เหมือน!

  • name = input()name = 'John Doe' (ทั้ง string)
  • name, lname = input().split()name = 'John', lname = 'Doe' (แยก 2 ตัว)

พักสมอง 😄

ข้อมูลจาก user อาจไม่เป็นอย่างที่เราคิด — ตรวจสอบเสมอ!

ที่มา: xkcd #327 — “Exploits of a Mom” (CC BY-NC 2.5)

f-string ✨

การจัดรูปแบบการแสดงผล — f'...{var}...'

f-string คืออะไร?

ใช้ f นำหน้า string แล้วแทรกค่าตัวแปรด้วย {}

num1 = 83
num2 = 9
print(f"The product of {num1} and {num2} is {num1 * num2}.")
The product of 83 and 9 is 747.

Important

ถ้าไม่มี f นำหน้า string ก็จะกลายเป็น string ธรรมดา และ {} ก็จะไม่มีความหมายพิเศษ

f-string vs concatenation

โจทย์ #38 — สองวิธีนี้ให้ผลเหมือนหรือต่างกัน?

print('Hello,' + name + '. Your last name is ' + lastname)
print(f'Hello,{name}. Your last name is {lastname}')

ได้ผล เหมือนกัน — แต่ f-string อ่านง่ายกว่ามาก!

f-string — Format Specifiers

กำหนด format specifier ต่อท้ายตัวแปรใน {} ด้วยเครื่องหมาย : เช่น {var:.2f} เพื่อจัดรูปแบบการแสดงผล

ทศนิยม :.Nf

pi = 3.14159265
print(f'{pi:.2f}')
print(f'{pi:.4f}')
3.14
3.1416

ความกว้าง :N (N = จำนวนตัวอักษร)

a = 3
print(f'We have {a:5} dogs.')
We have     3 dogs.

ข้อความ → ชิดซ้าย

a = 'CMU'
print(f'I love ❤︎⁠{a:6}❤︎⁠')
I love ❤︎⁠CMU   ❤︎⁠

ตัวเลข → ชิดขวา

a = 555
print(f'I love ❤︎⁠{a:6}❤︎⁠')
I love ❤︎⁠   555❤︎⁠

ถ้าอยากบังคับให้ก็ทำได้ {:>N} (ชิดขวา), {:<N} (ชิดซ้าย), {:^N} (กึ่งกลาง)

โจทย์ #37

แสดงชื่อและเกรด Hello, (name). You get GPA (grade).

โดยใช้ f-string

gpa = '4'            # Don't change this line
name = 'Somchai'     # Don't change this line
print(f'Hello, {name}. You get GPA {int(gpa):.2f}.')
Hello, Somchai. You get GPA 4.00.

โจทย์ #39

รับค่าส่วนสูงของนักเรียน 2 คน (a, b), หาค่าเฉลี่ย แล้วแสดงผลด้วย f-string

เงื่อนไข: แก้เฉพาะบรรทัดที่ 3 (ใน print()) เท่านั้น และพิมพ์ทศนิยม 4 ตำแหน่ง

a, b = input().split()
a = float(a)
b = float(b)
print(f'Average height = {(a+b)/2:.4f}.')
Average height = 167.5000.

Summary 🎯

สรุป Module 3b 🎉

Input / Output

  • input() — ได้ str เสมอ
  • int(input()), float(input()) — แปลงชนิดก่อนคำนวณ
  • input().split() — รับหลายค่าพร้อมกัน
  • print() — แสดงผลออกจอ

f-string

  • f'...{var}...' — แทรกค่าตัวแปรด้วย {}
  • อ่านง่ายกว่า concatenation (+)
  • Format specifiers
    • {x:.2f} — ทศนิยม 2 ตำแหน่ง
    • {x:5} — กำหนดความกว้าง