简体   繁体   中英

how to write a code that loops more than once using the for loop function in python

here is my code:

number = input("How many students are registering?")

for i in number:
    id_number = input("Enter your ID Number:")
    print(id_number)

with open("reg_form.txt","w") as f:
    f.write(id_number+"\n")

the code has to loop for the same number entered in variable "number" in my code above.

this question shows no research effort, but here is what you are looking for:

with open("reg_form.txt","w") as f:
    for i in range(int(input('how many students registering?'))):
        id_number = input("Enter your ID Number:")
        print(id_number)
        f.write(id_number+"\n")

this should do the trick (making sure the input is an integer & you iterate over an iterable (range))

number = int(input("How many students are registering?"))

for i in range(number):
    id_number = input("Enter your ID Number:")
    print(id_number)

All you need to do is use a For Loop with number .

Here's the code:

number = input("How many students are registering?")

for i in range(int(number)):
  id_number = input("Enter your ID Number:")
  print(id_number)

  with open("reg_form.txt","w") as f:
    f.write(id_number+"\n")

I believe you meant to put the With Statement within the For Loop, because it won't work otherwise (id_number isn't defined).

I don't exactly know what is your problem, but I think i can help you

number = input("How many students are registring")
for i in range(1,int(number))
   id_number = input("Enter your ID Number: ")
   print(id_number)
 with open("reg_form.txt","w") as f: f.write(id_number+"\n"
   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM