简体   繁体   English

如何正确编写多个 if 语句

[英]how to properly write multiple if statements

trying to condense if statements and want to know if there is a proper why of writing this.试图压缩 if 语句并想知道是否有写这个的正确原因。 Also this is my first post as well as being new to programming这也是我的第一篇文章,也是编程的新手

mark1 = int(input("Enter mark 1: "))
if mark1 < 0 or mark1 > 100:
    help()
    mark1 = input(1)

mark2 = int(input("Enter mark 2: "))
if mark2 < 0 or mark2 > 100:
    help()
    mark2 = int(input("Enter mark 2: "))

mark3 = int(input("Enter mark 3: "))
if mark3 < 0 or mark3 > 100:
    help()
    mark3 = int(input("Enter mark 3: "))

mark4 = int(input("Enter mark 4: "))
if mark4 < 0 or mark4 > 100:
    help()
    mark4 = int(input("Enter mark 4: "))

mark5 = int(input("Enter mark 5: "))
if mark5 < 0 or mark5 > 100:
    help()
    mark5 = int(input("Enter mark 5: "))

First, you should review the logic to get marks: in your case, it prompts once, and if the entered mark is outside the range, it prompts again.首先,您应该查看获取标记的逻辑:在您的情况下,它会提示一次,如果输入的标记超出范围,则会再次提示。 However, if an invalid value is entered at the second time of asking, it simply accepts that value.但是,如果在第二次询问时输入了无效值,它只会接受该值。 Instead, you should use a while loop so that it keeps asking until a valid value is returned.相反,您应该使用while循环,以便它一直询问直到返回有效值。 You also probably want to account for the case where the entered number is not an integer. You can do this by trying to cast it to an int() and then catching the resulting ValueError .您可能还想考虑输入的数字不是integer 的情况。您可以通过尝试将其转换为int()然后捕获生成的ValueError来做到这一点。

Now, repeated code can be wrapped in a function, and then you just call that function:现在,重复的代码可以包装在 function 中,然后您只需调用该 function:

def get_mark(prompt):
    while True:
        m = input(prompt)
        try:
            m = int(m)
        except ValueError:
            print("Please enter an integer")
            continue # skip the rest of the loop and prompt for input again

        if 0 <= m <= 100: # If it's a valid mark, we return it
            return m

        help() # If we haven't returned so far, it was an invalid mark so we call help()

Then, do然后做

mark1 = get_mark("Enter mark 1: ")
mark2 = get_mark("Enter mark 2: ")
...

To add to @Pranav Hosangadi's answer , repeated tasks should be run in a loop.要添加到@Pranav Hosangadi 的答案,重复的任务应该循环运行。 If you find yourself naming many variables like marks0 , marks1 , etc, you should probably have a list called marks and access it as marks[0] , marks[1] , etc:如果您发现自己命名了许多变量,如marks0marks1等,您可能应该有一个名为marks的列表,并以marks[0]marks[1]等方式访问它:

marks = []
for i in range(5):
    while True:
        mark = int(input(f"Enter mark {i + 1}: "))
        if 0 <= mark <= 100:
            break
    marks.append(mark)

If you use Pranav's function to replace the inner while loop, you can use a list comprehension:如果使用 Pranav 的 function 来替换内部while循环,则可以使用列表理解:

marks = [get_mark(f'Enter mark {i + 1}: ') for i in range(5)]

sounds like you can store the values to a list of numbers;听起来您可以将值存储到数字列表中; and you can use the try/except structure to catch that.您可以使用 try/except 结构来捕获它。

Since you want to handle the case where a user provides an input that is not a number(or within the range you have specified);由于您想处理用户提供的输入不是数字(或在您指定的范围内)的情况; I presume that you want to handle this as "ignore," show your help function's syntax and keep querying until they have filled in the appropriate number of items you originally requested?我假设您想将其处理为“忽略”,显示您的帮助函数的语法并继续查询,直到他们填写了您最初请求的适当数量的项目?

 def help():
    print('please enter a number between 0 & 100')


numOfElements = 5
mark = []
elementNumber=0


while elementNumber < numOfElements:
    
    try:
        value=int(input("Enter mark " + str(elementNumber+1) + ":"))
        if(0<value<100):
            mark.append(value)
            elementNumber+=1
        else:
            help()
    except ValueError:
        help()

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

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