0% found this document useful (0 votes)
7 views15 pages

Python Programming Basics Guide

This document provides an introduction to Python programming, covering coding standards, data types, and basic programming constructs. It explains how to use Python Shell and Jupyter Notebook for writing and testing code, as well as the importance of comments, variables, and expressions. Additionally, it includes practical exercises and assignments to reinforce learning.

Uploaded by

wrongaryan1234
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 views15 pages

Python Programming Basics Guide

This document provides an introduction to Python programming, covering coding standards, data types, and basic programming constructs. It explains how to use Python Shell and Jupyter Notebook for writing and testing code, as well as the importance of comments, variables, and expressions. Additionally, it includes practical exercises and assignments to reinforce learning.

Uploaded by

wrongaryan1234
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

Hwa Chong Institution H2 Computing

2 Getting Started with Python


Learning Outcome
Coding Standards
 Use indentation and white space
 Use naming conventions (e.g. meaningful identifier names)
 Write comments (name of programmer, date written, program description and version
book-keeping/control)
Programming Elements and Constructs
 Understand the different data types: integer, real, char, string and Boolean
 Use common library functions for input/output, strings and mathematical operations
Character Encoding
 Give examples of where and how Unicode is used
 Use ASCII code in programs

Python is a high-level, general-purpose programming language for solving problems on


modern computer systems. The official online resources can be found at [Link], and
its popularity has generated many websites and YouTube channels for self-learning.

Three tools that we can use to write a program and test it.

Python Shell

After downloading Python, launch the IDLE to open a Python shell. Shell is useful for
experimenting with short expressions or statements to learn new features of the language.

Python File

When we need to construct complex programs and test them, we can create and save files in
program libraries to reuse or share with others.

Open a New File in Shell and save the program files use .py extention.

1
Hwa Chong Institution H2 Computing

We can then run Python program files within IDLE using menu option F5 for Windows.

Here is a sample program for your first experiment.

Then we run the file in Python Shell.

Running Jupyter Notebook on the school laptop

Look for Computing Software shortcut (shown below) on the desktop. Double click on the
shortcut to open Windows Explorer.

In Windows Explorer, a list of shortcuts is listed. Double click on the Jupyter Notebook
shortcut to launch the application.

2
Hwa Chong Institution H2 Computing

A console windows will be launch prior to the browser. Do not close the console windows.

Take note that the console windows should remain open for Jupyter Notebook to work.

Jupyter notebook home page will be shown in the browser. By default, the home page will
display the files on the desktop.

Jupyter Notebook File

These files are saved in .ipynb extension.

Click ‘New’ to create a new notebook in Python 3.

Type the codes and run it by clicking the ‘Run’ button, or pressing ‘Ctrl’ + ‘Enter’.

Here is the output.

The convenience of using Jupyter Notebook is that we can write multiple programs in one file,
by clicking the ‘+’ button.
3
Hwa Chong Institution H2 Computing

2.1 Comments and Docstrings

Programs should be easily understood and modifiable by any users, so we need to insert
comments to explain how we solve the problem and sometimes the meaning of the variable
names we defined.

Docstring for a paragraph of comments:

For short explanation, we use end-of-line comment with #:

2.2 Input and Output


Programs usually accept inputs from a source, process them, and output results to a destination.
In terminal-based interactive programs like Python, these are the keyboard and terminal display,
respectively.

To get input from keyboard, we use: <variable identifier> = input (<a string prompt>)

To generate the output, we use: print(<expression>)

Question: why is it different for name and print(name)?

4
Hwa Chong Institution H2 Computing

2.3 Data Types

In real life, we take many things as data, for example, integers, decimal numbers, characters,
words, paragraphs. However, in programming, we need to define and categorize them properly.

A data type consists of a set of values, a set of operations that can be performed on the values
and the way values can be stored on computers. Here we learn the Python way of defining data
types though other programming languages may have different names and categories.

2.3.1 Integers

 In real life, the range of integers is infinite.


 Computer’s memory places a limit on largest magnitude of integers
 Python’s int typical range is –231 to 231 – 1

2.3.2 Floating-Point Numbers

 Python uses floating-point numbers to represent real numbers


 Python’s float typical range: –10308 to 10308
 Typical precision: 16 digits

2.3.3 Characters and Strings

