├── Nested-loops ├── README.md ├── sampleFactorial.py ├── sampleMethodsInput.py ├── sampleclass.py ├── sampledicts.py ├── sampleexceptions.py ├── samplefile.py ├── samplefunc.py ├── samplegame.py ├── samplegenerators.py ├── sampleimport.py ├── sampleinput.py ├── samplelistcomprehension.py ├── samplelists.py ├── sampleloops.py ├── samplepermutation.py ├── sampleprint.py ├── sampletuples.py └── samplewhile.py /Nested-loops: -------------------------------------------------------------------------------- 1 | #Program to understand working of loops and nested loops in python by a simple pattern formation. 2 | #suppose if user enters 4 then the following should be printed 3 | #output - 4 | # * 5 | 6 | # * * 7 | 8 | # * * * 9 | 10 | # * * * * 11 | # ignore all the '#' above in the output 12 | 13 | a=int(input("enter ")) #we take an input from the users of how many lines the pattern should run. 14 | for i in range(a): #executing a loop, here i's value will start from 0 till a-1. 15 | t=((a-1)-i) #carefuly observing the pattern we get to understand that we need loop for spaces and one for * so first we define t that will contain values from a-1 to 0 16 | for b in range(t): #creating a Nested loop for spaces 17 | print(" ",end=' ') 18 | k=i+1 #by observing the pattern above we can see that we need a variable that can print the number of * , and by logic the line number = number of * in that line 19 | for c in range(k): # making a loop to print * 20 | print("*"," ",end=' ') 21 | print("\n") 22 | 23 | # Hence loops work in a defined order to produce a specific result. 24 | # hence in all , all the logical patterns are solved by nested loop concept and to be a master in that getting the right logic and sufficient number of nested loops is important. 25 | # If possible try running this python code and try putting different input and see the output 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn-Python 2 | To make the users familiar with the syntax of Python. 3 | -------------------------------------------------------------------------------- /sampleFactorial.py: -------------------------------------------------------------------------------- 1 | def fatorial(n): 2 | if(n == 0 or n == 1): 3 | return 1 4 | else: 5 | return fatorial(n-1)*n 6 | 7 | n = int(input("Please, enter the numb: ")) 8 | fatorial(n) 9 | print(fatorial(n)) 10 | -------------------------------------------------------------------------------- /sampleMethodsInput.py: -------------------------------------------------------------------------------- 1 | # Example input: 2 | # 5 3 | # 1 2 3 4 5 4 | # Example Output: n = 5, data = [1, 2, 3, 4, 5] 5 | n, data = input(), [int(i) for i in input().strip().split()] 6 | 7 | # How to take input from multiple lines 8 | # Will take input until sees a blank line (sentinel) 9 | # Example input: 10 | # 1 2 3 11 | # 4 5 12 | # Example Output: user_input = '1 2 3 4 5' 13 | sentinel = '' 14 | user_input = '\n'.join(iter(input, sentinel)).replace('\n', ' ') 15 | 16 | # Example input: 17 | # 1 2 3 4 18 | # Example Output: var1 = 1, var2 = 2, var3 = 3, var4 = 4, such that var1, var2, var3, var4 are of type string 19 | var1, var2, var3, var4 = input().split() 20 | 21 | # Example input: 22 | # 1 2 3 4 23 | # Example Output: var1 = 1, var2 = 2, var3 = 3, var4 = 4, such that var1, var2, var3, var4 are of type int 24 | var1, var2, var3, var4 = map(int, input().split()) 25 | 26 | # Example input: 27 | # 1 2 3 28 | # 1 2 3 29 | # ... 30 | # 1 2 3 31 | while True: 32 | try: 33 | 34 | var1, var2, var3 = map(int, input().split()) 35 | 36 | except EOFError: 37 | break -------------------------------------------------------------------------------- /sampleclass.py: -------------------------------------------------------------------------------- 1 | # SAMPLE CODE TO ILLUSTRATE CLASSES IN PYTHON 2 | 3 | 4 | 5 | class TheThing(object): 6 | def __init__(self): 7 | self.number = 0 8 | def some_function(self): 9 | print "I got called." 10 | def add_me_up(self, more): 11 | self.number += more 12 | return self.number 13 | # two different things 14 | a = TheThing() 15 | b = TheThing() 16 | a.some_function() 17 | b.some_function() 18 | print a.add_me_up(20) 19 | print a.add_me_up(20) 20 | print b.add_me_up(30) 21 | print b.add_me_up(30) 22 | print a.number 23 | print b.number 24 | -------------------------------------------------------------------------------- /sampledicts.py: -------------------------------------------------------------------------------- 1 | # SAMPLE CODE TO UNDERSTAND THE CONCEPT OF DICTIONARIES IN PYTHON 2 | 3 | cities = {'CA': 'San Francisco', 'MI': 'Detroit','FL': 'Jacksonville'} 4 | cities['NY'] = 'New York' 5 | cities['OR'] = 'Portland' 6 | def find_city(themap, state): 7 | if state in themap: 8 | return themap[state] 9 | else: 10 | return "Not found." 11 | # ok pay attention! 12 | 13 | cities['_find'] = find_city 14 | 15 | while True: 16 | print "State? (ENTER to quit)", 17 | state = raw_input("> ") 18 | if not state: break 19 | 20 | # this line is the most important ever! study! 21 | 22 | city_found = cities['_find'](cities, state) 23 | print city_found 24 | -------------------------------------------------------------------------------- /sampleexceptions.py: -------------------------------------------------------------------------------- 1 | # python sampleexceptions.py 2 | 3 | # Minimal types of exceptions are used in this sample. 4 | # For a list of built in python exceptions see https://docs.python.org/2/library/exceptions.html 5 | 6 | 7 | # Expected Output: 8 | # 9 | # Basic exception raised. 10 | # Basic exception with message: ERROR. 11 | # Caught non basic exception: No module named badimport. 12 | # Caught non basic exception: unsupported operand type(s) for +: 'int' and 'str'. 13 | # Demonstrated how to handle multiple types of exceptions the same way. 14 | # Demonstrated how to handle multiple types of exceptions the same way with a message: No module named badimport. 15 | # Demonstrated how to handle exceptions differently. 16 | # This should appear. 17 | # Demonstrated how finally is run after exceptions. 18 | # Demonstrated how else is run when no exceptions occur. 19 | # Demonstrated how to use a basic custom exception: Custom Exception. 20 | 21 | 22 | try: 23 | raise Exception 24 | except: 25 | print "Basic exception raised." 26 | 27 | 28 | try: 29 | raise Exception("ERROR") 30 | except Exception as e: 31 | print "Basic exception with message: %s." % str(e) 32 | 33 | 34 | try: 35 | import badimport 36 | except ImportError as e: 37 | print "Caught non basic exception: %s." % str(e) 38 | 39 | 40 | try: 41 | test = 1 + '1' 42 | except TypeError as e: 43 | print "Caught non basic exception: %s." % str(e) 44 | 45 | 46 | try: 47 | import badimport 48 | except ImportError, TypeError: 49 | print "Demonstrated how to handle multiple types of exceptions the same way." 50 | 51 | 52 | try: 53 | import badimport 54 | except (ImportError, TypeError) as e: 55 | print "Demonstrated how to handle multiple types of exceptions the same way with a message: %s." % str(e) 56 | 57 | 58 | try: 59 | import badimport 60 | except ImportError: 61 | print "Demonstrated how to handle exceptions differently." 62 | except TypeError: 63 | print "This should not appear." 64 | 65 | 66 | try: 67 | import badimport 68 | except ImportError: 69 | print "This should appear." 70 | finally: 71 | print "Demonstrated how finally is run after exceptions." 72 | 73 | 74 | try: 75 | test = 1 + 1 76 | except: 77 | print "This should not appear." 78 | else: 79 | print "Demonstrated how else is run when no exceptions occur." 80 | 81 | 82 | class CustomBasicError(Exception): 83 | """ Custom Exception Type - Can be customised further """ 84 | pass 85 | 86 | 87 | try: 88 | raise CustomBasicError("Custom Exception") 89 | except CustomBasicError as e: 90 | print "Demonstrated how to use a basic custom exception: %s." % str(e) 91 | -------------------------------------------------------------------------------- /samplefile.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | script , filename =argv 3 | txt=open(filename) 4 | print "here is your file %r" %filename 5 | print txt.read() 6 | print "i'll also ask you to type it again" 7 | fi=raw_input("> ") 8 | tx=open(fi) 9 | print tx.read() 10 | -------------------------------------------------------------------------------- /samplefunc.py: -------------------------------------------------------------------------------- 1 | def multiply(a,b): 2 | c=a*b 3 | print "product is %r" %c 4 | def add(a,b): 5 | e=a+b 6 | print "addition is %r" %e 7 | multiply(3,4) 8 | add(3,4) 9 | -------------------------------------------------------------------------------- /samplegame.py: -------------------------------------------------------------------------------- 1 | # SAMPLE CODE TO ILLUTRATE THE CONCEPT OF BRANCHES AND FUNCTIONS IN PYTHON 2 | # Users are advised to go through this piece of code and dry run it to get an understanding of function calls. 3 | 4 | from sys import exit 5 | def gold_room(): 6 | print "This room is full of gold.How much do you take?" 7 | next = raw_input("> ") 8 | if "0" in next or "1" in next: 9 | how_much = int(next) 10 | else: 11 | dead("Man, learn to type a number.") 12 | if how_much < 50: 13 | print "Nice, you're not greedy, you win!" 14 | exit(0) 15 | else: 16 | dead("You greedy bastard!") 17 | def bear_room(): 18 | print "There is a bear here." 19 | print "The bear has a bunch of honey." 20 | print "The fat bear is in front of another door." 21 | print "How are you going to move the bear?" 22 | bear_moved = False 23 | while True: 24 | next = raw_input("> ") 25 | if next == "take honey": 26 | dead("The bear looks at you then slaps your face off.") 27 | elif next == "taunt bear" and not bear_moved: 28 | print "The bear has moved from the door. You can go through it now." 29 | bear_moved = True 30 | elif next == "taunt bear" and bear_moved: 31 | dead("The bear gets pissed off and chews your leg off.") 32 | elif next == "open door" and bear_moved: 33 | gold_room() 34 | else: 35 | print "I got no idea what that means." 36 | 37 | def cthulu_room(): 38 | print "Here you see the great evil Cthulu." 39 | print "He, it, whatever stares at you and you go insane." 40 | print "Do you flee for your life or eat your head?" 41 | next = raw_input("> ") 42 | if "flee" in next: 43 | start() 44 | elif "head" in next: 45 | dead("Well that was tasty!") 46 | else: 47 | cthulu_room() 48 | 49 | def dead(why): 50 | print why, "Good job!" 51 | exit(0) 52 | 53 | def start(): 54 | print "You are in a dark room." 55 | print "There is a door to your right and left." 56 | print "Which one do you take?" 57 | next = raw_input("> ") 58 | if next == "left": 59 | bear_room() 60 | elif next == "right": 61 | cthulu_room() 62 | else: 63 | dead("You stumble around the room until you starve.") 64 | 65 | start() 66 | 67 | -------------------------------------------------------------------------------- /samplegenerators.py: -------------------------------------------------------------------------------- 1 | # Generators hold values that are fetched lazily. 2 | # Meaning that the entire collection isn't stored 3 | # in memory all at once, but rather retrieved when 4 | # needed. 5 | 6 | # This is best used when dealing with a large 7 | # collection of items. Such as rows returned from 8 | # a database call or looping over a large csv. 9 | 10 | # Generators are intelligent enough to handle these 11 | # large collections without running out of memory. 12 | # They dispose of variables in memory that are no 13 | # longer used and do not worry about variables 14 | # that are not yet needed. 15 | 16 | # Here's the syntax for a generator. It's just a 17 | # function! Take note of the yield keyword. yield 18 | # basically means 'return', but lets Python know 19 | # we'll be coming back for more. 20 | def color_generator(): 21 | yield 'blue' 22 | yield 'orange' 23 | yield 'yellow' 24 | yield 'purple' 25 | 26 | # One way to use generators is by calling `next()` 27 | # on it's instance 28 | g = color_generator() # create the instance 29 | next(g) # 'blue' 30 | next(g) # 'orange' 31 | next(g) # 'yellow' 32 | next(g) # 'purple' 33 | 34 | # However, once a generator is exhausted, it will 35 | # not start back at the beginning. 36 | next(g) # Raises StopIteration error. 37 | 38 | # They're also iterables. No StopIteration errors 39 | # are thrown with this method. 40 | for color in color_generator(): 41 | print(color) 42 | 43 | # 'blue' 44 | # 'orange' 45 | # 'yellow' 46 | # 'purple' 47 | 48 | -------------------------------------------------------------------------------- /sampleimport.py: -------------------------------------------------------------------------------- 1 | # import command line argument reader 'argv' from the 'sys' python module 2 | from sys import argv 3 | 4 | # takes the two arguments after the 'python' command, 5 | # and assigns to the variables 'script' and 'user_name' 6 | script, user_name = argv 7 | 8 | # assigns the string with an arrow and space to the variable 'prompt' 9 | prompt = '> ' 10 | 11 | # user_name, the second argument, and 'sampleimport.py' replace %s in the order listed 12 | print "Hi %s, I'm the %s script." % (user_name, script) 13 | print "I'd like to ask you a few questions." 14 | 15 | # replaces %s with the variable user_name and prints 16 | print "Do you like me %s?" % user_name 17 | 18 | # prints '> ' and allows user to input a value, assigns user input to the 'likes' variable 19 | likes = raw_input(prompt) 20 | 21 | # repeats the process above two more times 22 | print "Where do you live %s?" % user_name 23 | lives = raw_input(prompt) 24 | print "What kind of computer do you have?" 25 | computer = raw_input(prompt) 26 | 27 | # takes the last three user inputs in order and inserts into the last print statement, replacing %r 28 | print """ 29 | Alright, so you said %r about liking me. 30 | You live in %r. Not sure where that is. 31 | And you have a %r computer. Nice. 32 | """ % (likes, lives, computer) 33 | -------------------------------------------------------------------------------- /sampleinput.py: -------------------------------------------------------------------------------- 1 | # import command line argument reader 'argv' from the 'sys' python module 2 | from sys import argv 3 | 4 | # takes the four arguments after the 'python' command, 5 | # and assigns to the variables 's', 'f', 'ss', and 't' 6 | s,f,ss,t=argv 7 | 8 | # prints the four arguments on separate lines with text 9 | print "the script is" , s 10 | print "var1 1 is" , f 11 | print "var 2 is" , ss 12 | print "var 3 is" , t 13 | -------------------------------------------------------------------------------- /samplelistcomprehension.py: -------------------------------------------------------------------------------- 1 | # Hi! Welcome to this mini tutorial on using list comprehensions in Python! 2 | # Check out samplelists.py if you need help with lists. 3 | 4 | # Starting off with list comprehensions! 5 | # Syntax used to make an ordinary list: 6 | my_list = ["apple", "banana", "pear", "peach"] 7 | 8 | # To concisely make a new list of elements, use a list comprehension: 9 | list_comp = [num for num in range(10)] # Notice how square brackets are 10 | # used to create a list. 11 | print list_comp 12 | 13 | # List comprehension syntax can be understood as so: 14 | # [num for num in range(5)] 15 | # Make a new num for each num in given range 16 | 17 | # The first expression (before the "for" keyword) can be altered to satisfy a 18 | # given condition over an iterable. 19 | doubled_list_comp = [num * 2 for num in list_comp] 20 | print doubled_list_comp 21 | 22 | # Furthermore, "if" statements can be used in list comprehensions as well. 23 | even_num_list_comp = [num for num in list_comp if num % 2 == 0] 24 | print even_num_list_comp 25 | -------------------------------------------------------------------------------- /samplelists.py: -------------------------------------------------------------------------------- 1 | # We now will build some lists using some loops and print them out: 2 | the_count = [1, 2, 3, 4, 5] 3 | fruits = ['apples', 'oranges', 'pears', 'apricots'] 4 | change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] 5 | 6 | # this first kind of for-loop goes through a list 7 | for number in the_count: 8 | print "This is count %d" % number 9 | 10 | # same as above 11 | for fruit in fruits: 12 | print "A fruit of type: %s" % fruit 13 | 14 | # also we can go through mixed lists too 15 | # notice we have to use %r since we don't know what's in it 16 | for i in change: 17 | print "I got %r" % i 18 | 19 | # we can also build lists, first start with an empty one 20 | elements = [] 21 | 22 | # then use the range function to do 0 to 5 counts 23 | for i in range(0, 6): 24 | print "Adding %d to the list." % i 25 | 26 | # append is a function that lists understand 27 | elements.append(i) 28 | 29 | # now we can print them out too 30 | for i in elements: 31 | print "Element was: %d" % i 32 | -------------------------------------------------------------------------------- /sampleloops.py: -------------------------------------------------------------------------------- 1 | # assigns numbers 1 through 3 to an array 2 | arr=[1,2,3] 3 | 4 | # assigns three names to an array 5 | arrstr=["ashu" , "himu" , "piyu"] 6 | 7 | # loops through each number from the number array, and prints the number 8 | for num in arr: 9 | print "numbers are %d" %num 10 | 11 | # loops through each name from the name array, and prints the name 12 | for name in arrstr: 13 | print "names are %s" %name 14 | 15 | # initializes an empty array 16 | arrinput=[] 17 | 18 | # asks the user for a input four times and pushes inputs into an array 19 | for i in range(0,4): 20 | print "enter element number %d" %i 21 | number = raw_input("> ") 22 | arrinput.append(number) 23 | 24 | # loops through the input array and prints each input 25 | for inp in arrinput: 26 | print "elements are %r" %inp 27 | -------------------------------------------------------------------------------- /samplepermutation.py: -------------------------------------------------------------------------------- 1 | # PowerSet.py 2 | # Description: given an array of numbers, generates 3 | # a power set 4 | 5 | def findPowerSet(originalSet, index, currentSet, powerSet): 6 | if (index >= len(originalSet)): 7 | # add list to power set(convert list to tuple) 8 | powerSet.append(currentSet) 9 | return 10 | 11 | # set where element was not added 12 | notAddedSet = currentSet[:] 13 | 14 | # append both sets 15 | currentSet.append(originalSet[index]) 16 | 17 | # recursive call to other elements in originalSet 18 | findPowerSet(originalSet, index + 1, currentSet, powerSet) 19 | findPowerSet(originalSet, index + 1, notAddedSet, powerSet) 20 | 21 | 22 | if __name__ == "__main__": 23 | print("in main file") 24 | testSet = [1, 2, 3] 25 | powerSet = [] 26 | 27 | findPowerSet(testSet, 0, [], powerSet) 28 | 29 | print("Final Set = " + str(powerSet)) 30 | -------------------------------------------------------------------------------- /sampleprint.py: -------------------------------------------------------------------------------- 1 | # prints an empty space since comments are ignored 2 | print #"Hello World!" 3 | 4 | # prints the following strings and separate lines 5 | print "Hello Again" 6 | print "I like typing this." 7 | print "This is fun." 8 | print 'Yay! Printing.' 9 | print "I'd much rather you 'not'." 10 | print 'I "said" do not touch this.' 11 | 12 | # prints the boolean value of this mathematical comparison 13 | print 3 + 2 < 5 - 7 14 | 15 | # assigning numerical values to variables 16 | cars = 100 17 | space_in_a_car = 4.0 18 | drivers = 30 19 | passengers = 90 20 | 21 | # performing mathematical operations on the variables above, 22 | # and assigning the answers to new variables 23 | cars_not_driven = cars - drivers 24 | cars_driven = drivers 25 | carpool_capacity = cars_driven * space_in_a_car 26 | average_passengers_per_car = passengers / cars_driven 27 | 28 | # the new variables are printed on separate lines 29 | print "We need to put about", average_passengers_per_car, "in each car." 30 | print "We have", passengers, "to carpool today." 31 | print "There will be", cars_not_driven, "empty cars today." 32 | print "We can transport", carpool_capacity, "people today." 33 | print "There are only", drivers, "drivers available." 34 | print "There are", cars, "cars available." 35 | -------------------------------------------------------------------------------- /sampletuples.py: -------------------------------------------------------------------------------- 1 | # SAMPLE CODE TO ILLUSTRATE TUPLES IN PYTHON 2 | 3 | days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") 4 | print "tuple: ", days 5 | 6 | # a tuple is a collection 7 | for day in days: 8 | print day 9 | 10 | print day[0] 11 | 12 | # we can get each element in a tuple 13 | monday, tuesday, wednesday, thursday, friday, saturday, sunday = days 14 | print monday, tuesday, wednesday, thursday, friday, saturday, sunday 15 | 16 | # A tuple also can have differents types. Arrays, dicts even other tuples 17 | tupleMix = (1,"happy", 3.1416, True, [1,2], {"lang": "English"}, (1,2)) 18 | print tupleMix 19 | 20 | # we can concat tuples 21 | a = (1,2,3) 22 | b = (4,5,6) 23 | c = a + b 24 | print c 25 | 26 | # or multiply a tuple 27 | a = ("hi",) * 4 28 | print a 29 | 30 | # :) learn more about tuples right here https://docs.python.org/3.1/tutorial/datastructures.html -------------------------------------------------------------------------------- /samplewhile.py: -------------------------------------------------------------------------------- 1 | # A while-loop will keep executing the code block under it as long as a boolean expression is True. 2 | # If we write a line and end it with a colon then that tells Python to start a new block of code. 3 | # Then we indent and that is the new code. 4 | # This is all about structuring your programs so that Python knows what you mean. 5 | # If you do not get that idea then go back and do some more work with if-statements, functions, and the for-loop until you get it. 6 | 7 | # SAMPLE CODE 8 | 9 | # initialize the while iterator to 0 10 | i = 0 11 | 12 | # initialze empty numbers array 13 | numbers = [] 14 | 15 | # keep running this while loop as long as 'i' is less than 6 16 | while i < 6: 17 | 18 | # prints the value of i at the beginning of the loop 19 | print "At the top i is %d" % i 20 | 21 | # adds the number i to the number array 22 | numbers.append(i) 23 | 24 | # increase the number i by 1 25 | i = i + 1 26 | 27 | # prints the current numbers array 28 | print "Numbers now: ", numbers 29 | 30 | # prints the value of i at the end of the loop 31 | print "At the bottom i is %d" % i 32 | 33 | # prints the numbers of the numbers array, 34 | # every value of i during the loop before it exited (0 through 5) 35 | # since the while loop exited when i reached 6 36 | print "The numbers: " 37 | for num in numbers: 38 | print num 39 | --------------------------------------------------------------------------------