我正在尝试对我的程序做的是要求用户输入一个输入字符串,稍后将使用str.upper或str.lower将其转换为大写或小写。
我有5套用户可以选择的选项:
a = 'convert to upper case'
b = 'convert to lower case'
c = 'switch case of every alphabetic character to the opposite case'
d = 'convert first and last chrs of each word to upper case, and others to lower'
e = 'no change'
到目前为止,我已经完成了选项a和b的转换。但在我继续为选项c,d和e创建代码之前。我正在尝试创建一个循环,但我不知道如何使用raw_input和字符串来完成它。
这是我到目前为止的代码:
# Conversion Rules
a = 'convert to upper case'
b = 'convert to lower case'
c = 'switch case of every alphabetic character to the opposite case'
d = 'convert first and last chrs of each word to upper case, and others to lower'
e = 'no change'
def upper():
print 'Your Input: %s' % choice
print 'Choosen Conversion Rule: %s' % a
return 'Conversion Result: %s' % option_A
def lower():
print 'Your Input: %s' % choice
print 'Choosen Conversion Rule: %s' % b
return 'Conversion Result: %s' % option_B
choice = str(raw_input('Choose an Option:'))
if (choice == 'A') or (choice == 'a'):
value_A = str(raw_input('Enter a String to Convert:'))
option_A = str.upper(Value_A)
print upper()
elif (choice == 'B') or ('b'):
value_B = str(raw_input('Enter a String to Convert:'))
option_B = str.lower(value_B)
print lower()
else:
print 'Goodbye' # Here I want to break if 'Q' is entered if 'Q' is entered.
所以用户输入选项后。例如'A'或'a'。第一个条件将运行,但后来我想添加一个回到代码开头的循环,并允许用户再次输入选项或选择其他选项,以便运行不同的条件。
choice = str(raw_input('Choose an Option:'))
if (choice == 'A') or (choice == 'a'):
value_A = str(raw_input('Enter a String to Convert:'))
option_A = str.upper(Value_A)
print upper()
# I want to add a loop here to go back to the 'choice' variable.
答案 0 :(得分:2)
您可以将所有用户界面放在一个永久循环的while循环中(直到某些键被按下为止)。
# Conversion Rules
a = 'convert to upper case'
b = 'convert to lower case'
c = 'switch case of every alphabetic character to the opposite case'
d = 'convert first and last chrs of each word to upper case, and others to lower'
e = 'no change'
def upper():
print 'Your Input: %s' % choice
print 'Choosen Conversion Rule: %s' % a
return 'Conversion Result: %s' % option_A
def lower():
print 'Your Input: %s' % choice
print 'Choosen Conversion Rule: %s' % b
return 'Conversion Result: %s' % option_B
while True:
choice = str(raw_input('Choose an Option:'))
if (choice == 'A') or (choice == 'a'):
value_A = str(raw_input('Enter a String to Convert:'))
option_A = str.upper(Value_A)
print upper()
elif (choice == 'B') or ('b'):
value_B = str(raw_input('Enter a String to Convert:'))
option_B = str.lower(value_B)
print lower()
else:
print 'Goodbye' # Here I want to break if 'Q' is entered if 'Q' is entered.
break
请注意,“break”会让你脱离循环。由于用户界面部分处于while循环中,因此它将重复。