Nhập xuất (input/output) cơ bản trong Python

Đây là bài 8/54 bài của series môn học Ngôn ngữ lập trình Python

1. Nhập (input) trong Python

Python cung cấp sẵn hàm input() để giúp chúng ta nhập dữ liệu cần thiết từ bàn phím cho chương trình. Ví dụ:

val = input("Enter your value: ")
print(val)
num = input ("Enter number: ")
print(num)
name1 = input("Enter name: ")
print(name1)
  
# Printing type of input value
print ("type of val is ", type(val))
print ("type of num is ", type(num))
print ("type of name1 is ", type(name1))
Kết quả
Enter your value: 5
5
Enter number: 9
9
Enter name: gochocit.com
gochocit.com
type of val is  <class 'str'>
type of num is  <class 'str'>
type of name1 is  <class 'str'>

Khi hàm input() thực thi, luồng chương trình sẽ bị dừng lại cho đến khi người dùng nhập ký tự gì đó vào.

Lưu ý: Bất cứ thứ gì chúng ta nhập vào, hàm input() sẽ chuyển đổi nó thành một chuỗi. Nếu chúng ta nhập một số nguyên thì hàm input() vẫn chuyển nó thành một chuỗi. Do đó, chúng ta có thể chuyển đổi sang kiểu dữ liệu số với các hàm được hỗ trợ sẵn trong Python. Ví dụ:

val = input("Enter your value:")
num = input ("Enter number:")
name1 = input("Enter name:")

# Convert data type
val = int(val)
print(val)
num = float(num)
print(num)
print(name1)

# Printing type of input value
print ("type of val is ", type(val))
print ("type of num is ", type(num))
print ("type of name1 is ", type(name1))
Kết quả
Enter your value:5
Enter number:9
Enter name:gochocit.com
5
9.0
gochocit.com
type of val is  <class 'int'>
type of num is  <class 'float'>
type of name1 is  <class 'str'>

Chúng ta cũng có thể chuyển đổi input() thành integer, float string như sau:

# input
print("input integer:")
num1 = int(input())
num2 = int(input())
  
# printing the sum in integer
print("sum of num1 and num2 = ", num1 + num2)

# input
print("input float:")
num1 = float(input())
num2 = float(input())
  
# printing the sum in float
print("sum of num1 and num2 = ", num1 + num2)

# input
print("input string:")
string = str(input())
  
# output
print(string)
Kết quả
input integer:
5
2
sum of num1 and num2 =  7
input float:
2.1
5.0
sum of num1 and num2 =  7.1
input string:
gochocit.com
gochocit.com

Nhập nhiều giá trị từ user trong Python

Sử dụng hàm split()

Giúp nhận được nhiều giá trị nhập vào từ user. Mỗi giá trị được cách nhau bởi một dấu phân cách (separator). Mặc định, separator là khoảng trắng. Cú pháp:

input().split(separator, maxsplit)

Trong đó, separator là dấu phân cách, mặc định là khoảng trắng. Tham số maxsplit là số giá trị tối đa được nhập vào từ user.

Ví dụ:

# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)

# taking two inputs at a time with comma (,)
x, y = input("Enter two values: ").split(",")
print("Number of boys: ", x)
print("Number of girls: ", y)

# taking three inputs at a time
x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
 
# taking two inputs at a time
a, b = input("Enter two values: ").split()
print("First number is {} and second number is {}".format(a, b))
 
# taking multiple inputs at a time
# and type casting using list() function
x = list(map(int, input("Enter multiple values: ").split()))
print("List of numbers: ", x)
Kết quả
Enter two values: 5 9
Number of boys:  5 
Number of girls:  9
Enter two values: 5,9
Number of boys:  5
Number of girls:  9
Enter three values: 1 7 3
Total number of students:  1
Number of boys is :  7
Number of girls is :  3
Enter two values: 9 8
First number is 9 and second number is 8
Enter multiple values: 7 8 1 2 3
List of numbers:  [7, 8, 1, 2, 3]

Sử dụng list comprehension

Đây là cách đơn giản đề tạo một list trong Python. Nhưng chúng ta cũng có thể sử dụng để nhập nhiều giá trị vào chương trình từ user.

# taking two input at a time
x, y = [int(x) for x in input("Enter two values: ").split()]
print("First Number is: ", x)
print("Second Number is: ", y)

