擅长:python、mysql、java
<p>将<code>try/except</code>放入循环中。在</p>
<pre><code>while True:
try:
n = int(input("How many numbers to sum up?: "))
if n <= 0:
print("You have to write a positive integer; try again!")
continue
break
except ValueError:
print("You have to write a positive integer; try again!")
</code></pre>
<p>您还可以将代码的最后一部分(第一个循环之后的部分)替换为:</p>
^{pr2}$
<p>但是不建议使用lambda <code>;)</code>。当然,您可以使用普通函数:</p>
<pre><code>def squares(x):
print('{0} * {0} = {1}'.format(x, x**2))
return x**2
</code></pre>