简体   繁体   English

如何使无效输入仅出现在数字输入中? 以及如何将输入转换为列表并增加每个输入的计数?

[英]How do I make the invalid input appear for only number inputs? And how do I turn the inputs into a list and increase the count for every input?

So I'm confused on how to make the invalid input appear for only number inputs, how to turn the inputs into a list, and how to increase the count for every input?所以我很困惑如何使无效输入仅出现在数字输入中,如何将输入转换为列表,以及如何增加每个输入的计数? I genuinely tried but I just can't figure it out:(.我真的尝试过,但我就是想不通:(。

This is the question:这是问题:

Exercise #17c: Lists #3练习 #17c:列表 #3

  1. You're going to take the same idea from a previous exercise that asked the user for multiple numbers and until the user entered "done".您将从之前的练习中采用相同的想法,该练习要求用户输入多个数字,直到用户输入“完成”。

  2. On the very top of your program, you need to assign (=) an empty list ([]) to a variable (line above the While True loop)在程序的最顶部,您需要assign (=)一个empty list ([])分配给一个变量(While True 循环上方的行)

  3. The program is going to continuously ask for a list of names.该程序将不断要求提供姓名列表。

  4. Once the user types in 'done', your program should then display how many names were entered and display the final list.一旦用户输入“完成”,您的程序就会显示输入了多少名称并显示最终列表。 An example is shown below of what yours should look like下面显示了一个示例,说明您的应该是什么样子

EXAMPLE:例子:

Enter a name: Mrs. Brown输入姓名:布朗夫人

Enter a name: Ms. Bliss输入姓名:Bliss 女士

Enter a name: 3输入姓名:3

That's not a name!那不是名字! TRY AGAIN!再试一次!

Enter a name: Mr. Kent输入姓名:肯特先生

Enter a name: done输入名称:完成

There are 3 names in the list ['Mrs.列表中有 3 个名字 ['Mrs. Brown', 'Ms.布朗','女士。 Bliss', 'Mr.幸福”,“先生。 Kent']肯特']

This is what is have so far:这是目前为止的:

namesList = []
while True:
  name = input("Please enter a name, then press enter. When finished type done: \n")
  if name == "done":
    namesList = namesList[:-1]
    print("There are " + str(len(namesList)) + " names in the list " + str(namesList))
    break
  else:
    continue

This is how you are going to add the names given in your list这就是您要添加列表中给出的名称的方式

namesList = []
while True:
  name = input("Please enter a name, then press enter. When finished type done: \n")
  if name == "done":
    print("There are " + str(len(namesList)) + " names in the list " + str(namesList))
    break
  else:
    namesList.append(name) #append method adds all the given names in the end of the list
    continue

You have a tricky question about what is a name and what is not a name.你有一个棘手的问题,什么是名字,什么不是名字。 ( https://www.bbc.com/news/magazine-36107590 ) https://www.bbc.com/news/magazine-36107590

But, in any case, the requirements you were provided do not clearly define what is to be accepted, rejected.但是,无论如何,您提供的要求并没有明确定义要接受,拒绝什么。 The example you have indicates that digits are to be rejected.您的示例表明要拒绝数字。

There are several ways you can achieve that.有几种方法可以实现这一目标。 One way you can check for specific patterns in python is with regular expressions (regex).在 python 中检查特定模式的一种方法是使用正则表达式 (regex)。 You can search for that here and identify robust methods for pattern matching.您可以在此处搜索并确定用于模式匹配的可靠方法。

In this case, if the only requirement is to reject digits, you can also make use of the fact that python will generate an error if you request to convert text to an integer.在这种情况下,如果唯一的要求是拒绝数字,您还可以利用 python 将生成错误的事实,如果您请求将文本转换为 integer。 You can make use of that fact to distinguish between all-digits and not-all-digits in a character string.您可以利用这一事实来区分字符串中的全数字和非全数字。

This example below shows how you can do that using a try/except block (also a python paradigm).下面的这个例子展示了如何使用 try/except 块(也是 python 范例)来做到这一点。

ls_test_names = ['Brooke', 'Raj2', '567', '3', '3.141592654']
for t in ls_test_names:
    try:
        name = int(t)
        print('%s looks like digits to me' % t)
    except ValueError as ve:
        print('ValueError : %s' % str(ve))
        print('%s : is not all digits' % t)
        name = t
ValueError : invalid literal for int() with base 10: 'Brooke'
Brooke : is not all digits
ValueError : invalid literal for int() with base 10: 'Raj2'
Raj2 : is not all digits
567 looks like digits to me
3 looks like digits to me
ValueError : invalid literal for int() with base 10: '3.141592654'
3.141592654 : is not all digits

Try this:尝试这个:

def hasNumbers(inputString):
  return any(char.isdigit() for char in inputString)

namesList = []
while True:
  name = input("Please enter a name, then press enter. When finished type done: \n")
  if hasNumbers(name):
    print ("That’s not a name! TRY AGAIN!")
    continue
  else:
    if name == "done":
      print("There are", len(namesList), "names in the list", namesList)
      break
    else:
      namesList.append(name)
      continue

You can check for numbers in a string using any() and a comprehension to detect inputs that are not names.您可以使用 any() 和理解来检查字符串中的数字,以检测不是名称的输入。 The.isdigit() method tells you if a string (or character) if formed of only numbers. .isdigit() 方法告诉您字符串(或字符)是否仅由数字组成。 The.isalpha() method is similar for letters. .isalpha() 方法与字母类似。

names = []
name  = None
while name != "done":
    if name : names.append(name)             # add to list if name present
    name = input("Enter a name: ")           # get a name
    if sum(c.isalpha() for c in name) < 2 \
    or any(c.isdigit() for c in name):       # 2+ letters, no numbers
        name = print("That's not a name! TRY AGAIN!") # sets name to None
print("There are",len(names),"names in the list",names)

BTW, the else: continue in your code is not needed given that you are not doing anything in the loop afterward and the break statement on the if will not go there either.顺便说一句,鉴于您之后没有在循环中执行任何操作,并且if上的break语句也不会出现 go ,因此不需要else: continue在您的代码中。 Also, as a general rule, you should make an effort to avoid using break/continue when possible.此外,作为一般规则,您应该尽可能避免使用中断/继续。 Those are often an indication that you are not in complete control of your variable states and hint at unforeseen side effects.这些通常表明您无法完全控制您的变量状态,并暗示了不可预见的副作用。

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

相关问题 我如何从一个输入创建多个输入 - How do i create a number of inputs from an input 如何使输入成为 python 脚本的一部分,这样每次打开程序时都会永远显示输入? - How do I make inputs part of a python script, so the input will forever be displayed every time the program is openned? 如何一次只用一个输入扩展一个列表,而不是说明我打算首先输入的输入数量? - How do I extend a list by one input at a time, rather than stating the number of inputs I intend to put in first? 如何计算while循环中的用户输入以停止10个输入? - How do I count the user input in a while loop to stop at 10 inputs? 如何进行验证循环以确保用户在 a.split 输入中输入正确的次数? - How do I make a validation loop to make sure the user inputs the correct amount of times in a .split input? 如何从特定输入中排除输入? - How do I exclude inputs from a specific input? 如何指定要存储的输入数量? - How do I specify the number of Inputs to store? 如何让程序询问用户输入的数量,并将他们输入的结果加在一起? - How do I make a program ask the user for the number of inputs, and add the result of their inputs togther? 我如何处理此类列表输入? - How do I handle such list inputs? 如何将下面的示例代码转换为接受多个输入? - How do I turn the sample code below into accepting multiple inputs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM