Python มีฟังก์ชัน built-in สองฟังก์ชันสำหรับอ่านบรรทัดข้อความจาก standard input ซึ่งโดยค่าเริ่มต้นมาจากคีย์บอร์ด ฟังก์ชันเหล่านี้คือ:
- raw_input
- input
ฟังก์ชัน raw_input
ฟังก์ชัน raw_input([prompt]) อ่านหนึ่งบรรทัดจาก standard input และคืนค่าเป็นสตริง (ตัด trailing newline ออก)
#!/usr/bin/python
str = raw_input("Enter your input: ")
print "Received input is : ", str
นี่จะพรอมพ์ให้คุณป้อนสตริงใดๆ และจะแสดงสตริงเดียวกันบนหน้าจอ เมื่อฉันพิมพ์ "Hello Python!" ผลลัพธ์จะเป็นแบบนี้:
Enter your input: Hello Python
Received input is : Hello Python
ฟังก์ชัน input
ฟังก์ชัน input([prompt]) เทียบเท่ากับ raw_input ยกเว้นว่ามันสมมติว่า input เป็นนิพจน์ Python ที่ถูกต้องและคืนค่าผลลัพธ์ที่ประเมินแล้วให้คุณ
#!/usr/bin/python
str = input("Enter your input: ")
print "Received input is : ", str
นี่จะให้ผลลัพธ์ดังต่อไปนี้สำหรับ input ที่ป้อน:
Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]