More Functions and Variables

# Dawn, sources say that the variables we used in our functions at test18.py
# Are not connected to the variables in our script 😦
# What do you make of it?
# Well this is an exercise to get us thinking

# Dawn do you remember test18.py? Its a similar to the one we ve here
# Here, cheese_crackers is defined. Any word could be used instead
# And now the variables (cheese_count, boxes_of_crackers)
def cheese_and_crackers(cheese_count, boxes_of_crackers): # This is a function too
print “You have %d cheeses!” % cheese_count # This is the variable % cheese_count
print “You have %d boxes of crackers!” % boxes_of_crackers # This too
print “Man thats enough for a party!”
print “Get a blanket.\n” # Remember this? It allows spacing in sentences

print “We can just give the function numbers directly:”
cheese_and_crackers(20, 30) # And well, we can use numbers too
# Same thing as previous.
# The first number goes to ‘You have %d cheeses!’
# The second number applies to ‘You have %d boxes of crackers!”

print “OR, we can use variables from our script:”
amount_of_cheese = 10
amount_of_crackers = 50

cheese_and_crackers(amount_of_cheese, amount_of_crackers) # You would realise that the
# The Main def is always used
# cheese_and_crackers
# It matters most
# Don’t forget please Dawn

print “We can even do math inside too:” # Lets do some Maths. Hope you dont mind 🙂
cheese_and_crackers(10 + 20, 5 + 6) # As additions are used here,
# We can use other symbols as well (-, /, x, +)

print “And we can combine the two, variables and math:” # Variables and Maths
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) # Pure sample

# This is Dawn inputs 🙂
print “Dawn loves coding and hacking. Its in his DNA”
cheese_count = 87
boxes_of_crackers = 250

cheese_and_crackers(cheese_count, boxes_of_crackers) # When using a def, dont use ‘=’

def halo(code, clients, warrior): # Remember to always add the colon: when using def please
print “Boss Dawn, congratulations! You are the richest man on earth!”
print “Ok guys, lets %s” % code
print “Champ Dawn, we heard you got %s” % clients
print “Ok, no problem. By God’s grace we are on course”
print “Cobra7 aka Dawn, real %s are you” % warrior
print “Game on boys, we ain’t stopping yet!\n”

halo(“code”,”clients”,”warrior”) # Over here, we give real values to the variables

def c(c, g, p): # We define a new function ‘c’ which would take 3 arguments (c, g, p)
print “Welcome my people to Dawn’s world of %s!” % c
print “Well its all good %s!” % g
print “This is what he has %s for!” % p
print “No stopping Eagle99”
print “Hurray! We are on course!\n”

c(“coding”,”guys”,”passion”)

print “Hi guys” # This is optional, without it, still 3 statements would be printed
c(“Reg_Sec”,”yeah”,”always killed himself”) # If function ‘c’ has the needed arguments

# Interestingly, we can use as many functions as we want
# All we needed is to to define it and add the variables as many as we want
# Then ‘edit’ the content for other structures if we want repeated ones as in ‘def c’
# Bingo, we should be done and dusted
# Yes Boss Dawn

 

Using Argv, functions, name, variables

# We are going to use Names, Variables, Code, Functions
# Functions more importantly
# Functions do 3 things;
# They name piece of code the way variables name strings and numbers
# They take arguments the way your scripts thake argv
# Using #1 and #2 they let you make your own “mini scripts” or “tiny vommands”

# this one is like our scripts with argv

def print_two(*args):
arg1, arg2 = args
print “arg1: %r, arg2: %r” % (arg1, arg2)

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print “arg1: %r, arg2: %r” % (arg1, arg2)

# this just takes one argument
def print_one(arg1):
print “arg1: %r” % arg1

# this one takes no arguments
def print_none():
print “I got nothin’.”

# this is Dawn’s own. We are just using any word 🙂
def output(demo, demo2):
print “This demo is %s, the other is %s” % (demo, demo2)

# another Dawn’s work. Lets try blacknode 🙂
def black_node(*node):
node1, node2 = node
print “Dawn’s code name is %s, well, is it %s?” % (node1, node2)

