Print first n multiples of a given number using python
Hello, in this post I am going to show you how you can print out n mulitples of a value using a custom python program.
Alright first of all, let me paste the code here for you then i'll go over it to explain whats going on at each stage;
while True:
a = input('enter value:')
b = input('enter how many multiple:')
b=int(b)
a=int(a)
print('find multiples of', a)
print('this many times:', b)
for i in range (1, b+1):
i=int(i)
print ('{0} x {1} = {2}'.format(a, i, a*i))
print('Do you want to exit:')
c=input('yes or no:')
if c =='yes':
break
The use of the "while true" statement is to enable you to re-run your code after successful execution instead of just exiting the program.
Next create 2 variables and assign them to user inputs;
- a is equal to the value whose multiples you wish to print out
- b is equal to the number of multiples of a you wish to print out
Next convert the input values to integers using the int() function
Using print(f" ") statement, we output some dynamic formatted strings (i.e a and b are replaced by the values inputed by the user).
Next we use a for statement to perform an arithmetic operation on diffrent values (i) within a range of 1 and b+1 ( I added 1 to the value of b because I want the final multiple to be included as well).
Convert the i value into integer using the int() function.
This line "print ('{0} x {1} = {2}'.format(a, i, a*i))" is used to format how how output is arranged. From this arrangement we want our output to be printed like so
number specifed by user (a) X current value of i = multiple value
By the next line, the for statement would have finished running and we'll be asked if we want to exit the program. If you input in yes the program ends and if you input no it runs again and asks you to input the values of a and b.
Example
Lets say we want to print out the first 6 multiples of 2. All we have to do is run our program, and enter the required data and on successful code execution we should see a multiples list printout in our terminal like so
enter value:2
enter how many multiple of 2:6
find multiples of 2
this many times: 6
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
Do you want to exit:
yes or no:
Conclusion
Utilizing a few lines of python code we have created a program that is capable of printing out any number of multiples for any number specified by the user. As always thanks for reading, I hope this post has helped you along in your programming journey. Leave a comment down below if you have any questions.