Saving data - Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

Coding for Beginners in Easy Steps: Basic Programming for All Ages (2015)

2. Saving data

This chapter demonstrates how to create code to use various types of data stored inside your programs.

Storing input

Controlling output

Recognizing types

Converting data

Guessing game

Correcting errors

Summary

Storing input

The ability to store and replace coded program data in a variable is great, but this ability can also be used to store data input by a user – allowing your programs to become interactive.

In Python programming a built-in input() function can be used to accept user input from a keyboard and assign it to a variable. Optionally, this function can specify a string, within quote marks inside its parentheses, that will be displayed to request the input. The program will wait until the user hits the Return key before assigning their input to the variable and proceeding onwards.

Stored variable values can be output by the built-in print() function by specifying the variable name within the function’s parentheses. Multiple values may also be specified for output as a comma-separated list within the parentheses.

image

input.py

imageOpen an IDLE Edit Window then enter this code to request user input with which to initialize a variable

name = input( ‘Please enter your name: ‘ )

imageNext, add a statement to output both a string and the value stored within the variable

print( ‘Hello’ , name )

imageNow, add statements to output a string then both a string and the value stored within the variable once more

print( ‘Welcome to Coding for Beginners’ )

print( ‘Remember to have fun’ , name , ‘!’ )

imageSave then run the program, enter your name when requested, and hit Return to see your name in the output

image

image

There is no need to include spaces in the comma-separated lists – they are ignored by the interpreter but are shown here for clarity.

Controlling output

As the example on the facing page demonstrates, a value stored in a variable remains available for repeated use until it is replaced by a new value or until the program ends.

There are also two points worth noting with regard to this example’s output. Firstly, the print() function automatically adds an invisible \n newline character after its output – so the next print() function output will by default appear on the next line below. Secondly, the print() function automatically adds a space between each item when a comma-separated list is specified for output.

You can override the automatic newline behavior by specifying that the line should end with a space, rather than the \n default. You can also avoid the automatic spacing behavior by “concatenating” items with a + symbol, rather than a comma.

image

concat.py

imageOpen an IDLE Edit Window then enter this code to request user input with which to initialize a variable

name = input( ‘Please enter your name: ‘ )

imageNext, add a statement to output a string and the value stored within the variable – but without a final newline

print( ‘Hello ’ + name , end = ‘ ‘ )

imageNow, add statements to output a string then a string concatenated to the value stored within the variable

print( ‘Welcome to Coding for Beginners’ )

print( ‘Remember to have fun ’ + name + ‘!’ )

imageSave then run the program, enter your name when requested, and hit Return to see controlled output

image

image

Notice that the strings have been edited to nicely format the output.

Recognizing types

There are four essential types of data you can represent when coding a computer program and that can be stored in variables. Although variables in the Python language can store any type of data it is important to understand the different types as you will sometimes need to convert from one type to another in your code:

Data type:

Description:

Example:

str

A string of characters, which can include letters, numbers, spaces, and symbols

‘Daytona 500’

int

An integer whole number, which DOES NOT have a decimal point part

1000

float

A floating-point number, which DOES have a decimal point part

98.6

bool

A Boolean logical truth value, which is either True or False

True

image

Integer int numbers should not include any punctuation – so code one thousand as 1000 rather than 1,000.

Strings are simply any collection of characters you can enter from the computer keyboard, grouped together within quote marks. Variables recognize a value being assigned to it as belonging to the str “class” if that value is enclosed within quote marks.

image

String str values must always be enclosed with quote marks.

Numbers are any numeric value you can enter from the keyboard but are defined by the inclusion or omission of a decimal point. Variables recognize a numeric value being assigned to it as belonging to the int “class” if that value has no decimal point or as belonging to the float class if it does indeed have a decimal point.

Booleans are a logical truth value. Variables recognize a Boolean value being assigned to it as belonging to the bool “class” by the keywords True and False, or if that value evaluates to True or False.

In Python programming you can easily discover the type of data stored within a variable by specifying that variable’s name within the parentheses of the built-in type() function.

image

types.py

imageOpen an IDLE Edit Window and initialize a variable by assigning it a string, then display its value and data type

race = ‘Daytona 500’

print( race , ‘is‘ + type( race ) )

imageNext, initialize a variable by assigning it a whole number then display its value and data type

kilo = 1000

print( kilo , ‘is‘ + type( kilo ) )

imageNow, initialize a variable by assigning it a decimal number, then display its value and data type

