[英]How can I modify the following program so that I can make sure that each letter it replaces is unique?
[英]“How can I modify the below program so it prints in a specific format?”
我正在嘗試修改以下程序,因此它將以以下格式打印字符串
輸入 : Fred, 4
輸出 :
Fred
Fred Fred
Fred Fred Fred
Fred Fred Fred Fred
此代碼中有3個錯誤:
def prlines(str, num):
n in range(0,num):
print (str (n + 1))
prlines()
所以我已經嘗試了以下代碼:
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))
我得到以下實際結果(例如,名稱為“ Fred”,數字為“ 4”):
Fred
FredFred
FredFredFred
FredFredFredFred
None
我的問題是如何獲得預期的結果並顯示以下約束:
最后沒有沒有
字符串之間有空格
您可以使用:
f'{s} ' * n + f'{s}'
代碼 :
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)
幾點 :
不要將變量命名為str
。
默認情況下,不帶return
函數返回None
,因此結尾處為None
。
第一
代碼分析
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"
print(func())
是您從中獲得None的地方
由於您僅多次打印str,因此不包含空格(python不會知道:)
回答
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)
忠告
這段代碼很粗糙,當有人在第二個輸入中未輸入int時,您需要考慮錯誤處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.