0% found this document useful (0 votes)
12 views64 pages

Week 2 - Writing Programs

The document discusses programming concepts like designing programs, input/output, variables, data types, strings, and functions. It provides examples and explanations of these concepts to help a reader learn the basics of writing simple Python programs.

Uploaded by

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

Week 2 - Writing Programs

The document discusses programming concepts like designing programs, input/output, variables, data types, strings, and functions. It provides examples and explanations of these concepts to help a reader learn the basics of writing simple Python programs.

Uploaded by

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

WRITING A SIMPLE PROGRAM

WEEK 2

2-1
Topics (1 of 2)
• Designing a Program
• Input, Processing, and Output
• Displaying Output with print Function
• Comments
• Variables
• Reading Input from the Keyboard
• Performing Calculations
• String Concatenation
2-2
Topics (2 of 2)
• More About The print Function
• Displaying Formatted Output
• Named Constants

2-3
Designing a Program (1 of 3)
• Programs must be designed before they are written
• Program development cycle:
– Design the program
– Write the code
– Correct syntax errors
– Test the program
– Correct logic errors

2-4
Designing a Program (2 of 3)
• Design is the most important part of the program
development cycle
• Understand the task that the program is to perform
– Work with customer to get a sense what the program is
supposed to do
– Ask questions about program details
– Create one or more software requirements

2-5
Designing a Program (3 of 3)
• Determine the steps that must be taken to perform the
task
– Break down required task into a series of steps
– Create an algorithm, listing logical steps that must be
taken
• Algorithm: set of well-defined logical steps that must
be taken to perform a task

2-6
Example - Algorithm

2-7
Pseudocode
• Pseudocode: fake code
– Informal language that has no syntax rule
– Not meant to be compiled or executed
– Used to create model program
 No need to worry about syntax errors, can focus on
program’s design
 Can be translated directly into actual code in any
programming language

2-8
Flowcharts (1 of 2)
• Flowchart: diagram that graphically depicts the steps
in a program
– Ovals are terminal symbols
– Parallelograms are input and output symbols
– Rectangles are processing symbols
– Symbols are connected by arrows that represent the
flow of the program

2-9
Flowcharts (2 of 2)

Figure 2-2 The program development cycle

3 - 10
EXERCISE
• Create a flow chart based on the following Algorithm :

2 - 11
Input, Processing, and Output
• Typically, computer performs three-step process
– Receive input
 Input: any data that the program receives while it is
running
– Perform some process on the input
 Example: mathematical calculation
– Produce output

2 - 12
Displaying Output with the print
Function
• Function: piece of prewritten code that performs an
operation
• print function: displays output on the screen
• Argument: data given to a function
– Example: data that is printed to screen
• Statements in a program execute in the order that
they appear
– From top to bottom

2 - 13
Writing your First Program in Python

<----Type the Code

<----Press CTRL +Enter

Output

2 - 14
Comments in Python
• Comments: notes of explanation within a program
– Ignored by Python interpreter
 Intended for a person reading the program’s code
– Begin with a # character
• End-line comment: appears at the end of a line of
code
– Typically explains the purpose of that line

2 - 15
Comments - Example

2 - 16
Keywords in Python
• Keywords in Python are reserved words that can not
be used as a variable name, function name, or any
other identifier.

2 - 17
Variables
• Variable: name that represents a value stored in the
computer memory
– Used to access and manipulate data stored in memory
– A variable references the value it represents
• Assignment statement: used to create a variable and
make it reference data
– General format is variable = expression
 Example: age = 29
 Assignment operator: the equal sign (=)

2 - 18
Reassigning a Variable to a Different
Type
• A variable in Python can refer to items of any type

Figure 2-7 The variable x references an integer

Figure 2-8 The variable x references a string

2 - 19
Variables (cont’d.)
• Python Variable is containers that store values.
• An Example of a Variable in Python is a representational
name that serves as a pointer to an object.
• Once an object is assigned to a variable, it can be referred
to by that name.
• In assignment statement, variable receiving value must be
on left side
• A variable can be passed as an argument to a function
– Variable name should not be enclosed in quote marks

• You can only use a variable if a value is assigned to it


