This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this problem---
Write code that will print a multiplication table for 10 positive integers across the columns and 10 positive integers down the rows. Prompt the user for the starting values for both the columns and the rows.
My attempt after some explanation from another question, which doesn't print like Id expect it. Where do I call the print statements and what is wrong with the iterations
row = int(raw_input("Enter the first row number: " ))
col = int(raw_input("Enter the frist column number: "))
lastRow = row + 10
lastCol = col + 10
while (row < lastRow):
print "%4d" % (col * row)
while(col < lastCol):
print "%4d" % (col * row),
col += 1
print "%4d" % (col * row)
row += 1
Here's a second go, better but not what I thought get
row = int(raw_input("Enter the first row number: " ))
col = int(raw_input("Enter the frist column number: "))
lastRow = row + 10
lastCol = col + 10
x=row
y=col
while (x < lastRow):
while(y < lastCol):
y += 1
print "%4d" % (y * x)
x += 1
Sorry about the duplicate post, I didn't know that was bad etiquette
(1) Your col variable is not getting reset for each new row.
It is just always incrementing.
Maybe use another pair of variables, like r and c for the iteration itself.
Or store the original row and col in differently-named variables.
(2) Your indentation of the last two lines seems wrong - shouldn't it be inside the first while loop?
(3) You do not need so many print statements.
You should only need one print statement in the inner loop, and another (empty one) to end each line.
Update: Please don't post duplicate questions
Quick edit that does the trick:
row = int(raw_input("Enter the first row number: " ))
col = int(raw_input("Enter the frist column number: "))
lastRow = row + 5
firstCol = col
lastCol = col + 5
while (row < lastRow):
while(col < lastCol):
print "%4d" % (col * row),
col += 1
col = firstCol
row += 1
print
Problems in your code:
col kept at lastCol value in the end of first cycle iteration. It should be reset to starting point after each row
Too many unnecessary print's
row increment should be done inside of first while
And a tip: if you get stuck with problems like this, get a piece of paper, put down simple and small starting values: row = 1, col = 1, up to 3's instead of 10's. And reproduce your algorithm by hand, step by step.
Related
I'm trying to make a loop that prints numbers exactly like this:
1
12
123
1234
12345
I already have this pattern down for different characters, and can even print this:
1
22
333
4444
55555
But I'm having a big headache trying to figure out how I can make it count. Any help would be greatly appreciated.
Here is the code I have to print the list above:
for row in range (number_of_rows + 1):
for column in range(row)
print (row, end='')
print()
Sorry, I was just going to make a comment, but this will be easier:
for row in range (number_of_rows + 1):
for column in range(row)
print (column+1, end='') #<-- put column here instead of row and add a "+1"
print()
Some more details of what is going on:
for row in range (number_of_rows + 1):
Iterate from zero to number_of_rows. e.g. if number of rows was 5 this would iterate through a row of 0,1,2,3,4,5
for column in range(row):
For each row iterate from 0 to the row number minus 1. e.g. row 3 would iterate through 0, 1, 2
print (row+1, end='')
Print the column, one digit at a time. To start the row at 1 we need to add 1
If I'm understanding correctly, you could do something like
for i in range(1, rows + 1):
print(''.join(str(j) for j in range(1, i + 1)))
outputs:
1
12
123
1234
12345
This should be how the code works:
n = int(input()) #number of rows, for example 3
m = int(input()) #number of columns, for example 5
Then the user is going to enter a value for a row followed by a value for column.
x = int(input()) #This should be the row number, for example row 1
y = float(input()) #This should be the value for each position inside of each x.
Both x and y need to follow certain conditions so I have them apart. In theory it should look something like this:
matrix = [ [0.4], [0.3, 0.2, 0.5], [0.7] ] #Row 1 has 1 float, Row 2 has 3 float and Row 3 only 1
Some floats are going to enter on different rows, like row 1 can have three floats from the input, and another row (row 3) could have 5 floats from the input.
I have tried using the following loop:
for i in range(n): #I have tried multiple ways using len function, append function, etc.
for j in range(m):
But I can't seem to be able to assign each value on the matrix as I have to make sure that the inputs follow certain conditions as the program should read as many different floats as te variable "m" goes.
The reason why I am elaborating the code this way is because I have to calculate an average (in a different function) based on the different values that I get from the float input, making them go through a formula that I already had done before.
From what I understand, this should be roughly what you need:
row_input_count = int(input("please enter the number of rows you want to input: "))
column_count = int(input("please enter the number of columns: "))
matrix = []
for _ in range(row_input_count):
row_index = -1
while row_index < 0:
row_index = int(input(f"please select a row: "))
matrix = matrix + [[0] * column_count] * (row_index + 1 - len(matrix))
values = [0] * (column_count + 1)
while len(values) > column_count:
value_string = input(f"please input up to {column_count} values for row {row_index}: ")
values = [float(x) for x in value_string.split()]
values = values + [0] * (column_count - len(values))
matrix[row_index] = values
print("The resulting matrix: [")
for row in matrix:
print(row)
print("]")
Does this help you understand how the parts you already figured out could work together? I think it should be all relatively easy to read. Python's syntax for repeating elements in a list might be a bit strange to get used to:
>>> ["hi"] * 3
['hi', 'hi', 'hi']
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: ')
I have a coding assignment to input row and column length, and create a power table. THe example below is for 5 rows, 5 columns.
The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work. It just shows a table of 1's, five by five.
rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))
x = 1
y = 1
z = 1
line = ""
while x <= cols :
line = line + format(y**cols, "4d")
x = x + 1
while z <= rows :
print(line)
z = z + 1
The basic problem is that you need to nest your loops. Your second problem is that you never change y. What you do at the moment is to compute the power sequence for 1 into five different lines -- and then you print that last line only five times. Try two changes:
Compute a line, then print it immediately. Then you go to the next line.
Use the correct variable.
After changes:
while z <= rows:
while x <= cols:
line = line + format(x**cols, "4d") # Note the variable change
x = x + 1
print(line)
z = z + 1
Also, look up the for statement, as this will simplify things. After that, look up list comprehension for even more compression.
Here is a way to do it that preserves padding no matter what:
def grid(rows, cols, padding):
max_num_len = len(str(rows**cols))
return '\n'.join([
''.join(['{{:>{}}}'.format(max_num_len+padding).format((row+1)**(col+1))
for col in range(cols)])
for row in range(rows)
])
print(grid(5, 5, 3))
Instead, try creating a 2D array in Python such as a 2D list.
Matrix = [[0 for x in range(5)] for y in range(5)]
for i in range(5):
for j in range(5):
Matrix[i][j]=j^i
Then, print the data you need using nested for loops.
for i in range (5):
for j in range(5):
print(Matrix[j][i])
Alright, so I've been staring at my screen for the past few hours trying to solve this problem. I have to create a diagonal line that which could have any character.
Needs to look like something like this:
*
*
*
This is my code that I have right now.
# Draw a Diagonal
row = 1
while row <= size:
# Output a single row
col = 1
while col <= row:
# Output the drawing character
print()
# The next column number
col = col + 1
# Output a newline to end the row
print(end=drawingChar)
# The next row number
row = row + 1
print()
and it doesn't come out close to anything like a diagonal line! Could use some insight, thank you for the help. I have to use nested loops. I saw a couple other questions like this on the search, but they don't work for my assignment.
you can do this with a simple for loop:
>>> for i in range(5):
print(' '*i, end = '*\n')
*
*
*
*
*