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: ')
Related
Is it possible to select a specific question marks from a loop and replace it with random.choice(letters) when chosen?
For example:
0 1 2
0 ? ? ?
1 ? ? ?
2 ? ? ?
User inputs 11 for example:
0 1 2
0 ? ? ?
1 ? M ?
2 ? ? ?
This is what i have done to show the board, but I have no clue how to select each question marks when the user input e.g (01 (0row 1column))
def create_game_board(rows, cols):
board = dict()
# save dimensions inside the dict itself
board['cols'] = cols
board['rows'] = rows
for y in range(rows):
for x in range(cols):
# add random letter to board at (x,y)
# x,y makes a tuple which can be a key in a dict
# changed to use string.ascii_uppercase so that you don't forget any letter
board[x, y] = random.choice(string.ascii_uppercase)
# change last element to # when both dimensions are odd
if (rows * cols) % 2 == 1:
board[rows-1, cols-1] = "?"
return board
def display_board(board):
# get dimensions
cols, rows = board['cols'], board['rows']
# print header
print(' '*30+" ".join([' '] + [str(x) for x in range(cols)]))
for y in range(rows):
# print rows
# print(' '.join([str(y)] + [board[x, y] for x in range(cols)])) # to display the actual letter at this location
print(' '*30+" ".join([str(y)] + ['#' if board[x, y] == '?' else '?' for x in range(cols)])) # using your display function
print() # separator empty line
board = create_game_board(rows[0], columns[0])
display_board(board)
def choice():
print('Hello ' + player[0]+"!")
cellnumber = input("Which cell do you want to open? (rowcolumn)")
print(cellnumber)
choice()
First, I suggest simplifying the majority of your code with the itertools module. To change get the user input (assuming it is valid), use a list comprehension to convert each character to an integer, destructure the list into col and row, then change board[col, row] to random.choice(string.ascii_uppercase). Like this:
import itertools
import random
import string
def create_board(cols, rows):
board = {k: '?' for k in itertools.product(range(cols), range(rows))}
board['dims'] = (cols, rows)
return board
def display_board(board):
cols, rows = [int(x) for x in board['dims']]
print(' ', *(str(x) for x in range(cols)))
for row in range(rows):
print(row, *(board[col, row] for col in range(cols)))
board = create_board(3, 3)
while True:
display_board(board)
row, col = [int(ch) for ch in input('Which cell do you want to open? (rowcolumn) ')]
board[col, row] = random.choice(string.ascii_uppercase)
I also added an infinite loop to keep the program going, but you can change this to fit the constraints of your program.
You can try to update the choice function to:
def choice(board):
print('Hello ' + player[0]+"!")
cellnumber = input("Which cell do you want to open? (rowcolumn)")
row = int(cellnumber[0])
col = int(cellnumber[1])
board[row, col] = random.choice(string.ascii_uppercase)
display_board(board)
enter image description here5
I have to use a for loop to code this. I have tried many times but it never works.
enter code here
num_of_times = 5
for x in range(1, num_of_times, 5):
for y in range(5, i+5):
print(y, end= '')
print('')
You can try this:
lst = []
for i in range(1, 5):
lst.append(i * 5)
print(*lst)
You basically want to print multiple of 5. That could be achieved with two nested for loops:
max = 5
for i in range(max):
line = ''
for j in range(i+1):
line += str(5 * (j+1)) + ' '
print(line)
The first loop goes from 0 to max-1 and stores the index in i ; the second loop goes from 0 to i+1 and stores the index in j.
Then, the result of 5 * (j+1) is added to a variable called line printed at the end of the j-loop.
Feel free to follow the loops and the value of each variable at every step with a paper and a pen, that should help you.
Here you go
for i in range(1,6):
for j in range (1, i+1):
print(j*5, end = ' ')
print('')
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])
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]
I'm a beginner and trying to learn Python by myself. I've been working on coding some basic shape exercises, so far I have the following code to make a diagonal.
size = input('Please enter the size: ')
chr = raw_input('Please enter the drawing character: ')
row = 1
while row <= size:
col = 1
while col < row:
print ' ',
col = col + 1
print chr
row = row + 1
print ''
I get this output :
X
X
X
X
I would love some help on how to make this into a triangle like this....
X X X X
X X X
X X
X
Any explanations on how to make the loop necessary for the characters to show up to make the triangle shaped output would be appreciated.
You can do:
>>> for i in xrange(4):
... print ' ' * i + 'X ' * (4 - i)
...
X X X X
X X X
X X
X
The value of i goes from 0 to 3 (by using xrange) and it prints the string ' ' (two spaces) i number of times and it prints 'X ' in total (4 - i) number of times. This means it'll print the inverted triangle as desired.
The simplest fix is just to print the character print chr, instead of space print ' ',.
To invert the result vertically a simple change in the condition, from while col < row: to while col < (size - row + 1): will suffice. And finally, to invert it horizontally, add a loop that prints spaces:
size = input('Please enter the size: ')
chr = raw_input('Please enter the drawing character: ')
row = 1
while row <= size:
col = 1
while col < row:
print ' ',
col = col + 1
col = 1
while col < (size - row + 1):
print chr,
col = col + 1
print chr
row = row + 1
print ''
And finally, you can simplify this a bit:
size = input('Please enter the size: ')
chr = raw_input('Please enter the drawing character: ')
row = 1
while row <= size:
col = 1
while col < size:
if col < row:
print ' ',
else:
print chr,
col = col + 1
print chr
row = row + 1
print ''
Result:
Please enter the size: 4
Please enter the drawing character: x
x x x x
x x x
x x
x
And of course you can make this really simple looking at Simeon Visser's answer.
I wrote some code earlier that does shapes, its a bit more detailed than what you might need, but here it is:
>>> def make_triangle(size, siblings=1, step=1, char='*'):
return '\n'.join([' '.join(line) for line in [[char * (i-(step*sib)) + ' ' * (((size-(step*sib))-(i-(step*sib)))) for sib in xrange(siblings)] for i in xrange(1, size+1)]])
Making some triangles:
>>> print make_triangle(4, char='X') # standing
X
XX
XXX
XXXX
>>> print make_triangle(4, char='X')[::-1] # hanging (reversed)
XXXX
XXX
XX
X
Some of the extra features:
>>> print make_triangle(6,3,2)
*
**
*** *
**** **
***** *** *
****** **** **