我是Python的新学习者。我有一个关于while循环的问题。 我在下面写了一个程序来寻找平方根。 当我输入除整数之外的任何内容时,消息"不是整数"显示并重复,直到我输入正确的数据(整数)。
我的问题是,为什么它在第5行返回值时返回循环,返回(int(val))?
感谢您的关注。
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
答案 0 :(得分:-1)
要回答原始问题,请返回'有效地退出循环并提供“返回”后的结果。声明,但你必须明确打印它:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
如果你只是简单地说'read_int(12,14)'而不是' print(read_int(12,15))'在这种情况下,你不会打印任何东西,但你会退出循环。
如果您允许我,以下是对原始代码的一些修改:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
最后的&#39;打印&#39;您实际拥有的代码,在程序中输入一串文本会产生错误。现在它没有;)。希望这在某些方面很有用。祝你有美好的一天!