first day of posting lecture notes

# Save your reference of data on some online platform, like blogger.com
# code data is most of the time in kbs, so just dump it on there. This is not for traffic or earning. This is just for your quick reference. so that you can get this back whenever you need it in future.



# secret_number = 9
# guess_count = 0
# guess_limit = 3
# while guess_count < guess_limit:
# guess = int(input('Guess: '))
# guess_count += 1
# if guess == secret_number:
# print('You Won!')
# break
#else:
# print('Sorry you failed!')

# -------------

# > help
# start - to start the car
# stop - to stop the car
# quit - to exit

# >asd
# I don't understand that...

# >start
# Car started...Ready to go!
# >stop
# Car stopped
# >quit
# Programmmm terminated
commands = "Commands: help, start, stop, quit"

print(commands)

command = ""

while command.lower() != 'quit':
command = input("> ").lower()
if command == "help":
print('start - to start the car', '\n stop - to stop the car', '\n quit - to exit')
# continue
elif command == "start":
print("Car starred...Ready to go!")
# continue
elif command == "stop":
print("Car stopped")
# continue
elif command == "quit":
print("Program stopped!")
break
else:
print("I don't understand that...")
# ==========
command = ""

while command.lower() != 'quit':
command = input("> ").lower()
if command == "help":
print('start - to start the car', '\n stop - to stop the car', '\n quit - to exit')
elif command == "start":
print("Car starred...Ready to go!")
elif command == "stop":
print("Car stopped")
elif command == "quit":
print("Program stopped!")
break
else:
print("I don't understand that...")

# ============

# the purpose of empty "" , ()... = they can be assigned different values later during program. assigning values as
# "True" or "False". when you want to use boolian value in programming using tripple quotattions,, """""",,,
# you can add three lines of comments (Number of quotations = number of lines.. indentation will be as per in
# programming window.
#
#===============

# Car Game... Start and stop the car and exit the programe through quit

command = ""
started = False
while command != 'quit':
command = input("> ").lower()
if command == "help":
print('start - to start the car', '\n stop - to stop the car', '\n quit - to exit')
elif command == "start":
if started:
print("Car is already started!")
else:
started = True
print("Car starred...Ready to go!")
elif command == "stop":
if not started:
print("Car is already stopped")
else:
started = False
print("Car stopped")
elif command == "quit":
print("Program stopped!")
break
else:
print("I don't understand that...")

# =================
# alternative for new lines

if command == "help":
print(
"""start - to start the car
stop - to stop the car
quit - to exit""")

# ==============
# for calculating total of all prices in a list.
prices = range(20, 30, 5)
total = 0
for a in prices:
total += a
print("Total Prices: ", {total})

# ================
# Supplying Arguments

def echo(user, lang, sys):
print("A", user, "B", lang, "C", sys)
echo("a", "b", "c")
echo("a", "b", "c")
def mirror(user, lang):
print("A", user, "B", lang)
mirror("a", "b")

def magic(user = "Sohaib", lang = "Urdu"):
print("E", user, "F", lang)
magic("e", "f")
magic(user= "ANwar")
magic()
magic("Zahoor")

# ===================
# K.W ---- return ---
# - it just appears at the end of function. i.e. after this the fundtion ends and stops. kinda does "break" for a loop. when funtion goes into return statement, it doesn;t continue on.
# most importantly, it does allowa parameter... " return 'Hello' " ... "Hello" is its parameter.
def greet():
return "Hello"
print(greet(), 'Sohaib')
print(greet(), 'Musab')
# Rwturning Values

num = input("Enter an Integer: ")
def square (num):
if not num.isdigit():
return "Invalid Entry"
num = int(num)
return num * num
print(num, "Squared is: ", square(num))

# ==============

# Square of a number
# use of return() -- Python built-in keyword

num = input("Enter an Integer: ")
def square (num):
if not num.isdigit():
return "Invalid Entry"
num = int(num)
return num * num
print(num, "Squared is: ", square(num))

# ====================== OR

num = input("Enter an Integer: ")
def square (num):
if not num.isdigit():
return "Invalid Entry"
num = int(num)
return num * num
answer = square(num)
print(num, "Squared is: ", answer)

# ======================
# Further changes ,, adding Comparing values condition

