How to create a right triangle with asterisk without def function? - python

So far what I have is:
base = int(input("Enter a value"))
for row in range(base):
for colomb in range(row+1):
print('*', end='')
print()

You were nearly there. You just need to unindent the last print(). Example -
for row in range(base):
for colomb in range(row+1):
print('*', end='')
print()

Sharon's answer is the quickest solution to make the code you have work, but you could also do fewer runs through for loops by just printing (once) the entire string. "a" * 3 is "aaa", for instance, so you could do:
for row in range(1, base+1): # now the range runs [1-base] instead of [0-base-1]
print("*" * row)

Related

Printing a simple matrix in python using nested for loops

I am having trouble with my assignment.
Print out a 3x3 matrix of “-”s using for loops.
It should look like this:
- - -
- - -
- - -
This is the closest I have come but it's not working
x = "-"
for i in range(3):
for n in range(3):
for x in range(3):
print x,
You will need nested for loops to accomplish this.
I have been trying this for an hour with no luck, can someone please point me in the right direction?
for i in range(21/7):
print ' '.join(['-' for _ in range(264/88)])
In your code, x is defined to be -, so you shouldn't enumerate over it.
I edited your code to produce a working version.
Note that in the internal loop you need to put spaces between the -, while in the external loop you want to move to the next line.
Here is the code for python 3:
x = "-"
for i in range(3):
for n in range(3):
print(x, end=' ')
print('\n')
Here is the code for python 2:
x = "-"
for i in range(3):
for n in range(3):
print x,
print('\n')
Very good start!
Let's think through, what were you trying to achieve with your 3rd loop.
(Hint: you don't need a third loop).
If you talk out what you need to happen it becomes:
1) print a "- " three times. (inner loop)
2) print a new line
3) now go back and repeat steps 1) and 2) three times (outer loop)
That would only be 2 loops, not 3.
Try This:
x = "- "
for i in range(3):
for n in range(3):
print x,
print "\n"
You could even shorten this to
for i in range(3): # print the following line 3 times
for n in range(3): # print 3 dashes, separated by a space
print "- ",
print "\n" # begin a new line
BTW, print x, is proper if using Python 2, but for Python 3, it will need to be changed to print(x, end='').
construct a matrix using nested loop:
matrix = [[],[],[]]
for x in range(0,3):
for y in range(0,3):
matrix[x].append("-")
then print it:
for i in range(3):
print(matrix[i])

How do I print only one new line in Python? "\n" does not give me my desired effect

I am well aware of print("\n"), but that gives this result in my cmd:
The first output (with the "raw" lists) continue on to the next line, but using \n seems to skip a line. How can I make sure that the print_pretty function goes to the next line, instead of skipping a line?
This is my code so far:
board = [["#" for i in range(5)] for y in range(5)]
def print_pretty(b):
for _ in b:
for __ in _:
print(__, end=" ")
print("\n")
print(board)
print_pretty(board)
print() adds a newline. Just print without arguments:
print()
or tell it not to add a newline:
print('\n', end='')
The latter is much more verbose than it needs to be of course.
This line print("\n") needs to be under print(__, end=" ") remember the spaces
or add print('\n', end='') to print the new line

(Python 3) avoid printing comma at the end in print(variableName,end=',')

