[英]How to print something a specific number of times based on user input?
So I'm a beginner to Python, I don't know many things and I'm stuck on one specific thing.所以我是 Python 的初学者,我不知道很多事情,我被困在一个特定的事情上。
I don't know how to print {variable}
number of times stored in choice
我不知道如何打印存储在
choice
{variable}
次数
Sorry if this sound stupid对不起,如果这听起来很愚蠢
choice = input("How many time do you want to {something}: ")
{variable} = "{something}"
# End of Variables
if choice_number > 0:
print({variable})
I'm very sorry, if my question sounds weird English isn't my first language..非常抱歉,如果我的问题听起来很奇怪 英语不是我的母语..
Use a for
loop:使用
for
循环:
choice = input("How many times do you want to print {something}: ")
variable = "{something}"
for i in range(int(choice)):
print(variable)
We use int(choice)
to transform the string that user input gets parsed as, into an integer.我们使用
int(choice)
将用户输入解析为的字符串转换为整数。 Then we use the built-in function range()
to create a list of numbers from zero until that integer, and iterate through them with a variable named i
.然后我们使用内置函数
range()
创建一个从零到该整数的数字列表,并使用名为i
的变量迭代它们。 We don't do anything with i
(though we could), just print variable
once for every iteration.我们不对
i
做任何事情(尽管我们可以),只是为每次迭代打印一次variable
。
Will print会打印
{something}
{something}
{something}
...
Green Cloak Guy 's magnificent answer is definitely the best if you want to print the same thing on multiple lines.如果您想在多行上打印相同的东西, Green Cloak Guy的宏伟答案绝对是最好的。 For the sake of completeness, I think it would be helpful for you to learn that in python you can multiply a string by a number.
为了完整起见,我认为了解在python中可以将字符串乘以数字对您有所帮助。 Let's see an example:
让我们看一个例子:
choice = input("How many times do you want to print {something}: ")
variable = "{something}"
print(variable * int(choice))
variable will be printed choice
times on the same line.变量将在同一行上打印
choice
时间。 Your output will be:您的输出将是:
{something}{something}{something}{something}...
{某事}{某事}{某事}{某事}...
usually, in many languages, when you wanna do_something()
, x
times what you do is use a loop.通常,在许多语言中,当您想要
do_something()
, x
倍您所做的是使用循环。
for i in range(x):
do_something()
here:这里:
choice = int(input("How many time do you want to {something}: "))
variable = "{something}"
#} End of Variables
if choice > 0:
for i in range(choice):
print(variable)
notice that I did some syntax cleanup注意我做了一些语法清理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.