# Mice84 at work. Lol its Dawn 🙂
# Lets use just one argument ok?
def mice84(mice84):
print “Ok, so our new codename would maybe be %s” % mice84

# We give it no argument Dawn
def reg_sec():
print “Regent Security would be our Company’s name someday. Yes!”

# Ok, so we have realised that functions help reduce repeated works
# For instance, for us to type…print “This demo %s, the other is %s” % (demo, demo2)
# Several times, all we need to do is to use the function module. 🙂
# Der nor ur guy guy come 🙂 🙂 🙂 swear
# Anyway, we define (def) it at the start of the script 🙂
# Then we tend to use it later, so as where ever there is ‘output’, the defined words go

# As in just down here. One print sentence, four words. So the function generates
# A second one for us. All we need is just to give
# Some partnering variables to ‘output’. Bingo, we a re good to go.
# The word ‘output’ is been used randomly, any one could do. Like ‘dawn’ 🙂

output(“better”, “good”)
output(“worse”, “worst”)

black_node(“Cobra7″,”Whitefrog”) # If you repeat the defined function twice, it comes 2
black_node(“Black_node”,”Mice84″) # If for a 1000 times, it will come as such

mice84(“Mice84”)

reg_sec()

print_two(“Zed”,”Shaw”)
print_two_again(“Zed”,”Shaw”)
print_one(“First!”)

print_none()

Making changes to a file

# More files
# In here, Dawn we would do well to write a Python script to copy one file to another
# Yes, don’t worry. It would end well 🙂
# Vhim yazo! 🙂
# Dawn we beg you, scripting needs lots of attention and care
# Always pay close attention even to the smallest of details
# Ayoo
# You really want to reduce bugs among others?
# Then do it
# Do well to read on Pythons import statement and start python to try it out

from sys import argv
from os.path import exists

script, from_file, to_file = argv # We nedd 2 files as compared to test16.py
# One is for the from_file and another is to_file
# We use the to_file because of the ‘os.path import’

print “Copying from %s to %s” % (from_file, to_file)

# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()

print “The input file is %d bytes long” % len(indata)

print “Does the output file exist? %r” % exists(to_file) # If the output file doesnt exist, its False
print “Ready, hit RETURN to continue, CTRL-C to abort.”
raw_input() # As usual raw_input provides us with a space to type something in.

output = open(to_file, ‘w’) # File is opened in the system background. Ready for ‘w’ writing
output.write(indata) # File gets written to

print “Alright, all done.”

output.close() # File is closed
input.close() # After writing is done, it closes

Writing More files

# More of reading and writing files
# The use of close, read, readline, truncate, write
# This software can be used to save and retrieve files.
# Softsafe.py does that function. Add other writings to it and save it
# Test16.py writes to only files does not append or continue.

 

from sys import argv

script, filename = argv

print “We’re going to erase %r.” % filename
print “If you don’t want that, hit CTRL-C (^C).”
print “If you do want that, hit RETURN.”

raw_input(“?”)

print “Opening the file…”
target = open(filename, ‘r+U’) # The ‘w’ mode writes new user data into the file. Existing ones writes off.
# The ‘a’ mode writes to a file and even add to it
# The ‘r’ + ‘U’ mode does same function as ‘w’. It seems ‘r’ cant be used alone.
print “Truncating the file. Goodbye!”
target.truncate()

print “Now I’m going to ask you for three lines.”

line1 = raw_input(“line 1: “)
line2 = raw_input(“line 2: “)
line3 = raw_input(“line 3: “)

print “I’m going to write these to the file.”

target.write(line1) # This jumps to first line
target.write(“\n”) # This write write the line1 input from (raw_input)
target.write(line2) # This jumps to second line
target.write(“\n”) # This write the line2 input from (raw_input)
target.write(line3) # This jumps to line3
target.write(“\n”) # This write the line3 input from (raw_inpt)

print “And finally, we close it.”
target.close()

Writing to files

# Everything we’ve learnt about raw_inputs and argv is so we can start reading files. We would’ve to play with this exercise the most to understand what’s going on. So do it carefully and remember your Checks.Working with files is an easy way to erase our work if not careful 😦
# This file involves writing two files.
# One is test15.py and the other is test15_sample.txt.
# This second file ins’t a script but a plain text file we’ll be reading in # Our script.

# We can ‘Hard code’ the file to get our results but we dont want to
# It is why we are using the argv and raw_input
# In order to ask for the file name

from sys import argv

script, filename = argv

txt = open(filename)

print “Here’s your file %r:” % filename
print txt.read()

print “I’ll also ask you to type it again:”
file_again = raw_input(“\n> “)

txt_again = open(file_again)

print txt_again.read()

print “Anything else please?”
yes = raw_input(“\n> “)

server = “server down”

print “Oops, %s” % server

print “Thank you”

 

 

Argument Variables and Advanced Input

# Prompting and Passing
# We are doing one more exercise where the usage of argv and raw_input counts
# Learning how to read and write files is important
# Dawn, we will ‘ve raw_input print a simple > prompt.
# This is similar to a game like Zork or Adventure 🙂
# Try to find out what Zork and Adventure game is and play 🙂

from sys import argv

script, user_name = argv
prompt = ‘> ‘

print “Hi %s, I’m the %s script.” % (user_name, script)
print “I’d like to ask you some few questions.”
print “\nDo you like me %s?” % user_name
likes = raw_input (prompt)

print “\nWhere do you live %s?” % user_name
lives = raw_input(prompt)

print “\nWhat kind of computer do you have?”
computer = raw_input(prompt)

print “””
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
“”” % (likes, lives, computer)

Dealing with parameters in Python

# Parameters, Unpacking, Variables
# We will cover one more input type in here Dawn
# You can use to pass variables to a script (script being another name for # Your .py files)
# The test3.py part of the command is called an “argument”
# What we’ll do now is write a script that also accepts accepts arguments

from sys import argv

script, Dawn, Lin, Collins = argv

print “The script is called:”, script
print “Your first variable is:”, Dawn
print “Your second variable is:”, Lin
print “Your third variable is:”, Collins

print “\nWho are you?”
name = raw_input()

print “\nWhats your mission?”
purpose = raw_input()

print “\nWho is your prime target?”
entity = raw_input()

print “\nSo you are %s and your mission is to %s. And well prime target is %s” % (name, purpose, entity)

print “\nReally?”
answer = raw_input()

Taking inputs

# Now its time to pick up the pace.
# Lets do some ‘real’ software thing
# All along we have been printing
# We haven’t taken in any inputs talk less of changing it
# Don’t worry pal, we are in line 🙂
# You should go online to find out what python ‘raw_input’ does 🙂

print “How old are you?”,
age = raw_input ()

print “How tall are you?”,
height = raw_input()

print “How much do you weigh?”,
weight = raw_input()

print “So, you’re %r old, %r tall and %r heavy.” % (age, height, weight)

Doing more with backslash

# Doing more with backslash \ and ‘n’
# They are called escape keys too
# Some other time we would search online to find out what other
# Escape sequences we have

print “I am 6’2\” tall.” # Escape double-quote inside string
print ‘I am 6\’2″ tall.’ # Escape single-quote inside string

tabby_cat = “\tI’m tabbed in.”
persian_cat = “I’m split\non a line.”
backslash_cat = “I’m \\ a \\ cat.”

fat_cat = “””
I’ll do a list:
\t* Cat food
\t* Fishes
\t* Catnip\n\t* Grass
“””

single_quotes = ”’
We we’re using thripple single quotes
“How would it fair down here”
Down here
”’
black_node = “Dawn”
code = “White”
number = 200

print “%r Dawn” % ‘Hi’

print “Dawn says his next code name would be %s” % ‘white_frog’
print single_quotes
print tabby_cat
print persian_cat
print backslash_cat
print fat_cat
print “He is %s, loves %s and would live for a %d yrs” % (black_node, code, number)