Multiplication Tables in Python

Free Video Tutorial and Guide

In this video, we're going to look at how to build Multiplication Tables in Python

Video Transcription

Hi, my name is Art, and I teach Python at Noble Desktop. In this video, II'll show you how to solve a very popular job interview question: How to Build a Multiplication Table in Python. We all know what multiplication is and how it works, but how do we build it in Python?

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

We'll need to use the Python built-in function range() and I have a special video on how to use it. If you're not sure how to use range(), don't worry. Just run help() and you'll see that range() returns a sequence of integers. Stop is exclusive, right?

For our multiplication table, we need to generate a range from 1 to 10. We can't multiply by zero, so run for i in range(1, 11). Here we're printing I and we get all the numbers 1-10.

Now let me show you something else. If you run help() on the print() function, don't underestimate it. It has a keyword argument "/n" which, if placed here, won't do anything as it's a new line and it's already there by default. For example, if I replace it with "Hello", it will append "Hello" after each time it prints.

The idea with a multiplication table is to grab one item from one sequence and the other number from the other sequence and multiply them together. So it sounds like a nested for loop. We need to remove the print statement and we see we have two nested for loops.

We want to do I * J and this will give us a multiplication table. But it looks a bit messy, so let's make it better. We'll add a print statement here and since "/n" is a new line, it will look much better.

However, it's still not the nicest. We can use the method format() to convert them to strings. We can use nested brackets and use format to insert the value of "name" into the curly braces. This acts as a placeholder.

We can also use format to create spaces between numbers. We can do ":4" which means four spaces between numbers. If we do ":7", it will change. We can use this trick in our example. To do this, we'll insert curly braces and use format() to print.

Thank you for watching!

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram