3

I have to write a program that prompts user for input and should print True only if every character in string entered by the user is either a digit ('0' - '9') or one of the first six letters in the alphabet ('A' - 'F'). Otherwise the program should print False.

I can't use regex for this question as it is not taught yet, i wanted to use basic boolean operations . This is the code I have so far, but it also outputs ABCH as true because of Or's. I am stuck

string = input("Please enter your string: ")

output = string.isdigit() or ('A' in string or 'B' or string or 'C' in string or 'D' in string or 'E' in string or 'F' in string)

print(output)

Also i am not sure if my program should treat lowercase letters and uppercase letters as different, also does string here means one word or a sentence?

2
  • string is the entire object. You should loop over each element in string like for char in string: and then perform your logic. Commented Apr 24, 2019 at 20:54
  • @SyntaxVoid i used this , still returns true on WEDA string = input("Please enter your string: ") for char in string: if char == ("A" or "B" or "C" or "D" or "E" or "F"): alphabet_output = "True" else: alphabet_output = "False" output = string.isdigit() or alphabet_output print(output) Commented Apr 24, 2019 at 21:05

1 Answer 1

2

We can use the str.lower method to make each element lowercase since it sounds like case is not important for your problem.

string = input("Please enter your string: ")
output = True # default value

for char in string: # Char will be an individual character in string
    if (not char.lower() in "abcdef") and (not char.isdigit()):
        # if the lowercase char is not in "abcdef" or is not a digit:
        output = False
        break; # Exits the for loop

print(output)

output will only be changed to False if the string fails any of your tests. Otherwise, it will be True.

Sign up to request clarification or add additional context in comments.

3 Comments

You could also use the built-in all() to further simplify: output = all(c.isdigit() or c.lower() in 'abcdef' for c in s)
@syntaxVoid: this code fails for test case ABCDD, it should return true but it returns false
Sorry, it is fixed now. I changed the or to and in the if statement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.