CodeWell Academy()

and
R.M.Z. Trigo

presents:

Programming Python,

Master's Handbook Edition

Code like a PRO in 24 hrs or less!

Proven Strategies & Process!

A Beginner's TRUE guide to Code,

with Data Structures & Algorithms

Master’s Handbook Series

© Copyright 2015 - All rights reserved.

In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic means or in printed format. Recording of this publication is strictly prohibited and any storage of this document is not allowed unless with written permission from the publisher. All rights reserved.

The information provided herein is stated to be truthful and consistent, in that any liability, in terms of inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any legal responsibility or blame be held against the publisher for any reparation, damages, or monetary loss due to the information herein, either directly or indirectly.

Respective authors own all copyrights not held by the publisher.

Legal Notice:

This ebook is copyright protected. This is only for personal use. You cannot amend, distribute, sell, use, quote or paraphrase any part or the content within this ebook without the consent of the author or copyright owner. Legal action will be pursued if this is breached.

Disclaimer Notice:

Please note the information contained within this document is for educational and entertainment purposes only. Every attempt has been made to provide accurate, up to date and reliable complete information. No warranties of any kind are expressed or implied. Readers acknowledge that the author is not engaging in the rendering of legal, financial, medical or professional advice.

By reading this document, the reader agrees that under no circumstances are we responsible for any losses, direct or indirect, which are incurred as a result of the use of information contained within this document, including, but not limited to, —errors, omissions, or inaccuracies.

Table of Contents

Introduction

========================= ======

Welcome to the Path of Mastery

We thank you for purchasing & downloading our work, the Master’s Handbook. By doing so, we can tell you have a curiosity to learn Programming in a deeper, more comprehensive way.

We notice that you don’t just want to learn a few tricks here and there, but you want the confidence to take on any programming challenge with ease.

Hence, you’ve come to the right place…

The Master’s Circle

You aren’t alone.

Behind this book are programmers hailing from some of the most Best Computer Science Programs taught by some of the most Advanced Universities in the World Today.

The Master Structure

We start by observing the world and defining the code to represent things (data) or actions (functions). As you progress through the book, you’ll find more advanced concepts and ways to combine them all together.

You’re also accommodated with the Main Programming Language this book comes with, as well as general PseudoCode to help understand coding concepts. Often times, you’ll find that our PseudoCode bridges you from learning this Book’s Main Language to learning your Next Language!

Whether you haven’t coded a single line before, or you’ve already build serious projects, you WILL find great value in this book. Often times, you’ll run into a coding challenge in your programming journey. This book will help you identify how to progress through it!

========================= ======

Python Introduction

========================= ======

Python: The Swiss Army Code

There are reasons why some of the biggest websites today, like Youtube, were originally constructed in Python. It’s the go-to code for many startups, since its easy-to-learn and less demanding syntax give it a more welcoming appeal. Early projects are often in their core code phases, so they often choose a programming language that does nearly everything.

However, it’s this distinct lack of specialization that limits Python. There are programming languages available that have sheer processing speed (C and C++), while there are other languages that have specific roles performed extremely well (PHP as server-side code).

Python offers a great start for most programmers. As an available option to any coding situation, it will always be a great addition in a coder’s ensemble.

Python Advantages:

-VERY easy to learn

-Flexible

-Less code required

-Generally used

Python Disadvantages:

-relatively slower performance

-no distinct specialization

Python Workshops:

These workshops are yours to complete in whichever way you like (However, the code MUST work!).

They’re designed to put the most recent concepts into real-life practice, yet giving you the flexibility and critical thinking along the way.

And of course, flexibility and deep critical thinking are key programmer traits!

Find them throughout the book!

========================= ======

Prelude: Atomic Data Types

First off, we’ll briefly start with primitive data types. It’s important to know what they are, because you’ll be identifying real-life information with them later.

Booleans

Booleans, often called bools, are either TRUE or FALSE. This is the simplest data type, but often one of the most important. A LOT of functionality depends on Booleans, as you will find out later

A Boolean will always be a two-state situation. For example, the lights in your living room are either on (TRUE) or off (FALSE).

Integers

These are all the standard whole numbers, both positive and negative. The highest and lowest integers depend on the number of bits to represent them (i.e. 8-bit integers, 16-bit, etc.). Mathematic and boolean operators often use Integers,.i.e.

10 + 50 == 60,

-4 - 12, != -10,

and so on.

Characters

These are all letters and symbols that can be represented by ASCII characters. Think of one character as a single symbol or letter.

