深度阅读

How to take integer input in Python?

作者
作者
2023年08月22日
更新时间
11.74 分钟
阅读时间
0
阅读量

To take integer input in Python, you can use the input() function to read the user’s input as a string first, and then use the int() function to convert the string to an integer. Here’s an example:

num = int(input("Enter an integer: "))
print("You entered:", num)

In this example, the input() function reads the user’s input as a string, and the int() function is used to convert the string to an integer. The resulting integer is then stored in the num variable, and printed using the print() function.

Note that if the user enters anything other than an integer, such as a string or a decimal number, the program will throw a ValueError. To handle this, you can use a try-except block to catch the error and handle it appropriately. Here’s an example:

try:
    num = int(input("Enter an integer: "))
    print("You entered:", num)
except ValueError:
    print("Invalid input. Please enter an integer.")

This example uses a try-except block to catch the ValueError that’s raised if the user enters anything other than an integer. If a ValueError is caught, the program will print an error message and prompt the user to enter an integer again.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。