Trong bài học này, bạn sẽ học cách kiểm tra đầu vào của người dùng là một số hoặc chuỗi trong Python. Chúng tôi cũng sẽ đề cập đến cách chấp nhận số làm đầu vào từ người dùng. Khi chúng ta nói một số, nó có nghĩa là nó có thể là số nguyên hoặc nổi.
Hiểu đầu vào của người dùng
Python 3 có đầu vào hàm tích hợp [] để chấp nhận đầu vào của người dùng. Nhưng nó không đánh giá dữ liệu nhận được từ hàm
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'0, tức là, hàm
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'0 luôn chuyển đổi đầu vào của người dùng thành một chuỗi và sau đó trả lại cho chương trình gọi.
Hãy cho chúng tôi hiểu điều này với một ví dụ.
number1 = input["Enter number and hit enter "]
print["Printing type of input value"]
print["type of number ", type[number1]]
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'
Như bạn có thể thấy, đầu ra hiển thị loại biến dưới dạng chuỗi [STR].
Giải pháp: Trong tình huống như vậy, chúng ta cần chuyển đổi đầu vào của người dùng một cách rõ ràng thành số nguyên và nổi để kiểm tra xem nó có một số không. Nếu chuỗi đầu vào là một số, nó sẽ được chuyển đổi thành int hoặc float mà không có ngoại lệ.: In such a situation, We need to convert user input explicitly to integer and float to check if it’s a number. If the input string is a number, It will get converted to int or float without exception.
Chuyển đổi đầu vào chuỗi thành int hoặc float để kiểm tra xem nó có phải là số không
Cách kiểm tra xem đầu vào là số hoặc chuỗi trong Python
- Chấp nhận đầu vào từ người dùng
Sử dụng chức năng
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'
0 để chấp nhận đầu vào từ người dùng - Chuyển đổi đầu vào thành số nguyên
Để kiểm tra xem chuỗi đầu vào có phải là số nguyên hay không, hãy chuyển đổi đầu vào của người dùng thành loại số nguyên bằng hàm tạo
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'
3. - Chuyển đổi đầu vào thành số float
Để kiểm tra xem đầu vào có phải là số float hay không, hãy chuyển đổi đầu vào của người dùng thành loại float bằng hàm tạo
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'
4. - Xác nhận kết quả
Nếu đầu vào là số nguyên hoặc số float, nó có thể được chuyển đổi thành công thành loại
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'
5 hoặcOutput Enter number and hit enter 10 Printing type of input value type of number class 'str'
6. Khác, chúng ta có thể kết luận nó là một chuỗi
Lưu ý: Nếu đầu vào là số nguyên hoặc số float, nó có thể được chuyển đổi thành công thành int hoặc float và bạn có thể kết luận rằng đầu vào đã nhập là một số. Mặt khác, bạn có ngoại lệ Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
7, có nghĩa là đầu vào người dùng đã nhập là một chuỗi.: If an input is an integer or float
number, it can successfully get converted to int or float, and you can conclude that entered input is a number. Otherwise, You get a
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'7 exception, which means the entered user input is a string.
Chương trình : :
def check_user_input[input]:
try:
# Convert it into integer
val = int[input]
print["Input is an integer number. Number = ", val]
except ValueError:
try:
# Convert it into float
val = float[input]
print["Input is a float number. Number = ", val]
except ValueError:
print["No.. input is not a number. It's a string"]
input1 = input["Enter your Age "]
check_user_input[input1]
input2 = input["Enter any number "]
check_user_input[input2]
input2 = input["Enter the last number "]
check_user_input[input2]
Output Enter your Age 28 Input is an integer number. Number = 28 Enter any number 3.14 Input is a float number. Number = 3.14 Enter the last number 28Jessa No.. input is not a number. It's a string
- Như bạn có thể thấy ở đầu ra ở trên, người dùng đã nhập 28 và nó được chuyển đổi thành loại số nguyên mà không có ngoại lệ.
- Ngoài ra, khi người dùng nhập 3.14 và nó được chuyển đổi thành loại float mà không có ngoại lệ.
- Nhưng khi người dùng nhập một số với một số ký tự trong đó [28Jessa], Python đã tăng ngoại lệ
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'
8 vì nó không phải là int.
Sử dụng phương thức chuỗi Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
9 để kiểm tra đầu vào của người dùng là số hoặc chuỗi
Lưu ý: Hàm Output
Enter number and hit enter 10
Printing type of input value
type of number class 'str'
9 sẽ chỉ hoạt động cho các số nguyên dương. tức là, nếu bạn vượt qua bất kỳ số float nào, nó sẽ không hoạt động. Vì vậy, tốt hơn là sử dụng phương pháp đầu tiên.: The
Output Enter number and hit enter 10 Printing type of input value type of number class 'str'9 function will work only for positive integer numbers. i.e., if you pass any float number, it will not work. So, It is better to use the first approach.
Hãy để thực hiện chương trình để xác nhận điều này.
def check_is_digit[input_str]:
if input_str.strip[].isdigit[]:
print["User input is Number"]
else:
print["User input is string"]
num1 = input["Enter number and hit enter"]
check_is_digit[num1]
num2 = input["Enter number and hit enter"]
check_is_digit[num2]
Output Enter number and hit enter 45 User input is Number Enter number and hit enter 45Jessa User input is string
Ngoài ra, nếu bạn có thể kiểm tra xem biến Python có phải là số hoặc chuỗi hay không, hãy sử dụng hàm
def check_user_input[input]:
try:
# Convert it into integer
val = int[input]
print["Input is an integer number. Number = ", val]
except ValueError:
try:
# Convert it into float
val = float[input]
print["Input is a float number. Number = ", val]
except ValueError:
print["No.. input is not a number. It's a string"]
input1 = input["Enter your Age "]
check_user_input[input1]
input2 = input["Enter any number "]
check_user_input[input2]
input2 = input["Enter the last number "]
check_user_input[input2]
1.Thí dụ
num = 25.75
print[isinstance[num, [int, float]]]
# Output True
num = '28Jessa'
print[isinstance[num, [int, float]]]
# Output False
Chỉ chấp nhận một số làm đầu vàoaccept a number as input
Hãy để viết một chương trình đơn giản bằng Python để chỉ chấp nhận các số đầu vào từ người dùng. Chương trình sẽ chỉ dừng lại khi người dùng nhập số đầu vào.
while True:
num = input["Please enter a number "]
try:
val = int[num]
print["Input is an integer number."]
print["Input number is: ", val]
break;
except ValueError:
try:
float[num]
print["Input is an float number."]
print["Input number is: ", val]
break;
except ValueError:
print["This is not a number. Please enter a valid number"]
Output Please enter a number 28Jessa This is not a number. Please enter a valid number Please enter a number 28 Input is an integer number. Input number is: 28
Vấn đề thực hành: Kiểm tra đầu vào của người dùng là số dương hoặc âm
Hiển thị giải pháp
user_number = input["Enter your number "]
print["\n"]
try:
val = int[user_number]
if val > 0:
print["User number is positive "]
else:
print["User number is negative "]
except ValueError:
print["No.. input string is not a number. It's a string"]
Bước tiếp theo
Hãy cho tôi biết ý kiến và phản hồi của bạn trong phần dưới đây.
Ngoài ra, giải quyết:
- Bài tập đầu vào và đầu ra của Python
- Đầu vào Python và bài kiểm tra đầu ra
- Bài tập Python cho người mới bắt đầu
- Câu đố Python cho người mới bắt đầu
Bài tập và câu đố Python
Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.
- Hơn 15 bài tập và câu đố dành riêng cho chủ đềTopic-specific Exercises and Quizzes
- Mỗi bài tập chứa 10 câu hỏi
- Mỗi bài kiểm tra chứa 12-15 mcq