Floats

Formally called floating-point numbers, these represent decimals - including the decimal point and decimal numbers beyond.

Examples:

2.3

0.75

Prelude: Data Sequences & Combinations

Strings

These are merely a collection of Characters in sequence. Think of these as words or phrases.

In most programming languages, Strings are represented by a sequence of characters between quotation marks: “Hi there”, or “Hello.”, for example.

How these would look like as a sequence of characters is as follows:

“Hi There” is represented as characters H,i, space, T, h,e , r, and e

“Hello.” is represented as characters H, e, l, l, o, and the period.

Lists

These are a sequence of individual elements put together as a list. Often times, all the elements within that list are the same data type

Examples would be:

a List of Integers: [3, 1, 4, 9, 2]

a List of Strings: [“Apple”, “Banana”, “Caramel”]

a List of Booleans: [true, false, true, true]

Enumerations

These are fixed sets of data values. The data within these sets are the same data type. You would have to choose between one of the data elements within that set.

For example, traffic lights are either red, orange, or green.

As an enumeration, traffic lights would be: [“Red, “Green”, “Yellow”]

What differs Enumerations from lists is that Enumerations have a FIXED set of values. You wont be able to add or delete the elements unless you edit the code directly.

Itemizations

Itemizations combine different data types together to form a finite set. Depending on the data type of a single element, you’ll have to process that data in a certain way (you’ll learn about this later in function templates).

Enumerations have the same data type, but Itemizations have different data types in the set. You also won’t be able to add or delete any of the elements as well.

For example, a Space Rocket launch would be a set of integers 10 to 1, then the booleans true or false, to signifiy whether or not it has launched yet.

As an itemization, a Space Rocket Launch would be: [ false, 10, 9, … 1, true]

Prelude: Your Coding Environment

Simple Online IDE

For now, it’s all about understanding all the Programming Concepts, from the simple to the downright advanced.

To test out these concepts, you’ll only need a simple online Compiler to run your code and make sure it works the way you planned it to.

Here’s a few ones online. They’re FREE and they don’t require any membership to test out your code:

www.codechef.com/ide

codepad.org

rextester.com

Full Development Kits

You may also set up your computer for app development, if you wish.

First, identify what Programming Language(s) and Framework(s) you wish to use. Then choose and set up the ideal Integrated Development Environment (IDE) for your language-framework combinations.

Popular IDE’s include IntelliJ, Eclipse, Netbeans, CodeLite, XCode (for Mac Users) and more. But remember: make sure your IDE supports the programming languages of your choice.

NOTE: Comments

For those only learning how to program, it’s important to describe what your lines of code are and why you have them.

For programming teams, comments are essential. Even seasoned programmers who work in teams need to explain what their code does and why they have it. They find that it saves them time in analyzing and figuring out other people’s code. They will also have less errors along the way - knowing that they’re coding what they mean to, or editing code to be the way they originally want it to be.

PART I: Your Code Structure and Foundations

Chapter 1: Defining & Designing your Data

Anything in this universe can be represented by data. Your name, age, gender, what car you drive, what city you live in, country, planet, galaxy, and so on.

To design great apps, games, and any other digital tool you can think of, you’ll have to identify what type of data you’re dealing with.

Identify your Data Type

There are two questions to ask yourself when you’re designing data to represent something.

First, identify whether or not you can define that ‘thing’ as an Integer, Number, Boolean (yes/no type things), or String. For example, your name is a String (a sequence of letters), your Age is a Number, and you live in a City or Town. Your city of town has a name - another String.

Second, identify whether or not that thing is a part of a whole; included in a larger thing. For example, you may have a friend named Jamie. She’s included in a list of your friends.

Representing your information as a Data Type

In most programming languages, you can define your data as a line of code. Here we define your data as a Global Variable - meaning this editable line of data is available throughout your program.

In most languages, you’ll very likely declare the Type of data you represent, as well as the Name of your data.

Let’s start with your name, using pseudocode for now:

String NAME;

In the above line of code, you defined your data as a String of characters, labelled as a NAME.

An Explanation for your Data

A good practice in defining your data is to make comments above the line of code that explains why you have your data the way it is. One of the lines can be in the format of “____ is a (Data Type)”.