num = input("Enter an Integer: ")
def square (num):
if not num.isdigit():
return "Invalid Entry"
num = int(num)
if num > 5:
# num += 1
return "Enter Value less than 5"
return num * num
answer = square(num)
print(num, "squared is: ", answer)

# ======================
# ======================
# K.W. -- lambda() = to allow an anonymous un-named function to be created.
# may only contain a single expression that must always return a value.
# it returns a "function object"
# Hot Tip: In-line lambda callbacks are often used to define the behavior of buttons in a GUI program
# lambda is used to create a function that you only need to use once (i.e. not repetitive use is required)
# it may be created within an other code
# by using it you reduce the lines of codes to be written
# The \ backslash character can be used to allow code to continue on the next line – as seen here.


def function_1(x):
return x**2
def function_2(x):
return x**3
def function_3(x):
return x**4
callbacks = [function_1, function_2, function_3]
print('\nNamed Functions:')
for function in callbacks : print("Result ", function(3))
callbacks =\
[lambda x : x**2, lambda x : x**3, lambda x : x**4]
print('\nAnanymous Functions:')
for function in callbacks : print("Result ", function(2))

# =======================
# Adding placeholders
# use of K.W ----- pass

title = "\nPython in Easy Steps\n"
for char in title :
print(char, end='')
for char in title :
if char == 'y':
print('*', end='')
continue
print(char, end='')
for char in title :
if char == 'y':
print('*', end='')
pass
print(char, end='')

# =========================
# =========================
# Try and Except

astr = '456g'
try:
istr = int(astr)
except:
istr = -1
print('First', istr)
astr = '456'
try:
istr = int(astr)
except:
istr = -1
print('Second', istr)

# ====================
# when try and except will not work

astr = '456g'
try:
print('Hello')
istr = int(astr) # wrong statement here will blow up the next instructions and will skip to the next (i.e. except)
print('there')
except:
istr = -1
print('First', istr)
# ====================

# Example Try and Except ,, data input,,, converted into int()... feedback to user for correct data entry
# Error Detection Example

rawstr = input('Enter a Number: ')
try:
ival = int(rawstr)
except:
ival = -1
if ival > 0:
print('Nice Work')
else:
print('Not a Number')

# ========================

# ========================
# Greeting App

def greet(lang):
if lang == 'ur':
print("Assalam-o-Alaikum")
elif lang == 'fr':
print('Bonjour')
elif lang == 'es':
print('Hola')
else:
print('Hello')
greet('ur') # urdu greeting ## Assalam-o-Alaikum
greet('kj') # general greeting ## Hello
greet('fr') # french greeting ## Bonjour
greet('es') # spanish greeting ## Hola
greet('') # general greeting-- while there is no comment ## Hello
# ========================
# with K.W. return ''

def greet(lang):
if lang == 'ur':
return "Assalam-o-Alaikum"
elif lang == 'fr':
return 'Bonjour'
elif lang == 'es':
return 'Hola'
else:
return 'Hello'

print(greet('ur'), 'Sohaib')
print(greet('fr'), 'Musab')
print(greet('es'), 'Ahmad')
print(greet('kjfr'), 'Babar')
print(greet(''), 'Zahoor')

# ========================

# Multiple parameters,, a,b and accordingly multiple arguments,, 2,3

def add(a,b):
added = a + b
return added
x = add(2, 3)
print(x)

# ========================

#Void (non-fruitful) function
# you don't have to have return for a functions. return is always implicitly happening as the last line of function.
# ========================
# Sequential
# Conditional
# Store and Re-use
# Loops and Iteration

# ... K.W -- while()
# in while loop, function are really much like "if-statement"
# Iteration Variable: defining variable, and using it helps in making and "Exit" out of loop
# Zero-Trip-Loop: Idea is just to exit without entering into loop..
# While loops are called "Indefinite Loops", they keeps going untill a logical condition becomes 'Fales'.

n = 0
while n > 0:
print('Sohaib', n)
n = n-1
print("Exit")
print(n)

# ===========
# Breaking out of loop
# 1st Method: K.W. -- break
# note: once you done a break, it goes out of the loop, that loop is done
# it just says: get out of the loop

while True:
line = input('> ')
if line == 'done':
break
print(line)
print("Exit")

