How do I put full stops (.) at the end of each line in the code below?
num = 0
for i in range(0, 3):
for j in range(0, 5):
print(num, end=",")
num = num + 1
print("\r")
Current output:
0,1,2,3,4,
5,6,7,8,9,
10,11,12,13,14,
Output I want:
0,1,2,3,4.
5,6,7,8,9.
10,11,12,13,14.
Thank you in advance for any help!
num = 0
for i in range(0, 3):
for j in range(0, 5):
if j == 4:
print(num, end=". ")
else:
print(num, end=", ")
num = num + 1
print("\r")
num = 0
for i in range(0, 3):
for j in range(0, 5):
print(num, end=", ")
print('.')
num = num + 1
print("\r")
This should work. As the end of your variable 'num' when printed has been set to a comma and a space, printing the full stop should work in this way
You can do such like this. Hope this will work on your side
i_range = 3
j_range = 5
num = 0
for i in range(0, i_range):
for j in range(0, j_range):
ends_ = '.' if j_range - j == 1 else ','
print(num , end=ends_)
num +=1
print('\r')
You can build a dynamic list with the second range, then print it using *. This allows you to put the , character as separator, and also the . character as end in the same line.
num = 0
step = 5
for i in range(0, 3):
print(*range(num, num + step), sep=", ", end=". ")
num = num + step
print("\r")
Related
I have the code for the 1st and the second pyramid, I just don't know how to put it together like how the question is asking. The first code below is for pyramid 1 and second is for the 2nd pyramid.
`
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
`
`
rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1
count1 = count = k = 0
print()
`
You just need to run the second loop after the first loop. Also your code for the second pyramid is incorrect so I changed that.
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
for k in range(i,0,-1):
print(k, end=' ')
for k in range(2,i+1):
print(k, end=' ')
count = 0
print()
Since the algorithm for constructing both pyramids is similar, it is better to make a function
def pyramid(n_rows, s_type='*'):
max_width = n_rows * 2 - 1
for i in range(0, n_rows):
stars = i * 2 + 1
side = (max_width - stars) // 2
if s_type == '*':
print(f"{' ' * side}{'* ' * stars}")
else:
side_nums = ' '.join(f'{x+1}' for x in range(0,i+1))
print(f"{' ' * side}{side_nums[1:][::-1]}{side_nums}")
rows = int(input("Enter number of rows: "))
pyramid(rows)
pyramid(rows, s_type='0')
You only need to input the row count once. You may also find using str.rjust easier for formatting.
rows = int(input('Enter a number from 1 to 9: '))
assert rows > 0 and rows < 10
output = [None] * (rows*2)
stars = '*' * (rows * 2 - 1)
for i in range(rows):
output[i] = stars[:i*2+1].rjust(rows+i)
s = ''.join(map(str, range(1, i+2))) + ''.join(map(str, range(i, 0, -1)))
output[i+rows] = s.rjust(rows+i)
print(*output, sep='\n')
Output:
Enter a number from 1 to 9: 6
*
***
*****
*******
*********
***********
1
121
12321
1234321
123454321
12345654321
So I have this piece of code so far:
def OfN(n):
print("Factors of ",n,"= ", end="")
factor = []
for j in range(2, n + 1):
if n % j == 0:
print(j, end=" ")
factor.append(j)
sumN = sum(factor)
print("\nSum of all factors = " + str(sumN))
if sumN < n:
return True
else:
return False
My problem is I don't know how to exclude the number itself from the sums/printing. I excluded 1 by starting counting from 2. How would I exclude the number from appearing?
For example, if we use 5, this should happen:
>> OfN(5)
>>
>> Factors of 5 =
>> Sum of all factors = 0
>> True
Thanks in advance.
Just remove the +1 in your range. This will iterate from 2 to n - 1, which will exclude n from the factors.
def OfN(n):
print("Factors of ",n,"= ", end="")
factor = []
for j in range(2, n):
if n % j == 0:
print(j, end=" ")
factor.append(j)
sumN = sum(factor)
print("\nSum of all factors = " + str(sumN))
if sumN < n:
return True
else:
return False
OfN(5)
I have written a code which finds unique elements from the list of integers.
def Distinct(arr, n):
for i in range(0, n):
d = 0
for j in range(0, i):
if (arr[i] == arr[j]):
d = 1
break
if (d == 0):
print(arr[i], end=',')
n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
a = input('enter the number: ')
arr.append(a)
print(Distinct(arr, n))
if my given input array is [1,2,2,3,4] where n = 5 i get the output as 1,2,3,4,None but i want the output to be 1,2,3,4
can anyone tell how to fix this ?
Your function Distinct has no return statement so it will always return None. When you call print(Distinct(arr, n)) this is printing the None that is returned. You can simply remove the print() like so:
Distinct(arr, n)
To remove the last comma you can't print a comma on the first iteration, then print the commas before the items. This is because you don't know which item will be the last one.
if d == 0 and i == 0:
print(arr[i], end='')
elif d == 0:
print("," + arr[i], end='')
Try something like this:
def Distinct(arr, n):
lst = []
for i in range(0, n):
for j in range(0, i):
if (arr[i] == arr[j]):
lst.append(arr[i])
break
print(*lst, sep=',')
n = int(input('Enter length of numbers: '))
arr = []
for i in range(n):
a = input('enter the number: ')
arr.append(a)
Distinct(arr, n)
So first you compute all the numbers, and only at the end you print them
How do I rewrite the first code to use a while loop instead of the given for loop? The output of the two programs should be the same.
num = 500
for j in range(30, 100):
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
print("program output is", num)
I have tried this but it does not work correctly:
num = 500
while j > 30 and j < 100:
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
A for loop automatically updates the loop variable (j) in every iteration.
In a while loop however, you have to assign a new value to the variable yourself, otherwise the loop will never end.
A for loop like
for j in range(a, b):
# do something ...
is equivalent to this while loop:
j = a
while j < b:
# do something ...
j += 1
(Note that j += 1 means the same as j = j + 1.)
In your case, you need to write:
num = 500
j = 30
while j < 100:
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
j += 1
print("program output is", num)
so i have some code that works perfectly without a function. But i want to change this inside a function, but it does not work properly.
For example, i have the end="". This doesn't work in a function, without using print.
I also have more than one print statements. When i turn these to return, they don't work. So could someone please help me change this code to work in a function?
Thanks!
My code
def underscore_hash_staircase(number):
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
print(end=" ".replace(" ", "_"))
k = k - 1
for j in range(0, i + 1):
print("#", end="")
print("")
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
print('', end=' '.replace(" ", "_"))
j -= 1
k = 1
while k <= i:
print('#', end='')
k += 1
print()
i -= 1
print(underscore_hash_staircase(8))
so the code above doesn't work properly in a function, without the print statements. Please let me know how to get this working in a function without the print statements. Using returns. It should be exact output as what is being returned in this not function-working code.
Thanks again!
Since a function can only return one value, instead of printing, you want to add to a variable to return instead of printing. Try:
def underscore_hash_staircase(number):
returnValue = "" # start as empty string
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
returnValue += "_"
k = k - 1
for j in range(0, i + 1):
returnValue += "#"
returnValue += "\n" # adding a new line
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
returnValue += "_"
j -= 1
k = 1
while k <= i:
returnValue += "#"
k += 1
returnValue += "\n"
i -= 1
print(underscore_hash_staircase(8))
Edit: missed a print when replacing
The function should append to a string instead of printing, and then return the string. Append \n to add a newline.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
result += "_"
k = k - 1
for j in range(0, i + 1):
result += "#"
result += "\n"
else:
number = -number
i = number
while i >= 1:
j = number
while j > i:
result += "_"
j -= 1
k = 1
while k <= i:
result += "#"
k += 1
result += "\n"
i -= 1
return result
print(underscore_hash_staircase(8))
You also don't need all those inner loops. You can repeat a string by multiplying it.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(1, number + 1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
else:
number = -number
for i in range(number, 0, -1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
return result
print(underscore_hash_staircase(8))
print(underscore_hash_staircase(-8))