Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use one 'for loop' for 2 different lists

Tags:

python

I want to print out a sentence inside of a for loop where a different iteration of the sentence prints out for each different situation i.e. I have two different lists: student_result_reading and student_name

student_result_reading = []
student_name = []

while True:

   student_name_enter = input("Please enter student name: ")
   student_name.append(student_name_enter)

   student_enter = int(input("Please enter student result between 0 - 100%: "))
   student_result_reading.append(student_enter)

   continueask = input("Would you like to enter someone else? ")
   if continueask == "yes":
          continue
   else:
          break

for studread, studentname in student_result_reading, student_name:
   print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))     

Here are my two issues:

  1. When I enter 2 or more names, they are not formatted correctly.

  2. When I enter 1 name, I get an error.

Any help as to any solutions is appreciated.

like image 675
GoGoAllen Avatar asked Oct 16 '22 20:10

GoGoAllen


1 Answers

You can use built-in function zip for that:

for studread, studentname in zip(student_result_reading, student_name):
   print("Student Name: {} | Test Name: Reading Test | Percentage Score: {}".format(studentname, studread))

Also, if you are using Python 2, you, probably, encountering problem, with this two lines:

student_name_enter = input("Please enter student name: ")

and

continueask = input("Would you like to enter someone else? ")

I.e., if you enter something like student name as input for student name, you will get SyntaxError or NameError. Reason is, in Python 2, input function expects valid Python expression, in you case, string, like "student name", not simply student name. For later expression to be valid input, you can use function raw_input.

like image 127
Grigoriy Mikhalkin Avatar answered Nov 15 '22 04:11

Grigoriy Mikhalkin