Building Our First Programs - Python Made Easy (2013)

Python Made Easy (2013)

Chapter 3: Building Our First Programs


“Now, it's my belief that Python is a lot easier than to teach to students programming and teach them C or C++ or Java at the same time because all the details of the languages are so much harder. Other scripting languages really don't work very well there either.”-Guido van Rossam

In this chapter you will learn:

· What are indentations

· The basics of Python Programming

· The components of Python Programming

· Basic coding

Now that we have seen Python in action, it's time to dive in head first. Before coding our own program, there are a few things that need to be understood about the language to make the early learning process go as seamlessly as possible.

Indentation

One of the first caveats that experienced programmers run into when making the switch to Python is the fact that the language does not use braces to indicate blocks of code – instead all blocks of code are denoted by indentation. This indentation is a strict function of the language. If you indent the wrong number of spaces – the program won't run correctly. So, you need to be careful when making codes. Using comments to help you spot a code can help identify a code.

In Python, the number of spaces for indentations is variable. However, all of the statements within a single block of code have to be intended the same amount. To drive this point home, the following code would run fine;

if True:

print“True”

else:

print“False”

Notice that both “print” statements are indented different amounts. This is fine, because they are two separate blocks of code. Here's an example of incorrectly indented code;

if True:

print“Answer”

print“True”

else:

print“Answer”

print“False”

This block of code won’t run properly. Both “print” commands inside the “else” statement belong to one block of code, but are not indented the same amount. This causes the interpreter to regard “print “False”” as if it were it's own statement, outside of the “else” statement's influence.

Variables

Variables, in every programming language, are memory locations that store values and so, every time you create a variable, you also reserve memory for that particular variable.


Unlike some other programming languages, you need not declare a variable explicitly in Python. All you need to do is to use the equal to (=) sign to assign a value to a variable. Here’s an example:

age= 29

city= X

name= Ron

print age

print city

print name

As you run the program, you will get the following output:

29
X
Ron

With Python you can assign one value to several variables at the same time. The general syntax for this is as follows :

x= y= z= 2

One can assign more than one value to several variables, too.

Data Types

All programming languages available today use data types as a way to store information, categorized by similarities. Like many other languages, Python uses the standard data types. These include;

Numbers

Number data types are used to store numeric values. Unlike other languages that include several different data types for storing numbers based on storage needs, Python creates a new object with a new memory allocation for larger numbers. Although for our purposes you won't have to worry about individual number data types, the different numerical types include;

· int (signed integers)

· long (long integers)

· float (floating point values)

· complex (complex numbers)

Numbers do not require that you name the data type. Here is an example of assigning a number to a variable;

var1 = 3

var2 = 5

Now“var 1” holds the value 3, and“var 2” holds the value 5.

Strings

Phrases or words are stored as strings. Strings are always within quotations. Anything inside of quotation marks is considered to be a string, whether or not it is assigned to a variable. Some examples of the different ways in which strings are used include;

str = 'Hello World!'

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character

print str * 3 # Prints string three times

print str + "YOYO" # Prints concatenated string

These commands would produce an output that looks like:

Hello World!

H

llo

llo World!

Hello World!Hello World!Hello World!

Hello World!YOYO

· Lists:Python lists provide very versatile ways to store lists of items. A list contains items that are separated by commas and enclosed within brackets. There are multiple ways to access information that is stored within lists. Here are some examples of the more popular ways to use strings:

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

tinylist = [123, 'john']

print list # Prints complete list

print list[0] # Prints first element of the list

print list[1:3] # Prints elements starting from 2nd till 3rd

print list[2:] # Prints elements starting from 3rd element

print tinylist * 2 # Prints list two times

print list + tinylist # Prints concatenated lists

Which would produce the following results;

['abcd', 786, 2.23, 'john', 70.200000000000003]

abcd

[786, 2.23]

[2.23, 'john', 70.200000000000003]

[123, 'john', 123, 'john']

['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']

· Tuples:In many ways, Tuples are similar to lists. They contain a number of values that are separated by commas. Unlike lists, Tuples have their data enclosed within parenthesis instead of brackets. Tuples are not able to have their values updated.

· Dictionary:A Python dictionary is a table. They are very similar to arrays and can be used to store large amounts of data. There is no order within dictionaries.

Operators

Operators are used to change or check the value of a provided piece of data. There are many different types of operators including arthmetic operators (+, -, /, %. *), comparison operators, assignment operators, logical operators, bitwise operators, membership operators and identity operators. For our purposes today, we will simply focus on arithmetic operators and comparison operators.

The Different types of arithmetic operators include;

· +-Addition. Adds two values on either side of the operator together.

- - Subtraction. Subtracts right side from left side.

· - Multiplication. Multiplies values on both sides of the operator together.

· / - Division. Divides left hand side from right hand side.

· % - Modulus. Divides left hand side from right hand side and returns the remainder

The Different types of comparison operators include;

