我试图用我的程序做的是要求用户输入一个输入字符串,稍后将使用 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.
最佳答案
您可以将所有用户界面放入一个永远循环的 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
请注意,“中断”是让您脱离循环的原因。由于用户界面部分位于 while 循环中,因此它将重复。
关于python - 如何从 Raw_Input 字符串值创建循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35618706/