Create multiplication table? - python

Am a beginner in Programming and am practicing how to use nested for loops to make a multiplication table in python 2.7.5.
Here is my code
x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j
pass
well,the result is correct but it does not appear in a square matrix form as i wish.Please help me improve the code

You should print without a line break.
x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
print i*j, # will not break the line
print # will break the line

you may add formatting to keep constant cell width
x = range(1,11)
y = range(1,11)
for i in x:
for j in y:
# substitute value for brackets
# force 4 characters, n stands for number
print '{:4n}'.format(i*j), # comma prevents line break
print # print empty line

Python's print statement adds new line character by default to the numbers you wish to have in your output. I guess you would like to have just a trailing spaces for inner loop and a new line character at the end of the outer loop.
You can achieve this by using
print i * j, # note the comma at the end (!)
and adding just a new line at the end of outer loop block:
print ''
To learn more about the trailing coma, and why it works, look here: "How to print in Python without newline or space?". Mind that it works differently in Python 3.
The final code should look like:
x=range(1,11)
y=range(1,11)
for i in x:
for j in y:
print i*j,
print ''
You can also look for '\t' special character which would allow you to get better formatting (even this old resource is good enough: https://docs.python.org/2.0/ref/strings.html)

USE This Code. It works MUCH better. I had to do this for school, and I can tell you that after putting about 4 hours into this it works flawlessly.
def returnValue(int1, int2):
return int1*int2
startingPoint = input("Hello! Please enter an integer: ")
endingPoint = input("Hello! Please enter a second integer: ")
int1 = int(startingPoint)
int2 = int(endingPoint)
spacing = "\t"
print("\n\n\n")
if int1 == int2:
print("Your integers cannot be the same number. Try again. ")
if int1 > int2:
print("The second number you entered has to be greater than the first. Try again. ")
for column in range(int1, int2+1, 1): #list through the rows(top to bottom)
if column == int1:
for y in range(int1-1,int2+1):
if y == int1-1:
print("", end=" \t")
else:
individualSpacing = len(str(returnValue(column, y)))
print(y, " ", end=" \t")
print()
print(column, end=spacing)
for row in range(int1, int2+1, 1): #list through each row's value. (Go through the columns)
#print("second range val: {:}".format(row))
individualMultiple = returnValue(row, column)
print(individualMultiple, " ", end = "\t")
print("")
Have a good day.

#Generate multiplication table by html
import random
from copy import deepcopy
N = 15
colors = ['F','E','D','C','B','A']
i = 0
colorsall = []
while i < N:
colornow = deepcopy(colors)
random.shuffle(colornow)
colornow = "#"+"".join(colornow)
colorsall.append(colornow)
i += 1
t = ""
for i in range(1,N+1):
s = ''
for j in range(1,N+1):
if j >= i:
s += '<td style="background-color:' + colorsall[i-1] + '">'+str(i*j)+'</td>'
else:
s += '<td style="background-color:' + colorsall[j-1] + '">'+str(i*j)+'</td>'
s = "<tr>" + s + "</tr>"
t = t + s + '\n'
print('<table>' + t + '</table>')
Taken from https://todaymylearn.blogspot.com/2022/02/multiplication-table-in-html-with-python.html [Disclosure : my blog]

Related

How can I fix this error for popping a word in a list/string? (Python 3.x)

I'm not exactly the kind of guy you call "good" at coding. In this particular scenario, on line 13, I'm trying to pop the first word in the list until I'm done, but it keeps giving me the 'str' object can not be interpreted as an integer issue.
What am I doing wrong here?
n = n.split(" ")
N = n[0]
K = n[1]
f1 = input()
f1 = f1.split(" ")
f1 = list(f1)
current = 0
for x in f1:
while current <= 7:
print(x)
f1 = list(f1.pop()[0])
current = current + len(x)
if current > 7:
print("\n")
current = 0
According your comments, this program will split lines to contain max K characters:
K = 7
s = "hello my name is Bessie and this is my essay"
out, cnt = [], 0
for word in s.split():
l = len(word)
if cnt + l <= K:
cnt += l
if not out:
out.append([word])
else:
out[-1].append(word)
else:
cnt = l
out.append([word])
print("\n".join(" ".join(line) for line in out))
Prints:
hello my
name is
Bessie
and this
is my
essay
You could try splitting the string on the index, and inserting a newline there. Each time you do this your string gets one character longer, so we can use enumerate (which starts counting at zero) to add a number to our slice indexes.
s = 'Thanks for helping me'
new_line_index = [7,11, 19]
for i, x in enumerate(new_line_index):
s = s[:x+i] + '\n' + s[x+i:]
print(s)
Output
Thanks
for
helping
me

I no longer have an alignment issue, however, when I print out my X's and O's there will be a 0 next to them. Does anyone know a different solution?

This is what I have so far, if you have any ideas please let me know. It would mean a lot to me.
a_list = list(range(1, squared_input + 1))
turn = 0
Symbol_1 = "X"
Symbol_2 = "O"
while turn <= 9:
X = 1
while X < squared_input + 1 :
print(str(a_list[X - 1]).zfill(2), end= "")
if X%board_size == 0 :
print("")
print(("--+" * (board_size - 1)), end="")
print("--")
else:
print("|", end="")
X = X + 1
turn = turn + 1
Symbol_1, Symbol_2 = Symbol_2, Symbol_1
print("You are user " + Symbol_1 + ".")
user_input = input("Please pick a slot on the game board (using numbers 1 - " + str(squared_input) + "): ")
a_list[int(user_input) - 1] = Symbol_1
The zeros come from your call to zfill which explicitly pads a string with 0 to a requested size. You call zfill(2) with a string that contains a single character. So the function pads that to length two by adding a 0.
To pad with blanks you can for example use the format() function or just something like
'%2d' % a_list[X-1]
which will pad each number to length 2 from the left with blanks, or
'%-2d' % a_list[X-1]
which will pad each number to length 2 from the right with blanks.

get single index number of a duplicate element in a list

I want to turn this "RqaEzty" into this "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy". it basically prints out a letter as many times as the index of it is.
I created the following method, but it has one mistake.
Every time a letter occurs twice or more in the input my output is wrong, because my code takes the same index of the letter appearing for the first time as for the same letter appearing the second time
E.g. "ZpglnRxqenU" should be
"Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu"
but I get:
"Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnn-Uuuuuuuuuuu"
because my code takes the same index for the first "n" as for the second "n"
def accum(s):
x = list(s)
s = ""
for y in x:
amount = 1 + (x.index(y))
word = y * amount
s += word.capitalize() + "-"
s = s.rstrip('-')
print(s)
my idea is to implement an if function into the "for loop" to control wether a letter occurs more than once and if yes to put out the index of the second (or third or fourth...) letter.
My question:
how do I put out the index of a duplicate as a single value?
Instead of looking for the index every time, you could iterate over the indexes themselves:
for i in range(len(x)):
y = x[i];
amount = 1 + i
word = y * amount
s += word.capitalize() + "-"
You can use a counter variable instead of (x.index(y))
def accum(s):
x = list(s)
s = ""
i=1 #change happens here
for y in x:
word = y * i #change happens here
s += word.capitalize() + "-"
i+1
s = s.rstrip('-')
print(s)
It will solve the error
If you need a value that increases each step, you can use enumerate().
Then it will work.
def accum(s):
x = list(s)
s = ""
for idx, y in enumerate(x):
amount = 1 + idx
word = y * amount
s += word.capitalize() + "-"
s = s.rstrip('-')
print(s)

Code randomly doesn't follow instructions of For Loop

I am attempting to create a program that finds the number of possible configurations using factorials. Here is my code so far:
from collections import Counter
letters = []
lettnum = []
trash = []
booleans = []
boolet = {}
def fact(n):
if n == 0:
return 1
else:
return n * fact(n - 1)
word = input("Word: ")
x = fact(len(word))
for char in word:
letters.append(char)
z = Counter(letters)
y = list(z.values())
ans = "print("
print(letters)
print(y)
for element in y:
if y[0] == element:
ans = ans + str(fact(element))
else:
ans = ans + "*" + str(fact(element))
ans = ans + ")"
print(ans)
If you enter the word tool, it is supposed to give an answer of
print(1*2*1)
but instead prints out
print(1*1*21*1)
I've noticed that it combines the 2 and 1 without adding a *, and it also adds random 1's for absolutely no reason. What's up with my code?
Some more info:
Text editor: Visual Studio Code
Python Version: Python 3.7.3
I don't fully understand the goal your program is trying to accomplish however I do see the issue of the behavior you are seeing
Your issue lies in how you are checking the first element
Notice this line is checking that element is == 1
if y[0] == element:
The last element is also 1 so it goes along the same path
A solution to this would be to write the loop like this
ans = "print(" + str(fact(y[0]))
for element in y[1:]:
ans += "*" + str(fact(element))
ans = ans + ")"
print(ans)

Diagonal shape in Python using while loops

I am working on a basic shapes program in Python and can't seem to work out my code. I need to keep it simple using while loops and the variables given, nested loops are usable.
Here is my code for a square:
def drawSquare(size, drawingChar):
print('Square: ')
row = 1
while row <= size:
# Output a single row
drawRow(size, drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
It is supposed to print like:
x
x
x
x
based on a size and character entered by the user.
drawRow is another function similar to drawSquare:
def drawRow(size, drawingChar):
col = 1
while col <= size:
print(drawingChar, end=' ')
col = col + 1
It would make more sense with a for loop:
def drawSquare(size, drawingChar):
for i in range(size):
print(" "*i + drawingChar)
Example:
drawSquare(4, "p")
Output:
p
p
p
p
Please show your work for drawDiagonal (or anything) when asking a question.
Diagonal is probably the easier case here:
def drawDiagonal(size, drawingChar):
for y in range(size):
s = ' '* y + drawingChar
print(s)
drawDiagonal(4,"X")
X
X
X
X
(Maybe pick a fixed font)
The solution I came up with is:
def drawDiagonal(size, drawingChar):
print('Diagonal: ')
row = 1
while row <= size:
# Output a single row
drawRow(row - 1, ' ')
print(drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
Note: drawRow is defined separately (above, in question)
& drawDiagonal was called separately as well:
drawDiagonal(userSize, userChar)
where
userSize = input('Size: ')
userChar = input('Character: ')

Categories

Resources