1. 直接使用数字表示:
x = 10 定义一个整数变量x,赋值为10
y = -5 定义一个整数变量y,赋值为-5
2. 使用`int()`函数将其他类型的值转换为整数:
x = int(3.14) 将浮点数3.14转换为整数,结果为3
3. 使用`str.isdigit()`方法判断字符串是否为整数:
while True:
x = input('Input an integer: ')
if x.isdigit():
break
else:
print('Please input an integer')
4. 使用`try-except`语句捕获`ValueError`异常:
while True:
try:
x = input('Input an integer: ')
x = int(x)
break
except ValueError:
print('Please input an integer')
5. 使用`abs()`函数计算整数的绝对值:
x = abs(-5) 计算-5的绝对值,结果为5
6. 使用`int()`方法将字符串转换为整数:
x = int('10') 将字符串'10'转换为整数,结果为10
Python的整数类型是无限精度的,可以表示任意大的整数