[英]Creating a loop to check a variable to make sure it is a positive integer
I'm trying to create a program that creates a list of the first nth Fibonacci terms. 我正在尝试创建一个程序,该程序创建前n个斐波纳契项的列表。 The program itself works in that it creates the list of Fibonacci numbers.
该程序本身的工作方式是创建斐波那契数字列表。 The problem is that I want to make it check to make sure that n is a positive integer but I do not know how.
问题是我要进行检查以确保n是一个正整数,但我不知道怎么做。
Here's the code: 这是代码:
n = int(input("Please enter the number of Fibonacci numbers you want: "))
def fib(n):
if 0 <= n <= 1:
return 1
else:
return(fib(n-1) + fib(n-2))
if n < 0:
print("Please enter a positive integer")
n = None
fib(n)
else:
for i in range(n):
print(fib(i), end=", ")
ender = input("\nPress enter to end the program\n")
How would I go about creating a loop that removes the negative value of n and asks for it again? 我将如何创建一个删除n负值并再次请求的循环?
Many Thanks 非常感谢
设置n
为-1,然后有一个循环,询问新n
只要当前值n
为负。
To expand a bit on what the others have given you: 进一步介绍其他人给您的东西:
n = -1
while n < 0:
try:
n = int(input("Please enter the number of Fibonacci numbers you want: "))
except ValueError:
continue
Which will handle users who try to sneakily put in values like HELLO
instead of 5
它将处理试图偷偷输入
HELLO
之类的值(而不是5
A good way to go about this is the following: 解决此问题的好方法如下:
n = int(input("Please enter the number of Fibonacci numbers you want: "))
while n < 0:
n = int(input("Bad input! try again: "))
*** do your other things ***
This way, it repeatedly checks until you have good input. 这样,它将反复检查,直到您输入正确。
You can set up a while loop in the beginning of your code: 您可以在代码的开头设置while循环:
n = -1
while n <= 0:
n = int(input("Please enter the number of Fibonacci numbers you want: "))
You can use a boolean variable, you keep looping until you enter a positive number, in this case you turn the value to be False
您可以使用布尔变量,一直循环直到您输入正数,在这种情况下,您将值设为
False
def fib(n):
if 0 == n and n == 1:
return 1
else:
return(fib(n-1) + fib(n-2))
isTrue= True
while isTrue:
n = int(input("Please enter the number of Fibonacci numbers you want: "))
if n < 0:
print("Please enter a positive integer")
else:
isTrue= False
for i in range(n):
print(fib(i), end=", ")
ender = input("\nPress enter to end the program\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.