# ==========
# 2nd Method: Finishing with K.W. -- continue
# it just say: stop this iteration

while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print("Exit")

# =====================

#### Definite Loops
# K.W. -- for
# K.W. -- in
# we don't need to use iteration variable to control number of times the loop will run. Rather it has explicit iteration variables that changes each time through a loop. These iteration variables move through the sequence or set.

# 'i' in following example is like assignment statement. its an iteration variable created in 'for' statement.

for i in [1, 2, 3, 4, 5]:
print(i)
print('Done')

# ===========

# 2nd example
for i in [1, 2, 3, 4, 5]:
print(i, end='')
print('Sohaib\t', end='')
print('\nDone')

# ===========
# 3rd Example

for i in [1, 2, 3, 4, 5]:
name = input('\nYour Name: ')
print(name, 'is a wonderful person', end='')
print('\nDone')

# ============
# 4rth Example

friends = ['Sohaib', 'Muqaddas', 'Saif', 'Shoaib']
for friend in friends:
print('Happy New Year', friend)
print('\nDone')

# ============
# 4th example extended

friends = ['Sohaib', 'Muqaddas', 'Saif', 'Shoaib']
for friend in friends:
i = input('>').lower() # another input condition is added to control the number of iterations of loop.
if i == "done" :
break # with K.W. -- break
print('Happy New Year', friend)
print('\nDone')

# ==================
# Again Example 4 - extended differently

friends = ['Sohaib', 'Muqaddas', 'Saif', 'Shoaib']
for friend in friends:
i = input('>').lower()
if i == "done" :
continue # with K.W. -- continue
print('Happy New Year', friend)
print('\nDone')

# ============================

# Finding the largest Value

largest_so_far = -1
print('Before: ', largest_so_far)
for the_num in [3,8,65,23,45,78,15]:
if the_num > largest_so_far:
largest_so_far = the_num
print(largest_so_far, the_num)
print('After: ', largest_so_far)

# =========================

# More loop patterns:
# counting
# Totalling
# Averaging
# Finding the smallest number

# Finding the count, total and average Value

total, zork = 0, 0 # zork == ultimate count variable
print('Before: ', total)
for the_num in [3, 8, 65, 23, 45, 78, 15]:
total += the_num
zork += 1
print(zork, total, the_num)
print('After: ', total)
avg = total/zork
print('Average: ', avg)

# ----------
# Finding the Value greater than 50 e,g.

position, zork = 0, 0 # zork == ultimate count variable
print('BEFORE')
for the_num in [3, 8, 65, 23, 45, 78, 15]:
position += 1
if the_num > 50:
zork += 1
print(zork, ': ','Position: ',position,';', 'Greater than 20: ', the_num)
print('AFTER')

# ---------

# Finding a specific Value 45 e,g.

position, zork = 0, 0 # zork == ultimate count variable
print('BEFORE')
for the_num in [3, 8, 45, 23, 45, 78, 15]:
position += 1
if the_num == 45:
zork += 1
print(zork, ': ','Position: ', position, ';', 'The Desired Value Found: ', the_num)
print('AFTER')

# -------------

# again
# Finding a specific Value 45 e,g.

position= 0
found = False
print('BEFORE', found)
for the_num in [3, 8, 65, 23, 45, 78, 15]:
position += 1
if the_num == 45:
found = True
print(position, found, the_num)
print('AFTER', found)

# --------------

# again, again,,, use of break statement

# Finding a specific Value 45 e,g.

position = 0
found = False
print('BEFORE', found)
for the_num in [3, 8, 65, 23, 45, 78, 15]:
position += 1
if the_num == 45:
found = True
print(position, found, the_num)
break
print(position, found, the_num)
print('AFTER', found)

# ------------

# Types of Values:
# Integer -- Has infinite number of Values
# Floating Point -- Has infinite number of Values
# Boolean -- Only has two Values: True & False
# None -- Only has one Value. "None" is a constant. It means , its just empty.

# Finding smallest value


smallest_so_far = None
print('Before: ')
for the_num in [13, 8, 65, 4, 78, 15]:
if smallest_so_far is None:
smallest_so_far = the_num
elif the_num < smallest_so_far:
smallest_so_far = the_num
print(smallest_so_far, the_num)
print('After: ', smallest_so_far)

