Skip to content

Commit 0c185f8

Browse files
authored
Merge pull request #1 from lugnitdgp/master
update
2 parents 303d63f + a6f8bf6 commit 0c185f8

11 files changed

+319
-1
lines changed

Nested-loops

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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

sampleMethodsInput.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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

sampleexceptions.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
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)

samplegenerators.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+

sampleimport.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,30 @@
1+
# import command line argument reader 'argv' from the 'sys' python module
12
from sys import argv
3+
4+
# takes the two arguments after the 'python' command,
5+
# and assigns to the variables 'script' and 'user_name'
26
script, user_name = argv
7+
8+
# assigns the string with an arrow and space to the variable 'prompt'
39
prompt = '> '
10+
11+
# user_name, the second argument, and 'sampleimport.py' replace %s in the order listed
412
print "Hi %s, I'm the %s script." % (user_name, script)
513
print "I'd like to ask you a few questions."
14+
15+
# replaces %s with the variable user_name and prints
616
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
719
likes = raw_input(prompt)
20+
21+
# repeats the process above two more times
822
print "Where do you live %s?" % user_name
923
lives = raw_input(prompt)
1024
print "What kind of computer do you have?"
1125
computer = raw_input(prompt)
26+
27+
# takes the last three user inputs in order and inserts into the last print statement, replacing %r
1228
print """
1329
Alright, so you said %r about liking me.
1430
You live in %r. Not sure where that is.

sampleinput.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1+
# import command line argument reader 'argv' from the 'sys' python module
12
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'
26
s,f,ss,t=argv
7+
8+
# prints the four arguments on separate lines with text
39
print "the script is" , s
410
print "var1 1 is" , f
511
print "var 2 is" , ss

samplelistcomprehension.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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

sampleloops.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,26 @@
1+
# assigns numbers 1 through 3 to an array
12
arr=[1,2,3]
3+
4+
# assigns three names to an array
25
arrstr=["ashu" , "himu" , "piyu"]
6+
7+
# loops through each number from the number array, and prints the number
38
for num in arr:
49
print "numbers are %d" %num
10+
11+
# loops through each name from the name array, and prints the name
512
for name in arrstr:
613
print "names are %s" %name
14+
15+
# initializes an empty array
716
arrinput=[]
17+
18+
# asks the user for a input four times and pushes inputs into an array
819
for i in range(0,4):
920
print "enter element number %d" %i
1021
number = raw_input("> ")
1122
arrinput.append(number)
23+
24+
# loops through the input array and prints each input
1225
for inp in arrinput:
1326
print "elements are %r" %inp

samplepermutation.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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))

sampleprint.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,31 @@
1+
# prints an empty space since comments are ignored
12
print #"Hello World!"
3+
4+
# prints the following strings and separate lines
25
print "Hello Again"
36
print "I like typing this."
47
print "This is fun."
58
print 'Yay! Printing.'
69
print "I'd much rather you 'not'."
710
print 'I "said" do not touch this.'
11+
12+
# prints the boolean value of this mathematical comparison
813
print 3 + 2 < 5 - 7
14+
15+
# assigning numerical values to variables
916
cars = 100
1017
space_in_a_car = 4.0
1118
drivers = 30
1219
passengers = 90
20+
21+
# performing mathematical operations on the variables above,
22+
# and assigning the answers to new variables
1323
cars_not_driven = cars - drivers
1424
cars_driven = drivers
1525
carpool_capacity = cars_driven * space_in_a_car
1626
average_passengers_per_car = passengers / cars_driven
27+
28+
# the new variables are printed on separate lines
1729
print "We need to put about", average_passengers_per_car, "in each car."
1830
print "We have", passengers, "to carpool today."
1931
print "There will be", cars_not_driven, "empty cars today."

samplewhile.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,33 @@
66

77
# SAMPLE CODE
88

9+
# initialize the while iterator to 0
910
i = 0
11+
12+
# initialze empty numbers array
1013
numbers = []
14+
15+
# keep running this while loop as long as 'i' is less than 6
1116
while i < 6:
17+
18+
# prints the value of i at the beginning of the loop
1219
print "At the top i is %d" % i
20+
21+
# adds the number i to the number array
1322
numbers.append(i)
23+
24+
# increase the number i by 1
1425
i = i + 1
26+
27+
# prints the current numbers array
1528
print "Numbers now: ", numbers
29+
30+
# prints the value of i at the end of the loop
1631
print "At the bottom i is %d" % i
17-
print "The numbers: "
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: "
1837
for num in numbers:
1938
print num

0 commit comments

Comments
 (0)