此代码的问题如下:
-
我输入的内容在第一句话之后被截断。
-
当询问用户是否希望再次运行程序时,代码无法再次运行。
-
当输入其他输入时,程序不会结束。在下面的代码之后,我粘贴了运行程序时的外观。
def main ():
string=input('Enter sentences to be modified:') #enter sentences
sentence=string.split('.')
for i in sentence:
print ("Your modified setences is:" + i.strip().capitalize()+". ",end='')
print ()
rerun ()
def rerun ():
while True:
again = input("Run again? ") #asks user if they want to run again
if 'y' in again:
main () #reruns def main
else:
print("bye") #ends program
main()
代码返回:
Enter sentences to be modified:yes. hello
Your modified setences is:Yes.
Run again? y
Run again? n
Run again?
你需要break
退出while循环,如果他们说不,你就没有中断,所以它永远不会结束。你的if
声明不在while
之下。。。
def run():
string=input('Enter sentences to be modified:') #enter sentences
sentence=string.split('.')
for i in sentence:
print ("Your modified setences is:" + i.strip().capitalize()+". ",end='')
def main():
while 1:
run()
again = input("Run again? Y/N ") #asks user if they want to run again
if again.lower() != 'y': #clean break on N
break
main()
您已经将main()
函数定义为递归函数,而不必递归
def main ():
while True:
string = input('Enter sentences to be modified: ')
sentence = string.split('.')
for i in sentence:
print("Your modified setences is: " + i.strip().capitalize() + ". ")
print()
while True:
again = input("Run again? ")
if 'y' in again:
break # breaks out of inner while loop, not outer
else:
return print("bye") # prints "bye" and ends function
main()
while True:
将永远运行,因为if 'y' in again
和else
语句在循环之外。您还需要缩进该表达式!在Python中,缩进是极其重要的。