简体   繁体   English

为什么我的Validation()函数没有运行?

[英]Why isn't my Validation() function running?

This is the code I have written to try and display a message of whether or not somebody is able to vote, after taking in age and the type of election, but after I enter the type of election it stops. 这是我编写的代码,试图显示年龄和选举类型后,某人是否能够投票的信息,但是在输入选举类型后,它将停止。 Can anyone help? 有人可以帮忙吗? Here is my code: 这是我的代码:

def Validation():
if election == 'EU' or election == 'UK':
    if age < 110 and age > 18:
        print('You are eligable to vote in this election')
    else:
        print('You are not eligable to vote in this election')

    if election is 'Scottish' or election is'local':
        if age < 110 and age > 16:
            print('You are eligable to vote in this election')
        else:
            print('You are not eligable to vote in this election')

Put == instead of is . 放置==而不是is Also be aware that == should match every character in order to be true (It's somewhat oubvious, but just remebering you that), so if you have a selection named " L ocal" and you're trying to compare with " l ocal", it's not the same. 另请注意, ==应该匹配每个字符才能正确显示(这有点让人生畏,但请记住一下),因此,如果您有一个名为“ L ocal”的选择,并且尝试与“ l ocal”进行比较, 这是不一样的。

Your code should look like this: 您的代码应如下所示:

def Validation():
    if election == 'EU' or election == 'UK':
        if age < 110 and age > 18:
            print('You are eligable to vote in this election')
        else:
            print('You are not eligable to vote in this election')

        if election == 'Scottish' or election == 'local':
            if age < 110 and age > 16:
                print('You are eligable to vote in this election')
            else:
                print('You are not eligable to vote in this election')

In addition to what @Fusseldieb writes, think about separating the configuration from the validation function. 除了@Fusseldieb所写的内容之外,还要考虑将配置与验证功能分开。

The rules can be expressed like this: 规则可以这样表示:

rules = {
    'UK': {'min-age': 18, 'max-age': 110},
    'EU': {'min-age': 18, 'max-age': 110},
    'Scottish': {'min-age': 16, 'max-age': 110},
    'local': {'min-age': 16, 'max-age': 110},
}

With that out of the way, the validation function becomes shorter and, in contrast to your current approach, it does not need any changes if the set of rules gets bigger. 这样一来,验证功能将变得更短,并且与当前的方法相比,如果规则集变得更大,则不需要任何更改。

def Validation(election):
    if election in rules:
        rule = rules[election]
        if age >= rule['min-age'] and age <= rule['max-age']:
            print('You are eligible to vote in this election')
        else:
            print('You are not eligible to vote in this election')
    else:
        print('No rules configured for this country')

Disclaimer: The following isn't what I usually do, or what usually happens on this site. 免责声明:以下不是我通常要做的事情,也不是本网站上通常发生的事情。 It exceeds the question scope by far and pretty much comes down to a 101 or a tutorial. 它远远超出了问题的范围,几乎可以归结为101或教程。


Your code has multiple problems and none of them can easily be fixed by spotting the mistake and pointing you to it. 您的代码有多个问题,通过发现错误并将其指向,可以轻松解决所有问题。 The entire approach to the problem needs to be re-worked from scratch. 解决问题的整个方法需要从头开始。 You try to do to many things at once, which always results in code that has interlocked issues. 您尝试一次做很多事情,这总是导致代码存在问题。

Let's break down what you try to do. 让我们分解一下您尝试做的事情。

  1. ask the user for his age, which must be an integer between 0 and 110. 询问用户年龄,该年龄必须为0到110之间的整数。
  2. ask them for their region, which must be one of a limited set of choices 向他们询问他们的地区,这一定是一组有限的选择之一
  3. inform them whether their age allows them to vote in their region 告知他们年龄是否允许他们在所在地区投票

Even more basically, you want to do this: 基本上,您想这样做:

  1. ask the user for a value 向用户询问价值
  2. make sure the value fulfills a certain criterion (like "is a number" or "is a number between x and y" ) 确保该值满足特定条件(例如“是数字”“是x和y之间的数字”
  3. repeat until the user has entered a compliant value 重复此操作,直到用户输入了合规值

These steps could be expressed in pseudo code: 这些步骤可以用伪代码表示:

def input_value():
    while True:
        value = input('Please enter a value: ')
        if value == 'valid':
            return value

So we have an endless loop that keeps asking the user for a value and only when the value is okay we return it. 因此,我们有一个无限循环,不断向用户询问一个值,只有在该值确定时,我们才返回它。


To ask for an integer, the function could look like this: 要索取整数,该函数可能如下所示:

def input_int():
    while True:
        value = input('Please enter a number: ')
        if value.isdigit():
            return int(value)

To ask for an integer that falls into a certain range, like an age value, we can utilize the same pattern and use the input_int() function: 要请求一个落入一定范围内的整数(例如年龄值),我们可以利用相同的模式并使用input_int()函数:

def input_int_in_range(min, max):
    while True:
        value = input_int()
        if value >= min and value <= max:
            return value
        else:
            print('Please input values between %i and %i.' % (min, max))

Notice how the else: branch informs the user about the valid range after the first wrong entry. 注意else:分支在第一次输入错误后如何通知用户有效范围。

Now assuming that we have a dict of voting rules, like indicated in my other answer: 现在假设我们有一个dict的投票规则,就像我的其他答复中指出:

regions = {
    'UK': {'min-age': 18, 'max-age': 110},
    'EU': {'min-age': 18, 'max-age': 110},
    'Scottish': {'min-age': 16, 'max-age': 110},
    'Local': {'min-age': 16, 'max-age': 110},
}

we could write another function that lets the user pick one of those by key. 我们可以编写另一个函数,使用户可以通过按键选择其中一个。 The function nicely follows the established pattern: 该函数很好地遵循了已建立的模式:

def input_choose(dict):
    while True:
        value = input('Please input your choice: ')
        if value in dict:
            return dict[value]
        else:
            print('Valid choices are: %s'  % ', '.join(dict.keys()))

Now we have all the basic parts in place and can put them together: 现在我们已经准备好所有基本部分,可以将它们放在一起:

# main program
while True:
    print("\nPlease enter your age.")
    age = input_int_in_range(0, 110)

    print("\nPlease enter the election you are voting for.")
    rule = input_choose(rules)

    if age >= rule['min-age'] and age <= rule['max-age']:
        print("\nYou are eligible to vote in this election.\n")
    else:
        print("\nYou are not eligible to vote in this election.\n")

As an exercise you can create a validation function, but the way this has been designed every input step is self-validating, so that a final validation step is not really necessary. 作为练习,您可以创建一个验证功能,但是在每个输入步骤中设计该功能的方法都是自验证的,因此最终的验证步骤实际上并不是必需的。

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

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