简体   繁体   中英

Why isn't my end = "" function working when being run?

When I ran this code in Python, it said that a syntax error had occurred at the equal sign.

x = int(input('Enter a number greater than 0:'))
while x <= 0:
    x = int(input('Enter a number greater than 0:'))
for i in range (x):
    print ("x", end="")

There are a couple things wrong with it

1. Using the print function in Python 2

You cannot use the syntax "print('something', end='')" in Python 2. The print statement in Python 2 has no attribute "end". It should just be print(x) or print x.

2. Trying to print the variable x in the loop

I think here you want it to print something like this:

x = 3
for i in range(x):
    print(i)

1 2 3

But you put this instead:

x = 3
for i in range(x):
    print(x)

3 3 3

Also, you put it as a string instead of the variable, so you won't even get that:

x = 3
for i in range(x):
    print('x')

x x x 

As others have already correctly pointed out, you are using python2 , and so print is still a statement and not a method , and it is written like :

print "your text"

Hence you not being able to access the end= method.


Now for some work abouts for them ( python2 ):

1. The easiest, import the python3 print method.

from __future__ import print_function

for i in xrange(x):
    print(x, end="")

2. Otherwise store the values that you want to print in a string and then print it at last.

s=''
for i in xrange(x):
    s+=str(i)

print(s)

3. Using list comprehension and join

print ''.join(str(i) for i in xrange(x))

For both, #driver values :

In : x = 3
Out : 012

Edit : in case it was as you wrote, and you want to print x x number of times, an easier way to do that is to do :

print str(x) * x

Out : 333

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