How do I use while loops to create a multiplication table? - python

This is my code, it outputs a multiplication table but it's not what I wanted!
num = int(input("Multiplication using value? : "))
while num <= 10:
i = 1
while i <= num:
product = num*i
print(num, " * ", i, " = ", product, "\n")
i = i + 1
print("\n")
num = num + 1
I am basically creating a multiplication table from the user's input from 1-9.
Ex. If the user inputs "3",
I should get this output:
1*1=1
1*2=2
1*3=3
2*1=2
2*2=4
2*3=6
3*1=3
3*2=6
3*3=9

The reason why you have an infinite loop on your hands is because you are comparing i to num, while also increasing num on every run. If you make sure i is always <= 10, you get your desired output:
while num <= 10:
i = 1
while i <= 10:
product = num*i
print(num, " * ", i, " = ", product, "\n")
i = i + 1
num = num + 1
print("\n")

Even if the code you posted is not pythonic at all (it is very close to what could be written in C language), it nearly works: with minimum modifications, it can be fixed as follows to give your expected ouput:
numInput = int(input("Multiplication using value? : "))
num = 1
while num <= numInput:
i = 1
while i <= numInput:
product = num*i
print(num, " * ", i, " = ", product)
i = i + 1
print("") # no need to add explicit newline character because it is automatically added
num = num + 1
In a more pythonic way, you can also do the following:
numInput = int(input("Multiplication using value? : "))
for i in range(1,numInput+1):
for j in range(1,numInput+1):
print(i, " * ", j, " = ", i*j)
print("")

For this problem it's easier to use for loops.
num = int(input("Multiplication using value? : "))
for left in range(1,num+1): # 1st loop
for right in range(1,num+1): # 2nd loop (nested)
print(left, " * ", right, " = ", left * right)
print() # newline
To understand this problem, look at the two multiplicands: left and right.
Left multiplicand goes from (1-->num), hence the first for loop.
Then, for each value of the left multiplicand, the right multiplicand goes from (1-->num), hence the 2nd loop is nested inside the first loop.

You've lots of logical error. Please have a look at this updated code:
num = int(input("Multiplication using value : "))
i=1 #you haven't initialized this variable
while i <=num:
j=1
while j <= num:
product = i*j #updated
print(i, " * ", j, " = ", product, "\n") #updated
j = j + 1
print("\n")
i = i + 1
Output (for input 3):
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

In Python 3.6+, you can use f-strings with a nested for loop:
num = int(input("Multiplication using value? : "))
for i in range(1, num+1):
for j in range(1, num+1):
print(f'{i} * {j} = {i*j}')
Multiplication using value? : 3
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

multiplication table using while loop in python
num = int(input("enter the number= "))
i = 1
while i<=10:
print(num, "X", i, "=", num * i)
i = i+1
output
enter the number= 33
33 X 1 = 33
33 X 2 = 66
33 X 3 = 99
33 X 4 = 132
33 X 5 = 165
33 X 6 = 198
33 X 7 = 231
33 X 8 = 264
33 X 9 = 297
33 X 10 = 330

num = int(input("Enter the number: "))
i = 1
print("Mulltiplication of number:", num)
while i<=10:
print(f"{num}X{i}={num*i}")
i = i + 1

Multiplication table 1 to 10
for x in range(1,11):
for y in range(1,11):
print(x*y, end='\t')
print()
print()

input any number to get your normal multiple table(Nomenclature) in 10 iterate times.
num = int(input("Input a number: "))
# use for loop to iterate 10 times
for i in range(1,11):
print(num,'x',i,'=',num*i)

num = int(input('Enter the number you want the multiplication table for:'))
i=1
while i<=10:
product = num*i
print(product)
i=i+1
print('Thank you')

Creating a multiplication table using while loop is shown below:
b = int(input('Enter the number of the multiplicaction table : '))
print('The multiplication table of '+ str(b) + 'is : ')
a=0
while a<=11:
a=a+1
c= a*b
print( str(b)+' x '+str(a)+' ='+str(c))
print('done!!!!')

To create a multiplication table in python:
name=int(input("Enter the number of multiplication"))
i=1
while(i<=10):
print(str(name)+"X"+str(i)"="+str(name*i))
i=i+1

