I am trying to modify the below program so it prints the string in the following format
input : Fred, 4
output :
Fred
Fred Fred
Fred Fred Fred
Fred Fred Fred Fred
There are 3 mistakes in this code:
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
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
.
A function by default with no return
, returns None
, hence you have a None
at the end.
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
Since you are only printing the str multiple times, you didn't include spaces (python won't know :)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.