2 - 20
Variable Naming Rules
• Rules for naming variables in Python:
– A Python variable name must start with a letter or the
underscore character.
– A Python variable name cannot start with a number.
– A Python variable name can only contain alpha-
numeric characters and underscores (A-z, 0-9, and _ ).
– Variable in Python names are case-sensitive (name,
Name, and NAME are three different variables).
– The reserved words(keywords) in Python cannot be
used to name the variable in Python.

2 - 21
Example

2 - 22
Python Data Types
• Data types are the classification or categorization of
data items.
• It represents the kind of value that tells what
operations can be performed on a particular data.
• Since everything is an object in Python programming,
data types are classes and variables are instances
(objects) of these classes.

2 - 23
Python Data Types

2 - 24
Numeric Data Types, Literals, and the
str Data Type
• Data types: categorize value in memory
– e.g., int for integer, float for real number, str used for
storing strings in memory
• Numeric literal: number written in a program
– No decimal point considered int, otherwise, considered
float
• Some operations behave differently depending on
data type

2 - 25
Example
• This code assigns variable ‘x’ different values of
various data types in Python.

2 - 26
Type () Function
• type() function is used to determine the type of Python
data type.
Example: This code demonstrates how to
determine the data type of variables in
Python using the type() function.

It prints the data types of three variables:


a (integer),
b (float), and
c (complex).

The output shows the respective data type


Python for each variable.

2 - 27
Strings and String Literals
• String: sequence of characters that is used as data
• String literal: string that appears in actual code of a
program
– Must be enclosed in single (') or double (") quote marks
print("A Computer Science portal for geeks")
print('A')

– String literal can be enclosed in triple quotes (''' or """)


 Enclosed string can contain both single and double quotes and
can have multiple lines

2 - 28
Example
In this example, we will demonstrate different ways to create a Python String. We will
create a string using single quotes (‘ ‘), double quotes (” “), and triple double quotes (“””
“””).
The triple quotes can be used to declare multiline strings in Python.

2 - 29
Accessing Characters in Python String
• In Python, individual characters of a String can be accessed by using
the method of Indexing.
• Indexing allows negative address references to access characters
from the back of the String, e.g. -2 refers to the second last character,
and so on. -1 refers to the last character,
• While accessing an index out of the range will cause an IndexError.
Only Integers are allowed to be passed as an index, float or other
types that will cause a TypeError.

2 - 30
Example
• In this example, we will define a string in Python and
access its characters using positive and negative indexing.
• The 0th element will be the first character of the string
whereas the -1th element is the last character of the string.
# Python Program to Access
# characters of String Initial String:
GeeksForGeeks
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1) First character of String is:
G
# Printing First character
print("\nFirst character of String is: ")
print(String1[0]) Last character of String is:
s
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1]) 2 - 31
String Slicing
• In Python, the String Slicing method is used to access
a range of characters in the String.
• Slicing in a String is done by using a Slicing operator,
i.e., a colon (:).
• One thing to keep in mind while using this method is
that the string returned after slicing includes the
character at the start index but not the character at the
last index.

2 - 32
Example # Python Program to
# demonstrate String slicing
• In this example, we will use the
string-slicing method to extract # Creating a String
a substring of the original 1 String1 = "GeeksForGeeks"
string. print("Initial String: ")
print(String1)
• The [3:12] indicates that the
string slicing will start from the # Printing 3rd to 12th character
2 print("\nSlicing characters from 3
3rd index of the string to the
12th index, (12th character not 12: ")
print(String1[3:12])
including).
• We can also use negative 3 # Printing characters between
indexing in string slicing. # 3rd and 2nd last character
print("\nSlicing characters betwee
"+
"3rd and 2nd last character:
")
print(String1[3:-2])
2 - 33
Example
# Python Program to
# demonstrate String slicing

# Creating a String
String1 = "GeeksForGeeks" Initial String:
print("Initial String: ") 1
GeeksForGeeks
print(String1)

# Printing 3rd to 12th character


print("\nSlicing characters from 3-
12: ") Slicing characters from 3-12:
2
print(String1[3:12])
ksForGeek
# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between
"+ 3
"3rd and 2nd last character: Slicing characters between 3rd
") and 2nd last character:
print(String1[3:-2]) ksForGee
2 - 34
String Concatenation (1 of 2)
• To append one string to the end of another string
• Use the + operator to concatenate strings

>>> message = 'Hello ' + 'world'


>>> print(message)
Hello world
>>>

2 - 35
String Concatenation (2 of 2)
• You can use string concatenation to break up a long
string literal

print('Enter the amount of ' +


'sales for each day and ' +
'press Enter.')

This statement will display the following:

Enter the amount of sales for each day and press Enter.

2 - 36
Implicit String Literal Concatenation (1 of 2)
• Two or more string literals written adjacent to each
other are implicitly concatenated into a single string

>>> my_str = 'one' 'two' 'three'


>>> print(my_str)
onetwothree

2 - 37
Implicit String Literal Concatenation (2 of 2)

print('Enter the amount of '


'sales for each day and '
'press Enter.')

This statement will display the following:

Enter the amount of sales for each day and press Enter.

2 - 38
Python Indentation
• Python indentation refers to adding white space before a
statement to a particular block of code.
• In another word, all the statements with the same space to
the right, belong to the same code block.

2 - 39
Example 1
• The lines print(‘Logging on to
geeksforgeeks…’) and
print(‘retype the URL.’) are two
separate code blocks.
• The two blocks of code in our
example if-statement are both
indented four spaces.
• The final print(‘All set!’) is not
indented, so it does not belong to
the else block.

2 - 40
Example 2
To indicate a block of code in Python, you must
indent each line of the block by the same
whitespace.

The two lines of code in the while loop are both


indented four spaces. It is required for indicating
what block of code a statement belongs to.

For example, j=1 and while(j<=5): is not indented,


and so it is not within the Python while block.

So, Python code structures by indentation.

2 - 41
Input Function in Python
• Developers often need to interact with users, either to get
data or to provide some sort of result. Most programs
today use a dialog box as a way of asking the user to
provide some type of input.
• While Python provides us with two inbuilt functions to read
the input from the keyboard.
– input ( prompt )
– raw_input ( prompt )

2 - 42
Input ()
• input (): This function first takes the input from the
user and converts it into a string. The type of the
returned object always will be <class ‘str’>.
• It does not evaluate the expression it just returns
the complete statement as String.

2 - 43
Displaying Multiple Items with the
print Function
• Python allows one to display multiple items with a
single call to print
– Items are separated by commas when passed as
arguments
– Arguments displayed in the order they are passed to
the function
– Items are automatically separated by a space when
displayed on screen

2 - 44
Reading Input from the Keyboard
• Most programs need to read input from the user
• Built-in input function reads input from keyboard
– Returns the data as a string
– Format: variable = input(prompt)
 prompt is typically a string instructing user to enter a value
– Does not automatically display a space after the
prompt

2 - 45
Performing Calculations
• Math expression: performs calculation and gives a
value
– Math operator: tool for performing calculation
– Operands: values surrounding operator
 Variables can be used as operands
– Resulting value typically assigned to variable
• Two types of division:
– / operator performs floating point division
– // operator performs integer division
 Positive results truncated, negative rounded away from zero

2 - 46
Operator Precedence and Grouping
with Parentheses
• Python operator precedence:
1. Operations enclosed in parentheses
 Forces operations to be performed before others
2. Exponentiation (**)
3. Multiplication (*), division (/ and //), and remainder
(%)
4. Addition (+) and subtraction (-)
• Higher precedence performed first
– Same precedence operators execute from left to right

2 - 47
The Exponent Operator and the
Remainder Operator
• Exponent operator (**): Raises a number to a power
– x ** y = xy
• Remainder operator (%): Performs division and returns
the remainder
– a.k.a. modulus operator
– e.g., 4%2=0, 5%2=1
– Typically used to convert times and distances, and to
detect odd or even numbers

2 - 48
Converting Math Formulas to
Programming Statements
• Operator required for any mathematical operation
• When converting mathematical expression to
programming statement:
– May need to add multiplication operators
– May need to insert parentheses

2 - 49
Mixed-Type Expressions and Data Type
Conversion
• Data type resulting from math operation depends on
data types of operands
– Two int values: result is an int
– Two float values: result is a float
– int and float: int temporarily converted to float,
result of the operation is a float
 Mixed-type expression
– Type conversion of float to int causes truncation of
fractional part

2 - 50
More About The print Function (1 of 2)
• print function displays line of output
– Newline character at end of printed data
– Special argument end='delimiter' causes print
to place delimiter at end of data instead of newline
character
• print function uses space as item separator
– Special argument sep='delimiter' causes print
to use delimiter as item separator

2 - 51
More About The print Function (2 of 2)
• Special characters appearing in string literal
– Preceded by backslash (\)
 Examples: newline (\n), horizontal tab (\t)
– Treated as commands embedded in string

2 - 52
Displaying Formatted Output with
F-strings (1 of 8)
• An f-string is a special type of string literal that is
prefixed with the letter f
>>> print(f'Hello world')
Hello world

• F-strings support placeholders for variables

>>> name = 'Johnny'


>>> print(f'Hello {name}.')
Hello Johnny.

2 - 53
Displaying Formatted Output with
F-strings (2 of 8)
• Placeholders can also be expressions that are
evaluated

>>> print(f'The value is {10 + 2}.')


The value is 12.

>>> val = 10
>>> print(f'The value is {val + 2}.')
The value is 12.

2 - 54
Displaying Formatted Output with
F-strings (3 of 8)
• Format specifiers can be used with placeholders

>> num = 123.456789


>> print(f'{num:.2f}')
123.46
>>>

• .2f means:
– round the value to 2 decimal places
– display the value as a floating-point number

2 - 55
Displaying Formatted Output with
F-strings (4 of 8)
• Other examples:
>> num = 1000000.00
>> print(f'{num:,.2f}')
1,000,000.00

>>> discount = 0.5


>>> print(f'{discount:.0%}')
50%

2 - 56
Displaying Formatted Output with
F-strings (5 of 8)
• Other examples:
>> num = 123456789
>> print(f'{num:,d}')
123,456,789

>>> num = 12345.6789


>>> print(f'{num:.2e}')
1.23e+04

2 - 57
Displaying Formatted Output with
F-strings (6 of 8)
• Specifying a minimum field width:
>>> num = 12345.6789
>>> print(f'The number is {num:12,.2f}')
The number is 12,345.68
Field width = 12

The number is 12,345.68

Field width = 12

2 - 58
Displaying Formatted Output with
F-strings (7 of 8)
• Aligning values within a field
– Use < for left alignment
– Use > for right alignment
– Use ^ for center alignment

• Examples:
– print(f'{num:<20.2f}')
– print(f'{num:>20.2f}')
– print(f'{num:^20.2f}')

2 - 59
Displaying Formatted Output with
F-strings (8 of 8)
• The order of designators in a format specifier
– When using multiple designators in a format specifier, write them
in this order:

[alignment][width][,][.precision][type]

• Example:
– print(f'{number:^10,.2f}')

2 - 60
Magic Numbers
• A magic number is an unexplained numeric value that
appears in a program’s code. Example:

amount = balance * 0.069

• What is the value 0.069? An interest rate? A fee


percentage? Only the person who wrote the code
knows for sure.

2 - 61
The Problem with Magic Numbers
• It can be difficult to determine the purpose of the
number.
• If the magic number is used in multiple places in the
program, it can take a lot of effort to change the
number in each location, should the need arise.
• You take the risk of making a mistake each time you
type the magic number in the program’s code.
– For example, suppose you intend to type 0.069, but you
accidentally type .0069. This mistake will cause mathematical
errors that can be difficult to find.

2 - 62
Named Constants
• You should use named constants instead of magic
numbers.
• A named constant is a name that represents a value
that does not change during the program's execution.
• Example:
INTEREST_RATE = 0.069
• This creates a named constant named
INTEREST_RATE, assigned the value 0.069. It can be
used instead of the magic number:
amount = balance * INTEREST_RATE
2 - 63
Advantages of Using Named Constants
• Named constants make code self-explanatory (self-
documenting)
• Named constants make code easier to maintain
(change the value assigned to the constant, and the
new value takes effect everywhere the constant is
used)
• Named constants help prevent typographical errors
that are common when using magic numbers

2 - 64

You might also like