# ______________
# _________ Same Technique for Largest Number

# Finding Largest value


largest = None
print('Before: ')
for the_num in [13, 8, 65, 4, 78, 15]:
if largest is None:
largest = the_num
elif the_num > largest:
largest = the_num
print(largest, the_num)
print('After: ', largest)

# ===================
# ====================

# Operator "is" and "is not".
# These both are stronger than "==" and "!=".
# Example : 0 == 0.00 ----- True---- Same value wise,, doesn't matter if type is same or not
# where as: 0 is 0.00 -------False --- not same type wise,,, so its False
# uses: use in booleans and none..
# don't use in integers, floats and strings
#- while loops (indefinite)
#- for loops (definite)
#- infinite loops
#- Iteration Variables
#- using “break”
#- Loop idioms
#- using “continue”
#- Largest and Smallest
#- “None” Constants and Variables
# ==============================
# ==============================
# ==============================
# ==============================

# PARSE
#### STRINGS -- Looking inside Strings

# index number of string,, adding and substracting

fruit = 'Orange'
letter = fruit[1]
print(letter) # answer is -- r

x = 3
w = fruit[x-1]
print(w) # answer is -- a

r = fruit[x + 1]
print(r) # answer is -- g

# ============
# ============

# K.W. -- len() .... just another function.
# Function definition: a stored code that we use. A function takes input and produces output.


# index number of string,, finding the length of string

fruit = 'Orange'
print(len(fruit)) # answe is --- 6

# =============
# or
fruit = 'Orange'
x = len(fruit)
print(x) # answe is --- 6


# =============
# index number of string,, Looping through strings (one way of looping)

fruit = 'Orange'
index = 0
while index < len(fruit): # index is '0' and hense less than length of fruit which is 6.
letter = fruit[index] # letter will be determined based on calling index function " fruit[index]. in first round, since index is '0'. so letter will be assigned fruit[0] = O.
print(index, letter) # here in first round index is '0', and first letter at '0' index is first letter of string, which in this case is 'O'.
index += 1

# ----------
# again

# index number of string,, Looping through strings

fruit = 'Orange'
index = 3 # by changing the initial value of index variable,, we can choos the starting point of desired result
while index < len(fruit):
letter = fruit[index]
print(index, letter)
index += 1

# ---------
# once again..
# index number of string,, Looping through strings

fruit = 'Orange'
index = 9 # Starting value of index variable should be carefully written, further a warning message can be generated through introducing 'else' command.
while index < len(fruit):
letter = fruit[index]
print(index, letter)
index += 1
else:
print('Given index value is incorrect')

# =================
# =================


# Alon downy and
#Jeff eltner authors

# ===============

# index number of string,, Looping through strings (other way of looping, using 'for')
# counting the letters in strings

fruit = 'banana'
count = 0
for letter in fruit:
if letter == 'a':
count += 1
print(count)

# ==============
# K.W. -- in ,,,,, -- math hint,,, "set notation"
# Looking deeper into 'in'.

# index number of string,, Looping through strings (other way of looping, using 'for')
# mechanism of 'in'

fruit = 'banana'
for letter in fruit:
print(letter)

# ------------

# STRINGS: More string operations.

# Slicing strings. i.e. taking a part of string as output.
# use of colon,,, ":"
# use of square bracket,, "[]".

# ----------

# More string operations:
# Slicing a string

str = 'Monty Python'
print(str[0:4]) # it will be called as "str" sub "0" through "4". # up to but not including the final index-character of string
print(str[6:7])
print(str[6:20]) # if the second number is beyond the end of string,, it just stops at the end of string.

print(str[:2]) # if we leave first number or the last number of the slice, it is assumed to be the beginning or the ending of the string.
print(str[8:])
print(str[:])


# =========


# More string operations:
# String Concatenation
# use of "+" operator

a = 'Hello'
b = a + 'There'
print(b) # answer is -- Hellothere

c = a + ' ' + 'There'
print(c) # answer is -- Hello There


# =============

# More string operations:
# using "in" as logical operator
# This K.W. can be used to check if a String is in another String.
# Its a Logical Expression that returns True and False & can be used in an "if-statement".

