Ha Khanh Nguyen (hknguyen)
x
, y
, z
. Find the smallest even number among them and store it in a variable called result
. If none of them is even, then result = -1
. Note that they are all positive numbers.even = []
if x % 2 == 0:
even.append(x)
if y % 2 == 0:
even.append(y)
if z % 2 == 0:
even.append(z)
if even == []:
result = -1
else:
result = min(even)
if
statements, each for each number. That's tedious but doable.for
Loops¶for
loops are for iterating over a list of objects (or a collection of objects or an iterater).for
loop is:for value in list:
# do something with value
nums = [5, 2, 9, 14, 3]
for i in nums:
print(i)
5 2 9 14 3
nums = [5, 2, 9, 14, 3]
sum = 0
for i in nums:
if i % 2 == 0:
sum = sum + i
sum
16
for
loop for the smallest even problem¶nums
.even = []
for i in nums:
if i % 2 == 0:
even.append(i)
if even == []:
result = -1
else:
result = min(even)
for
loop with strings¶for
loop works very well with string!s = 'hello'
for c in s:
print(c)
h e l l o
s
containing a mathematical expression with 2 operands and an addition. For example, s = '3+2.5'
. There is no space between the number (operand) and the operator. Write a Python program to evaluate the expression and store the result in a variable named result
.# method 1
temp = ''
for c in s:
if c == '+':
num1 = float(temp)
temp = ''
else:
temp = temp + c
num2 = float(temp)
result = num1 + num2
split()
function in Python splits a string by a specified delimiter.'hello'.split('e')
['h', 'llo']
s
by +
!# method 2
nums = s.split('+')
result = float(nums[0]) + float(nums[1])
range()
function¶range()
function in Python returns an iterator that yields a sequence of evenly spaced integers.range(10)
range(0, 10)
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range()
function is: range(start, end, step)
list(range(0, 20, 2))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
list(range(5, 0, -1))
[5, 4, 3, 2, 1]
nums = [5, 2, 9, 14, 3]
total = 0
for i in range(len(nums)):
if nums[i] % 2 == 0:
total = total + nums[i]
total
16
total2 = 0
for i in nums:
if i % 2 == 0:
total2 = total2 + i
total2
16
while
Loops¶while
loop specifies a condition and a block of code that is to be executed until the condition evaluates to False
or the loop is explicitly ended with break
.nums = [1, 14, 3, 7, 32, 19, 4]
i = 0
total = 0
while total < 20:
total = total + nums[i]
i = i + 1
total
25
break
keyword is extremely useful in cases like this:nums = [1, 1, 3, 2, 2, 1, 4]
i = 0
total = 0
while total < 20:
total = total + nums[i]
i = i + 1
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-12-6acf41fe9194> in <module> 3 total = 0 4 while total < 20: ----> 5 total = total + nums[i] 6 i = i + 1 IndexError: list index out of range
nums = [1, 1, 3, 2, 2, 1, 4]
i = 0
total = 0
while total < 20:
if i == len(nums):
break
total = total + nums[i]
i = i + 1
total
14