1

I want to create a rectangular pattern in Python (2.7). However, the end= option in the print statement gives the error.

rows =int(input("How many rows? ")
cols = int(input("How many columns? ")

for r in range(rows):
    for c in range(cols):
        print("*", end="")
    print()

My output should be like this when enter 5 rows and 10 columns

**********
**********
**********
**********
**********
mmustafaicer
  • 434
  • 6
  • 15

3 Answers3

4

If the end='' is giving an error, you're on Python 2; to use the Py3 print function, you need to add the following to the top of your program/module (or run it in the interpreter if you're running this code interactively):

from __future__ import print_function

Side-note: Python lets you multiply strings, so you can do this in a much easier way:

for r in range(rows):
    print('*' * cols)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
2

Your problem was that print("*",end="") is for Python 3. In Python 2, you should use a comma after print("*") to print on same line

(EDIT: Thanks @ShadowRanger, also note that the parenthesis are also optional in Python 2):

rows = int(input("How many rows? "))
cols = int(input("How many columns? "))

for r in range(rows):
    for c in range(cols):
        print("*"),
    print("")

See: Print in one line dynamically for more information on printing on same line.

Community
  • 1
  • 1
Patrick Yu
  • 972
  • 1
  • 7
  • 19
  • There is no reason to include the parens if you're using the Py2 print statement; the parens just fool you into thinking it's a function when it's not. Either import `print_function` from `__future__` and use parens, or use the statement form `print 'a',` and `print` without parens (and printing an empty line doesn't require printing an empty string at all). – ShadowRanger Dec 10 '15 at 02:23
  • @ShadowRanger Most times i would not include the parens on Py2 however when printing a string concatenated over multiple lines you can use parens to group it – jamylak Dec 10 '15 at 02:36
  • @ShadowRanger You said there is no reason to include the parens if youre using Py2 print statement, though it is sometimes necessary to group. It's maybe even good practise to use it in Python 2 so code can conveniently work in Python 3 – jamylak Dec 10 '15 at 03:03
2

First of all, you need an extra closing parenthesis after "int(input("How many rows? ")" and "int(input("How many columns? ")". Second, if you don't want to rely on the other methods mentioned, try this:

rows =int(input("How many rows? "))
cols = int(input("How many columns? "))
cnt = 0
for r in range(rows):
    for c in range(cols):
        cnt += 1
    strToPrint = "*" * cnt
    cnt = 0
    print(strToPrint)

This will work in both versions of Python.

sikez
  • 85
  • 10