Trying to validate a text input, so it allows characters in the alphabet only as the input but I'm having problems. (Python)

Question:

So, I have a homework where I’m assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It’s also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text…)
Keep in mind this is the first time in my life I’ve attempted to write any code (I’ve looked up instructions for guidance)

import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
    try:
        x = int(input("Enter an integer: "))
    except ValueError:
        print("Please enter a valid integer: ")
        continue
    else:
        break
while True:
    try:
        answer = str
        y = answer(input("Enter a text: "))
    except ValueError:
        print("Please enter a valid text")
        continue
    else:
        print(x*y)
        break

This is what I got, validating the integer is working, but I can’t validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I’m also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.

Asked By: Juj

||

Answers:

Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?

In that case input() in python always returns a string.

So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.

In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.

while True:
    x = input("Enter an integer: ")
    try:
        x = int(x)
    except ValueError:
        print("Please enter a valid integer: ")
        continue
    
    break

while True:
    y = input("Enter a text: ")
    if not y.isalpha():
        print("Please enter a valid text")
        continue
    else:
        print(x*y)
        break
Answered By: ak_slick
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.