SlideShare a Scribd company logo
1 of 39
Download to read offline
Programming Fundamentals
Lecture 1: Introduction to Programming
This Lecture
• Establishing a context
– Approach to the unit
– What is programming?
– Program implementation and source code
• Program design
– Pseudocode and flowcharts
• Introduction to Python
– A simple program
– Variables, comments and concatenation
2
Textbook
• Starting Out with Python, 4th Edition (Global)
– Tony Gaddis
• Reading the chapter(s) is required
– Read the indicated chapter(s) before class
• This week covers the following textbook chapter(s):
– Chapter 1 – Introduction to Computers and Programming
• Entire chapter
– Chapter 2 – Input, Processing, and Output
• You can skip the “Turtle Graphics” section of this and all future chapters
– Appendix A and B
3
Establishing a Context
Approach to the Unit
• This unit aims to teach you introductory programming
– It does not aim to just teach you “programming in Python”
• The language you happen to use when learning to program is not the focus or
goal, it is simply the tool you are using
– When learning to drive, you learn to drive a car – not a red 1997 Ford Festiva Trio
• We will focus on the core concepts of programming
– What they entail
– Why they are necessary, important or desirable
– How (and why) their implementations differ between languages
– Most of the examples, and your lab/assignment work, will just happen to use the
Python programming language
5
Approach to the Unit
• While Python is the programming language we focus on, this unit will discuss and
demonstrate other languages
– This is to keep you focused upon the concepts being covered, rather than their
specific implementation in Python
• Code samples written in Python will look like this:
• Code samples written in other languages will look like this:
6
# print "Hello world!" to the screen
print('Hello world!')
Python
// print "Hello world!" to the screen
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}
Java
What is Programming?
• Let us first consider “What is a computer?”
• A computer is a device with a few basic components:
– A processor (CPU) which can execute basic instructions
– Memory to store data and instructions that are in use
– Storage for ongoing retention of data and programs
– Input and output devices to communicate/interact with users
• Computers exist to be useful; To do things for us
– e.g. Automation of a manual process, or making something possible that would
otherwise be impossible or unfeasible
– Computers need to be told exactly how to do things
– These instructions must be written in a way that a computer can understand
i.e. they must follow a pre-defined set of rules
7
“A computer program does what you tell it to do,
not what you want it to do.”
“Computers do not solve problems,
they execute solutions.”
8
What is Programming?
• So, what is programming? Programming is problem solving
– Programs are written in order to fulfil a need / solve a problem
– A programming language is the tool used to create a solution
By writing a program using a programming language,
you can make a computer do something useful
11
Problem Solution
Design Implement
print
variable
if condition
print
variable
for condition
print
function
...
Why Learn Programming?
• Learning to program is about developing cognitive processes - i.e. ways of
thinking - not memorising syntax
– Programming teaches you to think about a problem and design a solution that
adheres to an established set of rules
– Programming teaches you to think in a precise and methodical manner when
approaching a problem
– Programming teaches you to think of solutions that are appropriate, elegant,
modular and well-structured
Programming teaches you to think
12
Program Implementation
• A computer’s processor can only understand a set of very basic instructions,
such as simple arithmetic operations
– This is known as machine code, and it is not feasible to write large or complex
programs directly in machine code
• To make this easier, assembly language was developed
– Assembly language replaces the numeric instruction codes of machine code with
short descriptive words, e.g. “add”
– Each instruction corresponds to a machine code instruction, so it is still very low level
and unfeasible for large, complex programs
B801000000
BF02000000
01F8
Machine Code
mov eax, 0x1
mov edi, 0x2
add eax, edi
Assembly
13
Program Implementation
• In order to write complex programs in a way that is easy to read and write as well
as being processor-independent, we use high-level languages
– These are the programming languages you hear about / use: Python, C, Java, PHP,
C++, C#, JavaScript, Swift, Go, etc
– Instructions in high-level languages are referred to as “statements”, and usually
translate to multiple machine code instructions
– These languages are much easier for people to write code in, as well as reading and
editing that code at a later stage
• The code of a program written in a high-level language is known as the
“source code” of the program
– The computer’s processor still only understands machine code; the source code must
be translated into machine code in order to be run
14
Program Implementation
• There are two main approaches for translating high-level source code into
machine code:
– Compilation: The entirety of the source code is translated into machine code and an
executable file of it is produced
• This is a relatively slow process, however the resulting file runs quickly as it is not being
translated on the spot, and the compiler can spend time to further optimise the resulting file
• Some compiled languages include C and C++
– Interpretation: An interpreter translates and executes each source code statement
one at a time as the program is run
• Slower to run as it is “doing it live”, but fewer steps involved
• Some interpreted languages include Python, PHP and JavaScript
• Some languages, e.g. Java & .NET languages, use a hybrid method – compiling
to a lower-level known as “bytecode” and interpreting that
15
Source Code
• A program’s source code consists of a list of statements written in a programming
language
• Every statement must adhere to the syntax of the language:
– The “words” that the language recognises
– The “phrasing” required to specify values
– The ways of arranging these into valid “sentences”
• Any errors in your syntax will prevent the code from running
– Do not fear error messages; read them and learn from them
16
prunt('Hello world!')
Traceback (most recent call last):
File "C:PythonScriptstest.py", line 1, in <module>
prunt('Hello world!')
NameError: name 'prunt' is not defined
Python
Error location
Erroneous statement
Type of error
Source Code
• A program’s source code consists of a list of statements written in a programming
language
• Every statement must adhere to the syntax of the language
– The “words” that the language recognises
– The “phrasing” required to specify values
– The ways of arranging these into valid “sentences”
• Any errors in your syntax will prevent the code from running
– Do not fear error messages; read them and learn from them
print('Hello world!'
SyntaxError: unexpected EOF while parsing
Python
“End Of File”
Oh no, I forgot the “)”!
English Translation:
“When trying to interpret your code,
I reached the end of the file without finding the
closing parenthesis needed to make it valid”
17
Source Code
• When a program is run, it runs the statements in the source code from start to
end (unless it encounters an error that causes it to end prematurely)
– Some statements obtain input from users, or display output to users (Input/Output)
– Some statements can choose between different sections of code to run based upon
the result of a conditional check (Selection)
– Some statements can repeatedly run a section of code while a certain condition is
met, or a certain number of times (Iteration)
– Some statements define sections of code that can be used at other points in the
program where it is needed, or call upon other pre-defined code (Functions)
• Programs typically involve using selection, iteration and functions to manipulate
and process input, in order to transform it into useful output
– Some programs (typically ones with graphical interfaces) are “event-driven” – they
wait for the user to do something (e.g. click a button) and run statements in response
18
Program Design
Program Design
• Writing syntactically correct code is difficult and can distract you from the problem
that you are trying to solve
– Hence it is useful to be able to plan out the logic and structure of your solution prior to
commencing the actual programming
– This is the concept of program design
• Pseudocode and flowcharts are two ways of representing the steps and
statements that a program will implement
• Pseudocode and flowcharts…
– are valuable design tools that experienced programmers use
– are designed to be read by people, not parsed by a computer
– follow the conventions of programming, e.g. selection & iteration
– often omit minor, insignificant and assumed statements
22
“First, solve the problem. Then, write the code.”
“Weeks of coding can save you hours of planning.”
23
Program Design
• Pseudocode does not have defined standards, rules or syntax that need to be
adhered to – focus upon internal consistency, not external consistency
– There is no single “correct” way to write pseudocode
– To emphasise this, different conventions have been used in each of the following
pseudocode examples
• Flowcharts are a more visual approach to program design, using symbols with
specific meanings associated with them
– They are “stricter” than pseudocode, but this is a necessity in order to produce
flowcharts that anyone can read
• Always remember that the goal of these design tools is to illustrate and
communicate your design in a clear way
24
Flowchart Symbols
• This table summarises the main symbols used in flowcharts
– Note that flowcharts are used to illustrate algorithms to solve problems in many fields,
not just programming – very useful!
25
Symbol Meaning
Flow Line (indicates direction and connection between things)
Processing (indicates a basic operation, step or action)
Terminator (indicates start or end of a flowchart)
Input/Output (indicates input or output)
Decision (indicates a choice with true/false outcomes)
Predefined Process/Function (indicates a sub-process – may be detailed in separate flowchart)
Pseudocode and Flowchart Examples
• Let’s look at some examples of pseudocode, flowcharts, and corresponding
source code…
26
Prompt the user for a value
Multiply the value by 2
Show the result on the screen
Pseudocode
value = input('Enter a value: ')
result = int(value) * 2
print(result)
Python
Result = value * 2
Get value
Display result
Pseudocode and Flowchart Examples
if (name.length() > 15)
{
System.out.println("Error: Name too long.");
}
else
{
System.out.println("Your name has been saved.");
}
Java
IF length of name > 15 THEN
PRINT name length error message
ELSE
PRINT name saved message
Pseudocode
Name
length >
15?
True False
Display name
length error
Display name
saved message
27
Pseudocode and Flowchart Examples
get user details from database
while (rows remaining in result set)
{
get next row of data
print name from row
}
Pseudocode
$result = $db->query("SELECT * FROM users");
foreach ($result as $row)
{
echo $row['first_name'];
}
PHP
Get user details from
database
Row
remaining?
True
Display name
from row
False
Get next row of
results
28
Writing Good Code…
xkcd.com
30
Introduction to Python
Introduction to Python
• Python is a general purpose scripting language
released in 1991 by Guido van Rossum
– Started gaining popularity in 2000 when Python 2.0
was released, becoming a community-driven project
– Although development of the language is now open-source, Guido
was the “benevolent dictator for life” until stepping down in 2018
– Python 3.0 was released in late 2008, and had a big focus upon cleaning up some
redundant and inconsistent parts of the language
• The changes made it impossible for versions 2 and 3 to be fully compatible, so they were
developed side-by-side until 2011
• Development now focused upon version 3, which is the recommended version for modern
usage and education
• Designed to be elegant, simple and readable, allowing for clear and concise code
32
Features and Design of Python
• Python supports many different “styles” (paradigms) of programming;
object-oriented, procedural, functional…
• Python is interpreted, available on all major operating systems, and can do many
useful things “out of the box” due to its large library of modules
• Python is known for using indentation to delimit blocks of code, rather than
braces/curly brackets (“{“ and “}”) or keywords (e.g. “endif”)
– This helps code remain readable, since it eliminates ambiguity (particularly when there
are blocks within blocks within blocks) and makes all Python code visually consistent
33
if (status == 'complete')
cout << 'All done!';
saveResults();
C++
!
if (status == 'complete'){
cout << 'All done!';
saveResults();
}
C++
if (status == 'complete'){
cout << 'All done!';
saveResults();
}
C++
if (status == 'complete')
{
cout << 'All done!';
saveResults();
}
C++
if status == 'complete':
print('All done!')
save_results()
Python if (status == "complete")
{
cout << "All done!";
save_results();
}
C++
Our Programming Environment
• Obtaining Python is as simple as downloading it from python.org and installing it
like any other program – a guide is available on Blackboard for Windows or Mac
• The quickest and easiest way to get started is to run IDLE, the integrated
development environment (IDE) for Python
– This opens a “Python Shell” window, indicated by a “>>>”, where you can type
Python code and it will be run immediately
• The Python shell is useful for quickly trying and testing bits of code, but most of
the time you will want to create a file so that you can code a Python program
– Press Ctrl+N or go to “File > New File” to create a new file
(of course, you can also open existing Python code files)
– This opens a “Python Editor” window which you can type multiple lines of code into,
before saving (Ctrl+S) and running (F5) the code
– Output from the code and prompts for input appear in the Shell window
34
• Python Editor
– Type code into file to create program
– Save file with Ctrl+S or File > Save
– Run program by pressing F5
• Right click a Python file and select
“Edit with IDLE” to open it for editing
– (or double-click it if using a Mac)
• Python Shell
– Type code to run it immediately
– Shows input and output of programs
Run the file
(F5)
Our Programming Environment
35
Save the file
(Ctrl+S)
A Simple Program
• Let’s look at a simple program to convert pounds to kilos:
• Each line in the program is a statement; a single step:
1. Prompt the user for a value and save it as “value”
2. Multiply “value” by 0.454, and save the result as “result”
3. Display the result
• Python does not require a “;” after each statement
– Many languages do require this – see slide notes for why!
36
Prompt the user for a value in pounds
Multiply the value by 0.454
Show the result on the screen
Pseudocode
# convert pounds to kilograms
value = input('Enter a value in pounds: ')
result = float(value) * 0.454
print(value, 'pounds is', result, 'kilograms')
Python
Result = value *
0.454
Get value
Display
result
Variables
• This program introduces the concept of variables
– A variable allows you to associate a value with a name
– The variable name can then be used in future statements to refer to the value that it
contains (which is stored in memory)
– This is useful, since programs need to use values that are not known in advance
(e.g. the result of user input or a calculation)
• To overwrite the value that a variable contains, simply assign a new value to it:
example = 2
print(example)
2
example = 'Now it contains this text!'
print(example)
Now it contains this text!
Python
37
Variables
• We have seen examples of assigning a value to a variable
– <variable name> = <value to assign>
example = 'This is an example!'
– There is likely to be input needed or calculations to perform before arriving at a value
value = input('Enter a value in pounds: ')
result = float(value) * 0.454
– Everything to the right of the “=” will be evaluated, and the final value assigned to the variable
• We have also seen examples of variables being used
– Simply refer to the name of the variable where it is needed
print(value, 'pounds is', result, 'kilograms')
– The type of value that the variable contains may need to be taken into account
e.g. converting a string (text) to a float – more on this next week!
38
Variables
• Variables names should describe what they represent
– If the name involves multiple words, use a consistent naming convention, e.g.
total_value (Python’s recommendation) or TotalValue
– Variable names must begin with a letter, and usually cannot contain any spaces or
special symbols such as @, # or *
– In many languages (including Python), variable names are case-sensitive
– Avoid variable names that match the name of a command or function of the language,
as this will either not work, cause problems, or be confusing
• Always make your variable names clear and consistent
• In some languages, all variable names must begin with a certain symbol – this
helps to make them easy to spot (both for humans, and the language)
– e.g. Variables names in PHP begin with a “$”, e.g. $total
41
Comments
• Comments are descriptive or informative text that can be added to source code
to assist humans reading the code
– They do nothing; When code is run, comments are ignored
– Usually shown in green, however IDLE shows them in red by default
• Comments are used for a few key reasons:
– Summarising the functionality of a code section
– Providing details about complex or confusing statements
– Providing metadata about a file or code section (e.g. author details)
# single line comment
''' multi
line
comment
'''
Python // single line comment
/* multi
line
comment
*/
Most Languages
42
A Simple Program
• Let’s get back to our simple program…
• In each statement, we have used one of the many built-in functions of Python:
input(), float() and print()
– Functions are the commands of a language that you can use to do things
•input() shows a prompt and then waits for user input
•float() converts a value to a floating point number
•print() displays text on the screen
– The parentheses let you provide data for the function to make use of,
e.g. the text to show as a prompt for input, a value to convert, text to display…
– Functions often return a value as a result – e.g. the user’s input, a converted value…
43
# convert pounds to kilograms
value = input('Enter a value in pounds: ')
result = float(value) * 0.454
print(value, 'pounds is', result, 'kilograms')
Python
A Simple Program
• We now have a good understanding of the program code…
1. Use the input() function to prompt the user for a value, and store that value in a
variable named “value”
2. Use the float() function to convert the value to a floating point number, multiply
it by 0.454 and store the result in a variable named “result”
3. Use the print() function to display the result in a user friendly way
44
# convert pounds to kilograms
value = input('Enter a value in pounds: ')
result = float(value) * 0.454
print(value, 'pounds is', result, 'kilograms')
Python
Enter a value in pounds:
2 pounds is 0.908 kilograms
2
Concatenation & the Print Function
• It is worthwhile to look a little closer at the print()function
• Python’s print() function allows you to give it as many values as you want
– The code above gives it two variables and two strings of text, with commas between
– The values will all be converted to strings (text) as needed, and then joined together
with a space between each one. The end result is then displayed on the screen
• A more generic approach to joining (i.e. “concatenating”) strings and other values
is to convert non-string values to strings and concatenate them with a “+” sign
– This is also supported in Python – The str() function converts a value to a string:
– Which approach you take is up to you! Sometimes the automatic conversion and
inclusion of spaces is useful, other times you want more control…
45
print(value, 'pounds is', result, 'kilograms') Python
print(value + ' pounds is ' + str(result) + ' kilograms') Python
Conclusion
• A lot of this lecture covered preliminary information
– The concept of programming and reasons for learning it
– The capabilities and role of computers
– Types of programming languages and their implementation
• We introduced the important concept of program design
– Using pseudocode and flowcharts to design and depict code
• We became familiar with the Python programming language
– History and design of Python and the IDLE environment
• We looked at a simple program that introduced concepts of statements,
variables, comments and built-in functions
– We discussed how concatenation is handled in languages
46

