Python 12-22

Python 12-21
In [1]:
## exercise 13
from sys import argv

#script, first, second, third = argv
script, first, second = argv

print ("The script is called:", script)
print ("Your first variable is:", first)
print ("Your second variable is:", second)
#print ("Your third variable is:", third)

# instead, do this to hardcode the parameters that will be passed

script = "Exercise13"
first = "string param1"
second = 34
third = 23.5

print ("The script is called:", script)
print ("Your first variable is:", first)
print ("Your second variable is:", second)
print ("Your third variable is:", third)
The script is called: C:\Users\nirva\Anaconda3\lib\site-packages\ipykernel\__main__.py
Your first variable is: -f
Your second variable is: C:\Users\nirva\AppData\Roaming\jupyter\runtime\kernel-07d93d18-9999-4fcd-b96b-d78747ffa9f4.json
The script is called: Exercise13
Your first variable is: string param1
Your second variable is: 34
Your third variable is: 23.5
In [2]:
#exercise 14
from sys import argv

script = argv              # read from the argument
user_name = "pyLover"      # username hardcoded
prompt = '> '

print ("Hi", user_name, " I'm the script ", script)
print ("I'd like to ask you a few questions.")
print ("Do you like me ?",  user_name )
likes = input(prompt)
print(user_name, "says ", likes)
Hi pyLover  I'm the script  ['C:\\Users\\nirva\\Anaconda3\\lib\\site-packages\\ipykernel\\__main__.py', '-f', 'C:\\Users\\nirva\\AppData\\Roaming\\jupyter\\runtime\\kernel-07d93d18-9999-4fcd-b96b-d78747ffa9f4.json']
I'd like to ask you a few questions.
Do you like me ? pyLover
> ef
pyLover says  ef
In [3]:
#exercise 15
filename = "sample.txt"

txt = open(filename)

print ("Contents of your file ",  filename)
print (txt.read())

print ("Type the filename again:")
file_again = input("file? ")

txt_again = open(file_again)

print (txt_again.read())
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-3-c3dca6592310> in <module>()
      2 filename = "sample.txt"
      3 
----> 4 txt = open(filename)
      5 
      6 print ("Contents of your file ",  filename)

FileNotFoundError: [Errno 2] No such file or directory: 'sample.txt'
In [4]:
#exercise 16

filename = "junk.txt"

print ("We're going to erase", filename)
print ("If you don't want that, hit CTRL-C (^C).")
print ("If you do want that, hit RETURN.")

input("?")

print ("Opening the file...")
target = open(filename, 'w')

print ("Truncating the file.  Goodbye!")
target.truncate()

print ("Now I'm going to ask you for three lines.")

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print ("I'm going to write these to the file.")

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print ("And finally, we close it.")
target.close()

readfile = open(filename)

print ("Contents of your file ",  filename)
print (readfile.read())
We're going to erase junk.txt
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?ddw
Opening the file...
Truncating the file.  Goodbye!
Now I'm going to ask you for three lines.
line 1: wefw
line 2: wrgerg
line 3: grhyh
I'm going to write these to the file.
And finally, we close it.
Contents of your file  junk.txt
wefw
wrgerg
grhyh

In [5]:
#exercise 17
from sys import argv
from os.path import exists

from_file = "sample.txt"
to_file = "copy-sample.txt"

print ("Copying from ", from_file, "to ", to_file)

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

print ("The input file is ", len(indata)," bytes long")

print ("Does the output file exist?", exists(to_file))
input("continue ..")

out_file = open(to_file, 'w')
out_file.write(indata)

print ("Alright, all done.")

out_file.close()
in_file.close()

readfile = open(to_file)

print ("Contents of your file ",  to_file)
print (readfile.read())
Copying from  sample.txt to  copy-sample.txt
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-5-b549ea0ae1ea> in <module>()
      9 
     10 # we could do these two on one line, how?
---> 11 in_file = open(from_file)
     12 indata = in_file.read()
     13 

FileNotFoundError: [Errno 2] No such file or directory: 'sample.txt'
In [6]:
#exeercise 18
def print_two(*args):
    arg1, arg2 = args
    print ("arg1: ", arg1, "arg2: ", arg2)

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

# this just takes one argument
def print_one(arg1):
    print ("arg1: ", arg1)

# this one takes no arguments
def print_none():
    print ("I got nothin'.")


print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
arg1:  Zed arg2:  Shaw
arg1:  Zed arg2:  Shaw
arg1:  First!
I got nothin'.
In [7]:
#exercise 19

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print ("You have ",cheese_count, "cheeses!")
    print ("You have ", boxes_of_crackers,"  boxes of crackers")
    print ("Man that's enough for a party!")
    print ("Get a blanket.\n")


print ("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)


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)


print ("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)


print ("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
We can just give the function numbers directly:
You have  20 cheeses!
You have  30   boxes of crackers
Man that's enough for a party!
Get a blanket.

OR, we can use variables from our script:
You have  10 cheeses!
You have  50   boxes of crackers
Man that's enough for a party!
Get a blanket.

We can even do math inside too:
You have  30 cheeses!
You have  11   boxes of crackers
Man that's enough for a party!
Get a blanket.

And we can combine the two, variables and math:
You have  110 cheeses!
You have  1050   boxes of crackers
Man that's enough for a party!
Get a blanket.

In [8]:
#exercise 20

input_file = "sample.txt"

def print_all(f):
    print (f.read())

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print (line_count, f.readline())

current_file = open(input_file)

print ("First let's print the whole file:\n")

print_all(current_file)

print ("Now let's rewind, kind of like a tape.")

rewind(current_file)

print ("Let's print three lines:\n")

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-8-8e779bf68a89> in <module>()
     12     print (line_count, f.readline())
     13 
---> 14 current_file = open(input_file)
     15 
     16 print ("First let's print the whole file:\n")

FileNotFoundError: [Errno 2] No such file or directory: 'sample.txt'
In [9]:
#exercise 21

def add(a, b):
    print ("ADDING ", a, b)
    return a + b

def subtract(a, b):
    print ("Subtracting ", a, b)
    return a - b

def multiply(a, b):
    print ("Multiplying ", a, b)
    return a * b

def divide(a, b):
    print ("Dividing ", a, b)
    return a / b


print ("Let's do some math with just functions!")

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print ("Age: Height: Weight: IQ: " , age, height, weight, iq)


# A puzzle for the extra credit, type it in anyway.
print ("Here is a puzzle.")

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print ("That becomes: ", what, "Can you do it by hand?")
Let's do some math with just functions!
ADDING  30 5
Subtracting  78 4
Multiplying  90 2
Dividing  100 2
Age: Height: Weight: IQ:  35 74 180 50.0
Here is a puzzle.
Dividing  50.0 2
Multiplying  180 25.0
Subtracting  74 4500.0
ADDING  35 -4426.0
That becomes:  -4391.0 Can you do it by hand?
In [ ]:

Comments

Popular posts from this blog

Python 22-39

Machine Learning with Python example