gpt4 book ai didi

python - 要求正整数并验证输入的简单函数

转载 作者:行者123 更新时间:2023-12-01 03:32:19 25 4
gpt4 key购买 nike

我只是想创建一个要求正整数的函数,然后验证输入确实是正整数:

def int_input(x):
x = input('Please enter a positive integer:')
if x != type(int()) and x < 1:
print("This is not a positive integer, try again:")
else:
print(x)

int_input(x)

它给我“NameError:名称'x'未定义”。

这太简单了,我觉得我应该找到很多关于这方面的帖子,所以也许我是盲目的......

谢谢!

最佳答案

def int_input():
x = input('Please enter a positive integer:')
if x != type(int()) and x < 1:
print("This is not a positive integer, try again:")
else:
print(x)

int_input()

应该是这样的,不声明x就不能调用函数int_input()

关于python - 要求正整数并验证输入的简单函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40769595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com