· == - Checks to see if two values on either side are equal or not. If they are then the condition returns true.

· != - Checks to see if two values on either side are equal or not. If they are not, the condition returns true.

Ø - Greater than.

· < - Less than.

· >= - Greater than or equal to.

· <= - Less than or equal to.

PROJECT: Variables

Try to complete this project on your own without looking at the answer.

Create 2 numbers and 2 strings. Add the numbers together and then print the total. Then, display the strings four times a piece.

Answer

var1 = 3

var2 = 5

str1 =“Testing”

str2 =“Testing2”

var3 = var1 + var2

print(var3)

print str1 *4

print str2 * 4

Now you should have an understanding of the basic set of operators that are available to you. Think about the different ways in which these could be used, and how you might manipulate or check data using them. Now we will put these to use using decision making statements;

Conditional Operators (If/Else Statements)

Python also makes use of decision making statements. These structures allow the programmer to specify one or more conditions that will be tested by the program. The program will determine if the statement is true, and execute the code given. If the statement is false, the programmer may also provide additional statements and code to run. Python uses a number of different types of decision making statements;

If Statement

If statements allow the program to check to see whether a statement is true, and then execute code that corresponds with a true statement. Here is an example of an if statement;

var = 55

if ( var == 55 ) : print "Value of expression is 55"

print "Good bye!"

This If Statement checks to see if the variable “var” is equal to 55. If the value of “var” is 55, then it will print the expression “Value of expression is 55”. Should the variable not be equal to 55, the program would only print “Good Bye!”

If/Else Statement.

An If statement can also include another path for the program to take. In the previous example, had the var stored a value of 87, the program would have not run any code, except for saying “Good bye!” The else statement contains code that runs should the boolean expression returned by the If statement be false. Here is an example of an if/else statement;

temperature = float(input('What is the temperature? '))

if temperature > 65:

print('Wear shorts.')

else:

print('Wear jeans.')

print('Enjoy the sun.')

This program begins by prompting the user to tell them what the temperature is. The user enters the temperature, which is stored in a float variable named “temperature.” This variable is then checked by the program. The If Statement states that if the temperature provided by the user is higher than 65, print the line “Wear shorts.” Keep in mind that there can be multiple if statements in the same block of code. When that happens, you use the term “elif” which stands for “elseif.” In example:

temperature = float(input('What is the temperature? '))

if temperature < 50:

print('Bundle Up')

elif temperature > 75:

print('Go Swimming.')

else:

print('Either Or')

This program instructs the computer to print “Bundle up” when the temperature is below 50, “Go Swimming” when the temperature is above 75, and “Either Or” when the temperature is between 50 and 75.

This is where the Else Statement comes in. The Else Statement only comes into play if the temperature is not higher than 65, so the Boolean expression returned by the If Statement is False. If the user entered a temperature of 64, then the program would print “Wear jeans.” Regardless of what the user enters, the program prints “Enjoy the sun.”

Nested Statements

It is also important to note that If/Else Statements can be nested inside of one another. Consider the last example. What if we wanted the program to instruct the user to go shirtless if the temperature was over 80 degrees? We could nest a new if statement within the previous statement. It would look like this;

temperature = float(input('What is the temperature? '))

humidity = float(input('What is the humidity? '))

if temperature > 65:

print('Wear shorts.')

if humidity >= 80:

print('Go Shirtless.')

else:

print('Wear jeans.')

print('Enjoy the sun.')

This program adds a new conditional statement into the mix. Now, it asks the user two questions. First, they provide the temperature. Then, they provide the humidity. If the temperature is both over 65 degrees and over 80 humidity, the program tells them to wear shorts, and go shirtless. Should the user enter a temperature of 70 and a humidity of 60, the program would just tell the user to wear shorts.

PROJECT: Decision Making

Now that you are familiar with decision making statements, it's time for you to try it on your own. Try to complete the project on your own without looking at the answer. Create a program that asks the user for the time (1-24). Depending on what time it is, print a different phrase. If the time is before 10, print“Good Morning.” If the time is before 19, print“Good Day.” If the time is after 19, print“Good Night.”

Answer

time = float(input('What time is it? (1-24) '))

if time < 10:

print "Good morning"

elif time < 19:

print“Good day”

else

print“Good night”

Loops

Loops are present in every programming language. Loops exist to allow a program to execute a certain block of code a specified number of times. Within a loop, the code is executed one run after another. The program stays within a loop until it has run a specified amount of times. There can be multiple statements within a loop. The following types of loops are present in the Python Programming Language;

While Loops

The while loop allows the program to repeat a statement or several statements while a condition is true. The condition is tested by the program before executing the statement. Here is an example of a While Loop;

counter = 0

while (counter < 8):

print 'The counter is:', count

counter = counter + 1

This program sets counter to 0. Then, while counter is equal to less than 8, it prints the value of the counter variable and adds one to it each time the code is run. The result in your logs should look like this;