In most programming languages, comments usually start with two slashes (//). For the pseudocode we use here, we’ll do the same

For the above line, here’s the example:

// My Name is a String

String NAME;

Here are some more examples:

// My Age is a Number

Number AGE;

// I live in a City or Town, with a Name

// My city’s name is a String

String CITY;

// I am either hungry or not

// My hunger status is a Boolean

Boolean HUNGRY?;

// I either have a pet or I don’t

// Whether or not I have a pet is a Boolean

Boolean HASPET?;

PYT-01: Defining & Designing your Data

Python Comments

In Python, comment lines start with a single number sign (#).

Atomic Data in Python

Most atomic data in Python have the same syntax.

One exception is Booleans. They must have capitalized first letters.

So in Python, booleans are: True or False

Python Data Definitions

Here’s how to declare your Data Definitions in Python.

Most variable declarations in Python follow the sequence of:

(Variable Name) = (Initial Value)

In Python, you don’t openly declare the type of data you’re having for your variables. However you’ll have to set your variable’s first value at the very start.

Python will then know what data type you’ve set your data as - depending on whatever data type you’ve set your Initial Value to.

Also, where most programming languages require the Semicolon (;) to symbolize a line of code’s end, you don’t do that in Python.

So, in practice, let’s define your friend’s name. Let’s call her Jasmine. First, let’s add a comment to make a note of what data type you’re dealing with:

## Jasmine’s name is a String

Now, let’s define her name’s data.

## Jasmine’s name is a String

NAME = “Jasmine”

The Python compiler knows that NAME is going to be a String, since you’ve initialized NAME as a String.

PRACTICE:

Let’s start by declaring things that follow into each of: Strings, Numbers, Integers, and Booleans.

Fill in the blanks below, and copy-paste code between the lines to an IDE of your choice. You may also use online IDE’s such as ideone.com, codepad.org, or rextester.com

## ———————————

## Your name is a ____

MYNAME = “____”

## Your age is a ___

MYAGE = ____

## You are either Married or not.

## Your Marriage Status is a ____

ISMARRIED = _____

print (MYNAME)

print (MYAGE)

print “ You Are Married? “

print (ISMARRIED)

## ———————————

If you try to run your code - and it runs correctly - you should see the following:

(your name)

(your age)

You Are Married?

(True or False, depending on what you’ve set ISMARRIED to)

Chapter 2: Compound/Composite Data

From the last chapter’s example, you can start to wonder that there just has to be a way to group all that data: your name, age, location, whether or not you have pets, etc.

Also, notice that a person can neither be a String, Number, Integer, nor Boolean. A person just holds too much data to be defined as either one of the above.

So what do we do?

What a Composite Data Structure is

From the previous example, you can think of all the data you’ve defined as small parts of a whole. But what is this “whole”?

Enter Composite Data.

A Composite Data structure includes many parts of data within it.

Those parts of the Composite could be whatever you wish to declare. Strings, Integers, Booleans, Lists, and even Other Composite Data.

Identify & Defining a Composite Data Structure

When you were asked earlier to define what type of data are you dealing with, what if you designed & defined data for an object that you couldn’t identify as atomic data? What if it had plenty of Characteristics? What if there was more depth in that object?

The key thing to remember in identifying composite data is depth. There are more parts to that ‘thing’ you were trying to define as data. If there’s more to anything than just a name, number, or true/false switch, then it’s probably going to be a composite data structure.

Representing information as Composite Data

Let’s take YOU as an example. You are a Person. As a person, you’re not JUST a name or number; you are comprised of a lot of data. An endless amount of data, rather.

The Elements that Comprise your Data

As an example of Composite Data, let’s define you.

For now, let’s start with the basics.

Remember: you are a Person. Using simple pseudocode, let’s define that:

// I am a PERSON

CompositeStructure PERSON;

An Explanation for your Composite Data’s Parts

Similar to what you did earlier for defining data, it’s also best that you identify what your composite data structure is comprised of.

For practice, use comments to describe what your data structure has.

Following the example above, You have a Name and an Age as well. Let’s include that:

// I am a PERSON

// A person has:

// - a name (string)

// - an age (number)

CompositeStructure Person {

String NAME;

Number AGE;

{

You live in a City. Oh but wait, a City isn’t just a name is it? It’s comprised of plenty of data as well!

// This is a CITY

// A City has:

// - a name (string)

// - a Latitude and Longitude (2 numbers)

// - a Population count (an integer, above 0)

CompositeStructure City {

String NAME;

Number LATITUDE;

Number LONGITUDE;

Integer POPULATION;

{

Let’s not forget about YOU now. You live in a City, remember?

// I am a PERSON

// A person has:

// - a name (string)

// - an age (number)

// - a City they live in (Composite data City)

CompositeStructure PERSON {

String NAME;

Number AGE;

City LOCATION;

}

Notice what happened here. A compound data structure within another compound data structure!

PYT-02: Compound/Composite Data

Python as Object-Oriented Programming

Like other Object-Oriented Programming languages, composite data structures in Python can be declared as Classes.

However, in Python, indentation is a must. For each class you define, you need to indent each data attribute within that class (either by using TAB or 4 spacebar spaces).

You also need a colon (:) right after your class name.

Overall, a typical Composite Data class in Python looks like this:

class ClassName:

attribute1 = “Data Type as String”

attribute2 = 123

(NOTE: in case there are errors in formatting, attribute1 and attribute2 are supposed to be tab-indented)

Initializing a Python Class

To create an Object based on your class, the simplest way is defining a global variable, then setting it as your Class, followed by open-close Parentheses ()

It would look like the following notation:

object1 = ClassName()

In the above line, the Global variable object1 would be a composite data structure based on the Class it’s initialized to.

Accessing Class Attributes

This follows a similar structure to our PseudoCode.

To access a Class Attribute, you first have an object that has been assigned that Class structure. Then follow it up with a period (.) and the class attribute you want to access.

Let’s recall setting object1 into a class:

object1 = ClassName()

Then accessing object1’s attributes would look like the following notation:

object1.attribute1

EXAMPLE:

Think of a cup of coffee. Let’s start defining the Composite Data Structure for it.

First, let’s use comments to describe what our our data will look like.

“””

A CoffeeCup Has:

“””

Now think of the little attributes a cup of coffee has. There definitely are different types of coffee cups: styrofoam, coffe mugs, paper cups, etc. There are definitely different sizes too. And what type of Coffee is in that cup? Is that coffee still hot or no? How much did that Coffee Cost?

# A CoffeeCup Has:

# - a Cup Type (String)

# - a Size (String)

# - a Coffee Type (String)

# - either it’s hot or not (Boolean)

# - a price (Number)

Now, let’s design the Coffee Cup Class.

class CoffeeCup:

cupType = "a"

size = ""

coffeeType = ""

hot = True

price = 0.00

Let’s also make a cup of coffee named C, then make it a large, $5 coffee

C = CoffeeCup()

C.size = large

C.price = 5.00

PYTHON Workshop #1

A Dog With Class

Design a data class definition for a Dog. Just man’s best friend. A furry lil’ mutt. Think carefully. What attributes would a Dog have?

First, use comments to describe what attributes you want your dog to have. Then figure out what Data Types those attributes are. This is totally up to you. Make it up as you go along!

Then, code your data class to include those attributes.

Then, make a Dog named Sparky.
Afterwards, test and run your code in an IDE of your choice.

You can also use a free IDE such as http://rextester.com/runcode

Chapter 3: Data Initialization

Let’s recall the Composite Data Structure of a Person:

// A person has:

// - a name (string)

// - an age (number)

// - a City they live in (Composite data City)

CompositeStructure PERSON {

String NAME;

Number AGE;

City LOCATION;

}

We’ll also create two Atomic Data pieces as the Time: two integers.

Integer HOUR;

Integer MINUTE;

You have have noticed one thing: You’ve defined what types of data you’re dealing with - but we don’t know any people yet. Nor do we know what time it is!

Now we INITIALIZE our data. Now that we’ve defined what types of data we have, we then set our data for the first time.

Initializing Atomic Data

First, we’ll set the time.

Let’s say it’s 8:30 PM. We’ll set up our time as is.

To set data, most programming languages use the Equals (=) operator. Here, we’ll do the same.

HOUR = 20;

MINUTE = 30;

DON’T make this mistake…

But what if we tried to set HOUR and MINUTE to another data type?

HOUR = aaaa;

MINUTE = Composite{Integer; String; Boolean} ;

Notice earlier that you’ve set both HOUR and MINUTE as Integers. Here, we’re trying to set up those data as different data types. In some programming languages, it’s not going to work. And in most cases, your code might not work because of this.

Here, you’ve set up your data as Integers - therefore, you need to initialize & change them as Integers.

Lesson learned: if you set up your data as a certain data type, unless you really know what you’re doing, DO NOT try to set up that data as another data type!

Initializing Composite Data Structures

Now, let’s define an actual Person using our data structure.

There are FOUR KEY steps to do this:

STEP ONE:

Identify & describe a data object you’re trying to create.

For practice, use comments to describe what that object is & what it’s like.

We’ll use a friend of yours called Jamie, for example. We use comments to describe her:

// Jamie Denise is a person

// She has:

// - a name: Jamie Denise

// - an age: 19

// - a City she lives in: New York

STEP TWO:

Declare what type of composite data your object is.

In this example, we declare Jamie as a person:

// Jamie Denise is a person

Person Jamie;

STEP THREE:

You INITIALIZE your object’s data structure, so that your object actually IS represented by the Composite Data in your program. In most languages, you declare that you have a new ‘case’ or instance of this object. Think of this step as “registering” your new object into your data program.

In this example, we INITIALIZE Jamie as a data object that HAS the Person Composite Data Structure

// Jamie Denise is a person

Person Jamie = new Person;

Again, just like Atomic Data, we use the Equals (=) operator to set data.

STEP FOUR:

Identify your object. Then, for each data part that your Composite Data is made of, set those initial values.

Remember Jamie’s Attributes?

// Jamie Denise is a person

// She has:

// - a name: Jamie Denise

// - an age: 19

// - a City she lives in: New York

Now let’s initialize each attribute onto our Data Object Jamie. You first need to identify the data object you’re trying to reach. In this case, it’s Jamie.

Next (and this is important!), identify which attribute you’re planning to reach. Here’s it’s best to reference the Data Structure you’ve defined earlier:

CompositeStructure PERSON {

String NAME;

Number AGE;

City LOCATION;

}

Let’s set all three of Jamie’s Attributes:

// Jamie Denise is a person

// She has:

// - a name: Jamie Denise

// - an age: 19

// - a City she lives in: New York

Person Jamie = new Person;

Jamie-NAME = “Jamie”; // <— a “String”: Remember?

Jamie-AGE = Nineteen;

CITY = NewYork;

Okay, we’re done.
Hold on. This code is wrong. Why?

DON’T make these mistakes…

This line: Jamie-AGE = Nineteen; won’t work. Why?

Just a friendly reminder. Make sure the data type you’re trying to set MATCHES the data type you’ve defined. In most programming languages, this is one of the most common mistakes programmers make. Nineteen is definitely not a Number data type, nor is it a String (where’s the “Quotation marks?”). However, 19 works.

Jamie-AGE = 19;

Also, This line: CITY = NewYork; won’t work. Why?

What’s CITY? Did we mean Jamie’s current CITY?

Remember to first identify the DATA OBJECT you’re accessing. AND THEN that object’s attributes.

Well, let’s try that.

Jamie-CITY = NewYork;

This line: Jamie-CITY = NewYork; won’t work either. Why?

Because Jamie is a data object that follows the Person Composite Data Structure you’ve defined. And note how that Structure does NOT have any attributes named CITY in it.

Again, Remember to first identify the DATA OBJECT you’re accessing. AND THEN access that object’s correct attributes.

The Person Structure includes a separate City data structure, but it certainly isn’t called CITY.

CompositeStructure PERSON {

String NAME;

Number AGE;

City LOCATION;

}

Oh, so it should be Jamie-LOCATION= NewYork;

But you’re missing one more thing. Where in your program is NewYork defined?

Well, that can be arranged. Let’s recall the City data Structure and define the NewYork data object as well:

// This is a CITY

// A City has:

// - a name (string)

// - a Latitude and Longitude (2 numbers)

// - a Population count (an integer, above 0)

CompositeStructure City {

String NAME;

Number LATITUDE;

Number LONGITUDE;

Integer POPULATION;

{

// NewYork is a CITY

// NewYork has:

// - a name: “New York”

// - a Latitude and Longitude: 40.7127 and 74.0059

// - a Population count: 8406000

City NewYork = new City;

NewYork-NAME = “New York”;

NewYork-LATITUDE = 40.7127;

NewYork-LONGITUDE = 74.0059;

NewYork-POPULATION = 8406000;

and now, we fully complete Jamie’s data entry:

// Jamie Denise is a person

// She has:

// - a name: Jamie Denise

// - an age: 19

// - a City she lives in: New York

Person Jamie = new Person;

Jamie-NAME = “Jamie”;

Jamie-AGE = 19;

Jamie-LOCATION= NewYork

Chapter 4: Data Changes & Mutable States

In the previous chapters, you’ve defined some facts as data structures and even represented people and cities as data.

However, nothing ever stays the same in data.

Data changes over time - and it’s important to keep track of how data values change and what they currently are.

Modifying your Defined Data Over Time

In reality, modifying the data values you’ve set in place is nearly similar to initializing them in the first place. In most programming languages, the same principles between initializing and updating data apply: identify the data you want to access, use the Equals Operator (=), and set the new data to another value, but usually the SAME data type you’ve originally set. So change data defined as Strings to other Strings, Integers to Integers, and so on.

For example, let’s take a look at Jamie and New York from the past chapter:

// NewYork is a CITY

// NewYork has:

// - a name: “New York”

// - a Latitude and Longitude: 40.7127 and 74.0059

// - a Population count: 8406000

City NewYork = new City;

NewYork-NAME = “New York”;

NewYork-LATITUDE = 40.7127;

NewYork-LONGITUDE = 74.0059;

NewYork-POPULATION = 8406000;

// Jamie Denise is a person

// She has:

// - a name: Jamie Denise

// - an age: 19

// - a City she lives in: New York

Person Jamie = new Person;

Jamie-NAME = “Jamie Denise”;

Jamie-AGE = 19;

Jamie-LOCATION= NewYork

So let’s say 10 years have passed since we defined Jamie’s data object onto our program. Since then, Jamie got married and changed her last name. She also moved to Los Angeles. So how would her new Data Object look like?

You’re essentially setting up all your changed data values to their new values. If you wanted to know what these values are, they would give you their current values.

// Jamie Walker is a person

// She has:

// - a name: Jamie Walker (changed from Jamie Denise)

// - an age: 29 (was 19)

// - a City she lives in: LosAngeles (was NewYork)

Jamie-NAME = “Jamie Walker”;

Jamie-AGE = 29;

Jamie-LOCATION= LosAngeles;

and yes, make sure even LosAngeles is defined.

// LosAngeles is a CITY

// LosAngeles has:

// - a name: “Los Angeles”

// - a Latitude and Longitude: 34.0500 and 118.2500

// - a Population count: 3884000

City LosAngeles = new City;

LosAngeles-NAME = “New York”;

LosAngeles-LATITUDE = 34.0500;

LosAngeles-LONGITUDE = 118.2500;

LosAngeles-POPULATION = 3884000;

Keeping Track of your Defined Data

let’s recall the Clock from the previous chapter:

Integer HOUR = 20;

Integer MINUTE = 30;

At the moment, it’s definitely not 8:30 PM anymore; let’s say it’s 10 AM now.

How would the clock change? Easy:

HOUR = 10;

MINUTE = 0;

Then three and a half hours pass. How would the clock change? Again, easy.

HOUR = 13;

MINUTE = 30;

If you wanted the time afterwards, what would it be?

Not 8:30 PM, not 10 AM either. But 1:30 PM.

Here, you’ve been essentially setting up both your integers named HOUR and MINUTE to new values. If you wanted to know what these values are, they would give you their current values.

However, it’s Important that you keep track of your changes. You MUST understand what the changes to your data have been - and you MUST determine whether or not those changes are what you want.

We stress this because one of the many traits a programmer needs to have (and be good at) is managing what happens to your data.

If you don’t believe us, wait until you have your tech interviews for a programming position you’re applying for…

PYT-03: Data Changes & Mutable State

Some Sorta-Good News

Unlike some programming languages, Python lets you change whatever data types you’ve set your values to.

But BE CAREFUL. Unless you really know what you’re doing, at this point we DO NOT recommend you change your data types. This could be a recipe for disaster for you. If certain functionality you’ve set in your code expects a certain data type (your original one. Say, a String), but it’s actually different (you’ve changed the data type to an Integer), your code might not work at some points and you’ll have a bad time.

Changing Data in Python

Just like our pseudocode, you can set and reset your Global Variable using the Equals (=) sign.

Keeping Track of your Data

It’s important. Very important. You’ll see why in this example…

EXAMPLE:

(get your IDE ready…)

Let’s say we’re playing Chess on an 8x8 board. 0 is the Top Row AND the left Column. (Remember: in Computer Science, the FIRST number is always 0)

There is a Queen Class.

# A Queen Has:

# - an X (sideways) Coordinate (Integer, between 0 and 7)

# - a Y (up-down) Coordinate (Integer, between 0 and 7)

class Queen:

x = 0

y = 0

You have a Queen moving around the board during your turn. Let’s initialize it and say it’s currently at (2,3)

myQueen = Queen()

myQueen.x = 2

myQueen.y = 3

Now let’s move your queen around.

First, let’s move your queen to the right, 3 spaces. Then up by 2 spaces. Then down by 2 spaces. Then right by 2 spaces, Then up by 4 spaces.

Let’s see what that would look like:

# to right, 3 spaces

myQueen.x += 3

# to up, 2 spaces

myQueen.y -= 2

# to right, 2 spaces

myQueen.x += 2

# to up, 4 spaces

myQueen.y -= 4

So how do we know if your Queen went OUT OF BOUNDS on the 8x8 chessboard? That is, if either its x or y coordinate went below 0 or past 7?

Run these lines:

# print the values

print "x: ", myQueen.x

print "y: ", myQueen.y

You should see these values:

x: 7

y: -3

So yes, your Queen definitely went out of bounds. She just ran past the Top Row of the Chess Board.

(Gee, if this is a real Chess Game app, this would be a SERIOUS bug!)

So which line of code did your Queen run out of bounds?

Well, let’s go back to our moves and keep track of x and y.

Let’s look back at the code to where we moved your Queen around. Let’s make comments about where your Queen is, based on (X,Y) coordinates

# Initial spot

myQueen.x = 2

myQueen.y = 3

# to right, 3 spaces

myQueen.x += 3

# Queen is at (5,3)

# to up, 2 spaces

myQueen.y -= 2

# Queen is at (5,1)

# to right, 2 spaces

myQueen.x += 2

# Queen is at (7,1)

# to up, 4 spaces

myQueen.y -= 4

# Queen is at (7,-3) ITS THIS LINE!!!

In cases where you set clear boundaries for your data, yet you have some code that sets your data to go past those boundaries (and nothing is done about it), it might create problems for your code later on.

Now you understand how crucial it is to keep track of your data. There are many aspects of coding that depend on it, such as Debugging and making sure your code works the way you intend it to.

PYTHON Workshop #2

BlackJack

Yep. Let’s play some BlackJack.

Here are your initial lines of your code:

# ———

from random import randint

# These are the cards you have

# your HandValue is an Integer

handValue = 0

# These are the cards the Dealer has

# the DealerValue is an Integer

dealerValue = 0

# here are your first two cards

handValue += randint(1,11)

handValue += randint(1,11)

# here are the Dealers cards

dealerValue += randint(1,11)

dealerValue += randint(1,11)

# the Dealer always hits once

dealerValue += randint(1,11)

# Do you hit once? Insert your line of code below if yes

# Do you hit twice? Insert your line of code below if yes

#——-

How would you edit the above code to PRINT what you and the Dealer have? How would you edit the code to let you know if you beat the dealer or not?

How would you edit the code to let you know who busted? Hit 21?

Also, would you hit once? Twice? What code would you put in if you hit either way? (Hint: What data are you accessing and what are you changing it to?)

Test and run your code in an IDE of your choice.

You can also use a free IDE such as http://rextester.com/runcode

Chapter 5: Defining & Designing your Functions

Now we’ll move on to the parts of programming where the magic happens.

Functions.

Where data structures are used to represent “things” in this universe, you define functions as the “actions” or verbs in this universe.

And you can make your functions do whatever you want/need it to do, as long as you know what you’re doing. You can calculate math, write sentences for you, change or update data, sort out lists with tens of thousands of items, make websites for you, whatever you like. In reality, the possibilities can be endless.

But first let’s understand the core parts of function design: its inputs, its output, its signature, its effects, and its functionality.

A Function’s Inputs

You can set your function to accept whatever data you need it to.

These are called a function’s arguments or parameters. Your function will use this incoming data to perform what you intend it to.

Or, on the other hand, you can also have a function NOT require any inputs. Your function will then perform what you’ve programmed it to, but it won’t need any incoming data.

For practice, let’s use comments to declare what inputs we want our function to have. Let’s say we want a name (a string) as an input

// INPUT: - a name (String)

A Function’s Output

Your function can also return a data value - based on whatever you want to set it to. You can then program your function to output that same data type.

Or, you can also have a function NOT return anything. You can then program your function to do what you intend it to do, but it won’t return any data after it executes.

In most programming languages, functions only return ONE thing - whether it be a data value, an entire list, compound data, or more.

However, you must make sure your function outputs whatever you have set it to. Say, if you want your function to output a String, the very last line of that function MUST return a String data type. If you set your function to have no outputs, your function MUST NOT return any data types after it executes.

For practice, let’s use comments to declare what outputs we want our function to have. We’ll continue designing our function. We now have an input, now we want to have an output.

// INPUT: - a name (String)

// OUTPUT: - an ID (Number)

Defining what your Function will Do

Now we figure out what EFFECT our function will have once we run it.

This is your function’s main purpose - it’s the reason why you’re going to code these lines of code!

Your function’s effect will be whatever you intend it to do. Change data, create new data, calculate a few values together, whatever you want.

But isn’t an Output and Effect the same thing? Well, no.

There is a difference between a function’s OUTPUT and EFFECT. A function’s output is the data it returns, while a function’s effect is anything that the function does or anything the function’s action has affected.

For practice, let’s use comments to declare what effects we want our function to have. We’ll continue designing our function. We now have an input and output. Now we figure out what it does when we run it.

Let’s say we want it to come up with a random number. We first put in the comments of what we intend it to do

// INPUT: - a name (String)

// OUTPUT: - an ID (Number)

// EFFECT: generates a random number for a given name

Key Function Rule-of-Thumb:

Make sure your function only does the only one thing you want it to do. A function that does too many things will not only complicate your code and make it look bad, but it will cause headaches and frustration for programming teammates.

However, your function can include and call on many other functions to help process something. These are called Helper Functions (we’ll cover this later!)

A Function’s Signature

Here is when we start writing our function’s lines of code.

In most programming languages, a function’s signature defines a function’s name, inputs, outputs, and even particular traits it has.

Remember when we declared our Composite data? We first started out designing the name of our whole data structure, then we started designing what it consisted of.

For function signatures, we first code what its name is - as well as any inputs and outputs it has.

Now, let’s look back at the function we were designing for practice. We now know what it does, what it requires and what it returns.

For now, we’ll use Pseudocode to design our function’s Signature. Our signatures will then be structured in this form:

(OutputType) functionName(InputType inputName)

So our function’s signature will look like this:

// INPUT: - a name (String)

// OUTPUT: - an ID (Number)

// EFFECT: generates a random number for a given name

number createID(string name)

Implementing your Function

This can be the tricky part - unless you know exactly what you’re doing.

In designing functions, the last thing you do is to program your function’s actual functionality. You would now know what inputs & outputs it has, as well as what it’s trying to do. You’ve essentially planned what your function will do.

Now you’ll have your function do what you planned it to.

You program the functionality in the next few lines after your function’s signature.

In pseudocode, we’ll use curly brackets ( { } ) right after the function’s signature to include its functionality code. Our functions will then be structured in this form:

(OutputType) functionName(InputType inputName) {

(your function’s code)

return OutputType if any

}

Finally, let’s look back at the function we were designing for practice. We are ready to finish it.

Let’s say there’s such thing as a function named randomNumber() that creates a random number for us.

// INPUT: - a name (String)

// OUTPUT: - an ID (Number)

// EFFECT: generates a random number for a given name

number createID(string name) {

randomNumber()

}

A Common Error in Function Design

But wait. The above code isn’t going to work. Can you guess why?

Oh right.

In our signature, our function is supposed to RETURN a number. So in order for this function to work, it needs to actually return a number.

So we make the function RETURN whatever random number is generated by the inside function randomNumber()

// INPUT: - a name (String)

// OUTPUT: - an ID (Number)

// EFFECT: generates a random number for a given name

number createID(string name) {

return randomNumber()

}

and now, we finally complete our function - from design to code.

PYT-04: Function Structure

Functions in Python

The syntax structure for Python functions are so:

def functionName(inputs):

(your function’s actions here)

return (output Type)

(NOTE: if there are any Kindle Formatting errors, the two last lines are tab-indented)

There are a few key notes in Python Functions:

-Python functions always start with the word ‘def’, then your function name, parentheses along with any inputs, then the colon(:)

-Just like data classes in Python, the internal lines of the function is indented - either with TAB, or four spaces

-Python functions have a RETURN line that tells you the function finishes executing. If your function returns anything, it’s written just after the return line. For example, if you wanted your function to return your name as a string, the line would be: return “My Name”

Function Example

Here’s what the createID() function looks like in Python:

// INPUT: - a name (String)

// OUTPUT: - an ID (Number)

// EFFECT: generates a random number for a given name

def createID(name):

return randomNumber()

PHASE TWO CONTENT:

Thank you for downloading our book.

Like we said, you have access to all future editions of this book - for free.

So here’s what could be included in the Next Update:

-IF & ELSE Statements

-Data - Function Matches

-Helper Functions

-Designing Worlds & Simple Apps

-Lists & Collections

-Self-Reference & Iteration

-Abstract Data Types: Stacks and Queues