Home > Software engineering >  How do I prompt a user to key in correct input and reuse that input to go through a loop?
How do I prompt a user to key in correct input and reuse that input to go through a loop?

Time:08-27

I have a question for one of my assignments.

Inside the file “scrabble.py”, create a program which:

  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.

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]

new = [ ]

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

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}")

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? I would greatly appreciate feedback on how to improve this too!

CodePudding user response:

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. 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
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

CodePudding user response:

You need to make sure that the first lettre is in the lettres before entering the for loop by adding a while loop:

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}")

CodePudding user response:

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." Lastly, we do not need an entire "letters" array, we can just check if the character is within a range from 'a' to '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}")

CodePudding user response:

Here is a example code with comments for you :) (written in 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}")
  • Related