[英]“How can I modify the below program so it prints in a specific format?”
I am trying to modify the below program so it prints the string in the following format 我正在尝试修改以下程序,因此它将以以下格式打印字符串
input : Fred, 4
输入 :
Fred, 4
output : 输出 :
Fred
Fred Fred
Fred Fred Fred
Fred Fred Fred Fred
There are 3 mistakes in this code: 此代码中有3个错误:
def prlines(str, num):
n in range(0,num):
print (str (n + 1))
prlines()
So I already tried the following code: 所以我已经尝试了以下代码:
name=str(input('Enter a name:'))
num=int(input('Enter a number:'))
def prlines(str, num):
for n in range(0, num):
print(str*(n + 1))
print(prlines(name, num))
I get this Actual Results (eg with the Name 'Fred' and the Number '4'): 我得到以下实际结果(例如,名称为“ Fred”,数字为“ 4”):
Fred
FredFred
FredFredFred
FredFredFredFred
None
My question is How can I get the expected results to display with the following constraints: 我的问题是如何获得预期的结果并显示以下约束:
without None at the end 最后没有没有
with spaces between the strings 字符串之间有空格
You can use: 您可以使用:
f'{s} ' * n + f'{s}'
Code : 代码 :
name = input('Enter a name: ')
num = int(input('Enter a number: '))
def prlines(s, num):
for n in range(num):
print(f'{s} ' * n + f'{s}')
prlines(name, num)
Few points : 几点 :
Don't name variable as str
. 不要将变量命名为
str
。
A function by default with no return
, returns None
, hence you have a None
at the end. 默认情况下,不带
return
函数返回None
,因此结尾处为None
。
First 第一
Code Analysis 代码分析
name=str(input('Enter a name:'))
num=int(input('Enter a number:'))
def prlines(str, num):
for n in range(0, num):
print(str*(n + 1)) # No spaces added = No spaces on the output
print(prlines(name, num)) # You are printing the output of the above function, which is None since it has no "return"
The print(func())
is where you get your None from print(func())
是您从中获得None的地方
Since you are only printing the str multiple times, you didn't include spaces (python won't know :) 由于您仅多次打印str,因此不包含空格(python不会知道:)
Answer 回答
name=str(input('Enter a name:'))
num=int(input('Enter a number:'))
def prlines(str, num):
for n in range(0, num):
print((str+' ')*(n + 1))
prlines(name, num)
Advice 忠告
This code is quite rough, you would need to think about error handling when someone doesn't input an int in the second input. 这段代码很粗糙,当有人在第二个输入中未输入int时,您需要考虑错误处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.