I have a code that print x number of numbers. Firstly, I asked for the serious length. Then print all the previous numbers (from 0 to x).
My question is that:
when printing these number, I want to separate between them using comma. I used print(a,end=',') but this print a comma at the end also. E.g. print like this 1,2,3,4,5, while the last comma should not be there.
I used if statement to overcome this issue but do not know if there is an easier way to do it.
n=int(input("enter the length "))
a=0
if n>0:
for x in range(n):
if x==n-1:
print(a,end='')
else:
print(a,end=',')
a=a+1
The most Pythonic way of doing this is to use list comprehension and join:
n = int(input("enter the length "))
if (n > 0):
print(','.join([str(x) for x in range(n)]))
Output:
0,1,2
Explanation:
','.join(...) joins whatever iterable is passed in using the string (in this case ','). If you want to have spaces between your numbers, you can use ', '.join(...).
[str(x) for x in range(n)] is a list comprehension. Basically, for every x in range(n), str(x) is added to the list. This essentially translates to:
data = []
for (x in range(n))
data.append(x)
A Pythonic way to do this is to collect the values in a list and then print them all at once.
n=int(input("enter the length "))
a=0
to_print = [] # The values to print
if n>0:
for x in range(n):
to_print.append(a)
a=a+1
print(*to_print, sep=',', end='')
The last line prints the items of to_print (expanded with *) seperated by ',' and not ending with a newline.
In this specific case, the code can be shortened to:
print(*range(int(input('enter the length '))), sep=',', end='')

python asterisk triangle without using y* "*"

I'm trying to create a iso triangle (one that starts in the middle).
I have a code but the problem is that I'm not allowed to use Y* "*" 5 in my code.
(The y is a variable there)
Also I may only use one print statement at the end of my code.
Can you please help me out.
f = int(raw_input("enter"))
for i in range(f):
print " " * (f-i-1) + "*" * (2*i+1)
creats this triangle
*
***
*****
*******
*********
***********
However, you are not allowed to use the *-operator on string and int. So for example ''***'' * 3 is not allowed, but 3 * 4 is
This just creates a continuous string and then prints it at the end
f = int(raw_input("Enter height: "))
s = ''
for i in xrange(f):
for j in xrange(f-i-1):
s += ' '
for j in xrange(2*i+1):
s += '*'
s += '\n'
print s
This is a solution which i think is very easy to understand. You can make the parameter of range() variable, to make it more dynamic.
from __future__ import print_function
for i in range(1,12,2):
count=(11-i)/2
for j in xrange(count):
print(" ",end='')
for j in xrange(i):
print("*",end='')
for j in xrange(count):
print(" ",end='')
print(end="\n")
I think the best solution is using the center() string method:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
star += "**" if X>0 else ""
full_string += star.center(2*f-1) + "\n"
print full_string[:-1]
The str.center() documentation:
https://docs.python.org/2/library/string.html#string.center
EDIT: If you can't use the print statement within the for loop, you could concatenate the string during the loop and print it at the end:
f = int(raw_input("How many rows to print in the triangle? "))
star = "*"
full_string = ""
for X in xrange(f):
# the first row should take only one star
star += "**" if X>0 else ""
star2 = star.center(2*f-1)
full_string += star2 + "\n"
# slice the string to delete the last "\n"
print full_string[:-1]
I noticed that using a for loop add a newline character. If you want to avoid this, you can slice the string before printing.
There is no problem with this code, i just checked it and it worked fine. If you would post the error message we might be able to help a bit more.

Python - spaces

I can't get over this little problem.
The second is right.
How can i print without spaces?
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: print "*",
else: print "+",
print
thanks for help!
By not using print plus a comma; the comma will insert a space instead of a newline in this case.
Use sys.stdout.write() to get more control:
import sys
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: sys.stdout.write("*")
else: sys.stdout.write("+")
print
print just writes to sys.stdout for you, albeit that it also handles multiple arguments, converts values to strings first and adds a newline unless you end the expression with a comma.
You could also use the Python 3 print() function in Python 2 and ask it not to print a newline:
from __future__ import print_function
def square(n):
for i in range(n):
for j in range(n):
if i==0 or j==0 or i==n-1 or j==n-1: print("*", end='')
else: print("+", end='')
print()
Alternatively, join the strings first with ''.join():
def square(n):
for i in range(n):
print ''.join(['*' if i in (0, n-1) or j in (0, n-1) else '+' for j in xrange(n)])
Can you try to use sys.stdout.write("+") instead of print "+" ?
In python 3 you can overwrite the print behaviour, here this will solve your problem:
print("+", end="")

Categories

Resources