Intro to Programming with Python – #3

In my last post we discussed the concept of data types and conditional blocks. It gave us the power to make simple yet powerful logical decision in program. I also gave you some assignments, solutions to which I have uploaded here. In this post we will move on to yet another powerful construct exploited every now-and-then in programming – Loops. I will also be introducing you to the sequence data types of Python – list, tuple, str.

What we will Build?

In this post we will build a python program that will take input details of a student and will print a report of a student based on details entered. The final result will be something like this:

Why use list?

Here we will be using list data type. But why? List data type has a unique property that they are mutable sequence of different or same type (data type) of values. This allows us to store all values related to one thing at one place. For example, here we will need a list of all the subjects available, a list of marks which will be used to save marks as they are taken input from user and a list of grades for each subject.

Working with Python lists

Python list stores value which we can access at will using their index (position at which they are present in list). Data value present at first position in the list has an index 0, data value present at second position in the list has an index 1, and so on. Python lists can also be accessed in reverse order. So data value present at last position can be accessed with index -1, data value present at second last position can be accessed with index -2, and so on. For a concrete example hit up the interactive mode and play around with following code.

>>> # Initialize a list a list encapsules all its items inside square braces []
>>> i_am_a_list = ['Piyush', 'Malhotra', 22, 'piyush@predictiveprogrammer.com']
>>> # Accessing value at position 1 or index 0
>>> i_am_a_list[0]
'Piyush'
>>> # Accessing value at position 2 or index 1
>>> i_am_a_list[1]
'Malhotra'
>>> i_am_a_list[2]
22
>>> i_am_a_list[3]
'piyush@predictiveprogrammer.com'
>>> # Accessing in reverse value at last position 1 or index -1 
>>> i_am_a_list[-1]
'piyush@predictiveprogrammer.com'
>>> i_am_a_list[-2]
22

Keeping above code in the interactive mode let’s see some useful built-in functionalities of python lists. Toggle your way below and learn possible usage of python lists.

>>> empty_li = []
>>> empty_li
[]
>>> i_am_a_list.append('XXX-XX-XX-692')
>>> i_am_a_list
['Piyush', 'Malhotra', 22, 'piyush@predictiveprogrammer.com', 'XXX-XX-XX-692']
>>> i_am_a_list.pop()
'XXX-XX-XX-692'
>>> i_am_a_list
['Piyush', 'Malhotra', 22, 'piyush@predictiveprogrammer.com']
>>> del i_am_a_list[2]
>>> i_am_a_list
['Piyush', 'Malhotra', 'piyush@predictiveprogrammer.com']
>>> i_am_a_list[0] = 'xyz'
>>> i_am_a_list
['xyz', 'Malhotra', 'piyush@predictiveprogrammer.com']
>>> li1 = [22, 35, 76]
>>> li2 = [33, 3, 77]
>>> concat_list = li1 + li2
>>> concat_list
[22, 35, 76, 33, 3, 77]
>>> li1 = [22, 35, 76]
>>> len(li1)
3

Note: Any iterable can be changed to a list by passing the iterable to `list()` function. An iterable is any data type whose elements we can access using indices.

>>> # string is an iterable as we can access elements using index
>>> li = list('list from str')
>>> li
['l', 'i', 's', 't', ' ', 'f', 'r', 'o', 'm', ' ', 's', 't', 'r']
>>> # list using tuple; we will study tuples ahead
>>> t = (1, 2, 'a')
>>> li = list(t)
>>> t
(1, 2, 'a')
>>> li
[1, 2, 'a']

There are many other options that we will see in future usage!!

Usage of tuple

We will not be using tuples here, but it is as good as time as any to understand them. Tuple is an immutable list of values. This means once a tuple is made – we cannot change its length, we cannot change value at any position and we cannot delete value at any position. This makes sure that no one comes into our program, manipulates the data and leaves. The concept of indices remains the same here. Concrete example of using tuples:

>>> # Initialize a tuple; a tuple encapsules all its items inside simple braces ()
>>> i_am_a_tuple = ('Piyush', 'Malhotra', 22, 'piyushmalhotra28@gmail.com')
>>> i_am_a_tuple[0]
'Piyush'
>>> i_am_a_tuple[-2]
22

Let’s understand some key concepts of tuples.

>>> t1 = (22, 35, 76)
>>> t2 = (33, 3, 77)
>>> concat_tuple = t1 + t2
>>> concat_tuple
(22, 35, 76, 33, 3, 77)
>>> i_am_a_tuple[0] = 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> del i_am_a_tuple[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
>>> i_am_a_tuple.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'pop'
>>> i_am_a_tuple.append('Try')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

Note: Any iterable can be changed to a tuple by passing the iterable to `tuple()` function. An iterable is any data type whose elements we can access using indices.

>>> t = tuple('list from str')
>>> t
('l', 'i', 's', 't', ' ', 'f', 'r', 'o', 'm', ' ', 's', 't', 'r')
>>> li = [1, 2, 'a']
>>> t = tuple(t)
>>> t
(1, 2, 'a')

Usage of str

Strings are also sequence type. This means we can use indices to access characters at different positions in a string. But strings are immutable, this means we cannot change a string. However, we can create new strings from old once. we can format strings to our need for a clean, concise output. Concrete examples of usage of string:

>>> s = 'Predictive Programmer'
>>> s[0]
'P'
>>> s[-1]
'r'
>>> s[-3]
'm'
>>> s1 = 'Predictive'
>>> s2 = 'Programmer'
>>> res = s1 + ' ' + s2
>>> res
'Predictive Programmer'

We can use {} in a string as a substitute for values. This can be achieved using format() property of string data type.

>>> marks = 70
>>> total_marks = 100
>>> s = 'Student got {} marks out of {}'.format(marks, total_marks)
>>> s
'Student got 70 marks out of 100'

Say you want to make sure that your string no matter how short it is should occupy a minimum length of 20:

>>> s = '{:20s}'.format('short str')
>>> s
'short str '

Center Align the above string rather than left aligned:

>>> s = '{:^20s}'.format('short str')
>>> s
' short str '

Create copies of a string. s * k  (multiply operator) on a string s with an integer k copies string s, k times.

>>> s = 'a'
>>> s * 5
'aaaaa'

Lets Start our Program

Look at the output shown in what we build section (above)! Try to take the two inputs as taught in last post and then display the Grading Criteria using string formatting. Bonus, try to add a list of five subjects of your choice and name the list as subjects_list. Save this file as generate_student_report.py. Try to do it yourself before seeking help from my code below.

name = input('Enter Student Name: ')
roll_no = int(input('Enter Roll No: '))

subjects_list = ['Maths',
                 'Physics',
                 'Chemistry',
                 'English',
                 'Python']

print('\n' + '-' * 10 + 'GRADING CRITERIA' + '-' * 10)
print('|{:10s}|{:^23s}|'.format('A', '>=80%'))
print('|{:10s}|{:^23s}|'.format('B', '>=65% and < 80%'))
print('|{:10s}|{:^23s}|'.format('C', '>=50% and < 65%'))
print('|{:10s}|{:^23s}|'.format('D', '>=35% and < 50%'))
print('|{:10s}|{:^23s}|'.format('E', '<35%'))
print('-' * 36)

Note: `\n` is newline character it moves cursor to new line!

Output:

That’s 1/5th done!!

Now we have 4 steps to complete!

  1. Take Marks of subjects input.
  2. Compute Grade of each subject.
  3. Calculate overall Grade and average marks.
  4. Display Report!

Let’s tackle step 1 – Taking marks of subjects input. This step will bring a new construct into play. Till now we have built concept about data types on which we can iterate using numbers. In other words, we now have data types on which we can apply an operation one element at a time. Consider You have 20 subjects to take input marks for! Man a lot of redundant code. Every new line of code will just be for input of marks. To get over this we will use a powerful programming construct known as loops.

Loops in Python!!

Python Provides us with two types of loops for and while. Let us see the general structure of these loops:

for loop structure

for <element> in <sequence type>:
<do something>
...

while loop structure

while <condition>:
<do something>
...

Usage – for loop
For loops are generally used when we know how many times a loop needs to be run. The example below prints the elements present in a list each on new line.

>>> li = [2, -10, 50, -6, 79]
>>> for ele in li:
... print(ele)
...
2
-10
50
-6
79

Usage – while loop
While loops are generally used when we don’t know how many times a loop should run, but we do know a condition that needs to be True for the loop to run. The example below runs till the time user enters non-negative numbers. As the input number is negative the loop stops.

>>> a = int(input('Enter a number: '))
Enter a number: 10
>>> while a >= 0:
... a = int(input('Enter a number: '))
...
Enter a number: 20
Enter a number: 30
Enter a number: 0
Enter a number: 70
Enter a number: -10
>>>

REMEMBER: Any code that needs to be executed inside the loop should be indented to right. As we indent back to left the loop ends.

Now we can take marks as input and compute grades of each subject. Create two empty lists marks and subject_grade. Using loop over subjects_list, we created before, take marks as input and append it at the end of marks list. Also using the input marks try to find the grade using if-elif statements and the grading criteria shown below.

Grade Marks
A >=80%
B >=65% and <80%
C >=50% and <65%
D >=35% and <50%
E <35%

Code:

marks = []
subject_grade = []

for subject in subjects_list:
    subject_marks = float(input('Enter marks in subject ' + subject + ':'))

    if subject_marks >= 80:
        subject_grade.append('A')
    elif subject_marks >= 65:
        subject_grade.append('B')
    elif subject_marks >= 50:
        subject_grade.append('C')
    elif subject_marks >= 35:
        subject_grade.append('D')
    else:
        subject_grade.append('E')

    marks.append(subject_marks)

Output:

That’s 60% done!!!

Just some more lines of code. 🙂

Calculate Final Grade and Print Report

We know that average marks equals total marks divided by number of subjects. Now, python is a great programming language with very handy functions. One such function is sum(). It can calculate the sum of all the values in a sequence type, given they are addition compatible! A concrete example:

>>> li = [1, 2, 3, 4, 5]
>>> sum(li)
15

We also know len() function can be used to keep track on number of elements are present in the list. Other function that might come handy is range(). As you have to loop over 3 lists of same size – subject_grade, marks and subjects_list.

So, how does range() function works? range() function takes 1 to 3 values start, stop, step. If only 1 value is given, say k, then start = 0, stop = k and step=1. Now `range(k)` works as an iterable that goes from 0, 1, 2, … k-1. Concrete example:

>>> for a in range(10):
...     print(a)
...
0
1
2
3
4
5
6
7
8
9

Now, that you have everything you need. Add few more lines at the end of generate_student_report.py file that:

  1. Calculates average marks and save it in average_marks variable.
  2. Calculate overall grade using `average_marks` and the grading criteria, and save the grade in grade variable.
  3. Print the student report. Remember you have to loop over 3 lists together to generate output as shown in the what we will build section!!

Code:

average_marks = sum(marks) / len(marks)
if average_marks >= 80:
    grade = 'A'
elif average_marks >= 65:
    grade = 'B'
elif average_marks >= 50:
    grade = 'C'
elif average_marks >= 35:
    grade = 'D'
else:
    grade = 'E'

print('\n\n')

print('-' * 20 + 'Student Report' + '-' * 20)
print('NAME: ' + name)
print('ROLL NO.: ' + str(roll_no))
print('-' * 54)

print('|{:20s}|{:20s}|{:10s}|'.format('Subject',
                                      'Marks',
                                      'Grade'))
print('-' * 54)
for i in range(len(subjects_list)):
    print('|{:20s}|{:20s}|{:10s}|'.format(subjects_list[i],
                                          str(marks[i]),
                                          subject_grade[i]))

print('-' * 54)
print('Overall Grade: ' + grade)
print('Percentage: ' + str(average_marks) + '%')

Note: `\n` is newline character it moves cursor to new line!

Output:

Now that we have completed the program let’s have a look at complete code.

COMPLETE CODE

This brings us to the end of this post! Now pretty much you are equipped with knowledge that can help you make many programs. But good programs aren’t just about loops and ifs it requires paradigms to be followed to produce master pieces!!

In next post we will get a little more serious about code quality! And will be able to remove redundant code like if-elif blocks coming again for same thing (to calculate grade) in this post.

Till then get your hands dirty with these assignments!

  1. Write a program to take a number input and print its reverse. (HINT: A Number divided by (integer division) 10 gives remainder the last digit of the number and quotient as the number without last digit. Example 123 // 10 gives us 12 and 123 % 10 gives us 3).
  2. Write a program to take 10 numbers as input and print the maximum and minimum out of all the numbers without using built in functions max() and min().

Links to Some Useful Python Books

  1. Learn Python 3 The Hard Way
  2. Automate the Boring Stuff with Python
  3. Python Crash Course

This Post Has One Comment

Leave a Reply

Close Menu

SUBSCRIBE FOR WEEKLY POST UPDATES <3