Related

How to extract values from a while loop to print in python?

So I could print out the odd numbers. However, the output isn't what i want. It should look like 1+3+5+7 = 16 but I could not make it into a single line.
I couldn't figure out how to extract the values from the while loop as with my method it only gives the latest odd number which is 7 while 1,3 and 5 could not be taken out
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
odd = (str(oddNum))
print (odd)
total = total + oddNum
oddNum = oddNum + 2
count += 1
print (odd + "=" + str(total))
#output will be:
'''
1
3
5
7
7=16
but it should look like 1+3+5+7=16
'''
An alternative method would be the use of:
range() method to generate the list of odd numbers
.join() method to stitch the odd numbers together (eg. 1+3+5+7)
f-strings to print odds together with the total = sum(odd_nums)
Code:
num = int(input("Insert a postive integer:")) #4
odd_nums = range(1, num * 2, 2)
sum_nums = "+".join(map(str, odd_nums))
print(f"{sum_nums}={sum(odd_nums)}")
Output:
1+3+5+7=16
Note:
Same but using two lines of code:
num = int(input("Insert a postive integer:")) #4
print(f"{'+'.join(map(str, range(1, num * 2, 2)))}={sum(range(1, num * 2, 2))}")
Output:
1+3+5+7=16
You are not storing old oddNum values in odd. With minimal changes can be fixed like this:
num = int(input("Insert a positive integer:"))
oddNum = 1
total = 0
count = 1
odd = ""
while count <= num:
total = total + oddNum
odd += f"{oddNum}"
oddNum = oddNum + 2
count += 1
odd = "+".join(odd)
print(odd + "=" + str(total))
There are a few options, you can either create a string during the loop and print that at the end, or create a list and transform that into a string at the end, or python3 has the ability to modify the default end of line with print(oddNum, end='').
Using a string:
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
sequence = ''
while count <= num:
sequence += ("+" if sequence != "" else "") + str(oddNum)
total = total + oddNum
oddNum = oddNum + 2
count += 1
print (sequence + "=" + str(total))
Using print:
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
if count != 1:
print('+', end='')
print (oddNum, end='')
total = total + oddNum
oddNum = oddNum + 2
count += 1
print ("=" + str(total))
Alternatively using walrus (:=), range,print, sep, and end:
print(*(odd:=[*range(1,int(input('Insert a postive integer:'))*2,2)]),sep='+',end='=');print(sum(odd))
# Insert a postive integer:4
# 1+3+5+7=16

Generate Random Math in Python 3

