In this python tutorial, you will learn how to Calculate the Sum of Natural Numbers using the for loop and the assignment operators of the python programming language.
How to Generate Multiplication Table?
Let’s take a look at the source code , here the values are given as input by the user in the code, the print function along with the for loop carry out the function.RUN CODE SNIPPET
# Multiplication table (from 1 to 10) in Python taking input from the user num = int(input("Display multiplication table of: ")) # Iterate 10 times from i = 1 to 10 for i in range(1, 11): print(num, 'x', i, '=', num*i)
Display multiplication table of? 12 x 1 = 12 12 x 2 = 24 12 x 3 = 36 12 x 4 = 48 12 x 5 = 60 12 x 6 = 72 12 x 7 = 84 12 x 8 = 96 12 x 9 = 108 12 x 10 = 120
- Here we give the user the option to enter the values and the input values are scanned using the
inputfunction and are stored in the variable
numwith the statements/strings
("Display multiplication table of: "), we use the
intfunction and declare the input value as an integer value.
- In the STDIN section of the code editor the input values are entered.
- We declare a
forloop and the variable
ialong with the
rangefunction which will hold the values of
ibetween the range
(1, 11)followed by a
:. The loop will iterate till the final value of the range is used in the condition for iteration which is declared with the print function.
- As the iteration takes place, each step and its returned value will be displayed using the
(num, 'x', i, '=', num*i), in which
num*iis the condition for iteration.
- The input() function allows a user to insert a value into a program, it returns a string value.
- A For loop runs a block of code until the loop has iterated over every item in a condition, that is it helps to reduce any repetition in the code because it executes the same operation multiple times.
- The Range() function is used to generate a sequence of numbers, where the range() function is commonly used in for looping functions.
- The colon : at the end of the if, elif and else statement tells Python that the next line of code should only be run if the condition is true.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement/string to be displayed in enclosed in double quotes.