简体   繁体   English

如何打印一个短语n次?

[英]How to print a phrase n times?

this may seem like a question that's been asked before, and it is, but there are some tweaks I need help with.这似乎是一个以前被问过的问题,而且确实如此,但我需要帮助进行一些调整。

I am writing a program that will print a phrase n times both in upper and lower case one after another .我写一个程序,将在陆续大写和小写一个打印语句n次都。 My code so far is:到目前为止我的代码是:

expression = str("my name is TONY")
n = int(5)
for i in range(n):
        print(expression.lower())
        print(expression.upper())

Lets say the expression is "My name is Tony" and we want it printed 5 times, I am getting the following input:假设表达式是“我的名字是托尼”,我们希望它打印 5 次,我得到以下输入:

my name is tony
MY NAME IS TONY
my name is tony
MY NAME IS TONY
my name is tony
MY NAME IS TONY
my name is tony
MY NAME IS TONY
my name is tony
MY NAME IS TONY
my name is tony
MY NAME IS TONY

However, I want the following output, where the phrase is expression is printed 5 times in total, not 10 times like above.但是,我想要以下输出,其中短语是 expression总共打印了5 次,而不是像上面那样打印10 次。

my name is tony
MY NAME IS TONY
my name is tony
MY NAME IS TONY
my name is tony

You can use modulo operator % :您可以使用模运算符%

expression = "my name is TONY"
n = 5

for i in range(n):
    if i % 2:
        print(expression.upper())
    else:
        print(expression.lower())

Prints:印刷:

my name is tony
MY NAME IS TONY
my name is tony
MY NAME IS TONY
my name is tony

I see them repeated 3 times:我看到他们重复了 3 次:

expression = "my name is TONY"
n = 3

for i in range(n):
    print(expression.lower())
    if not i == 2:
        print(expression.upper())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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