【问题标题】:dimensions of a +--+ box in Python 3.4Python 3.4 中 ++ 框的尺寸
【发布时间】:2016-01-02 07:20:47
【问题描述】:

这是我的问题

创建一个接受用户输入的数字的程序。这个数字定义了正方形的尺寸,可以是任何正整数。输入 1 将输出:

    +--+
    +--+

while an input of 2 will output

    +--+--+
    +--+--+
    +--+--+

and an input of 3 will output

    +--+--+--+
    +--+--+--+
    +--+--+--+
    +--+--+--+

etc…Show outputs for user inputs of 1, 2, 3, and 4. 

不完全确定从哪里开始,并希望得到一些建议,但是我不是在寻找完整的答案(毕竟,这是家庭作业),但是非常感谢能够为我指明正确方向的东西.

【问题讨论】:

  • for _ in range(n + 1): print("--".join("+" * (n + 1))) 什么的。
  • 一次一步。首先创建一个接受用户输入的数字的程序。做到了吗?现在确保这是一个正数,记住 raw_input()(假设 Python 2)返回一个字符串。首先让所有这些工作。现在研究使用循环,或者甚至是字符串上的* 运算符,有几种方法可以做到这一点。
  • 非常感谢,谢谢

标签: python dimensions


【解决方案1】:

考虑一下:

"--".join("++")

给你一个盒子的一行:

+--+

要重复多行,你可以这样做:

"--".join("+" * (some_count+1))

为此,您将获得输出:

+--+        # 1
+--+--+     # 2
+--+--+--+  # 3
...

现在我们只需要对许多垂直线重复此操作。您可以考虑使用"\n".join 重复,或者您可以使用for 循环并打印多行。这就是你的工作!

【讨论】:

    【解决方案2】:

    结束了

    """Problem set 2 question 2 box problem Joe White 2016"""
    num=int(input("enter a number ")) #Assigns user's number to variable num
    for blank in range (num+1): print ("--".join("+" * (num+1))) #print ("--".join("+" * (num+1))): prints +--+ as many times as the user entered. However if more than 1 it prints in the form +--+--+ instad of +--++--+. for blank in range (num+1) adds another column of +--+ underneath to create a box 
    

    适用于所有输出。感谢所有发表评论/答案的人!

    【讨论】:

    • 如果你只是丢弃循环变量,你应该使用_ 而不是blank。在 Python 中 _ 没有什么特别之处,但它习惯性地用于告诉未来的编码人员您不使用该变量。 blank 可能有意义,_ 永远不会。
    • @AdamSmith。如果您正在进行国际化,_ 可能有意义。指示值被丢弃的显式名称可以使代码更清晰,更不容易出错。
    • @MadPhysicist 我们在 Python 中有一个。这是_for _ in some_iterator 在惯用的 Python 代码中随处可见。
    • 谢谢。我发现那个帖子是因为我第一次遇到_ 它把我搞糊涂了。
    猜你喜欢
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2020-12-26
    相关资源
    最近更新 更多