Variable, Conditional Structure and
Looping
Pertemuan 4
Pemrograman Komputer
Genap 2021/2022
Variables
Variable names don’t have static types –
values (or objects) do
• A variable name has the type of the value it
currently references
Variables actually contain references to
values (similar to pointers).
• This makes it possible to assign different object
types to the same variable
2
Variables contain references to data values
A 3.5
A=A*2 A 3.5
A = “cat”
7.0
“cat”
• Python handles memory management automatically. It will create new objects
and store them in memory; it will also execute garbage collection algorithms to
reclaim any inaccessible memory locations.
• Python does not implement reference semantics for simple variables; if A = 10 and
B = A, A = A + 1 does not change the value of B
3
Elements of programs: Names
BUT you and for raise
can’t use as from return
Python assert global try
keywords break if while
(reserved class import with
words) as continue in yield
names. def is
These are: del lambda
elif nonlocal
False else not
None except or
True finally pass
4
• Numeric types: integer, floats,
complex
• A literal with a decimal point is
a float; otherwise an integer
• Complex numbers use “j” or “J”
Basic Data Types to designate the imaginary
part: x = 5 + 2j
• type() returns the type of
any data value:
5
Data Types
type(15) 1j * 1j
<class 'int'> (-1+0j)
type (3.) s = 3 + 1j
<class 'float'> type(s)
<class 'complex'>
x = 34.8
type(x) x = "learning”
<class 'float'> type(x)
<class 'str'>
6
An expression calculates a value
Arithmetic operators: +, -, *, /, ** (exponentiation)
Expressions Add, subtract, multiply, divide work just as they do
in other C-style languages
Spaces in an expression are not significant
Parentheses override normal precedence
• Mixed type (integer and float) expressions are converted to
floats:
4 * 2.0 /6
1.3333333333333333
• Mixed type (real and imaginary) conversions:
x = 5 + 13j
Expressions y = 3.2
z=x+y
z
(8.2 + 13J )
• Explicit casts are also supported:
y = 4.999 x=8
int(y) float(x)
4 8.0
8
• Statement syntax: (EBNF notation)
print ({expression,})
where the final comma in the list is optional
• Examples:
Output Statements print() # prints a blank line
3.x version print(3, y, z + 10) #go to new
line
print('result: ',z,end=" ")# no
newline
• Output items are automatically separated by a
single space.
9
• Syntax: Assignment → variable = expression
• A variable’s type is determined by the type of the value assigned to
it.
• Multiple_assign →var{, var} = expr{, expr)
>>> x, y = 4, 7
Assignment >>> x
4
Statements
>>> y
7
>>> x, y = y, x
>>> x
7
>>> y
4
>>>
10
Interactive Input
• Syntax: input → variable = input(string)
The string is used as a prompt.
Inputs a string
>>> y = input("enter a name --> ")
enter a name --> max
>>> y
'max'
>>> number = input("Enter an integer ")
Enter an integer 32
>>> number
’32’
• input() reads input from the keyboard as a string;
11
Input
Input
• Multiple inputs:
>>> x, y = int(input("enter an integer: ")),
float(input("enter a float: "))
enter an integer: 3
enter a float: 4.5
>>> print("x is", x, " y is ", y)
x is 3 y is 4.5
• Instead of the cast you can use the eval( ) function and Python choose the correct types:
>>> x, y = eval(input("Enter two numbers: "))
Enter two numbers: 3.7, 98
>>> x, y
(3.7, 98)
13
Python Control Structures
• Python loop types:
• while
• for
• Decision statements:
• if
• Related features:
• range( ) # a function
• break # statements similar to
• continue # those in C/C++
14
General Information
• The control structure statement must end with a
semicolon (:)
• The first statement in the body of a loop must be
indented.
• All other statements must be indented by the same
amount
• To terminate a loop body, enter a blank line or
“unindent”.
15
If Statement
• Python if statement has three versions:
• The if (only one option)
• The if-else (two options)
• The if-elif-else (three or more options)
• The if-elif-else substitutes for the switch
statement in other languages.
• Each part must be followed with a semicolon and
whitespace is used as the delimiter.
16
If-elif-else Statement
x = int(input("enter an integer: “))
if x < 0:
print (‘Negative’)
elif x == 0:
print ('Zero‘)
elif x == 1:
print ('Single')
else:
print ('More' )
17
Right way Wrong way
if x < 0: >>> if x < 0:
y=x y=x
elif x == 0: elif x == 0:
y=1 y=1
elif x < 10:
elif x < 10:
y = 100
y = 100
else:
else:
print("none ")
print("none”)
SyntaxError: unindent does not
(you may have to override the match any outer indentation
IDLE indentation) level (<pyshell#86>, line 3)
18
REPETITION CAN BE USEFUL!
Sometimes you want to do the same thing several times.
Or do something very similar many times.
One way to do this is with repetition:
print 1
print 2
print 3
print 4
print 5
print 6
print 7
print 8
print 9
print 10
19
LOOPING, A BETTER FORM OF
REPETITION.
Repetition is OK for small numbers, but when you have to do something
many, many times, it takes a very long time to type all those commands.
We can use a loop to make the computer do the work for us.
One type of loop is the “while” loop. The while loop repeats a block of
code until a boolean expression is no longer true.
Syntax:
while (boolean expression) :
STATEMENT
STATEMENT
STATEMENT
20
While Loop
>>> x = 0
>>> while (x < 10): # remember semicolon!
print(x, end = " ")#no new line
x = x + 1
0 1 2 3 4 5 6 7 8 9
21
HOW TO STOP LOOPING!
It is very easy to loop forever:
while ( True) :
print “again, and again, and again”
The hard part is to stop the loop!
Two ways to do that is by using a loop counter, or a termination test.
A loop counter is a variable that keeps track of how many times you have
gone through the loop, and the boolean expression is designed to stop the
loop when a specific number of times have gone bye.
A termination test checks for a specific condition, and when it happens, ends
the loop. (But does not guarantee that the loop will end.)
22
LOOP COUNTER
timesThroughLoop = 0
while (timesThroughLoop < 10):
print “This is time”, timesThroughLoop, “in the loop.”
timesThroughLoop = timesThroughLoop + 1
Notice that we:
Initialize the loop counter (to zero)
Test the loop counter in the boolean expression (is it smaller than 10, if yes, keep looping)
Increment the loop counter (add one to it) every time we go through the loop
If we miss any of the three, the loop will NEVER stop!
23
WHILE LOOP EXAMPLE, WITH A
TERMINATION TEST
Keeps asking the user for their name, until the user types “quit”.
keepGoing = True
while (keepGoing):
userName = input(“Enter your name! (or quit to exit)” )
if userName == “quit”:
keepGoing = False
else:
print (“Nice to meet you, “ + username)
print (“Goodbye!”)
24
For Loops
• Syntax:
for <var> in <sequence>:
<body>
• <sequence> can be a list of values or it can be defined by the range( ) function
• range(n) produces a list of values: 0, 1, …,n-1
• range(start, n): begins at start instead of 0
• range(start, n, step): uses step as the increment
25
>>> for i in range(3):
print(i,end = " ")
012
>>> for i in range(5,10):
print(i,end = " ")
56789
>>> for i in range(6,12,2):
print(i)
6
8
10
>>> for i in (1, 2, 3):
print(i)
1
2
3
26
Ranges can also be specified using expressions:
>>> n = 5
>>> for i in range(2*n + 3):
print(i,end = “ “)
0 1 2 3 4 5 6 7 8 9 10 11 12
27
Using a List in a for loop
Lists are enclosed in square brackets
>>> for i in [3, 2, 1]:
print(i,end = " ")
3 2 1
>>> for i in ['cat', 'dog', 'elephant']:
print(i,end = " ")
cat dog elephant
28