More Related Content

Similar to ProgFund_Lecture_1_Introduction_to_Programming.pdf

Python-unit -I.pptx
Python-unit -I.pptxPython-unit -I.pptx
Python-unit -I.pptxcrAmth
 
Introduction_to_Programming.pptx
Introduction_to_Programming.pptxIntroduction_to_Programming.pptx
Introduction_to_Programming.pptxPmarkNorcio
 
Introduction to computer programming
Introduction to computer programming Introduction to computer programming
Introduction to computer programming VanessaBuensalida
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterHossam Hassan
 
Comso c++
Comso c++Comso c++
Comso c++Mi L
 
4_5802928814682016556.pptx
4_5802928814682016556.pptx4_5802928814682016556.pptx
4_5802928814682016556.pptxAshenafiGirma5
 
Cd ch1 - introduction
Cd   ch1 - introductionCd   ch1 - introduction
Cd ch1 - introductionmengistu23
 
CD - CH1 - Introduction to compiler design.pptx
CD - CH1 - Introduction to compiler design.pptxCD - CH1 - Introduction to compiler design.pptx
CD - CH1 - Introduction to compiler design.pptxZiyadMohammed17
 
introduction computer programming languages
introduction computer programming languages introduction computer programming languages
introduction computer programming languages BakhatAli3
 
