简体   繁体   English

Python 通过接受 5 位数字作为输入进行图案打印

[英]Python Pattern Printing by accepting 5 Digit number as input

We were asked to write python program to read 5 digit number for example if the user entered 12345 the result should be:我们被要求编写 python 程序来读取 5 位数字,例如,如果用户输入 12345,结果应该是:

1
12
123
1234
12345

I have written something like below but it's not working and appending the output to earlier digit.我写了类似下面的内容,但它不起作用并将 output 附加到较早的数字。

n = '12345'
for i in range(len(n)+1):
    for j in range(i+1):
         print(n[0:j],end = "")
    print()

The wrong output is错误的output是

1
112
112123
1121231234
112123123412345

Please help in achieving the output in above format mentioned.请帮助实现上述格式的 output。 Thanks in advance!提前致谢!

You can use您可以使用

for i in range(1, len(n) + 1):
    print(n[:i])   

There's no need for a nested loop here.这里不需要嵌套循环。

your answer has four errors你的答案有四个错误

error 1: range of i should be 1 to len(n)+1 if u take zero it will print space in first line,for avoiding that start ur range (1,len(n)+1)错误 1:i 的范围应该是 1 到 len(n)+1 如果你取零它会在第一行打印空格,以避免开始你的范围 (1,len(n)+1)

error 2: range of j should be i only cause i+1 is sending it out of range错误 2:j 的范围应该是 i 只是因为 i+1 将它发送到范围之外

error 3: as u are doing slicing of string u have to pass the the j only cause u are slicing the string from one index number to other....but u just need the letter of that index错误 3:当你正在对字符串进行切片时,你必须传递 j 只是因为你正在将字符串从一个索引号切片到另一个......但你只需要该索引的字母

error 4: in the last line u have to print("\r") so that it will go to new line错误 4:在最后一行你必须打印(“\r”)这样它将 go 换行

n = '12345'
for i in range(1,len(n)+1):
    for j in range(0,i):
        print(n[j],end = "")
    print("\r"

output will be like this: output 会是这样的:

 <pre> 1 12 123 1234 12345 </pre>

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

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