Python Programming

1. For Loop: indent is meaningful in Python

for count in [1, 2, 3]:
print(count)
print(‘Yes’*count)
print(‘Done counting.’)
for color in [‘red’, ‘blue’, ‘green’]:
print(color)

”’For”’
for count in [1, 2, 3]: #1
print(count) #2
print(‘Yes’*count) #3
print(‘Done counting.’) #4
for color in [‘red’, ‘blue’, ‘green’]: #5
print(color) #6
”’Repeat”’
items = [‘red’, ‘orange’, ‘yellow’, ‘green’]
number = 1
for item in items:
print(number, item)
number = 2

2. Dictionary:

“””A tiny English to Spanish dictionary is created,
using the Python dictionary type dict.
Then the dictionary is used, briefly.
“””
def createDictionary():
”’Returns a tiny Spanish dictionary”’
spanish = dict() # creates an empty dictionary
spanish[‘hello’] = ‘hola’
spanish[‘yes’] = ‘si’
spanish[‘one’] = ‘uno’
spanish[‘two’] = ‘dos’
spanish[‘three’] = ‘tres’
spanish[‘red’] = ‘rojo’
spanish[‘black’] = ‘negro’
spanish[‘green’] = ‘verde’
spanish[‘blue’] = ‘azul’
return spanish

def main():
dictionary = createDictionary()
print(dictionary[‘two’])
print(dictionary[‘red’])

def main2():
dictionary = createDictionary()
numberFormat = “Count in Spanish: {one}, {two}, {three}, …”
withSubstitutions = numberFormat.format(**dictionary)
print(withSubstitutions)
print(“Spanish colors: {red}, {blue}, {green}, …”.format(**dictionary))

main()
main2()

3. Function with Parameter:

def sumProblem(x, y):
sum = x + y
print(‘The sum of ‘, x, ‘ and ‘, y, ‘ is ‘, sum, ‘.’, sep=”)
def main():
sumProblem(2, 3)
sumProblem(1234567890123, 535790269358)
a = int(input(“Enter an integer: “))
b = int(input(“Enter another integer: “))
sumProblem(a, b)
main()

4. Input and Type Casting:

”’Conversion of strings to int before addition”’
xString = input(“Enter an integer: “)
x = int(xString)
yString = input(“Enter another integer: “)
y = int(yString)
print(‘The sum of ‘, x, ‘ and ‘, y, ‘ is ‘, x+y, ‘.’, sep=”)

5. Module Test:

main.py

import mod_test

list = [‘Tasnim’,’Anamika’,’Ananna’,’Priya’,’Laisa’]

mod_test.print_lol(list)

mod_test.py

def print_lol(the_list):
for each_item in the_list:
if isinstance(each_item, list):
print_lol(each_item)
else:
print(each_item)

6. String Formatting:

”’Fancier format string example.”’
x = 20
y = 30
formatStr = ‘{0} + {1} = {2}; {0} * {1} = {3}.’
equations = formatStr.format(x, y, x+y, x*y)
print(equations)

7. if and else: GPA calculation

print(‘Welcome to the GPA calculator.’)
print(‘Please enter all your letter grades, one per line.’)
print(‘Enter a blank line to designate the end.’)
# map from letter grade to point value
points = {‘A+’:4.0, ‘A’:4.0, ‘A-‘:3.67, ‘B+’:3.33, ‘B’:3.0, ‘B-‘:2.67, ‘C+’:2.33, ‘C’:2.0, ‘C’:1.67, ‘D+’:1.33, ‘D’:1.0, ‘F’:0.0}
num_courses = 0
total_points = 0
done = False
while not done:
grade = input( ) # read line from user
if grade ==”: # empty line was entered
done = True
elif grade not in points: # unrecognized grade entered
print(“Unknown grade {0} being ignored”.format(grade))
else:
num_courses += 1
total_points += points[grade]
if num_courses > 0: # avoid division by zero
print( ‘Your GPA is {0:.3}’ .format(total_points / num_courses))

8. Operator:

”’Fancier format string example, with locals().”’
x = 20
y = 30
sum = x+y
prod = x*y
formatStr = ‘{x} + {y} = {sum}; {x} * {y} = {prod}.’
equations = formatStr.format(**locals())
print(equations)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s