fruit = 'banana'
print('n' in fruit) # answer is True

print('m'in fruit) # answer is False

print('nan' in fruit) # answer is True

if 'a' in fruit:
print('Found it!')

# =================
# =================

# comparison of strings
# this has to do with character set of your computer, the character set that the Python is
# But in general,, it is LEXOGRAPHICALY less than and LEXOGRAPHICALLY greater than,
# ,,,, Upper case and Lower case are little wiered.
# ,,,, the setting of ur computer also matters,, e.g. earlier in example of max i found out that Upper case is Lower case.
# but in general,, it is bad to assume case,
# but its there a detirministic way to sort strings.
# you can have something equal to or greater than or less than. and all those operations work naturally.
# it becomes unpredictible, where there are punctutions, upper case,, lowr case,,, it dependes on CHARACTER-SET of your computer.
# it works easily as far as you use similar kind of characters (case wise,,) and without punctutions.

#========================================#========================================
#========================================#========================================

# String Library
# Python has number of string FUNCTIONS which are in the STRING LIBRARY.
# These FUNCTIONS are already BUILT-INTO every string - we invoke them by appending the function to the string variable
# These FUNCTIONS do not modify the original string, instead they return a new string that has been altered.
# Strings are Objects.
# and Objects have these things we call METHODS


greet = 'Hello Sohaib'
zap = greet.lower()
print(zap) # answer: -- hello sohaib
print(greet) # answer: -- Hello Sohaib ## Original string is never changed

print('Hi There'.lower()) # answer: -- hi there ## Calling methods is possible even on constants

# ------------

greet = 'Hello Sohaib'
print(type(greet)) # answer: -- <class 'str'>

print(dir(greet)) # answer: -- ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
# '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
# '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__',
# '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
# '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__',
# '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count',
# 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index',
# 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier',
# 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join',
# 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex',
# 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
# 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

## Done So far
# find
# upper and lower case
# replace
# startswith

greet = 'Hello Sohaib'
print(greet)
nstr = greet.replace('Sohaib', 'Zahoor')
print(nstr)
nstr = greet.replace('b', 'l')
print(nstr)
nstr2= nstr.replace('o', 'j')
print(nstr2)

# stripping whitespace # - lstrip() = left strip, # - rstrip() = right strip, # strip() = removes whitespaces both from left and right side

# prefixes # - .startswith() = returns values in True or False.

line = 'Please have a nice day'
print(line.startswith('Please')) # case sensitive.. Please,,, True
print(line.startswith('P')) # Capital P.. True
print(line.startswith('p')) # Small p.. False
print(line.lower().startswith('p')) # True -- as case is changed through .lower


# ================
# ================

# Parsing and Extracting Data, (May be this will help in Data Analysis field)
# example of extracting a slice of string ,, the school name: "uct.ac.za" -- from a given string
# 1 - finding index number from where the name of school will be started: "at_pos". It will be from the first found character like in this example "@".
# 2 - finding end point where the name of school will be ended: "sp_pos". The first found charcter after "ap-pos", in this example "' '".
# 3 - extracting the required slice through mentioning index number and storing it into a new variable: "host". slice of string as required in criteria.

data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
at_pos = data.find('@')
print(at_pos)
sp_pos = data.find(' ', at_pos)
print(sp_pos)
host = data[at_pos+1: sp_pos]
print(host)

# Hard way,, almost impossible,, but basic idea.
print(data[22:31])

# =================================
# =================================

# TWO KINDS OF STRINGS
# in Python 2 there was a distinction between string and a unicode
# But in Python 3, this issue is solved, and now Python 3 is accepting al kinds of information from around the globe in different languages, It treats them as strings only. Hence its more understanding than Python 2.

# ===================================# ===================================# ===================================
# ===================================# ===================================# ===================================
# ===================================# ===== CHAPTER NO. 7 ==========# ===================================
# ===================================# ===================================# ===================================
# ===================================# ===================================# ===================================

### READING FILES ###

# \n -- is a new line charachter, very useful in reading files
# print statement always have a "\n" at the ending of it statement. There are ways to replace it with something else, which we are going to learn later.
# "\n" is also a character in a string.
# its a non printable character. its a white space character.
# Every line ia ended by a New Line.