# taking three input at a time
x, y, z = [int(x) for x in input("Enter three values: ").split()]
print("First Number is: ", x)
print("Second Number is: ", y)
print("Third Number is: ", z)
 
# taking two inputs at a time
x, y = [int(x) for x in input("Enter two values: ").split()]
print("First number is {} and second number is {}".format(x, y))
 
# taking multiple inputs at a time
x = [int(x) for x in input("Enter multiple values: ").split()]
print("Number of list is: ", x)
Kết quả
Enter two values: 5 9
First Number is:  5 
Second Number is:  9
Enter three values: 5 7 9
First Number is:  5
Second Number is:  7
Third Number is:  9
Enter two values: 1 2
First number is 1 and second number is 2
Enter multiple values: 1 5 7 8 9
Number of list is:  [1, 5, 7, 8, 9]

2. Xuất (output) trong Python

Python hỗ trợ sẵn hàm print() để in dữ liệu ra màn hình. Cú pháp:

print(value(s), sep= ‘ ‘, end = ‘\n’, file= sys.stdout, flush=False)

Trong đó:

  • value(s): các giá trị sẽ được chuyển thành chuỗi để in ra màn hình.
  • sep=’ ’: tham số tùy chọn, có thể có hoặc không. Xác định dấu phân cách giữa các value muốn in ra trong trường hợp có nhiều value. sep mặc định là ’ ‘.
  • end=’\n’: tham số tùy chọn, có thể có hoặc không. Xác định ký tự được in ra cuối cùng. end mặc định là ‘\n’.
  • file: tham số tùy chọn, có thể có hoặc không. Xác định đối tượng nhận value để in ra. Mặc định là sys.stdout (được in ra màn hình).
  • flush: tham số tùy chọn, có thể có hoặc không. Nếu là True thì không lưu value vào bộ nhớ đệm. Nếu là False thì lưu value vào bộ nhớ đệm. Mặc định là False.

Ví dụ:

print("Gochocit.com")
print("Welcome to \n Gochocit.com")
print("Hello!", end= "**")
print("Welcome to Gochocit.com")
b = "to"
print("Welcome", b, "Gochocit.com")
print("Welcome", b, "Gochocit.com", sep="-")
x = 5
print("x =", x)
Kết quả
Gochocit.com
Welcome to 
 Gochocit.com
Hello!**Welcome to Gochocit.com
Welcome to Gochocit.com
Welcome-to-Gochocit.com
x = 5

Xuất (output) với định dạng (format)

Chúng ta có thể định dạng giá trị xuất lên màn hình với hàm str.format().

x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))
Kết quả
The value of x is 5 and y is 10
I love bread and butter
I love butter and bread

Trong ví dụ trên, chúng ta sử dụng dấu ngoặc nhọn {} đánh dấu giữ chổ giá trị được in ra. Chúng ta cũng có thể chỉ định thứ tự mà các giá trị được in ra với các chỉ số.

Chúng ta có thể sử dụng các đối số là các từ khóa do chúng ta tự định nghĩa để định dạng chuỗi.

print('Hello {name}, {greeting}'.format(greeting = 'Welcome to Gochocit.com', name = 'John'))
Kết quả
Hello John, Welcome to Gochocit.com

Chúng ta cũng có thể định dạng chuỗi giống như hàm printf() trong ngôn ngữ C++ với toán tử %.

x = 12.3456789
print('The value of x is %3.2f' %x)
print('The value of x is %3.4f' %x)
y = 5
name = "Gochocit.com"
print("num = %d" %y);
print("My name is %s" %name);
Kết quả
The value of x is 12.35
The value of x is 12.3457
num = 5
My name is Gochocit.com

Ở bài này, chúng ta đã tìm hiểu về nhập xuất (input/output) cơ bản trong Python. Ở bài tiếp theo, chúng ta sẽ tìm hiểu về bộ nhớ biến và quản lý bộ nhớ trong Python.

5/5 - (2 bình chọn)
Bài trước và bài sau trong môn học<< Các loại toán tử (operator) được hỗ trợ trong PythonBộ nhớ biến và quản lý bộ nhớ trong Python >>
Chia sẻ trên mạng xã hội:

Trả lời

Lưu ý:

1) Vui lòng bình luận bằng tiếng Việt có dấu.

2) Khuyến khích sử dụng tên thật và địa chỉ email chính xác.

3) Mọi bình luận trái quy định sẽ bị xóa bỏ.