I'm trying to create a program that creates a list of the first nth Fibonacci terms. 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.
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?
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
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:
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
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.