temp = 98.6

print( temp , ‘is‘ + type( temp ) )

imageInitialize a variable by assigning it a truth keyword then display its value and data type

flag = True

print( flag , ‘is‘ + type( flag ) )

imageFinally, replace the last variable value with a truth result of a comparison, then again display its value and data type

flag = 4 > 8

print( flag , ‘is‘ + type( flag ) )

imageSave then run the program to discover the types of data stored within the variables you have created

image

image

The comparison here examines whether 4 is greater than 8, which is of course untrue. Comparisons are demonstrated fully in the next chapter.

Converting data

Often you will need to convert data in your programs to perform some kind of manipulation – such as arithmetic or concatenation. Arithmetic can only be performed on numeric data types, such as int and float data, whereas concatenation can only be performed on string data types, such as strdata.

Python provides several built-in functions that allow you to easily convert data in your programs to a different data type. These do not convert the original specified value itself but merely return a converted representation of its value. In programming terms this is known as a “cast” operation:

Function:

Description:

int( x )

Converts x to an integer whole number

float( x )

Converts x to a decimal floating-point number

str( x )

Converts x to a string representation

image

Numeric values in your code should not be enclosed within quote marks – numbers within quotes will be seen as string values!

Numeric values assigned to variables manually in your code are automatically appointed the appropriate data type of int or float. Values assigned to variables from users by the built-in input() function are, however, always automatically appointed the str string data type – even when they are simply numeric values! This means they must be converted (cast) to an appropriate numeric type of int or float before you can perform arithmetic with them.

Conversely numeric values assigned to variables manually in your code, which are automatically appointed the appropriate data type of int or float, cannot be concatenated into a string. This means they must be converted to a str data type for inclusion in a string.

In Python, as in many other programming languages, the + symbol has more than one purpose according to its context. Where the + symbol is used between two numeric values it performs an addition (seen as an “addition operator”) but where the + symbol is used between two string values it performs a concatenation (seen as a “concatenation operator”). Variables that are assigned the result of either kind of operation will automatically be appointed the appropriate data type of the result.

image

Arithmetic performed on an int and float data type together will be automatically cast into a float result. Cast values to the float data type to allow for decimal number input.

image

cast.py

imageOpen an IDLE Edit Window and initialize two variables by assigning them numeric user input

num1= input( ‘Please enter a whole number: ’ )

num2= input( ‘Now enter another whole number: ’ )

imageNext, display the data type of each variable to see the numeric values are, in fact, stored as strings

print( ‘Input is: ‘ , type( num1 ) , type( num2 ) )

imageNow, use the + operator to attempt addition, but see the result gets concatenated as a str data type

total = num1 + num2

print( ‘Total:‘ , total , type( total ) )

imageAgain, use the + operator to attempt addition, but cast the stored values to see the result as an int data type

total = int( num1 ) + int( num2 )

print( ‘Total:‘ , total , type( total ) )

imageFinally, cast the stored values as a float data type and concatenate the float result value to the output str string

total = float( num1 ) + float( num2 )

print( ‘Total: ‘ + str( total ) , type( total ) )

imageSave then run the program to see the stored data types converted by casting them with the built-in functions

image

image

If you forget to convert to the correct data type the interpreter will report an error – try adding an int to a str data type to see the error message.

Guessing game

The previous simple examples have illustrated how variables can be used to store text string values, numeric integer and floating-point decimal values, and Boolean truth values in your programs. Now, they can be used to create a Guessing Game program by storing a random generated integer whose value the user will have to guess, a Boolean truth value that will end the game when the user guesses correctly, and a string containing the user’s guess.

The code in this example includes some features that are only demonstrated later in this book, but as Python is an easily human-readable programming language you should be able to understand in principle how this program works.

image

guess.py

imageOpen an IDLE Edit Window and begin a program by importing a “random” library class that provides random number generator functions

import random

imageNow, initialize three variables – a generated random number between one and 20, a Boolean value that will remain True as long as the game is in progress, and a zero value that will later store a number input by the user

num = random.randint( 1 , 20 )

flag = True

guess = 0

imageNext, display a message asking the user to make a guess

print( ‘Guess my number 1-20 : ‘ , end = ‘ ‘ )

imageThen, precisely copy this code that will compare the stored user’s guess to the stored random number

while flag == True :

guess = input( )

if not guess.isdigit() :

print( ‘Invalid! Enter only digits 1-20‘ )

break

