Python 如何运行连续循环并向文本添加输入
我必须运行一个连续循环,直到用户做出相反的决定,这将把输入添加到文本文件中,但我似乎无法让while循环正常工作 这就是我到目前为止所做的:Python 如何运行连续循环并向文本添加输入,python,loops,while-loop,constants,Python,Loops,While Loop,Constants,我必须运行一个连续循环,直到用户做出相反的决定,这将把输入添加到文本文件中,但我似乎无法让while循环正常工作 这就是我到目前为止所做的: def main(): #Open a file named names.txt. outfile = open('names.txt', 'w') #user enters input fname = input("Enter first name:\t") lname = input("Enter secon
def main():
#Open a file named names.txt.
outfile = open('names.txt', 'w')
#user enters input
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print("")
continues = input("Continue? (y = yes):\t")
input_list = [fname, lname, telephone, continues]
outfile.write(fname)
outfile.write(lname)
outfile.write(telephone)
outfile.close()
while continues == 0:
if continues == "y":
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print("")
continues = input("Continue?:\t")
outfile.write(fname)
outfile.write(lname)
outfile.write(telephone)
outfile.close()
else:
print("File Written")
#call main
main()
有人能帮我一下吗,我正在使用python 3.3.2,这里有一个循环正在工作。你能试一下并根据你的情况调整一下吗
run = None
while run != 'n':
run = raw_input('continue? [y/n]').lower()
您最好将整个过程包装在循环中: Ex:
def main():
while True:
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print ("")
continues = input("Continue? (y = yes):\t").lower() # y to break the loop
input_list = [fname, lname, telephone, continues]
if continues == 'y':
with open('names.txt', 'w') as outfile:
# write things to outfile.
# The with block auto closes
# the file after it's statements
print ('File Written')
break # this is how you exit the loop
编辑:
def main():
while True:
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print ("")
continues = input("Continue? (y = yes):\t").lower() # y to break the loop
input_list = [fname, lname, telephone, continues]
if continues == 'y':
with open('names.txt', 'w') as outfile:
# write things to outfile.
# The with block auto closes
# the file after it's statements
print ('File Written')
break # this is how you exit the loop
也许这句话更有意义:
continues = input("Write to File? (y = yes):\t").lower()
据我所知,请尝试:
continues='y'
while 1:
if continues == "y":
fname = input("Enter first name:\t")
lname = input("Enter second name:\t")
telephone = input("Enter telephone number:\t")
print("")
continues = input("Continue?:\t")
outfile.write(fname)
outfile.write(lname)
outfile.write(telephone)
outfile.close()
else:
print("File Written")
break
如果只给出代码的相关部分,您可能会得到更好的答案。
while continues==0:
-什么时候continues
会是0?这个循环应该在什么条件下进行?我不知道我只是做了一个例子,而continues==y,它一直说y没有定义…y
和“y”
是不一样的。第一个是名为y
(未定义)的变量,第二个是包含字符y
的字符串。非常感谢,唯一的问题是“y”应该使循环继续,而不是破坏它,但谢谢:)很高兴我能帮上忙。正如您可能看到的,根据您的目的定制这一部分很容易。