简体   繁体   English

如何提示用户键入正确的输入并通过循环将该输入重新用于 go?

[英]How do I prompt a user to key in correct input and reuse that input to go through a loop?

I have a question for one of my assignments.我对我的一项作业有疑问。

Inside the file “scrabble.py”, create a program which:在文件“scrabble.py”中,创建一个程序:

  1. Asks the user for a word (assume the word is in lowercase)询问用户一个词(假设这个词是小写的)
  2. Each character in the word must be found in the letters list above.单词中的每个字符都必须在上面的字母列表中找到。 If it is not, ask the user for a new input until a valid word is given如果不是,请向用户询问新的输入,直到给出有效的单词
  3. Print out the score achieved by adding the number of points associated to each letter in that word通过将与该单词中的每个字母相关的点数相加,打印出得分
  4. You should not use any string methods (if you are aware of them), such as.index, etc.您不应该使用任何字符串方法(如果您知道它们),例如 .index 等。

My solution:我的解决方案:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]字母 = ['a'、'b'、'c'、'd'、'e'、'f'、'g'、'h'、'i'、'j'、'k'、'l' ,'m','n','o','p','q','r','s','t','u','v','w','x',' y', 'z'] 点 = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1、4、4、8、4、10]

new = [ ]新 = [ ]

word = input("type a word (in lower case): ") word = input("输入一个单词(小写):")

for elm in word:对于榆树来说:

if elm in letters:
    idx = letters.index(elm)
    new.append(points[idx])
    continue
if elm not in letters:
    print("Key in a proper word!")
    word = input("type a word (in lower case): ")

print(new)打印(新)

Sum_of_points = sum(new) Sum_of_points = 总和(新)

print(f"The total points is: {Sum_of_points}") print(f"总分是:{Sum_of_points}")

The issue I am facing is that after the user inputs the wrong figure at the start, it will prompt the user again, but however it will not repeat the loop from the very beginning.我面临的问题是,用户一开始输入错误的数字后,它会再次提示用户,但是它不会从一开始就重复循环。 I would like it to repeat the loop, how should I go about doing this?我希望它重复循环,我应该如何 go 关于这样做? I would greatly appreciate feedback on how to improve this too!我也将非常感谢有关如何改进这一点的反馈!

You can try to use a dict instead of two lists so that the letter and the points associated with the letter is bound together.您可以尝试使用 dict 而不是两个列表,以便将字母和与字母关联的点绑定在一起。 This way, you avoid any string methods.这样,您可以避免任何字符串方法。

scrabble_dict = {
    'a' : 1,
    'b' : 3,
    'c' : 3
}

word = input("type a word (in lower case): ")
new = []

for elm in word:
    if elm in scrabble_dict.keys():
        new.append(scrabble_dict[elm])
    else:
        print("Key in a proper word!")
        word = input("type a word (in lower case): ")

To answer your edits (...inputs the wrong figure at the start, it will prompt the user again, but however it will not repeat the loop from the very beginning. I would like it to repeat the loop...)回答您的编辑(...在开始时输入错误的数字,它会再次提示用户,但是它不会从一开始就重复循环。我希望它重复循环...)

You can -你可以 -

  1. either add a break in the else part of the if and start over again在 if 的 else 部分添加一个中断并重新开始
input_remaining = True

while input_remaining:
    word = input("type a word (in lower case): ")
    new = []

    for elm in word:
        if elm in scrabble_dict.keys():
            new.append(scrabble_dict[elm])
        else:
            print("Key in a proper word!")
            break
            
    input_remaining = False

or或者

  1. just ask for a new letter if there is something invalid如果有无效的东西,只需要求一封新信
word = input("type a word (in lower case): ")
new = []

for elm in word:
    if elm in scrabble_dict.keys():
        new.append(scrabble_dict[elm])
    else:
        print("letter appears invalid")
        elm = input("type in correct letter ")
        if elm in scrabble_dict.keys():
            new.append(scrabble_dict[elm])
        else:
            print("wrong again, I quit!)
            exit()

in the second way, user does not have to repeat the entire word again.在第二种方式中,用户不必再次重复整个单词。 You can probably create a function to check if letter is valid and just exit() after say 3 attempts您可能可以创建一个 function 来检查字母是否有效,然后在尝试 3 次后exit()

This will continuously prompt the user to enter a new string until a valid word is given.这将不断提示用户输入一个新的字符串,直到给出一个有效的单词。 In addition, you can use ASCII character subtraction to avoid using string methods like "index."此外,您可以使用 ASCII 字符减法来避免使用诸如“索引”之类的字符串方法。 Lastly, we do not need an entire "letters" array, we can just check if the character is within a range from 'a' to 'z'最后,我们不需要一个完整的“字母”数组,我们只需检查字符是否在 'a' 到 'z' 的范围内

points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]

while word := input("type a word (in lower case): "):
    valid_word = True
    new = []
    print(word)
    for elm in word:
        if elm >= 'a' and elm <= 'z':
            new.append(points[ord(elm) - ord('a')])
            continue
        else:
            valid_word = False
            print("Key in a proper word!")
            break

    Sum_of_points = sum(new)
    if valid_word:
        break

print(f"The total points is: {Sum_of_points}")

You need to make sure that the first lettre is in the lettres before entering the for loop by adding a while loop:在进入 for 循环之前,您需要确保第一个字母在字母中,方法是添加一个 while 循环:

new = []
while True:
    word = input("type a word (in lower case): ")
    if (word[0] in letters):
        break;

for elm in word:

    if elm in letters:
        idx = letters.index(elm)
        new.append(points[idx])
        continue
    if elm not in letters:
        print("Key in a proper word!")
        word = input("type a word (in lower case): ")

print(new)
Sum_of_points = sum(new)
print(f"The total points is: {Sum_of_points}")

Here is a example code with comments for you:) (written in Python3)这是一个带有注释的示例代码:)(用 Python3 编写)

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10]

# Easier look up via dictionary
mapping = {k:v for k, v  in zip(letters, points)}

# Checking from time to time with while loop
_input = input("type a word (in lower case): ")
while set(_input) - set(letters):
    print("Key in a proper word!")
    _input = input("type a word (in lower case): ")

# Calculate the summation through dict look up
sum_of_points = sum(map(mapping.__getitem__, _input))
print(f"The total points is: {sum_of_points}")

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

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