Backup 2nd time
# 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
# ===================================
# ===================================
# ===================================
################################################ NEXT DAY ################################################
#### 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
# Strings are kinda data structure, but lists are first real data structure that we gonna think about and design and make use effectively.
# Collection #
# a Collection allows us to put many values in a single VARIABLE.
# Its nice cz ve can carry "all many" values in one convenient package.
# Lists #
# Lists constants are surrounded by square brackets and the elements in the list are seperated by commas.
# A list elements can be any "Python Object" - even another list.
# A list can be empty.
# ---------------------------------
# FUn GAme # checking if same name can be given to the iteration variable (same as of List's NAme"
# its behaviour is similar to the pattern of adopting new value i.e. value of an element of the list rather than the list as vlue itself.
x = ['j', 'k', 'l']
print(x)
for x in x:
print(x)
print(x)
# Answer is:
# ['j', 'k', 'l']
# j
# k
# l
# l
# --------------------------------
# calling an idex of a list is spoken about like this
# print f[1] -- print f sub one.
# --------------------------------
# Lists are mutable #
# means you can change the values of lists,,, campare it with strings where you can not chage the part of string, rather you have to generate a new list; may be a copy of old list by applying some particular method like lower, upper, etc
# we can change elements of list using "index operator"
fruit = 'Banana'
fruit[0] = 'b' # Traceback message
# ----------- rather we have to create a new string #------------
x = fruit.lower()
print(x) # answer is -- banana
print('\n')
lotto = [2, 14, 26, 41, 63]
print(lotto) # answer is -- [2, 14, 26, 41, 63]
lotto[2] = 30 # example of item assignment in a list.
print(lotto) # answer is -- [2, 14, 30, 41, 63]
# -------------------------------------------------------------
## Lenght of list ##
# use of len() function
# this function tell how many items there are, so do not confuse it with counting number of characters in a string.
# it returns the number of items, not index number total.
# --------------------------------
## Range() function ## 3:56:55
# it returns a list of numbers, that range from zero to "one less than parameter"
# we can construct an "index loop" using for and an integer iterator.
print(range(4)) # answer : range(0, 4)
friends = ['joseph', 'Glenn', 'Sally']
print(len(friends)) # answer : 3
print(range(len(friends))) # answer : range(0, 3)
# this can be used for constructing for loops.
# Issue: in my case the result is coming as (0, 4) and (0, 3).. means starting and ending value.
# but the solution provided otherwise gives answers like: (0, 1, 2, 3) and (0, 1, 2)
# now how can i use my results to construct loops based on index reference in for example "friends" list.
# ----------- next example
## A tale of Two Loops ##
friends = ['joseph', 'Glenn', 'Sally']
print(len(friends)) # answer : 3
print(range(len(friends))) # answer : range(0, 3)
print('\n 1st Solution:-')
for friend in friends:
print('Happy new year: ', friend)
print('\n 2nd Solution:-')
# when you want a more sophisticated loop.
# like when you want to be able to loop thorough where you know the position.
for i in range(len(friends)):
friend = friends[i]
i += 1 # added by me to synchronise with objective of making it understandable by the general user.
print(i, end='\t', ) # added by me for knowing the index positing at each loop
print('Happy new year: ', friend)
# ====================== Chapter No. 8 ========================
# ================= Operations that you can do with Loops =====
# Concatenating Lists using +
# Python has Object oriented approach towards its operators.
# Plus can add Numbers (Floating point numbers and integers), Strings etc and similarly it can add Lists
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print('a list: ', a) # answer: a list: [1, 2, 3]
print('b list: ', b) # answer: b list: [4, 5, 6]
print('\nc List: ', c) # answer: c List: [1, 2, 3, 4, 5, 6]
# --------------------------
# Lists can be sliced using " : ".
t = [9, 41, 12, 3, 74, 15]
print(t[1:3]) # [41, 12]
print(t[:4]) # [9, 41, 12, 3]
print(t[3:]) # [3, 74, 15]
print(t[:]) # [9, 41, 12, 3, 74, 15]
# --------------------------
# List Methods
x = list()
print(type(x)) # <class 'list'>
print(dir(x))
# ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
# '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
# '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__',
# '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
# '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
# '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__',
# 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
# 'reverse', 'sort']
# ----------------------------
# BUILDING a LIST from SCRATCH
# we can create an empty list and then add elements using ".append" method.
# the list stays in order and new elements are added at the end of the list.
stuff = list()
print(stuff) # []
stuff.append('book')
print(stuff) # ['book']
stuff.append(99)
stuff.append('Cycle')
print(stuff) # ['book', 99, 'Cycle']
# -------------------------------
# Is something in a List?
# Two logical operators serve this purpose in python "in" and "not in"
# As they are logical operators they return True or False
# They ("in" and " not in") do not modify the list
some = [1, 9, 21, 10, 16]
print(9 in some) # True
print(15 in some) # False
print(20 not in some) # True
# --------------------------------
# Lists are in Order, and they are sortable
# order of items in lists is maintained unless we do something about it.
# .sort() method is used to sort the items in list
# sort method means "sort yourself"
friends = ['Joseph', 'Glenn', 'Sally']
print(friends) # ['Joseph', 'Glenn', 'Sally']
friends.sort()
print(friends) # ['Glenn', 'Joseph', 'Sally']
print(friends[1]) # Joseph
# -------------------------------
# Built in functions and lists
# These take lists as their arguments where as methods like sort etc are part of list.
# len() -- Length
# max() -- Maximum
# min() -- Minimum
# sum() -- Summ of items
# combination of any of these built-in functions to get some particular result.
# like Average calculation -- sum() / len() -- Total/Number of Items
nums = [3, 41, 12, 9, 74, 15]
print('Length of List: ', len(nums)) # 6
print('Maximum Item: ', max(nums)) # 74
print('Minimum Item: ', min(nums)) # 3
print('Total of Items: ', sum(nums)) # 154
print('Average of Items: ', sum(nums) / len(nums)) # 25.666666666666668
# -------------------------------
# Two programs producing same results.
# Two Algorithams for same Solution
# Requirement: Finding Average of Given Numbers
# User is capable to Enter as many number as they want.
# The Calculation will be executed on providing a particular command.
# Output will be in the form of providing Average Calculation
# In Solution, "While Loop" is Used.
# 1st Solution,,,,, creating variables outside loop, a Solution without creating a List.
# Less memory is used by this solution.
total = 0
count = 0
while True:
inp = input('Enter a Number: ')
if inp == 'done':
break
value = float(inp)
total = total + value
count = count + 1
avg = total/count
print('Average: ', avg)
# ------------
# 2nd Solution: creating a list while entering the number
# This solution uses more memory
num_list = list() # Create an empty list
while True:
inp = input('Enter the Number: ') # asking user to enter the number
if inp == 'done': # command to stop the data entry and executing the calculation
break
value = float(inp) # converting the data entered into float (a precautionary measure to add all numbers).
num_list.append(value) # adding the numbers entered into the list through .append method
avg = sum(num_list) / len(num_list) # calculating the average
print('Average: ', avg) # printing out the result
# ---------------------
# 2nd Solution: continue
# Demand 1: both lower and upper case is to be acceptable
# Demand 2: in case of other text entered (wrong entry), message to be appeared asking user to enter correct value.
# Case issue of "done" is solved through .lower method
# invalid data issue is solved through "Try" and "Except" method.
num_list = list()
while True:
try:
inp = input('Enter the Number: ')
if inp.lower() == 'done':
break
value = float(inp)
num_list.append(value)
except:
print('The number you entered is not an integer!')
avg = sum(num_list) / len(num_list)
print('Average: ', avg)
# ===================================
# Best Friends: Lists and Operations
# How strings and lists are related
# both have zero based
# and we use the square bracket operator [] to do various things.
## split function ##
# split breaks a string into parts and produces a list of strings.
# we think of these as words
# we can access a particular word or loop through all the words.
# Similar results are obtained through use of "find" and ""Slicing", but people still prefer "split()" function for this purpose.
# split () with no parameter () -- will look for white spaces including also new lines, tabs etc.
# it will take as one space even if there are more spaces than one.
# There are other parameters that can be used by split() function other than white spaces like ; , 'a' or any other character.
# if itt does not found the given parameter, it does not split the input.
abc = 'with three words'
stuff = abc.split()
print(stuff) # ['with', 'three', 'words']
print(len(stuff)) # 3
print(stuff[0]) # with
for w in stuff:
print(w)
# with
# three
# words
# ---------------------
# Spliting can be done by giving a parameter within its paranthesis.
# when you don't specify a "delimeter", multiple spaces are treated like one delimeter.
# you can specify what "delimeter" character to use in the "spliting".
line = 'first;second;third'
thing = line.split(';')
print(thing) # ['first', 'second', 'third']
print(len(thing)) # 3
print(len(line.split(';'))) # 3 # since thing = line.split(';') -- so it will give same result as of len(thing).
print(line) # first;second;third
print(len(line)) # 18 # length of string without splitting
# where as without any given parameter, the output is as follows.
etc = line.split()
print(etc) # ['first;second;third'] # means no spliting is done as no white space is found.
print(len(etc)) # 1
# Used for managing lot of data coming from, loging system, routers, status-update --
# from where ever the data is coming, the delimeter is often something other than "white space" that you can do that with split()
# -------------------------------------------------------------
##### PARCING #####
# this spliting technique is used while parcing data from email.
# over there the data is avaiable in strings like:
# "From stephen.marqard@uct.ac.za Sat Jan 5 09:14:16 2008"
# Data is first converted into lists using split() function.
# Then the required data is called through calling index number relating to items of newly created lists.
fhand = open('mbox-short.txt')
for line in fhand:
line = line.rstrip() # throws away the white-space.
if not line.startswith('From '): # this will help ignoring all the lines not starting with "From ".
continue # condition going wrong, i.e. line not starting from 'From ', the next function will be skipped - cz of "continue".
words = line.split()
print(words[2]) # sat -- the third piece of the line.
# Since line in file is:
line = 'From stephen.marqard@uct.ac.za Sat Jan 5 09:14:16 2008'
# and
print(words) # ['From', 'stephen.marqard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
# ---------------------------
######## The Double Split Pattern ########
# Sometimes we split a line one way and then grab one of the pieces of line and split that piece again.
# e.g.
# From stephen.marqard@uct.ac.za Sat Jan 5 09:14:16 2008
words = line.split() # ['From', 'stephen.marqard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
email = words[1] # stephen.marqard@uct.ac.za
# then we are going to re-split that.
pieces = email.split('@') # ['stephen.marqard', 'uct.ac.za']
print(pieces[1]) # 'uct.ac.za'
# we did this exercise by using "find", using some slice obtaining method.
# but this approact, i.e. finding through split() function is much more cleaner.
# ===================================
# ===================================
##### 4:16:42 Pytohn Lists - Strings, Files, Lists and Guardian Pattern
# - now we are gonna learn how to write some code to do some parsing, read some data (for example looking for lines begining with "From "and extract the third wotd.
## - Task, Debuging a code already written for this purpose.
# -------------------------------------------------------------
# -------------------------------------------------------------
# -------------------------------------------------------------
# ===================================
# ===================================
# ===================================
Comments
Post a Comment