The counter is: 0

The counter is: 1

The counter is: 2

The counter is: 3

The counter is: 4

The counter is: 5

The counter is: 6

The counter is: 7

You can also use Else Statements inside of loops. In loops, else statements work exactly the same way as they do in if statements. If the condition is returned as False, the program is provided another path to take. Here is an an example of a While Loop with an Else Statement;

counter = 0

while counter < 8:

print counter, " is less than 8"

count = counter + 1

else:

print counter, " is not less than 8"

This program sets counter to 0. While counter is less than 8, the While loop is looped by the program. It prints the value of the counter, and adds one to it each time. Once the loop has run and counter is equal to 8, then the else statement will run. When run, the logs look something like this;

0 is less than 8

1 is less than 8

2 is less than 8

3 is less than 8

4 is less than 8

5 is less than 8

6 is less than 8

7 is less than 8

8 is not less than 8

For Loops

For loops are very similar to While Loops. They allow you to repeat a piece of code a number of times. Here is an example of a For Loop;

for count in [1, 2, 3]:

print(count)

print('Python' * count)

print('Done counting.')

for color in ['red', 'blue', 'green']:

print(color)

This program uses the count function, and lists three numbers. The first For Loop will cycle through 3 times, one for each number listed. Each time it will print the count, and print the word Python that many times. When finished, the program prints“Done Counting.” The log output for this program looks like this;

1

Python

2

PythonPython

3

PythonPythonPython

Done counting.

red

blue

green

Break Statements

The break statement is used to break the for or while loop.

Break statements are usually used when external conditions require that a loop be broken. This can be used to prevent the loop’s execution even before it is False. It will disrupt the execution of the code and start again. This will also impact the else block which will not be executed due to the break statement. The syntax for the break statement is as follows:

while (expression A) :

Statement_A
Statement_B

……..

if expression B
break

Now, let’s see how this works:

Numbers= 2, 4, 6 , 8, 10

num_sum= 0

count= 0

for a in numbers

count= count+ 2

if count== 8:

Break

Print


The conditions have been set and Python is told to break the loop if the count is 8. This is why you will get an output in which all numbers before 8 are added to one another. Hence, you will get an output of 20. After this, the loop will break due to the insertion of the break statement. You will also see that though the loop hasn’t been completed, it will break.
You can also insert the break statement in a while loop. Here’s how this is done-

num_sum= 0
count= 0
while (count<8)
num_sum= num_sum+count
count= count+2

if count == 8

Break
Print


Here, the break statement will be effective when the count is equal to 8. Again, you will get the same result as before. When the count is no longer less than 8, the loop will break due to the insertion of the break statement and it will start all over again.

The Continue Statement

The point of the continue statement is to “pause” or halt the loop and then, continue it from the same point. This, too, is used for the while and for loop. Here’s how the continue statement works:

For a in range (8)
if (a= 4 or a= 6)
continue
print (a)

So, in this case I’ve inserted the continue statement while placing the condition that if that value of a is equal to 4 or 6, the continue statement must take a break. The continue statement will halt at these numbers and then, go on to the next integer after 4 and 6. So, you will get the following output- a= 0, 1, 2, 3, 5, 7, 8.

As you can see, the values of a, when it was equal to 4 or 6, is not shown due to the continue statement. Once this loop is completed, it will restart and the continue statement will continue being effective the same way so long as it is inserted in the statement.

Pass Statement

This statement is used when you do not want a code to execute a statement. It is more of a null operation because nothing really happens with it. However, you can use it if you are yet to make your code. Let’s see how this statement works:

for letter in Christmas
if letter == a
pass
print Congrats
print ‘Current Letter:’, letter

print Merry Christmas



You will get the following output:

My Letter : C

Congrats

My Letter : h

My Letter : r

My Letter : i

My Letter : s

My Letter : t

My Letter : m

My Letter : a

My Letter : s

Happy Christmas!

If any code were inserted between C and h, it could be replaced with the pass statement.

Many people are unclear about the difference between the pass and continue statements. The pass statement doesn’t do anything significant as such while the continue statement will halt the execution of the code and resume from the next line.

PROJECT: Loops

Now you are familiar with Loops, so let's test your skills with a project. Try not to look at the answer until you have finished your own program. In this project we will count by two's, up to 100. Set a number variable named“num1” to 2. Use a While Loop to add 2 to num1 every time it loops and display the number. When 100 is reached, the program should say“100! I've just learned the basics of Python!”

Answer:

num1 = 2

while num1 < 100:

print num1

num1 = num1 + 2

else:

print num1, "! I've just learned the basics of Python!"

Summary

The following points were discussed in this chapter:

· Indentations in Python

· Variables

· How variables work

· How Strings and Numbers work in Python

· What are lists

· How the else, else if and nested statements work

· The Utility of loops

· The different types of loops

· How to break a loop

· How to ‘pause’ a loop

· How to use the pass statement