Introduction to computers and programming languages
Introduction to computers and programming languages Introduction to computers and programming languages
Introduction to computers and programming languages binoysatheesh
 
Session01 basics programming
Session01 basics programmingSession01 basics programming
Session01 basics programmingHarithaRanasinghe
 
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...yaminohime
 
Embedded programming Embedded programming (1).pptx
Embedded programming Embedded programming (1).pptxEmbedded programming Embedded programming (1).pptx
Embedded programming Embedded programming (1).pptxlematadese670
 

Similar to ProgFund_Lecture_1_Introduction_to_Programming.pdf (20)

Python-unit -I.pptx
Python-unit -I.pptxPython-unit -I.pptx
Python-unit -I.pptx
 
Introduction_to_Programming.pptx
Introduction_to_Programming.pptxIntroduction_to_Programming.pptx
Introduction_to_Programming.pptx
 
sege.pdf
sege.pdfsege.pdf
sege.pdf
 
Introduction to computer programming
Introduction to computer programming Introduction to computer programming
Introduction to computer programming
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
 
Comso c++
Comso c++Comso c++
Comso c++
 
Chapter 4 computer language
Chapter 4 computer languageChapter 4 computer language
Chapter 4 computer language
 
Nota (first)
Nota (first)Nota (first)
Nota (first)
 
programming.pptx
programming.pptxprogramming.pptx
programming.pptx
 
4_5802928814682016556.pptx
4_5802928814682016556.pptx4_5802928814682016556.pptx
4_5802928814682016556.pptx
 
Cd ch1 - introduction
Cd   ch1 - introductionCd   ch1 - introduction
Cd ch1 - introduction
 
CD - CH1 - Introduction to compiler design.pptx
CD - CH1 - Introduction to compiler design.pptxCD - CH1 - Introduction to compiler design.pptx
CD - CH1 - Introduction to compiler design.pptx
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
introduction computer programming languages
introduction computer programming languages introduction computer programming languages
introduction computer programming languages
 
Introduction to computers and programming languages
Introduction to computers and programming languages Introduction to computers and programming languages
Introduction to computers and programming languages
 
Session01 basics programming
Session01 basics programmingSession01 basics programming
Session01 basics programming
 
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
Understanding Computers: Today and Tomorrow, 13th Edition Chapter 13 - Progra...
 
Uc13.chapter.13
Uc13.chapter.13Uc13.chapter.13
Uc13.chapter.13
 
Embedded programming Embedded programming (1).pptx
Embedded programming Embedded programming (1).pptxEmbedded programming Embedded programming (1).pptx
Embedded programming Embedded programming (1).pptx
 
Presentation-1.pptx
Presentation-1.pptxPresentation-1.pptx
Presentation-1.pptx
 

More from lailoesakhan

ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdflailoesakhan
 
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdfProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdflailoesakhan
 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdflailoesakhan
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdflailoesakhan
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdflailoesakhan
 
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdfProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdflailoesakhan
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdflailoesakhan
 

More from lailoesakhan (8)

ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
 
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdfProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdf
 
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdfProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdf
 

Recently uploaded

CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 

Recently uploaded (20)

CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 

ProgFund_Lecture_1_Introduction_to_Programming.pdf

  • 1. Programming Fundamentals Lecture 1: Introduction to Programming
  • 2. This Lecture • Establishing a context – Approach to the unit – What is programming? – Program implementation and source code • Program design – Pseudocode and flowcharts • Introduction to Python – A simple program – Variables, comments and concatenation 2
  • 3. Textbook • Starting Out with Python, 4th Edition (Global) – Tony Gaddis • Reading the chapter(s) is required – Read the indicated chapter(s) before class • This week covers the following textbook chapter(s): – Chapter 1 – Introduction to Computers and Programming • Entire chapter – Chapter 2 – Input, Processing, and Output • You can skip the “Turtle Graphics” section of this and all future chapters – Appendix A and B 3
  • 5. Approach to the Unit • This unit aims to teach you introductory programming – It does not aim to just teach you “programming in Python” • The language you happen to use when learning to program is not the focus or goal, it is simply the tool you are using – When learning to drive, you learn to drive a car – not a red 1997 Ford Festiva Trio • We will focus on the core concepts of programming – What they entail – Why they are necessary, important or desirable – How (and why) their implementations differ between languages – Most of the examples, and your lab/assignment work, will just happen to use the Python programming language 5
  • 6. Approach to the Unit • While Python is the programming language we focus on, this unit will discuss and demonstrate other languages – This is to keep you focused upon the concepts being covered, rather than their specific implementation in Python • Code samples written in Python will look like this: • Code samples written in other languages will look like this: 6 # print "Hello world!" to the screen print('Hello world!') Python // print "Hello world!" to the screen class HelloWorld { public static void main(String[] args) { System.out.println("Hello world!"); } } Java
  • 7. What is Programming? • Let us first consider “What is a computer?” • A computer is a device with a few basic components: – A processor (CPU) which can execute basic instructions – Memory to store data and instructions that are in use – Storage for ongoing retention of data and programs – Input and output devices to communicate/interact with users • Computers exist to be useful; To do things for us – e.g. Automation of a manual process, or making something possible that would otherwise be impossible or unfeasible – Computers need to be told exactly how to do things – These instructions must be written in a way that a computer can understand i.e. they must follow a pre-defined set of rules 7
  • 8. “A computer program does what you tell it to do, not what you want it to do.” “Computers do not solve problems, they execute solutions.” 8
  • 9. What is Programming? • So, what is programming? Programming is problem solving – Programs are written in order to fulfil a need / solve a problem – A programming language is the tool used to create a solution By writing a program using a programming language, you can make a computer do something useful 11 Problem Solution Design Implement print variable if condition print variable for condition print function ...
  • 10. Why Learn Programming? • Learning to program is about developing cognitive processes - i.e. ways of thinking - not memorising syntax – Programming teaches you to think about a problem and design a solution that adheres to an established set of rules – Programming teaches you to think in a precise and methodical manner when approaching a problem – Programming teaches you to think of solutions that are appropriate, elegant, modular and well-structured Programming teaches you to think 12
  • 11. Program Implementation • A computer’s processor can only understand a set of very basic instructions, such as simple arithmetic operations – This is known as machine code, and it is not feasible to write large or complex programs directly in machine code • To make this easier, assembly language was developed – Assembly language replaces the numeric instruction codes of machine code with short descriptive words, e.g. “add” – Each instruction corresponds to a machine code instruction, so it is still very low level and unfeasible for large, complex programs B801000000 BF02000000 01F8 Machine Code mov eax, 0x1 mov edi, 0x2 add eax, edi Assembly 13
  • 12. Program Implementation • In order to write complex programs in a way that is easy to read and write as well as being processor-independent, we use high-level languages – These are the programming languages you hear about / use: Python, C, Java, PHP, C++, C#, JavaScript, Swift, Go, etc – Instructions in high-level languages are referred to as “statements”, and usually translate to multiple machine code instructions – These languages are much easier for people to write code in, as well as reading and editing that code at a later stage • The code of a program written in a high-level language is known as the “source code” of the program – The computer’s processor still only understands machine code; the source code must be translated into machine code in order to be run 14
  • 13. Program Implementation • There are two main approaches for translating high-level source code into machine code: – Compilation: The entirety of the source code is translated into machine code and an executable file of it is produced • This is a relatively slow process, however the resulting file runs quickly as it is not being translated on the spot, and the compiler can spend time to further optimise the resulting file • Some compiled languages include C and C++ – Interpretation: An interpreter translates and executes each source code statement one at a time as the program is run • Slower to run as it is “doing it live”, but fewer steps involved • Some interpreted languages include Python, PHP and JavaScript • Some languages, e.g. Java & .NET languages, use a hybrid method – compiling to a lower-level known as “bytecode” and interpreting that 15
  • 14. Source Code • A program’s source code consists of a list of statements written in a programming language • Every statement must adhere to the syntax of the language: – The “words” that the language recognises – The “phrasing” required to specify values – The ways of arranging these into valid “sentences” • Any errors in your syntax will prevent the code from running – Do not fear error messages; read them and learn from them 16 prunt('Hello world!') Traceback (most recent call last): File "C:PythonScriptstest.py", line 1, in <module> prunt('Hello world!') NameError: name 'prunt' is not defined Python Error location Erroneous statement Type of error
  • 15. Source Code • A program’s source code consists of a list of statements written in a programming language • Every statement must adhere to the syntax of the language – The “words” that the language recognises – The “phrasing” required to specify values – The ways of arranging these into valid “sentences” • Any errors in your syntax will prevent the code from running – Do not fear error messages; read them and learn from them print('Hello world!' SyntaxError: unexpected EOF while parsing Python “End Of File” Oh no, I forgot the “)”! English Translation: “When trying to interpret your code, I reached the end of the file without finding the closing parenthesis needed to make it valid” 17
  • 16. Source Code • When a program is run, it runs the statements in the source code from start to end (unless it encounters an error that causes it to end prematurely) – Some statements obtain input from users, or display output to users (Input/Output) – Some statements can choose between different sections of code to run based upon the result of a conditional check (Selection) – Some statements can repeatedly run a section of code while a certain condition is met, or a certain number of times (Iteration) – Some statements define sections of code that can be used at other points in the program where it is needed, or call upon other pre-defined code (Functions) • Programs typically involve using selection, iteration and functions to manipulate and process input, in order to transform it into useful output – Some programs (typically ones with graphical interfaces) are “event-driven” – they wait for the user to do something (e.g. click a button) and run statements in response 18
  • 18. Program Design • Writing syntactically correct code is difficult and can distract you from the problem that you are trying to solve – Hence it is useful to be able to plan out the logic and structure of your solution prior to commencing the actual programming – This is the concept of program design • Pseudocode and flowcharts are two ways of representing the steps and statements that a program will implement • Pseudocode and flowcharts… – are valuable design tools that experienced programmers use – are designed to be read by people, not parsed by a computer – follow the conventions of programming, e.g. selection & iteration – often omit minor, insignificant and assumed statements 22
  • 19. “First, solve the problem. Then, write the code.” “Weeks of coding can save you hours of planning.” 23
  • 20. Program Design • Pseudocode does not have defined standards, rules or syntax that need to be adhered to – focus upon internal consistency, not external consistency – There is no single “correct” way to write pseudocode – To emphasise this, different conventions have been used in each of the following pseudocode examples • Flowcharts are a more visual approach to program design, using symbols with specific meanings associated with them – They are “stricter” than pseudocode, but this is a necessity in order to produce flowcharts that anyone can read • Always remember that the goal of these design tools is to illustrate and communicate your design in a clear way 24
  • 21. Flowchart Symbols • This table summarises the main symbols used in flowcharts – Note that flowcharts are used to illustrate algorithms to solve problems in many fields, not just programming – very useful! 25 Symbol Meaning Flow Line (indicates direction and connection between things) Processing (indicates a basic operation, step or action) Terminator (indicates start or end of a flowchart) Input/Output (indicates input or output) Decision (indicates a choice with true/false outcomes) Predefined Process/Function (indicates a sub-process – may be detailed in separate flowchart)
  • 22. Pseudocode and Flowchart Examples • Let’s look at some examples of pseudocode, flowcharts, and corresponding source code… 26 Prompt the user for a value Multiply the value by 2 Show the result on the screen Pseudocode value = input('Enter a value: ') result = int(value) * 2 print(result) Python Result = value * 2 Get value Display result
  • 23. Pseudocode and Flowchart Examples if (name.length() > 15) { System.out.println("Error: Name too long."); } else { System.out.println("Your name has been saved."); } Java IF length of name > 15 THEN PRINT name length error message ELSE PRINT name saved message Pseudocode Name length > 15? True False Display name length error Display name saved message 27
  • 24. Pseudocode and Flowchart Examples get user details from database while (rows remaining in result set) { get next row of data print name from row } Pseudocode $result = $db->query("SELECT * FROM users"); foreach ($result as $row) { echo $row['first_name']; } PHP Get user details from database Row remaining? True Display name from row False Get next row of results 28
  • 27. Introduction to Python • Python is a general purpose scripting language released in 1991 by Guido van Rossum – Started gaining popularity in 2000 when Python 2.0 was released, becoming a community-driven project – Although development of the language is now open-source, Guido was the “benevolent dictator for life” until stepping down in 2018 – Python 3.0 was released in late 2008, and had a big focus upon cleaning up some redundant and inconsistent parts of the language • The changes made it impossible for versions 2 and 3 to be fully compatible, so they were developed side-by-side until 2011 • Development now focused upon version 3, which is the recommended version for modern usage and education • Designed to be elegant, simple and readable, allowing for clear and concise code 32
  • 28. Features and Design of Python • Python supports many different “styles” (paradigms) of programming; object-oriented, procedural, functional… • Python is interpreted, available on all major operating systems, and can do many useful things “out of the box” due to its large library of modules • Python is known for using indentation to delimit blocks of code, rather than braces/curly brackets (“{“ and “}”) or keywords (e.g. “endif”) – This helps code remain readable, since it eliminates ambiguity (particularly when there are blocks within blocks within blocks) and makes all Python code visually consistent 33 if (status == 'complete') cout << 'All done!'; saveResults(); C++ ! if (status == 'complete'){ cout << 'All done!'; saveResults(); } C++ if (status == 'complete'){ cout << 'All done!'; saveResults(); } C++ if (status == 'complete') { cout << 'All done!'; saveResults(); } C++ if status == 'complete': print('All done!') save_results() Python if (status == "complete") { cout << "All done!"; save_results(); } C++
  • 29. Our Programming Environment • Obtaining Python is as simple as downloading it from python.org and installing it like any other program – a guide is available on Blackboard for Windows or Mac • The quickest and easiest way to get started is to run IDLE, the integrated development environment (IDE) for Python – This opens a “Python Shell” window, indicated by a “>>>”, where you can type Python code and it will be run immediately • The Python shell is useful for quickly trying and testing bits of code, but most of the time you will want to create a file so that you can code a Python program – Press Ctrl+N or go to “File > New File” to create a new file (of course, you can also open existing Python code files) – This opens a “Python Editor” window which you can type multiple lines of code into, before saving (Ctrl+S) and running (F5) the code – Output from the code and prompts for input appear in the Shell window 34
  • 30. • Python Editor – Type code into file to create program – Save file with Ctrl+S or File > Save – Run program by pressing F5 • Right click a Python file and select “Edit with IDLE” to open it for editing – (or double-click it if using a Mac) • Python Shell – Type code to run it immediately – Shows input and output of programs Run the file (F5) Our Programming Environment 35 Save the file (Ctrl+S)
  • 31. A Simple Program • Let’s look at a simple program to convert pounds to kilos: • Each line in the program is a statement; a single step: 1. Prompt the user for a value and save it as “value” 2. Multiply “value” by 0.454, and save the result as “result” 3. Display the result • Python does not require a “;” after each statement – Many languages do require this – see slide notes for why! 36 Prompt the user for a value in pounds Multiply the value by 0.454 Show the result on the screen Pseudocode # convert pounds to kilograms value = input('Enter a value in pounds: ') result = float(value) * 0.454 print(value, 'pounds is', result, 'kilograms') Python Result = value * 0.454 Get value Display result
  • 32. Variables • This program introduces the concept of variables – A variable allows you to associate a value with a name – The variable name can then be used in future statements to refer to the value that it contains (which is stored in memory) – This is useful, since programs need to use values that are not known in advance (e.g. the result of user input or a calculation) • To overwrite the value that a variable contains, simply assign a new value to it: example = 2 print(example) 2 example = 'Now it contains this text!' print(example) Now it contains this text! Python 37
  • 33. Variables • We have seen examples of assigning a value to a variable – <variable name> = <value to assign> example = 'This is an example!' – There is likely to be input needed or calculations to perform before arriving at a value value = input('Enter a value in pounds: ') result = float(value) * 0.454 – Everything to the right of the “=” will be evaluated, and the final value assigned to the variable • We have also seen examples of variables being used – Simply refer to the name of the variable where it is needed print(value, 'pounds is', result, 'kilograms') – The type of value that the variable contains may need to be taken into account e.g. converting a string (text) to a float – more on this next week! 38
  • 34. Variables • Variables names should describe what they represent – If the name involves multiple words, use a consistent naming convention, e.g. total_value (Python’s recommendation) or TotalValue – Variable names must begin with a letter, and usually cannot contain any spaces or special symbols such as @, # or * – In many languages (including Python), variable names are case-sensitive – Avoid variable names that match the name of a command or function of the language, as this will either not work, cause problems, or be confusing • Always make your variable names clear and consistent • In some languages, all variable names must begin with a certain symbol – this helps to make them easy to spot (both for humans, and the language) – e.g. Variables names in PHP begin with a “$”, e.g. $total 41
  • 35. Comments • Comments are descriptive or informative text that can be added to source code to assist humans reading the code – They do nothing; When code is run, comments are ignored – Usually shown in green, however IDLE shows them in red by default • Comments are used for a few key reasons: – Summarising the functionality of a code section – Providing details about complex or confusing statements – Providing metadata about a file or code section (e.g. author details) # single line comment ''' multi line comment ''' Python // single line comment /* multi line comment */ Most Languages 42
  • 36. A Simple Program • Let’s get back to our simple program… • In each statement, we have used one of the many built-in functions of Python: input(), float() and print() – Functions are the commands of a language that you can use to do things •input() shows a prompt and then waits for user input •float() converts a value to a floating point number •print() displays text on the screen – The parentheses let you provide data for the function to make use of, e.g. the text to show as a prompt for input, a value to convert, text to display… – Functions often return a value as a result – e.g. the user’s input, a converted value… 43 # convert pounds to kilograms value = input('Enter a value in pounds: ') result = float(value) * 0.454 print(value, 'pounds is', result, 'kilograms') Python
  • 37. A Simple Program • We now have a good understanding of the program code… 1. Use the input() function to prompt the user for a value, and store that value in a variable named “value” 2. Use the float() function to convert the value to a floating point number, multiply it by 0.454 and store the result in a variable named “result” 3. Use the print() function to display the result in a user friendly way 44 # convert pounds to kilograms value = input('Enter a value in pounds: ') result = float(value) * 0.454 print(value, 'pounds is', result, 'kilograms') Python Enter a value in pounds: 2 pounds is 0.908 kilograms 2
  • 38. Concatenation & the Print Function • It is worthwhile to look a little closer at the print()function • Python’s print() function allows you to give it as many values as you want – The code above gives it two variables and two strings of text, with commas between – The values will all be converted to strings (text) as needed, and then joined together with a space between each one. The end result is then displayed on the screen • A more generic approach to joining (i.e. “concatenating”) strings and other values is to convert non-string values to strings and concatenate them with a “+” sign – This is also supported in Python – The str() function converts a value to a string: – Which approach you take is up to you! Sometimes the automatic conversion and inclusion of spaces is useful, other times you want more control… 45 print(value, 'pounds is', result, 'kilograms') Python print(value + ' pounds is ' + str(result) + ' kilograms') Python
  • 39. Conclusion • A lot of this lecture covered preliminary information – The concept of programming and reasons for learning it – The capabilities and role of computers – Types of programming languages and their implementation • We introduced the important concept of program design – Using pseudocode and flowcharts to design and depict code • We became familiar with the Python programming language – History and design of Python and the IDLE environment • We looked at a simple program that introduced concepts of statements, variables, comments and built-in functions – We discussed how concatenation is handled in languages 46