遍历if语句中的列表以检查可能的结果

时间:2020-07-08 17:13:46

标签: python python-3.x

我试图遍历变量if_yes的所有可能结果,以便可以计算BMI

代码如下:

Question = input("Do you want to calculate your BMI?")
if_yes = ["Yes", "yes", "y", "Y"]

for i in if_yes:
   if Question == i:
       bmi_calculation()
   elif Question == "No" or Question == "N" or Question == "no" or Question == "n":
       print("Thank you.Hope you'll use this program in the future")
   else:
       print("Enter a valid response!")

每当我编写Y时,else语句似乎就会执行3次,然后bmi_calculation()函数就会执行。我该如何避免呢?

输出

Do you want to calculate your BMI?Y
Enter a valid response!
Enter a valid response!
Enter a valid response!
Please Enter your Name: 

7 个答案:

答案 0 :(得分:1)

之所以这样做,是因为前三次将您的“ Y”与“ Yes”,“ yes”和“ y”进行比较,而答案并非如此。如果您打算保持这种编码方式,请尝试像这样分解代码(psuedocode,我不是python程序员)

Question = input("Do you want to calculate your BMI?")
if_yes = ["Yes", "yes", "y", "Y"]

yes_value = false

for i in if_yes:
   if Question == i:
       yes_value = true

if yes_value == true
   bmicalculation()

答案 1 :(得分:1)

它多次运行的原因是因为您正在遍历具有多个值的if_yes。我想您要执行的操作如下:

Question = None
if_yes = ["Yes", "yes", "y", "Y"]

while Question not in if_yes:
    Question = input("Do you want to calculate your BMI?")
    if Question == "No" or Question == "N" or Question == "no" or Question == "n":
        print("Thank you.Hope you'll use this program in the future")
        exit()
    else:
        print("Enter a valid response!")


bmi_calculation()

这基本上将迫使用户输入is_yes中的某项或某种类型的no来退出程序。

答案 2 :(得分:1)

您没有正确使用for循环,最后您需要做的是根据用户提供的输入来计算或不计算BMI:

question = input("Do you want to calculate your BMI?")
if_yes = ["Yes", "yes", "y", "Y"]

if question in if_yes:
    bmi_calculation()
elif question in ["No", "N", "no", "n"]:
    print("Thank you.Hope you'll use this program in the future")
else:
    print("Enter a valid response!")

我还对您的逻辑进行了一些改进。按照PEP-8设置代码样式。

答案 3 :(得分:1)

显示“输入有效回复!”的原因。执行该程序之前3次是因为在列表中进行迭代时,“ Y”(用户输入)不满足“ Y”等于i(从列表中获取前3个值)的条件。 您可以尝试使用成员运算符,而不是像这样遍历列表:

public static void main(String[] args) throws FileNotFoundException {

    Scanner sc = new Scanner (new File("data.txt"));
    Scanner inFile = new Scanner (new File("data.txt"));

    /*To get the dimension of the matrix*/
    String[] line = sc.nextLine().trim().split("\\s+");
    int row = 1, column = 0;
    column=line.length;
    while (sc.hasNextLine()) {
        row++;
        sc.nextLine();
    }
    sc.close();

    /*To read the matrix*/
    int[][] matrix = new int[row][column];
    for(int r=0;r<row;r++) {
        for(int c=0;c<column;c++) {
            if(inFile.hasNextInt()) {
                matrix[r][c]=inFile.nextInt();
            }
        }
    }
    inFile.close();

    /*To print the matrix*/
    System.out.println(Arrays.deepToString(matrix));
}

答案 4 :(得分:1)

您做错了方法,请尝试使用while循环,这样它将一直重复直到给出正确的输入为止,而不是遍历正确的输入

question = input("Do you want to calculate your BMI?\n1. Yes\n2. No\n")
while True:
    if question == "1":
        bmi_calculation()
        break
    elif question == "2":
        print("Hope you use the program in the future")
        break
    else:
        question = input("Please enter a valid response\n")

答案 5 :(得分:1)

这将起作用:

import time

def bmi_calculation():
    height = float(input("What is your height (metres?) "))
    weight = float(input("What is your weight (kg?) "))
    print("Your BMI is ", weight / height**2)


answer = input("Do you want to calculate your BMI? ")
yes_answers = ["Yes", "yes", "y", "Y"]
no_answers = ["No", "N", "no", "n"]

if answer in yes_answers:
    bmi_calculation()

elif answer in no_answers:
    print("What are you afraid of?")
    while True:
        try:
            time.sleep(1)
            print("scaredy-cat")
        except KeyboardInterrupt:
            pass
else:
    print("Enter a valid response!")

答案 6 :(得分:0)

我会做以下

yes_answer = ['y', 'Y', 'Yes', 'yes', 'YES']
no_answer = ['n', 'N', 'No', 'no', 'NO']
valid_answer = yes_answer + no_answer
answer = ''

while answer not in valid_answer:
    answer = input("Do you want to calculate your BMI? ")
 
    if answer in yes_answer:
        print('We will calculate your BMI')
  
    elif answer in no_answer:
        print("Thank you.Hope you'll use this program in the future")

    else:
        print("Enter a valid response!")