2015-10-04 38 views
-2

我已经遇到了麻烦特定打印在Python 3.4 输入:打印Python代码多次(NO LOOPS0

str=input("Input Here!!!:") 
num = len(str) 
x = num 
print (((str))*x) 

,但我在寻找,打印海峡x倍的输出,而不。使用循环

例如,如果我输入:

Input Here!!!: Hello 

我会得到:

>>>Hello 
>>>Hello 
>>>Hello 
>>>Hello 
>>>Hello 
+2

不使用变量名的关键字。 –

+0

问题是什么?看起来你已经做到了。 –

+0

你想在单独的行中得到你好,你给出的输出是预期的输出?请包含更多信息。 – garg10may

回答

0

你需要,如果你想在不同的行输出添加新行:

In [10]: n = 5 

In [11]: s = "hello" 

In [12]: print((s+"\n")* n) 
hello 
hello 
hello 
hello 
hello 

这是不可能得到的输出,就好像每个字符串是一个新的命令的输出。最接近您的预期输出将是上面的代码。

+0

最后还有一个额外的换行符。尝试使用rstrip来删除它。 –

+0

@MalikBrahimi,除非他自己补充说,看起来并非如此。 – garg10may

+0

@MalikBrahimi,是'((s +“\ n”)* n).rstrip()'如果这是个问题,将会被移除 –

0

您不应该使用内置关键字,变量名称的类型。 str是一个像列表,int等内置类型。下次你会尝试使用它,会给你错误。

防爆 -

>>> str = 'apple' 

现在,让我们尝试构建编号S作为字符串的简单列表。

>>> [ str(i) for i in range(4)] 

Traceback (most recent call last): 
    File "<pyshell#298>", line 1, in <module> 
    [ str(i) for i in range(4)] 

类型错误: '海峡' 对象不是可调用

因为我们已经代替了我们的STR用字符串。它不能被调用。

因此,让我们使用的',而不是 '海峡'

s=input("Input Here!!!:") 
print (s * len(s)) 

如果你想在不同的线路

print ((s+"\n")* len(s)) 
+0

这更多的是试图清理他的答案,并且提到不使用保留。 – garg10may

+0

但'str'用于将某些输入转换为字符串,如int等。也许在技术上它们被称为别的东西。我认为使用它并不好。 – garg10may

+0

嗯我的不好,但仍然不应该使用函数名称作为变量名称,对不对? – garg10may

0

可以使用join与列表理解输出:

>>> s='string' 
>>> print('\n'.join([s for i in range(5)])) 
string 
string 
string 
string 
string 

从技术上讲,列表理解是一个'循环'我想,但你还没有明确表示你的意思是什么b Y“不使用循环”

您也可以使用字符串在Python格式:

>>> fmt='{0}\n'*5 
>>> fmt 
'{0}\n{0}\n{0}\n{0}\n{0}\n' 
>>> print(fmt.format('hello')) 
hello 
hello 
hello 
hello 
hello 

但(作为任何使用*n会),将有一个最后的额外\n


正如Tim在评论中指出的那样:

>>> print('\n'.join([s]*5)) 
string 
string 
string 
string 
string 

问题最好的...

+1

'\ n'.join([s] * 5)''怎么样? –

0

我不知道你到底想要达到什么目的。我们可以随时replicate loopingrecursive function

def input(s): 
    print(s) 

def pseudo_for(n, my_func, *args): 
    if n==0: 
     return 
    else: 
     ''' 
     Write function or expression to be repeated 
     ''' 
     my_func(*args) 
     pseudo_for(n-1, my_func, *args) 

pseudo_for(5, input, "Hello")