elif int( guess ) < num :

print( ‘Too low, try again : ‘ , end = ‘ ‘ )

elif int( guess ) > num :

print( ‘Too high, try again : ‘ , end = ‘ ‘ )

else :

print( ‘Correct... My number is ‘ + guess )

flag = False

image

Many program languages use characters such as { } to group statements together but Python uses indentation – so the indentation shown here must be correctly preserved.

imageSave then run the program and enter guesses to see your input compared to a stored random number

image

image

Notice that the program rejects user input of str string or float values.

Guessing Game in Python – program analysis

•The random library class’s randint() function specifies an upper and lower random range within its parentheses

•The flag variable specifies an initial program condition that will allow the program to start examining the user’s input

•The while keyword specifies a “loop” control structure that will repeat the statements it contains until a tested condition fails

•The if not guess.isdigit() test specifies an action to break the loop if the user input is not an integer whole number

•The elif int( guess ) < num test specifies an alternative action if the cast user input is lower than the stored random number

•The elif int( guess ) > num test specifies an alternative action if the cast user input is higher than the stored random number

•The else keyword specifies a final alternative action to change the program condition, thereby ending the program

image

You need not yet understand this program in detail – each aspect is explained by examples later in this book.

Correcting errors

When coding programs there are three common types of error that can occur. It is useful to recognize these different error types in Python programming so they can be corrected more easily:

Syntax Error – occurs when the interpreter encounters code that does not conform to the Python language rules. For example, a missing quote mark around a string. The interpreter halts and reports the error without executing the program.

Runtime Error – occurs during execution of the program, at the time when the program runs. For example, when a variable name is later mis-typed so the variable cannot be recognized. The interpreter runs the program but halts at the error and reports the nature of the error as an “Exception”.

Semantic Error – occurs when the program performs unexpectedly. For example, when order precedence has not been specified in an expression. The interpreter runs the program and does not report an error.

image

Programming errors are often called “bugs” and the process of tracking them down is often called “debugging”.

Correcting syntax and runtime errors is fairly straightforward, as the interpreter reports where the error occurred or the nature of the error type, but semantic errors require code examination.

image

syntax.py

imageOpen an IDLE Edit Window then add a statement to output a string that omits a closing quote mark

print( ‘Coding for Beginners in easy steps )

imageSave then run the program to see the interpreter highlight the syntax error and indicate its nature

image

image

The red syntax error indicator points to the line where the End Of Line (EOL) error occurs.

imageInsert a quote mark before the closing parenthesis to terminate the string and save then run the program again – to see the error has been corrected

image

runtime.py

imageNext, begin a new program by initializing a variable then try to output its value with an incorrect variable name – to see the interpreter report a runtime error

title = ‘Coding for Beginners in easy steps’

print( titel )

image

imageAmend the variable name to match that in the variable declaration and save then run the program again – to see the error has been corrected

image

semantic.py

imageNow, begin a new program by initializing a variable then try to output an expression using its value without explicit precedence – to see a possibly unexpected result of 28

num = 3

print( ‘Result: ‘ , num * 8 + 4 )

image

imageAdd parentheses to group the expression as 3 * ( 8 + 4 ) then save the file and run the program again – to see the expected result of 36, correcting the semantic error

image

Details of how to handle runtime Exception errors in your script code are provided here.

Summary

•Variables can be used to store data values specified in program code and to store data values input by a user

•A value stored in a variable remains available for repeated use until it is replaced by a new value or until the program ends

•The Python built-in input() function can assign input to a variable and may optionally specify a string to be displayed

•The Python built-in print() function can specify multiple values for output as a comma-separated list in its parentheses

•By default, the print() function will automatically add a \n newline after its output unless an end alternative is specified

•The + concatenation operator can join two strings together

•Data types are essentially str text strings, int integer numbers, float decimal numbers, or bool Boolean truth values

•Booleans are logical truth values that are represented in Python by the True and False keywords

•The Python built-in type() function can identify to which class data type a value in any specified variable belongs

•Values assigned to a variable by the Python built-in input() function are always appointed the str string data type

•Data types can be converted for manipulation using the Python built-in int(), float(), and str() casting functions

•Arithmetic performed on an int integer number and a float decimal number will produce a float data type result

•Syntax errors due to incorrect code are recognized by the interpreter before execution of the program

Runtime errors due to exceptions are recognized by the interpreter during execution of the program

Semantic errors due to unexpected performance are not recognized by the interpreter