简体   繁体   中英

Creating a rectangular asterisk in Python 2.7

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

**********
**********
**********
**********
**********

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM