In Python the print function automatically takes new line after the statements, if we want to print the whole statement in a single line then what should be used?
For example:
>>> for number in range(1,6):
... for k in range (0,number):
... print ("*")
...
I got the following output:
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
While I need this one:
*
**
***
****
*****
Try the following in Python 2.x.x. You could use print "*"*i where i is a number which prints '*' for i number of times.
print "*" * 3
Output
***
All you have to do is to choose the value of i carefully.
for i in range(0,6): ## i increments through the range(0,6) for every iteration
print "*"*i ## "*" is printed 'i' times
Output:
*
**
***
****
*****
Set the end parameter of print to "" and put an extra print() just outside the inner loop:
for number in range(1,6):
for k in range (0,number):
print ("*", end="")
print() # This is needed to break up the lines.
Below is a demonstration:
>>> for number in range(1,6):
... for k in range (0,number):
... print ("*", end="")
... print()
...
*
**
***
****
*****
>>>
Use a comma after print:
>>> for number in range(1,6):
... for k in range (0,number):
... print ("*"),
... print()
Related
How do I print pattern in python as shown below:
My code:
for outer_loop in reversed(range(1, 5+1)):
for inner_loop in range(0,outer_loop):
# print(inner_loop*' ')
print('*',end='')
print()
Output:
*****
****
***
**
*
I want to give spaces on left side as shown below,
Expected Output:
*****
****
***
**
*
There is a method rjust on strings:
for n in range(5, 0, -1):
print( (n*"*").rjust(5) )
You don't need reversed(), range() can return a reversed range by using a negative step.
You can multiply a string to duplicate it, instead of using a loop.
Add the spaces by printing 5 - n spaces before n asterisks.
for n in range(5, 0, -1):
print(" " * (5-n) + "*" * n)
I'm supposed to create a recursive statement that if first calls triangle(n) it returns
'******\n *****\n ****\n ***\n **\n *'
This above is called for triangle(6) and if I print(triangle(6)) it returns below.
******
*****
****
***
**
*
Then I must create another code recursive_triangle(x, n) that returns a string with the LAST x lines of a right triangle of base and height n. For example if I did recursive_triangle(3, 6) it returns
' ***\n **\n *'
and if i print it should returns
***
**
*
So far my code is
#### DO NOT modify the triangle(n) function in any way!
def triangle(n):
return recursive_triangle(n, n)
###################
def recursive_triangle(k, n=0):
'''
Takes two integers k and n
>>> recursive_triangle(2,4)
' **\\n *'
>>> print(recursive_triangle(2,4))
**
*
>>> triangle(4)
'****\\n ***\\n **\\n *'
>>> print(triangle(4))
****
***
**
*
'''
# --- YOUR CODE STARTS HERE
if n == 1:
return "*"
else:
for i in range(1, n+1):
return ("*" *n) + "\n" + (' ' * i) + triangle (n - 1)
for print(triangle(4)) this is what i got
****
***
**
*
How do I modify the code to get the output above?
Your recursion case is ill-formed:
else:
for i in range(1, n+1):
return ("*" *n) + "\n" + (' ' * i) + triangle (n - 1)
First of all, this code returns after a single iteration: return ends your function instance, so i never gets to a value of 2. You need to do something simple, and then recur on a simpler case to handle the rest.
Next, triangle exists only to call recursive_triangle. Then, recursive_triangle needs to call itself, not loop back to triangle.
Finally, note that recursive_triangle utterly ignores the parameter k. This value is critical to determine where in the line to place the asterisks.
Each instance of recursive_triangle should produce a single line of the triangle -- you have that correct -- and then concatenate that line with the remainder of the triangle, returning that concatenated whole to the instance that called it. You'll want something roughly like:
else:
line = ... # build a line of k-n spaces and n asterisks
return line + recursive_triangle(k, n-1)
Can you take it from there? Among other things, remember to insert a few useful print commands to trace your execution flow and the values you generate.
First of all, there are better ways to achieve this.
However, if you really want to go this way, the following code can fix the spacing issues.
#### DO NOT modify the triangle(n) function in any way!
def triangle(n):
return recursive_triangle(n, n)
###################
def recursive_triangle(k, n=0):
'''
Takes two integers k and n
>>> recursive_triangle(2,4)
' **\\n *'
>>> print(recursive_triangle(2,4))
**
*
>>> triangle(4)
'****\\n ***\\n **\\n *'
>>> print(triangle(4))
****
***
**
*
'''
# --- YOUR CODE STARTS HERE
if n == 1:
return "*"
else:
for i in range(1, n+1):
return ("*" *n) + "\n" + (' ' * i) + triangle (n - 1).replace("\n", "\n ")
which gives you
****
***
**
*
in Python 3.6.5.
You can count the row with r and use a secondary parameter to count the spaces, s
def triangle (r = 0, s = 0):
if r is 0:
return ""
else:
return (" " * s) + ("*" * r) + "\n" + triangle (r - 1, s + 1)
print (triangle(5))
# *****
# ****
# ***
# **
# *
code.py:
#!/usr/bin/env python3
import sys
#### DO NOT modify the triangle(n) function in any way!
def triangle(n):
return recursive_triangle(n, n)
###################
def recursive_triangle(k, n=0):
'''
Takes two integers k and n
>>> recursive_triangle(2,4)
' **\\n *'
>>> print(recursive_triangle(2,4))
**
*
>>> triangle(4)
'****\\n ***\\n **\\n *'
>>> print(triangle(4))
****
***
**
*
'''
# --- YOUR CODE STARTS HERE
if k == 0:
return ""
else:
return "\n".join(["".join([" " * (n - k), "*" * k]), recursive_triangle(k - 1, n)])
#return " " * (n - k) + "*" * k + "\n" + recursive_triangle(k - 1, n)
def main():
print("triangle(6):\n{:s}".format(triangle(6)))
print("recursive_triangle(3, 6):\n{:s}".format(recursive_triangle(3, 6)))
print("repr recursive_triangle(2, 4): {:s}".format(repr(recursive_triangle(2, 4))))
print("repr triangle(4): {:s}".format(repr(triangle(4))))
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
Notes:
To make things simpler, you can look at recursive_triangle(k, n)'s argument meanings like:
k: Recursion step, and also the number of "*" characters. Decrements with every recursive function call
n: 1st (longest) triangle line length (the number of SPACEs + k). Remains constant inside recursion
Current line contains n - k SPACEs followed by k "*" s (n characters in total). Lines are joined together via [Python 3]: str.join(iterable) (or "manually", in the (next) commented line)
The function calls itself until there are no more "*" characters (k becomes 0)
Output:
(py35x64_test) e:\Work\Dev\StackOverflow\q052652407>"e:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py
Python 3.5.4 (v3.5.4:3f56838, Aug 8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32
triangle(6):
******
*****
****
***
**
*
recursive_triangle(3, 6):
***
**
*
repr recursive_triangle(2, 4): ' **\n *\n'
repr triangle(4): '****\n ***\n **\n *\n'
I am trying to print a pattern using Python but I cannot seem to figure out what I am doing wrong.
# The Pattern I am trying to create is as follows:
*******
******
*****
****
***
**
*
#Using the following code:
base = 8
for rows in range(base):
for columns in range(7,1,-1):
print('*',end='')
print()
for columns in range(7,1,-1) always prints 6 times. Maybe you meant for columns in range(7,rows,-1)? However this is easier:
for i in range(7,0,-1):
print('*' * i)
Another solution using "reverse order" slicing:
base = 8
for i in range(1, base)[::-1]:
print('*' * i)
The output:
*******
******
*****
****
***
**
*
Try the following:
for i in range(8):
print("*" * i)
That will actually print in wrong order, sorry, overlooked that.
for i in range(8,0,-1):
print("*" * i)
solution 1
for i in range(4,0,-1):
for j in range(0,i):
print('#',end=" ")
print()
solution 2
for i in range(0,4):
for j in range(0,4-i):
print('#',end=" ")
print()
You don't need to use Nested Loop You can easily do it with a simple for loop
base = 8
for rows in range(base,0,-1):
print("*"*rows)
I am trying to print out an arrow head using *s.
So far my code looks like this.
def head(n):
while n > 0:
print n * "*"
n = n - 1
print head(input())
and it works but if for example I enter 11, it prints this:
***********
**********
*********
********
*******
******
*****
****
***
**
*
But I want it to print like this:
*
***
*****
*******
*********
***********
Which has less arrows, but I can't figure out how to do it.
It makes the function a little simpler to think in terms of how many lines do you want:
def head(lines):
for n in range(1,lines*2,2): # count 1,3,5...
print(('*'*n).center(lines*2-1))
Output:
>>> head(5)
*
***
*****
*******
*********
Here's an alternate way to use a variable length format that is a little less obvious:
def head(lines):
for n in range(1,lines*2,2):
print('{:^{}}'.format('*'*n,lines*2-1))
use string formatting:
def head(size):
n=1
while n < size+1:
stars = n * "*"
print '{:^30}'.format(stars)
n += 2
it will center your asterisks on the field 30 chars wide.
def printHead(n):
for l in range(1,n):
print " "*(n-l)+"*"*(1 if l==1 else 2*l-1)
Each row has level-1 spaces. Then if it's the first level one start, otherwise it has 2*level-1.
>>> printHead(6)
*
***
*****
*******
*********
def head(n):
total = 2 * n - 1
s = ''
for i in xrange(1, n + 1):
k = 2 * i - 1
s += ' ' * ((total - k) / 2) + '*' * k + '\n'
return s
The number of stars on a line is equal to 2n - 1 where n is the line number.
I wouldn't call the parameter "n" in this function as it is not clear to me whether it refers to lines or stars.
You can use the center function to surround a string with whitespace, based on a specified width. You want the arrow to be centred around the longest line so you need 2 variables, one to keep track of the current line and another to remember the largest line.
You want to iterate in the opposite direction to what you have demonstrated, as you want the arrow to point up, not down.
I think this should work for you:
def head(total_lines):
for current_line in range(1, total_lines + 1):
print ((2 * current_line - 1) * "*").center(2 * total_lines - 1)
I would like to produce this picture in python!
*
**
***
****
*****
******
*******
********
*********
**********
I entered this:
x=1
while x<10:
print '%10s' %'*'*x
x=x+1
Which sadly seems to produce something composed of the right number of dots as the picture above, but each of those dot asterisks are separated by spaced apart from one another, rather than justified right as a whole.
Anybody have a clever mind on how I might achieve what I want?
'%10s' %'*'*x
is being parsed as
('%10s' % '*') * x
because the % and * operators have the same precedence and group left-to-right[docs]. You need to add parentheses, like this:
x = 1
while x < 10:
print '%10s' % ('*' * x)
x = x + 1
If you want to loop through a range of numbers, it's considered more idiomatic to use a for loop than a while loop. Like this:
for x in range(1, 10):
print '%10s' % ('*' * x)
for x in range(0, 10) is equivalent to for(int x = 0; x < 10; x++) in Java or C.
string object has rjust and ljust methods for precisely this thing.
>>> n = 10
>>> for i in xrange(1,n+1):
... print (i*'*').rjust(n)
...
*
**
***
****
*****
******
*******
********
*********
**********
or, alternatively:
>>> for i in reversed(xrange(n)):
... print (i*' ').ljust(n, '*')
...
*
**
***
****
*****
******
*******
********
*********
**********
My second example uses a space character as the printable character, and * as the fill character.
The argument to ljust or rjust is the terminal width. I often use these for separating sections with headings when you have chatty debug printout, e.g. print '--Spam!'.ljust(80, '-').
It's because of the operator precedence, use this one:
x=1
while x<10:
print '%10s' % ('*'*x)
x=x+1
print '\n'.join(' ' * (10 - i) + '*' * i for i in range(10))
To be exact, as your picture ends with 10 asterisks, you need.
for i in range(1, 11):
print "%10s"%('*' *i)