Characters in programming is not limited to the 26 English characters. It can also be space
character, question mark, Chinese character, etc.

A string is a sequence of characters. It can be a word, a sentence or a paragraph.

Text processing is by far the most common application of computing. E-mail, text messaging,
Web pages, and word processing all rely on and manipulate data consisting of strings of
characters. But computer only reads zeros and ones, so character sets are invented to use
numbers to represent English characters and notations we use. Unicode set and ASCII set are
common character sets in use. A bit is a binary digit, it can be a 1 or 0. So if we use seven bits,
we may have 27= 128 possible binary representation of numbers 0 - 127.

The original ASCII used seven bits to encode 128 different characters, as shown below.

5
Hwa Chong Institution H2 Computing

In Python, we use ord and chr to convert characters to and from ASCII.

There is surely no need to memorize the table but we might use it to traverse within all the
alphabets. For example, chr(ord('A')+5) gives ‘F’.

ASCII was further developed to eight bits to accommodate more characters. However, using
more digits takes more memory space as well.

Unicode was developed to use a variable bit encoding program and Unicode standard defines
UTF-8, UTF-16 and UTF-32. The large capacity of Unicode makes many non-English
languages available, e.g. Chinese and Japanese. Furthermore, ASCII is compatible with
Unicode.

2.3.4 Boolean
Boolean data type consists of two values: True and False

2.4 Literal

TYPE OF DATA PYTHON TYPE NAME EXAMPLE LITERALS


Integers int -1, 0, 1, 2, 3420000556008
Real numbers float -0.55, .333, 3.14, 6.0
Character strings str “Hi”, “ “, ‘A’, ’66’

6
Hwa Chong Institution H2 Computing

 A literal is the way a value of a data type looks to a programmer.


 In Python, a string literal is a sequence of characters enclosed in single or double