# ----------------
## how to read files in Python ##

# file handle -- a key to open, read, write and close the file. # file_handle = open('file_name.txt') # where: file_handle = name chosed for the handle variable. open() = function used to create file handle.
# there are number of ways to read through file but the most common one is to treat the file like a "sequence of line"
# determinant loop ( means "for" loop) will be used in example to read through file (a sequence of lines)

xfile = open('mbox.txt') # traceback message will appear as so far no file exixts in system with such name. just a proxy data.
for cheese in xfile:
print(cheese)

# ---------------

## counting lines in a File ##

fhand = open('mbox.txt') # traceback message will appear as so far no file exixts in system with such name. just a proxy data.
count = 0
for line in fhand:
count += 1

print('Line Count: ', count) # answer(when the file will be available) -- "Line count: XXXXX"


# ----------------------
## Reading the "WHOLE" File ##

fhand = open('mbox-short.txt')
inp = fhand.read()
print(len(inp)) # answer (if file is there) -- "XXXXX"

# now for desired slice of strings
print(inp[:20]) # asking for first 20 characters
# answer (if file is there) -- '0123456789 1234.56789'


# ----------------------

## Reading Through the File ##

# getting the lines meeting our criteria set through "if-statement" in a "for-loop".
# Requirement: "search lines that starts with prefix From: "

fhand = open('mbox-short.txt')
for line in fhand:
if line.startswith('From:'):
print(line)

# OOPS! #

# What are all blanks lines doing here?
# probably in result.
# Reason: the "\n" that each line has at its end.

# I had an idea about printing line by mentiontion the last index number like -- "print(line[:-1])"
# But they suggested otherwise. Like using function -- "rstrip()" -- that is removing the white spaces at the right-hand-side of line, which in our case is generated because of new-line-character: "\n"

# so new suggested solution is:

fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip() # making each line striping the white space at the end (right-hand-side) of it.
if line.startswith('From:'):
print(line)



# ----------------------

## structuring the loop little nit differently ##
## Skipping with "continue" ##

# For the reason of focusing only on "good" lines.


fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not line.startswith('From:'):
continue
print(line) # notice the indent-back, to form else statement.

# -----------------------
## Using "in" to select line ##

# looking for string anywhere in a line as out selected criteria.

fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip()
if not 'uct.ac.za' in line:
continue
print(line)


# ===================================
# ===================================
# ===================================

## Prompt for File Name ##

# asking from used the file name through input() function
# Requirement: count the number of lines that are "Subject Lines" in the file

fname = input('Enter the file name: ')
fhand = open(fname)
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)

# answer 1:
# Enter the file name: mbox.txt
# There were 1797 subject lines in mbox.txt


# answer 2:
# Enter the file name: mbox-short.txt
# There were 27 subject lines in mbox-short.txt

# ------------------
## BAD FILE NAMES ##

# what to do if user give file name that can not be opened,
# Solution through try and except block.
# and use of quit() function in case the code blow up at try stage.
# this quit() function is really important cz if its not there, the program will continue down the line and will give trace back message.

# Again the example used above with additional code

fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File can not be opened:', fname)
quit() # its use prevent from crashing out the program, and makes the coder look professional.

count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
print('There were', count, 'subject lines in', fname)

# answer 1:
# Enter the file name: mbox.txt
# There were 1797 subject lines in mbox.txt


# answer 2:
# Enter the file name: na na boo boo
# File can not be opened: na na boo boo


####### important Note:
# most of the programme in this course (the course i am taking right now) are going to say,
# open
# for
# rstrip
# look for
# and then do something interesting


# ===================================
# ===================================
# ===================================

#### DATA STRUCTURE ####

# Shape of Data

### Chapter 8 ###
# Lists


### PROGRAMMING ##
# Algorithm
# A set of rules oe steps used to solve a problem

# Data Structure
# A particular way of organisinf data in a computer
# These are clever ways to lay out the data.
# Clever ways to make sure that the data does what you want it to do.

# Lists are the first and simplest data structure



# ===================================
# ===================================
# ===================================



# ===================================
# ===================================
# ===================================




# ===================================
# ===================================
# ===================================



# ===================================
# ===================================
# ===================================

Comments