Question: Python Loops [Introduction]
Task:
The included code stub will read an integer, n, from STDIN. Without using any string methods, try to print the following: 123……..n
Note that "..." represents the consecutive values in between.
Example:
n = 5
Print the string 12345 .
Input Format:
The first line contains an integer n.
Constraints:
1 ≤ n ≤ 150
Output Format:
Print the list of integers from 1 through n as a string, without spaces.
Sample Input 0:
3
Sample Output 0:
1 2 3
Possible Solutions
The problem is very simple and we have to use the loops in Python. The following code is already given in the editor of the Hacker Rank:
if __name__ == '__main__':
n = int(input())
Now we will go through the following methods to solve the given problem.
Solution-1: Using for Loop
Let us now use the for loop to iterate through a given range:
if __name__ == '__main__':
n = int(input())
for i in range(0, n):
print(i**2)
This code snippet is takes an input integer 'n
' and then uses a for loop to iterate over a range of integers from 0
to 'n
' (not including 'n
'). For each iteration, it prints the square of the current integer. The if statement at the beginning is just a standard idiom in Python that is used to determine whether the script is being run directly or being imported as a module in another script. When the script is run directly, the value of the special built-in variable __name__
will be set to "__main__
", so the if statement will evaluate to True and the code inside the if block will be executed. When the script is imported as a module, the value of __name__
will be set to the name of the module, so the if block will not be executed.
Solution-2: Alternative method of using for loop
Now we will use for loop without specifying the starting of the loop:
if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i * i)
This will also solve the problem: The only difference is that, instead of taking the power to find the square, this time we are multiplying the number by itself.
Solution-3: Using a While loop
Now we will see, how we can use the while loop to solve the problem:
if __name__ == '__main__':
n = int(input())
i = 0
while(i<n):
print(i*i)
i+=1
Similar to the first two solutions, this one also takes an input integer 'n
' and then instead of a for loop, it uses a while loop to iterate over a range of integers from 0
to 'n
' (not including 'n
'). For each iteration, it prints the square of the current integer. The loop continues until the value of 'i
' is no longer less than 'n
'.
Summary
In this short article, we learned how we can solve Loops question on HackerRank. We discussed three different types of solutions and explained each of them.
Further Reading
Question on Hacker Rank: Python Loops [Introduction]