在这个练习中我应该把变量放在哪里?

我得到了这个练习,其中我打印的句子的结尾必须是符号/字母“p”。当我运行这个程序时,结果是这样的: 如果我使用数字 9:


p q p q


p q p


p q 


正如您所看到的,“p”始终位于句子的开头,但我希望它始终位于句子的末尾。像这样的东西。

q p q p


p q p


q p


p

我认为变量“a”每次都必须减1。虽然,我不知道该把它放在哪里。这是代码。

number = int((input()+1)/2 - 1)


i = 1


while i <= number:


    a = number

    while a >= i:

        if a % 2 == 0:

            print("q", end = " ")

            a -= 1

        elif a % 2 == 1:

            print("p", end = " ")

            a -= 1

    print()

    i += 1


杨魅力
浏览 4138回答 3
3回答

慕娘9325324

在此示例中,您要查看的行数是与输入 + 1 相加的整数。1+2+3+4 = 10 = 9+1。将有 4 行,并且在每行上您想要跟踪该行上的字母数。使用更好的变量名称可以更轻松地遵循代码。input = 9n_lines = 1i = 1while i < input:&nbsp; &nbsp; i += n_lines&nbsp; &nbsp; n_lines += 1for line_number in range(n_lines):&nbsp; &nbsp; number_letters = n_lines - line_number&nbsp; # This will be number of letters: 4, 3, 2, 1&nbsp; &nbsp; for i in range(number_letters - 1):&nbsp; &nbsp; &nbsp; &nbsp; print("q", end="")&nbsp; &nbsp; print("p")

HUH函数

我对你的代码做了一些更改(与 python 3 一起使用)input_num = int(input())number = int((input_num + 1) / 2 - 1)def print_line(line_length):&nbsp; &nbsp; if line_length % 2 == 1:&nbsp; &nbsp; &nbsp; &nbsp; # start with p&nbsp; &nbsp; &nbsp; &nbsp; letters = ['p', 'q']&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; # start with q&nbsp; &nbsp; &nbsp; &nbsp; letters = ['q', 'p']&nbsp; &nbsp; for i in range(line_length):&nbsp; &nbsp; &nbsp; &nbsp; pos = i % 2&nbsp; &nbsp; &nbsp; &nbsp; # print the relevant letter&nbsp; &nbsp; &nbsp; &nbsp; print(letters[pos], end=' ')&nbsp; &nbsp; print()我做了一个知道如何打印特定行的方法。它接收line_length并知道如何打印 p 和 q。如果行长是奇数,我们需要从 p 开始1 - p3-pqp5 - pqpqpETC..如果线长是偶数,我们从 q 开始2 - qp4 - qpqp6 - qpqpqpETC...for n in range(number, 0, -1):&nbsp; &nbsp; print_line(n)

SMILET

使用 [-1] 将“p”放在末尾
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python