Search code examples
pythonloopsuser-inputcalculatornested-loops

How can we add inputs in a loop and then further print these inputs in other nested loop?


I'm stuck on a problem relates to python. I just clarify it in simple words. How can we start a loop based on user input? For instance, let's say I want to ask the user to "Enter the total number of subjects" and store this value in a variable and do some type of conversions. Let's say the user enters the value is 6 "Total of Number of subjects = 6". Then initialization of for Loop I wants to print " Enter name of subject 1, 2, 3, 4, 5,6" etc. whatever user requirement on each line. Where a user enters the names of all 6 subjects.

Now, at the next stage, I want to print "Enter marks for subject Phy, Chem" etc. Here I want to start another loop i.e nested loop.

The program is on the aggregate calculator where the user input his total num of subjects and then based on user input I have to ask.

Enter subject 1 name: 
Enter subject 2 name:
......

And so on based on user input it will increment... After that, I will ask Marks of each subject that the user have input like physics, English etc.

Enter Marks of physics:
Enter marks of computer:
..
...

And so on based on user subjects input data...

After that, I will code in such a way that find average and aggregate etc.

Let's look at this example

Enter total subjects: 3      #user input
Enter the name of subject 1: English.   #user input
Enter the name of subject 2:  Computer Science. #user input
Enter the name of subject 3: Data Science.   # user input

Enter marks of English:- 56
Enter Marks of Computer Science:- 45
Enter marks of Data Science:- 66

And then the calculations process started but I am stuck on upper processes...

But how can I do it????


Solution

  • Number_of_subjects = int(input("Enter total subjects? "))
    Subjects = []
    for i in range(Number_of_subjects):
        Subjects.append(input(f"Enter the name of subject {i+1}: "))
    
    Marks = []
    for x in Subjects:
        Marks.append(float(input(f"Enter marks of {x}: ")))
    
    
    print (f"Average marks is {sum(Marks) / len(Marks)}")
    

    You can use the list of results in "Marks" to do further calculations like Average shown here