我正在尝试使编码选项起作用,以便如果用户在字符串中输入数字,它将以“请只写字母!”的形式答复。并提示用户。现在我遇到一个错误:
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
我的代码是这样的:
#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!")
答案 0 :(得分:2)
您可以通过使用字符串的isalpha
方法来确认输入是字符串,如果字符串仅包含字母,则返回True
,否则返回False
。
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.
在需要确认仅包含字母的字符串的任何地方使用isalpha
。