#Loops """ One of the biggest applications of loops is traversing data structures, e.g. lists, tuples, sets, etc. In such a case, the loop iterates over the elements of the data structure while performing a set of operations each time """ #The for Loop """ A for loop uses an iterator to traverse a sequence, e.g. a range of numbers, the elements of a list, etc. In simple terms, the iterator is a variable that goes through the list. The iterator starts from the beginning of the sequence. In each iteration, the iterator updates to the next value in the sequence. Structure: for val in sequence: loop body Here, val is the variable that takes the value of the item inside the sequence on each iteration. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation. """ #Looping through a list of items # Program to find the sum of all numbers stored in a list # List of numbers # numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] # variable to store the sum # sum = 0 # iterate over the list # for val in numbers: # sum = sum+val # print("The sum is", sum) #Looping through a sequence created by range function """ In Python, the built-in range() function can be used to create a sequence of integers. This sequence can be iterated over through a loop. A range is specified in the following format: range(start, end, step) 'The end' value is not included in the list. If the start index is not specified, its default value is 0. 'The step' decides the number of steps the iterator jumps ahead after each iteration. It is optional and if we don’t specify it, the default step is 1, which means that the iterator will move forward by one step after each iteration. """ #Check if a number is even or odd # for i in range(1, 11): # A sequence from 1 to 10 # if i % 2 == 0: # print(i, " is even") # else: # print(i, " is odd") # A loop changes when the step component of a range is specified # for i in range(1, 11, 3): # A sequence from 1 to 10 with a step of 3 # if i % 2 == 0: # print(i, " is even") # else: # print(i, " is odd") #Let’s double each value in a list using a for loop using the range function # float_list = [2.5, 16.42, 10.77, 8.3, 34.21] # print(float_list) # for i in range(0, len(float_list)): # Iterator traverses to the last index of the list # float_list[i] = float_list[i] * 2 # print(float_list) #The while loop """ The while loop keeps iterating over a certain set of operations as long as a certain condition holds True. It operates using the following logic: While this condition is true, keep the loop running """ #Basic while loop # a=0 # while a < 10: # print (a) # a+=1 #Let's find if a number is even or odd using a while loop # a = 1 # while a < 10: # if a % 2 == 0: # print(a, " is even") # else: # print(a, " is odd") # a += 1 #Cautionary Measures """ Compared to for loops, we should be more careful when creating while loops. This is because a while loop has the potential to never end. This could crash a program! For instance: while(True): print("Hello World") x = 1 while(x > 0): x += 5 """ #Nested for Loop """ A nested loop is a loop inside a loop. Use case : compare every element in a list with the rest of the elements in the list """ # #Example : print two elements whose sum is equal to a certain/given number # n = 50 # Count unique numbers # num_list = [7,10, 4, 23, 10, 18, 27, 47, 27, 10, 23, -5] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] #i=1 => 10 # 2=> 10 #j=0 => 7 #j=11 => # uniqueCounter=0 # isUnique=True # for i in range(0, len(num_list)): # for j in range(0, len(num_list)): # if i != j: # if num_list[i] == num_list[j]: # isUnique=False # if (isUnique != False): # uniqueCounter += 1 # isUnique=True # print(uniqueCounter) # write a function that returns a pair of numbers that sums up to n # def findPair(num_list, n): # isSumFound = False # pairOfNumbers = [] # for i in range(0, len(num_list)): # for j in range(0, len(num_list)): # if( i != j): # if(num_list[i] + num_list[j] == n): # isSumFound = True # pairOfNumbers.append(num_list[i]) # pairOfNumbers.append(num_list[j]) # break # if (isSumFound): # break # return pairOfNumbers # n = 50 # the_num_list = [10, 4, 25, 6, 18, 27, 47, 5, 5, 30, 101, -50] # print(findPair(the_num_list, n)) # The break Keyword """ The break statement ends the loop. The break statement can be used inside a loop or in a function. Use case : If you want to exit the loop because you have found what you were looking for and don’t need to make any more computations in the loop """ # n = 50 # num_list = [10, 4, 23, 6, 18, 27, 47] # found = False # This bool will become true once a pair is found # for n1 in num_list: # for n2 in num_list: # if(n1 + n2 == n): # found = True # Set found to True # break # Break inner loop if a pair is found # if found: # print(n1, n2) # Print the pair # break # Break outer loop if a pair is found #The continue Keyword# """ The continue statement instructs a loop to continue to the next iteration. Any code that follows the continue statement is not executed. Unlike a break statement, a continue statement does not completely halt a loop """ def fib(n): num1=0 num2=1 i=2 if n < 0: return -1 if n == 1: return num1 if n == 2: return num2 while i < n: tempNum = num2 num2 = num2 + num1 num1 = tempNum i += 1 return num2 # end of the function print(fib(5)) # def extractNumbers(listOfNumbers): # numbers=[] # for i in range(0, len(listOfNumbers)): # try: # num = int(listOfNumbers[i]) # numbers.append(num) # except ValueError as ex: # continue # return numbers # data = ["54", "?", " ", " 67", "hello", "10", "--"] # print(extractNumbers(data)) # def simpleCipher(encrypted, k): # # Write your code here # output = [] # encrypt = [] # letters=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] # for eachletter in encrypted: # index = letters.index(eachletter) # crypt= (index-k) % 26 # encrypt.append(crypt) # newletter = letters[crypt] # output.append(newletter) # return output # print(simpleCipher('DATES', 4)) # print(-5 % 4 ) # -5 mod4 => {0, 1, 2, 3} # print( 5 % 4 ) # 5 mod4 => {0, 1, 2, 3} # 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 # -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 #The pass Keyword """ In all practical meaning, the pass statement does nothing to the code execution. It can be used to represent an area of code that needs to be written. Hence, it is simply there to assist you when you haven’t written a piece of code but still need your entire program to execute. """ # num_list = list(range(20)) # for num in num_list: # pass # You can write code here later on # print(num_list)
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |