0% found this document useful (0 votes)
7 views

CSP1150_Lecture_1_Introduction_to_Programming - Part B

The document introduces Python as a general-purpose scripting language, highlighting its history, design philosophy, and features. It covers programming principles including variables, comments, and built-in functions through a simple program example that converts pounds to kilograms. Additionally, it provides guidance on using the Python development environment, IDLE, and emphasizes the importance of academic integrity in assessments.

Uploaded by

ashwin68732007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

CSP1150_Lecture_1_Introduction_to_Programming - Part B

The document introduces Python as a general-purpose scripting language, highlighting its history, design philosophy, and features. It covers programming principles including variables, comments, and built-in functions through a simple program example that converts pounds to kilograms. Additionally, it provides guidance on using the Python development environment, IDLE, and emphasizes the importance of academic integrity in assessments.

Uploaded by

ashwin68732007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

CSP1150

Programming Principles
Lecture 1: Introduction to Programming (Part B)

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 is the “benevolent dictator for life” (has final say)

– Python 3.0 was released in late 2000, dubbed “Python 3000”


and “Py3K” by some, and had a big focus upon cleaning up
some of the 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
The Philosophy of Python

• Python was designed to be elegant, simple and readable,


allowing programmers to write clear and concise code
– These features make it a good language to learn programming

• Tim Peters, a long time “Pythoneer” summarised the guiding


principles behind Python in “the Zen of Python”. It includes:
– Beautiful is better than ugly
– Simple is better than complex
– Complex is better than complicated
– Readability counts
– Special cases aren't special enough to break the rules
– Although practicality beats purity
– There should be one – and preferably only one – obvious way
to do it
Features and Design of Python

• Python supports many different “styles” (paradigms) of


programming; Object-Oriented, procedural, functional…

• Python is interpreted, available and compatible on most


platforms, and can do many useful things “out of the box”

• Python is known for using whitespace to delimit code


blocks, rather than braces (“{ }”) or keywords (e.g. “endif”)
– This helps code remain readable, since it eliminates ambiguity
(particularly when there are blocks within blocks within blocks)
if status == 'complete': Python if (status == "complete")
'complete'){
'complete') C++
print('All done!') coutcout
{ << 'All
<< 'All
done!';
done!';
saveResults() saveResults();
coutsaveResults();
cout
<< 'All
<< "All
done!';
done!";
}
saveResults();
saveResults();
!
}
Our Programming Environment

• Obtaining Python is as simple as downloading it from


python.org and installing it like any other program

• 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
– 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
code into, before saving (Ctrl+S) and running (F5) the code
– Output from the code and prompts for input appear in the shell
Our Programming Environment

• Python Shell • Python Editor

Save
Run the
the file
file
(Ctrl+S)
(F5)

– Type code into file


– Save file with Ctrl+S
– Run code with F5

– Type code to run it now – You can right click a Python


– Input and output of files file to “Edit with IDLE”
A Simple Program

• Let’s look at a simple program to convert pounds to kilos:


Prompt the user for a value in pounds Pseudocode
Get value
Multiply the value by 0.454
Show the result on the screen
Result = value *
# convert pounds to kilograms Python 0.454
value = input('Enter a value in pounds: ')
result = float(value) * 0.454 Display
print(value, 'pounds is', result, 'kilograms') result

• 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!
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 input or a calculation)

• In most circumstances, you can overwrite the value that a


variable contains simply by assigning a new value to it
example = 2 Python
print(example)
2
example = 'Now it contains a string!'
print(example)
Now it contains a string!
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 calculation or input resulting in the value…


value = input('Enter a value in pounds: ')
result = float(value) * 0.454

• 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 to a float
Variables

• In many languages (not Python), it is necessary to declare


a variable before you can assign a value into it
– This involves specifying the name of the variable, and the type
of values that it can store, e.g. integers, floats, strings (text)…
• Certain types may also require a size or length to be specified

int i; // declare an integer variable named "i" Java


float salary; // declare a float variable named "salary"
String name; // declare a string variable named "name"
int k, l, m; // you can declare multiple variables at once
int j = 10; // variables can be given a value when declared

• This is only required in “statically typed” languages, where


a variable can only ever store values of its declared type
– C, C++ and Java are statically typed languages
– Python, JavaScript and PHP are dynamically typed languages
Variables

• Variables names should describe what they represent


– If the name involves multiple words, use camelBack notation
– A common exception to this is naming integer variables that
are used to count something “i” (and “j”, “k”, etc, as needed)
– Variable names must begin with a letter, and usually cannot
contain any spaces or special symbols such as @, # or *
– In many languages (incl. Python), names are case-sensitive
– Variable names cannot be the same as a “reserved word” of
the programming language – i.e. the name of a command
• Some words are “special”, but not reserved. e.g., it’s possible
(but inadvisable) to create a Python variable named “float”

• In some languages, all variable names must begin with a


certain symbol – this helps to make them easy to spot
– e.g. Variables names in PHP begin with a “$”, e.g. “$total”
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

• 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)

# single line comment Python // single line comment Most Other


Languages
''' multi /* multi
line line
comment comment
''' */
A Simple Program

• Let’s get back to our simple program…


# convert pounds to kilograms Python
value = input('Enter a value in pounds: ')
result = float(value) * 0.454
print(value, 'pounds is', result, 'kilograms')

• 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 used to do things
• input() shows a prompt to the user for 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 do


something with (prompt text, value to convert, text to show…)
– Functions often return a value (input from the user, float value)
A Simple Program

• We now have a good understanding of the program code…


# convert pounds to kilograms Python
value = input('Enter a value in pounds: ')
result = float(value) * 0.454
print(value, 'pounds is', result, 'kilograms')

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, multiple that 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, including the input value

Enter a value in pounds: 2


2 pounds is 0.908 kilograms
Concatenation & the Print Function

• It is worthwhile to look a little closer at the print()function


print(value, 'pounds is', result, 'kilograms') Python

• The print() function in Python allows you to give it as


many values (“parameters”) as you want
– The code above gives it both variables and two strings of text
– The parameters will all be converted to strings (text) if needed,
and then joined together with a space between each one

• In most languages, joining together (“concatenating”) strings


and other values is a more manual process, often requiring
you to convert non-string values before concatenating them
– This is also supported in Python – use whichever way you like
print(str(value) + ' pounds is ' + str(result) + ' kilograms') Python

– The str() function converts a value to a string


Conclusion

• A lot of this lecture covered preliminary information


– The concept of programming and reasons for learning it
– Program implementation
– History of programming languages and design focus

• 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, design and philosophy 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
Workshop Preliminaries
Preliminaries
• Welcome to ECC! As this unit is likely to be at the very beginning of your course, this
workshop includes some preliminary information regarding your studies. Please read
over the information and remember that how well you do in university is entirely up
to you. It is up to you to take a mature and responsible approach to your studies, to
complete your assessments on time, and to seek help when you require it. Staff are
here to help you and facilitate your learning.
• The preliminary information that follows applies to most units, most of the time.
Always be sure to check with unit staff if you are uncertain about something or want
clarification regarding anything.

Activities
• Most units consist of two weekly activities: A lecture and a workshop. Lectures
generally introduce theories and concepts, while workshops give you an opportunity
to apply them. If studying on campus, you should aim to attend both activities every
week. If studying online you are also encouraged to attend activities if able (and if
there is room), but otherwise you should aim to keep up with the unit and study one
module per week; It is easy to fall behind, but hard to catch up.
Workshop Preliminaries
Assessments & Academic Misconduct
• Units have assessments of various types, including assignments, tests and assessable
workshops, and most units also have an end of semester exam. Be sure to dedicate
appropriate time and effort to completing all assessments. Manage your time
responsibly and don’t leave them for the last minute. Seek assistance from staff if you
are struggling, confused, or desire feedback on your work.
• Assessments allow staff to determine whether you have sufficiently understood the
unit content, so it is vital that the work you submit for an assignment is your own.
Submitting unreferenced work that is not entirely your own or working with
classmates in an individual assessment is academic misconduct. We take academic
misconduct very seriously, and the penalties for it will be applied.
Student Email
• All students receive a student email address, which you must use when contacting
ECC staff. This is to ensure that the person we are communicating with in indeed who
they claim to be, and it also helps to ensure that your email is not inadvertently
filtered as spam. Be polite and professional in all emails and be sure to include the
unit code in the email subject line. We operate on a two working day turnaround time
for emails.
• To access your student email, log in to the Student Portal on the ECC portal.
Workshop Setup / Preparation
Setup – Environment Setup
• Throughout the unit, we will be using Python’s development environment “IDLE” to
write and run our code. If you are working on an ECU lab computer, Python should
already be installed. If you are working on your own computer, download and install
the latest version of Python 3 from python.org:
• www.python.org
• I have included a youtube in case you have trouble:
• https://www.youtube.com/watch?v=i-MuSAwgwCU
• Create a folder on a portable storage device such as a thumb drive, or on your own
device if you are using one, where you will save your source code files. Create
subfolders within this as needed to keep things organised, and remember that you
are responsible for the security and backup of your work.
• You WILL have to submit all your workshops as part of your portfolio – so make sure
you keep them organised.
Workshop Task
Task 1 – Concept Revision in the Python Shell
• Launch the “IDLE (Python GUI)” program on your computer. As covered in the lecture,
this will open the Python Shell, where you can type Python code at the “>>>” prompt
to execute it immediately.
• Let’s get acquainted with the shell and Python code by typing some statements. Feel
free to deviate from the workshop and experiment!
• Type the following statements into the shell:
1. (1 + 2) * 3
• This statement demonstrates basic arithmetic and using parentheses.

2. print('Testing')
3. print('Testing)
4. print(Testing)
• Note the different error messages that you receive, depending on the error.

5. # print('Testing')
• Comments ignored when code is run.
Workshop Task
6. x = 6
7. x = x + 1
8. print(x)
• These statements create a variable named “x” with a value of 6, add 1 to the value of
x, then print the value of x. In most languages, a statement of “x++” can be used to
add 1 to x.

9. value = input('Type Something: ') (then type something at the prompt)


10. print('You typed', value)
• The first statement prompts the user to type something and stores it in a “value”
variable.
• The second statement then prints the content of the “value” variable

11. print('You typed', input('Type Something: '))


• This version nests the input function inside the print function, eliminating the need for
a variable. Programming languages are flexible in this way.
Workshop Task
Task 2 – A Simple Program
• Press Ctrl+N or go to “File > New File” in the Python shell to start a new source code
file in the Python Editor. This is where you can type code into a file, save the file and
then run it.
• Based upon the simple program from the lecture, write a program that performs a
conversion. Your program should prompt for a value, perform the necessary
arithmetic to convert the value to the desired result, and then display the result. I’ve
listed some common conversions between Metric and Imperial measurements below,
but feel free to google for others and implement them.
Workshop Task
• Whichever conversion you choose, the program should consist of three statements
that are very similar to the ones in the lecture:

1. Use the input() function to prompt the user for a value, and store that value in a variable.
2. Use the float() function to convert the value to a floating-point number, perform the
necessary arithmetic, and store the result in a variable.
3. Use the print() function to display the result in a user-friendly way.

• Once you’ve typed the three statements, save the file (Ctrl+S) into the folder you
created earlier, then press F5 to run the code. The prompt for a value will appear in
the shell window.
• Run the program a few times to test it and make sure that it is working as intended.
Try entering something that isn’t a number into the prompt and note what occurs
(and why). We will examine how to address this problem later in the semester, but
feel free to investigate it if you have time now.
• Write and test a few separate programs to do different conversions. (You will only
need to submit ONE but write as many as you are comfortable with).
Workshop Task
Task 4 – A Slightly Less Simple Program
• For a bit more of a challenge, let’s write a program with slightly more complex
processing. The code for this program will still follow the same basic structure of
obtaining input, performing arithmetic on it, and then displaying the result, but the
conversions/formulas are slightly more advanced. Again, you are welcome to
implement different conversions and formulas than the ones below.
Workshop Task
• Most of these programs will involve an additional statement or two in order to
prompt for all the necessary values or do additional calculations, but the logic behind
them is the same as before.
• Again, write a few of different programs and test them to ensure they are working
correctly. While it is a little bit redundant for such simple programs, write pseudocode
and draw flowcharts for the programs you create. How (if at all) does their design
differ from the design of previous programs?
• As a final exercise, enhance the output of all of the programs you have created by
using the built-in function round(). This function expects you to give it two
parameters – a number to round, and the number of digits to round it to. It returns
the number, rounded to the number of digits.
• Test it out by typing round(3.1416, 2) into the shell, then implement it in your
programs by using it on your result variables to round them to two decimal places.

• That’s all for this workshop. If you haven’t completed the workshop or readings, find
time to do so before next week’s class.

You might also like