quotation marks
 '' and "" represent the empty string
 Use ''' and """ for multi-line paragraphs

Press ‘Enter’
here to get
to next line

2.5 Escape Sequences

2.6 Variables and the Assignment Statement

A variable associates a name with a value to make it easy to remember and use later. Variable
naming rules:

– Reserved words cannot be used as variable names. Examples: if, def, import
– Name must begin with a letter or _
– Name can contain any number of letters, digits, or _
– Names are case sensitive. Example: WEIGHT is different from weight
– All uppercase letters for symbolic constants. Examples: TAX_RATE
– “camel casing”. Example: InterestRate
– Short names are preferred. If necessary, we can write comments to explain short forms.

Variables receive initial values, and can be reset to new values with an assignment statement.

<variable name> = <expression>

Subsequent uses of the variable name in expressions are known as variable references.
7
Hwa Chong Institution H2 Computing

2.7 Expressions

 A literal evaluates to itself


 A variable reference evaluates to the variable’s current value
 Expressions provide easy way to perform operations on data values to produce other values
 When entered at Python shell prompt, expression’s operands are evaluated and its operator
is then applied to these values to compute the value of the expression

2.7.1 Arithmetic Expressions

An arithmetic expression consists of operands and operators combined in a manner that is


already familiar to you in mathematics.

OPERATOR MEANING SYNTAX


** Exponentiation a ** b
− Negation −a
* Multiplication a*b
/ Division a/b
// Quotient a // b
% Remainder or modulus a%b
+ Addition a+b
− Subtraction a−b

Precedence rules of operators:

 ** has the highest precedence and is evaluated first


 Unary negation is evaluated next
 *, /, //, and % are evaluated before + and −
 + and − are evaluated before =
 With two exceptions, operations of equal precedence are left associative, so they are
evaluated from left to right (** and = are right associative)
 You can use () to change the order of evaluation

EXPRESSION EVALUATION VALUE


5+3*2 5+6 11
(5 + 3) * 2 8*2 16
6%2 3 0
2 * 3 ** 2 2*9 18
− 3 ** 2 − (3 ** 2) −9
8
Hwa Chong Institution H2 Computing

2**3 **2 2 ** 9 512


(2** 3) ** 2 8 ** 2 64
45 / 0 Error: cannot divide by 0
45 % 0 Error: cannot divide by 0
3.14*3**2 3.14*(3**2) 28.26

Quotient VS Division:

2.7.2 Augmented Assignment

Standard formatting

can be shortened to

Augmented assignment operations:

2.7.3 String Concatenation

You can join two or more strings to form a new string using the concatenation operator +.
The * operator allows you to build a string by repeating another string a given number of times

2.7.4 Type Conversions

Sometimes, we need to convert between data types for calculation or formatting.

9
Hwa Chong Institution H2 Computing

CONVERSION FUNCTION EXAMPLE USE VALUE RETURNED


int(<a number or a string>) int(3.77) 3
int("33") 33
float(<a number or a string>) float(22) 22.0
str(<any value>) str(99) ‘99’

Note that the int function converts a float to an int by truncation, not by rounding.

 Construction of strings from numbers and other strings.

Solution: use str function

 Input data type is string by default.

Solution: use int or float function

10
Hwa Chong Institution H2 Computing

2.8 Formatting Text for Output

 Many data-processing applications require output that has tabular format


 Field width: Total number of data characters and additional spaces for a datum in a
formatted string

Version 1: Using %

 This version contains format string, format operator %, and single data value to be
formatted
 To format integers, letter d is used instead of s

2.8.1 Format Sequence of Data Values

Notice there are six spaces between the two numbers.

2.8.2 Format Data Values of Type Float

where .<precision> is optional

11
Hwa Chong Institution H2 Computing

Version 2: Using format()

<string>.format (<datum-1>,…, <datum-n>)

The string can contain literal text or replacement fields delimited by braces {}.

Aligning the text and specifying a width

Format data values of type Float

{:<field width>.<precision>f}

12
Hwa Chong Institution H2 Computing

2.9 Using Functions and Modules


Python includes many useful functions, which are organized in libraries of code called modules.

2.9.1 Calling Functions: Arguments and Return Values

 A function is chunk of code that can be called by name to perform a task


 Functions often require arguments or parameters
 When function completes its task, it may return a value back to the part of the program
that called it

2.9.2 The math Module

To use a resource from a module, you write the name of a module as a qualifier, followed by a
dot (.) and the name of the resource.

You can avoid the use of the qualifier with each reference by importing the individual resources

You may import all of a module’s resources to use without the qualifier.

13
Hwa Chong Institution H2 Computing

2.9.3 The Main Module


Like any module, the main module can be imported.

We save the first file [Link] in the libraries of Python, and it can be imported directly.

2.9.4 Program Format and Structure

 Start with comment in the form of a docstring, including author’s name, purpose of program,
and other relevant information
 Then, include statements that:
– Import any modules needed by program
– Initialize important variables, suitably commented
– Prompt the user for input data and save the input data in variables
– Process the inputs to produce the results
– Display the results

Tutorial 2

1. Let the variable x be "dog" and the variable y be "cat". Write the values returned by the
following operations:
Operations Values Returned
x + y
"the" + x + "chase the" + y
x*4
print(x + y)
print(x,y)

2. Test the output below for round and int.


Code Output
round(10.6)
int(10.6)
round(10.666,2)

14
Hwa Chong Institution H2 Computing

3. Assume that the variable amount refers to 24.325. Write the output of the following
statements:
(a) print ("Your salary is $%0.2f" % amount)

(b) print ("The area is %0.1f" % amount)

(c) print ("%7f" % amount)

(d) print ("BMI btw {:f} and {:2.3f} is ideal".format(18.5,amount))

(e) print ("Overweight ={:>7.2f} – {:.2f}".format(amount, 29.9))

4. Write a code segment that displays the values of the integers x, y, and z on a single line,
such that each value is right-justified in 6 columns.

5. The math module includes a pow function that raises a number to a given power. The first
argument is the number and the second argument is the exponent. Write a code segment
that imports this function and calls it to print the value 82.

Assignment 2

1. Write a program that accepts the user’s name (as text) and age (as an integer) as input. The
program should output a sentence containing the user’s name and current age, and age in
10 years’ time.

2. Write a program that takes the radius of a sphere (a floating-point number) as input and
output the sphere’s diameter, circumference, surface area, and volume.

3. An employee’s total weekly pay equals the hourly wage multiplied by the total number of
regular hours plus overtime pay. Overtime pay equals the overtime hours multiplied by 1.5
times the hourly wage. Write a program that takes as inputs the hourly wage, total regular
hours, and total overtime hours and display an employee’s total weekly pay (round to the
nearest dollar).

15

You might also like