This program will ask the user a series of questions about two numbers. These two numbers will be generated randomly between 1 and 10 and it will ask the user 10 times. At the end of these 10 questions the program will display how many the user got correct out of those questions.
Each question should randomly decide between asking for the product, sum, or difference. Separate the question asking into a function, as well as the validating user input.
I tried using with three product, sum or difference in random to generate. I tried to use z = random.randint(1, 4) is to select from 1 is product, 2 is sum, or 3 is difference and then I used with if variable z is 1, then do product math or if var z is 3, then it should be difference like this x / y, but I couldn't figure it finish it up. I have the expected result when I first run with product but it works so I just need to add with sum and difference included.
EXPECTED OUTPUT with product (Some are incorrect for testing with scores):
> python3 rand3.py
What is 3 x 4
Enter a number: 12
What is 3 x 7
Enter a number: 27
What is 6 x 3
Enter a number: 18
What is 7 x 10
Enter a number: 70
What is 9 x 10
Enter a number: 90
What is 9 x 7
Enter a number: 72
What is 5 x 9
Enter a number: 54
What is 6 x 8
Enter a number:
Incorrect Input!
Enter a number: 48
What is 1 x 5
Enter a number: 5
What is 10 x 3
Enter a number: 30
You got 7 correct out of 10
My Work for Product Only (Success):
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 100)
y = random.randint(1, 100)
print("What is " + str(x) + " x " +str(y))
u = askNum()
if (u == x * y):
return 1
else:
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
My Currently Work: (I am working to add sum and difference like the expected output
UPDATED: After the expected output works well with product so I am trying to add new random int for z with 1-3 which means I am using with 1 is for product, 2 is for sum and 3 is difference by using if-statement by given random select. I am struggle at this is where I stopped and figure it out how to do math random because I am new to Python over a month now.
import random
def askNum():
while(1):
try:
userInput = int(input("Enter a number: "))
break
except ValueError:
print("Incorrect Input!")
return userInput
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
else if (z == 2):
x + y #sum
return 1
else if (z == 3):
x / y #difference
return 1
else
return 0
amount = 10
correct = 0
for i in range(amount):
correct += askQuestion()
print("You got %d correct out of %d" % (correct, amount))
OUTPUT:
md35#isu:/u1/work/python/mathquiz> python3 mathquiz.py
File "mathquiz.py", line 27
if (z == 1):
^
IndentationError: unexpected indent
md35#isu:/u1/work/python/mathquiz>
With this currently output, I double checked with corrected Python formatting and everything are sensitive, and still the same as running output. Any help would be more appreciated with explanation. (I hope my English is okay to understand since i'm deaf) I have started this since on Saturday, than expected on time to meet.
Your problem is that python 3 does not allow mixing spaces and tabs for indentation. Use an editor that displays the whitespace used (and fix manually) or one that replaces tabs into spaces. It is suggested to use 4 spaces for indentation - read PEP-0008 for more styling tips.
You can make your program less cryptic if you use '+','-','*','/' instead of 1,2,3,4 to map your operation: ops = random.choice("+-*/") gives you one of your operators as string. You feed it into a calc(a,ops,b) function and return the correct result from it.
You can also shorten your askNum and provide the text to print.
These could look like so:
def askNum(text):
"""Retunrs an integer from input using 'text'. Loops until valid input given."""
while True:
try:
return int(input(text))
except ValueError:
print("Incorrect Input!")
def calc(a,ops,b):
"""Returns integer operation result from using : 'a','ops','b'"""
if ops == "+": return a+b
elif ops == "-": return a-b
elif ops == "*": return a*b
elif ops == "/": return a//b # integer division
else: raise ValueError("Unsupported math operation")
Last but not least you need to fix the division part - you allow only integer inputs so you can also only give division problems that are solveable using an integer answer.
Program:
import random
total = 10
correct = 0
nums = range(1,11)
for _ in range(total):
ops = random.choice("+-*/")
a,b = random.choices(nums,k=2)
# you only allow integer input - your division therefore is
# limited to results that are integers - make sure that this
# is the case here by rerolling a,b until they match
while ops == "/" and (a%b != 0 or a<=b):
a,b = random.choices(nums,k=2)
# make sure not to go below 0 for -
while ops == "-" and a<b:
a,b = random.choices(nums,k=2)
# as a formatted text
result = askNum("What is {} {} {} = ".format(a,ops,b))
# calculate correct result
corr = calc(a,ops,b)
if result == corr:
correct += 1
print("Correct")
else:
print("Wrong. Correct solution is: {} {} {} = {}".format(a,ops,b,corr))
print("You have {} out of {} correct.".format(correct,total))
Output:
What is 8 / 1 = 3
Wrong. Correct solution is: 8 / 1 = 8
What is 5 - 3 = 3
Wrong. Correct solution is: 5 - 3 = 2
What is 4 - 2 = 3
Wrong. Correct solution is: 4 - 2 = 2
What is 3 * 1 = 3
Correct
What is 8 - 5 = 3
Correct
What is 4 / 1 = 3
Wrong. Correct solution is: 4 / 1 = 4
What is 8 * 7 = 3
Wrong. Correct solution is: 8 * 7 = 56
What is 9 + 3 = 3
Wrong. Correct solution is: 9 + 3 = 12
What is 8 - 1 = 3
Wrong. Correct solution is: 8 - 1 = 7
What is 10 / 5 = 3
Wrong. Correct solution is: 10 / 5 = 2
You have 2 out of 10 correct.
def askQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
z = random.randint(1, 4)
print("What is " + str(x) + " "+ str(z)+ " " +str(y))
u = askNum()
if (z == 1):
x * y #product
return 1
elif (z == 2):
x + y #sum
return 1
elif (z == 3):
x / y #difference
return 1
else:
return 0
Write your block like this your u = askNum() and next if loop should be on same vertical line.
To Generate n number of random number you can use
random.sample(range(from, to),how_many_numbers)
User this as reference for more info on random
import random
low=0
high=4
n=2 #no of random numbers
rand = random.sample(range(low, high), n)
#List of Operators
arithmetic_operators = ["+", "-", "/", "*"];
operator = random.randint(0, 3)
x = rand[0];
y = rand[1];
result=0;
# print(x, operator, y)
if (operator == 0):
result = x + y# sum
elif(operator == 1):
result = x - y# difference
elif(operator == 2):
result= x / y#division
else :
result=x * y# product
print("What is {} {} {}? = ".format(x,arithmetic_operators[operator],y))
The following stores a random number(int)
operator = random.randint(0, 3)
to compare it with the list for operators.
Example: operator = 2
elif(operator == 2):
result= x / y#division
than this code will executed and because operator=2, 3rd element from list(/) will be selected
Output:
What is 3 / 2?

Python Program not working as expected

I tried to create a python-based ISBN13 Validity Calculator, which is supposed to work according to the following snip of code. It takes in an argument of type string and prints the result.
I don't understand where I got wrong here, In this program, common sense tells me num will give a 3 or a 1 alternatively.
def isbncheck(isbn):
num = int(0)
for i in range(0,12):
if num % 2 is 1:
num = num + (int(isbn[i])*3)
print(isbn[i] + " * 3 + at i=" + str(i))
elif num % 2 is 0:
num = num + (int(isbn[i]))
print(isbn[i] + " * 1 + at i=" + str(i))
else:
print("Unhandled Exception.")
print("_"*7)
print(num)
num = num%10
print(num)
print(isbn[12])
print(int(isbn[12]))
if num != int(isbn[12]):
print("This is not valid")
else:
print("It is Valid.")
print(isbncheck("9788177000252"))
I expected the output to alternate factors of 1 and 3. Instead, I got this:
9 * 1 + at i=0
7 * 3 + at i=1
8 * 1 + at i=2
8 * 1 + at i=3
1 * 1 + at i=4
7 * 3 + at i=5
7 * 1 + at i=6
0 * 3 + at i=7
0 * 3 + at i=8
0 * 3 + at i=9
2 * 3 + at i=10
5 * 3 + at i=11
_______
96
6
2
2
This is not valid
None
How do you work around it? Other than not expanding the loop?
Your problem is here:
for i in range(0,12):
if num % 2 is 1:
num is your accumulated sum. You have to check the index, not the sum so far.
for i in range(len(isbn)):
digit = int(isbn[i])
if i % 2 == 1:
num += 3 * digit
Also note some minor improvements:
Since you have to refer to the value twice, convert to int and hold it in a temporary digit.
use == for numerical comparison; is gives you object comparison, which will fail for general cases.
According to the ISBN spec, the 3 goes on every other digit, so your if statement should be if i % 2 is 1:, not if num % 2 is 1: (and the elif should be changed accordingly).
Also, you must take 10 minus the result of the modulo operation; so after num = num%10 you would have the new line num = 10 - num. Otherwise your computed check digit (num) will be incorrect.
Another note: is only works on some implementations to compare numbers between -1 and 256 (source), which is why it works in this case. But in general == is more suited for comparing two numbers.

Print asterisk arrow using only While loops in Python

I am trying to create an arrow out of asterisk's, where the amount of columns is entered by the user. Yes, I do know how to use for loops to accomplish this:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
for x in range(1, columns):
for x in range(x):
print(" ", end="")
print("*")
for x in range(columns,0,-1):
for x in range(x):
print(" ", end="")
print("*")
#output looks like
"""
How many columns? 3
*
*
*
*
*
"""
However my question is, how would I accomplish the same outcome using only while loops?
Thanks
Edit: I was going to post what I had thus far in trying to work it out myself, but it is now of no use!
Thank you all for your efficient varying answers! Much appreciated!
Just for fun, here's a version that doesn't loop using indexing.
def print_arrow(n):
a = '*'.ljust(n + 1)
while a[-1] != '*':
print(a)
a = a[-1] + a[:-1]
a = a[1:]
while a[0] != '*':
a = a[1:] + a[0]
print(a)
# Test
print_arrow(4)
output
*
*
*
*
*
*
*
This should do:
columns = int(input("How many columns? "))
while columns <= 0:
print ("Invalid entry, try again!")
columns = int(input("How many columns? "))
x = 1
while x < columns:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x += 1
x = columns
while x > 0:
y = 0
while y < x:
print(" ", end="")
y += 1
print("*")
x -= 1
First, it's better to use functions. And easier if you know that character*number returns that character concatenated number times.
Example:
'*'*10
returns
'**********'
So your program using whiles would follow the same logic.
def print_arrow(k):
i = 0
while(i < k-1):
print(i*' ' + '*')
i +=1
while(i >= 0):
print(i*' ' + '*')
i -= 1
The first while prints the upper part, the last one uses the fact that i = k-1, so just do same in the reversed order.
Example:
print_arrow(3)
returns
*
*
*
*
*
n = int(input( ))
n1 = n//2 + 1
i = 1
while i <= n1:
space = 1
while space <= i - 1:
print(" ",end="")
space += 1
j = 1
p = "*"
while j <= i:
if j == i:
print(p,end="")
else:
print("* ",end="")
j += 1
print()
i += 1
i = n - n1
while i >= 1:
space = 1
while space <= i - 1:
print(" ",end="")
space += 1
j = 1
p = "*"
while j <= i:
if j == i:
print(p,end="")
else:
print("* ",end="")
j += 1
print()
i -= 1
Arrow pattern of asterisk
-Remember the n value here is always odd
for n = 5
output will be

Adding Consecutive integers in Python, with a twist

Here is my original code:
x = input("Please input an integer: ")
x = int(x)
i = 1
sum = 0
while x >= i:
sum = sum + i
i += 1
print(sum)
Here is what the second part is:
b) Modify your program by enclosing your loop in another loop so that you can find consecutive sums. For example , if 5 is entered, you will find five sum of consecutive numbers so that:
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
I have been stuck on this for 3 days now, and I just can't understand how to do it. I have tried this but to no avail.
while x >= i:
sum_numbers = sum_numbers + i
past_values = range(i)
for ints in past_values:
L = []
L.append(ints)
print(L, "+", i, "=", sum_numbers)
i += 1
Can anyone just help steer my in the correct direction? BTW. it is python 3.3
You could do this in one loop, by using range to define your numbers, and sum to loop through the numbers for you.
>>> x = input("Please input an integer: ")
Please input an integer: 5
>>> x = int(x)
>>>
>>> for i in range(1, x+1):
... nums = range(1, i+1)
... print(' + '.join(map(str, nums)), '=', sum(nums))
...
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
range(1, x+1) would give me [1, 2, 3, 4, 5], this acts as the controller for how many times we want to print out a sum. So, this for loop will happen 5 times for your example.
nums = range(1, i+1) notice we are using i instead here, (taken from the range above), which I am using to define which number I am up to in the sequence.
' + '.join(map(str, nums)):
map(str, nums) is used to convert all elements of nums into strings using str, since the join method expects an iterable filled with strings.
' + '.join is used to "join" elements together with a common string, in this case, ' + '. In cases where there is only 1 element, join will just return that element.
sum(nums) is giving you the sum of all numbers defined in range(1, i+1):
When nums = range(1, 2), sum(nums) = 1
When nums = range(1, 3), sum(nums) = 3
Etc...
reduce(lambda x,y:x+y,range(x+1))
You don't have to use a while loop, 2 for will do the trick nicely and with a more natural feeling.
x = input("Please input an integer : ")
x = int(x)
item = range(1, x + 1)
for i in item:
sum = 0
for j in range(1, i + 1):
sum = sum + j
print(str(sum))
Using list comprehension in python:
x = input("Please input an integer: ")
x = int(x)
i = 1
sums = [(((1+y)*y)//2) for y in range(i, x+1)] # creates list of integers
print(sums) # prints list of sums on one line
OR
[print(((1+y)*y)//2) for y in range(i, x+1)] # prints sums on separate line

Categories

Resources