繁体   English   中英

如何在 Python 中编写一个 for 循环以反复要求用户输入一个数字,直到他们输入一个整数(0、1、2 等)?

[英]How do I write a for loop in Python to repeatedly ask the user to enter a number until they enter in a whole number (0, 1, 2, etc)?

我知道如何使用 while 循环来执行此操作,并且知道如何在其他语言中使用 for 循环,例如 Java 和 C++。 我想使用一个 for 循环来代替我编写的 while 循环询问用户输入的地方。

# You are required to use for-loop to solve this and round your answer to 2 decimal places. Write
    # a program that takes n ∈ N (i.e., any positive integer including zero) from the user and use the
    # input value to compute the sum of the following series:
    
    n = -1
    while n < 0:
        n = int(input("Enter a value to compute: "))
        # keep asking for user input until a whole number (0, 1, 2, 3, etc...) has been entered
    k = 0
    sum = 0
    # To hold the sum of the fraction to be displayed
    lastTerm = 0
    # This variable represents the last term to be added to the fraction sum before the while loop below terminates
    
    if n == 0:
        sum = 0
    elif n == 1:
        sum = 1
    else:
        while lastTerm != 1 / n:
            lastTerm = (n - k) / (k + 1)
            sum = sum + (n - k) / (k + 1)
            k += 1
    print("{:.2f}".format(sum))
    # Print the sum to two decimal places

使用它来检查整数 -

if num < 0:
   # Not a whole number

elif num >= 0:
   # A whole number

对于for loop

import itertools

for _ in itertools.repeat([]):  # An infinite for loop
    num = input('Enter number : ')
    if num < 0:
       # Not a whole number
       pass # This will ask again
    
    elif num >= 0:
       # A whole number
       break  # break from for loop to continue the program

更简单的方法-

mylist = [1]
for i in mylist :  # infinite loop
    num = int(input('Enter number : '))
    if num < 0:
       mylist.append(1)
       pass # This will ask again

    
    elif num >= 0:
       # A whole number
       break

一种选择是捕获当您无法将输入转换为 int 时引发的异常,即

while(True):
    try:
        # read input and try and covert to integer
        n = int(input("Enter a value to compute: "))

        # if we get here we got an int but it may be negative
        if n < 0:
            raise ValueError
        
        # if we get here we have a non-negative integer so exit loop
        break
    # catch any error thrown by int()
    except ValueError:
        print("Entered value was not a postive whole number")

另一种选择,稍微干净一些,但我不是 100% 确定 isdigit() 将涵盖所有情况

while(true):
    n = input("Enter a value to compute: ")
    if value.isdigit():
        break
    else:
        print("Entered value was not a postive whole number")

这个怎么样? 它使用for循环并对列表中的所有值求和。

x=[1,2,3,4] #== test list to keep the for loop going 
sum_list=[]
for i in x:
    j=float(input("Enter a number: "))
    if not j.is_integer() or j<0:
        sum_list.append(j)
        x.append(1) #=== Add element in list to keep the cyclone going
    else:
        break
sums=sum(sum_list)
print("The Sum of all the numbers is: ",round(sums,2))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM