|
Post by deepak on Mar 31, 2020 20:39:48 GMT -5
Task
Ask the user to enter an integer. (say N)
Square all the numbers from 1 to N and print them each on separate lines. (Tip: use for loop to iterate from 1 to N)
Input Format
Please enter a positive integer: N
Output Format
Print N lines: 12 22 32 . . . N2
Sample Input: 5
Sample Output: 1 4 9 16 25
|
|
|
Post by deepak on Mar 31, 2020 20:44:46 GMT -5
# Start: Reading input from user:
N = int(input()) ...
|
|
|
Post by arnabbiswas on Apr 2, 2020 0:15:46 GMT -5
def printSquares(N): for i in range(1,N+1): print(i**2)
N=int(input()) printSquares(N)
|
|
|
Post by poorna on Apr 2, 2020 5:33:20 GMT -5
N = int(input()) for i in range (1,N+1): print(i*i)
|
|
|
Post by deepak on Apr 2, 2020 9:26:29 GMT -5
Good - both snippets above are correct! For anyone interested in knowing another clever/concise but convoluted way of doing it, here it is... print(*([i**2 for i in range(1,N+1)]), sep="\n") I don't suggest this "one liner" approach shown above (but good to know if you have to understand some else's code in an existing application) "Simplicity is best" Nice work
|
|
manoj
New Member
Posts: 1
|
Post by manoj on Apr 12, 2020 10:46:06 GMT -5
1. what does the first asterisk inside the first parentheses do?
2. are the square brackets used to improve readability or is it part of the syntax? meaning you have to use it when you insert a for-loop inside a print statement?
|
|
|
Post by arnabbiswas on Apr 13, 2020 9:53:18 GMT -5
Great questions Manoj. I had to read up on your first question and learnt something new 1. * here is used as the overloaded unpack operator. The objective was to print each element of the list in a separate line and hence we needed to unpack the elements first using the * operator. If we dont do so the answer would print as [1,4,9] since it would consider the list as a single argument to print and hence the sep="\n" would be effectively ignored 2. The [] is required syntax for list comprehensions, basically telling Python that the results of the enclosed operation is a list. www.digitalocean.com/community/tutorials/understanding-list-comprehensions-in-python-3 explains comprehensions in Python in detail. Apparently comprehensions are a feature common to other scripting languages too such as JS, matlab, scala etc.
|
|