1

I am trying to get the encoding option to function so that if the user inputs a number in the string it will reply with "Letters only please!" and reprompt the user. Right now I am getting an error:

Traceback (most recent call last):
  File "/Users/myname/Desktop/proj01.py", line 16, in <module>
    c = c + 1
TypeError: can only concatenate str (not "int") to str

My code is this:

#User Greeting
greeting = print("Hello! Welcome to the Caesar Cipher!")

#List Command Options
prompt1 = input("Select a commend: \n'e' to encode,\n'd' to decode, or\n'q' to quit\n")
while prompt1 != ("e" or "d" or "q"):
    print("Invalid choice")
    prompt1 = input("Select a commend: \n'e' to encode,\n'd' to decode, or\n'q' to quit\n")

#Encoding Option
if prompt1 == "e":
    prompt2 = input("Please enter a lowercase word string to encode: ")
    c = 0
    for c in prompt2:
        if not c.isalpha():
          c = c + 1
          print("Letters only please!")
          prompt2 = input("Please enter a lowercase string to encode: ")
        elif c.isupper():
          print("No uppercase please!")
          prompt2 = input("Please enter a lowercase string to encode: ")
    prompt3 = int(input("Please enter a rotation number between 1-25: "))
    while prompt3 != range(1, 25):
          print("Out of range")
          prompt3 = input("Please enter a rotation number between 1-25: ")

#Quit Option
if prompt1 == "q":
  print("Goodbye! Come back soon!")
martineau
  • 119,623
  • 25
  • 170
  • 301
Chris137
  • 11
  • 2
  • You can use `isalpha()` directly on the string rather than on each letter. The error is being thrown because `'1'` will still be considered as a `str` and not `int` – mad_ Mar 06 '19 at 20:18
  • 1
    You have initialized `c` as `0` before the `for` loop and you're using a variable of the same name to iterate through `prompt2`. `c` will always be of type `str` that way. – Vasilis G. Mar 06 '19 at 20:19
  • Your `c` value containing a string ( type). So, you can do a small test in your Python console: `test = "text" + 1` ... what will raise the error, of course. If you want convert ASCII character between and (the "char") use the `ord()` and `str()` for converting between both types. For example: `ord(65)` give you `"A"` string (one character) and `str("A")` give you the integer number `65`. A slightly longer explanation would be if you want to reflect even Unicode characters. – s3n0 Mar 06 '19 at 20:26

1 Answers1

2

You can confirm the input is a string by using the isalpha method of a string, which returns True if the string contains only letters and False otherwise.

prompt1 = input("Select a commend: \n'e' to encode,\n'd' to decode, or\n'q' to quit\n")
if not prompt1.isalpha():
    #prompt1 does not contain only letters, deal with it here.

Use isalpha anywhere you need to confirm a string contains only letters.

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42