Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Lab02 Python2

Uploaded by

letrungbao2502bt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lab02 Python2

Uploaded by

letrungbao2502bt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Ton Duc Thang University

Faculty of Information Technology

Applied Calculus for IT - 501031


Python tutorial 02

1. Python Indentation
Indentation refers to the spaces at the beginning of a code line. The indentation in Python is very
important, and it indicate a block of code.
- Example:

- Python will give you an error if you skip the indentation:

The content of error is: IndentationError: expected an indented block

- The number of spaces is up to you as a programmer, but it has to be at least one.

- You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error:

The content of error is: IndentationError: unexpected indent

Trinh Hung Cuong - Applied Calculus for IT - 501031 1/13


Ton Duc Thang University
Faculty of Information Technology
2. Python Conditions and If statements
- Python supports the usual logical conditions from mathematics, for ex., a == b, a != b, a > b, …
These conditions can be used in several ways, most commonly in "if statements" and loops.

- Python relies on indentation (whitespace at the beginning of a line) to define scope in the code.
If statement, without indentation (will raise an error):

- The elif keyword is pythons way of saying "if the previous conditions were not true, then try
this condition":

- The else keyword catches anything which isn't caught by the preceding conditions:

Trinh Hung Cuong - Applied Calculus for IT - 501031 2/13


Ton Duc Thang University
Faculty of Information Technology

- The and/or keyword is a logical operator, and is used to combine conditional statements:

- You can have if statements inside if statements, this is called nested if statements:

3. Python Functions
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result.
To call a function, use the function name followed by parenthesis, and then parameters can be
passed inside the parentheses.

print(“sum of a and b:”)


range(1, 10, 3)
Trinh Hung Cuong - Applied Calculus for IT - 501031 3/13
Ton Duc Thang University
Faculty of Information Technology
4. Python Lists
- Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are
Tuple, Set, and Dictionary, all with different qualities and usage.
- Lists are created using square brackets:

- List items are ordered, changeable, and allow duplicate values.


- To determine how many items a list has, use the len() function:

- A list can contain different data types:

- List items are indexed and you can access them by referring to the index number (the first item
has index [0], the second item has index [1]):

- To add an item to the end of the list, use the append() method:

Trinh Hung Cuong - Applied Calculus for IT - 501031 4/13


Ton Duc Thang University
Faculty of Information Technology
- To insert a list item at a specified index, use the insert() method:

- The remove() method removes the specified item:

- The pop() method removes the specified index:

- range() function: returns a sequence of integer numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
o Syntax: range(start, stop, step)
o Parameter:
▪ start: [ optional ] start value of the sequence, default is 0
▪ stop: next value after the end value of the sequence
▪ step: [ optional ] denoting the difference between any two numbers in the
sequence, default is 1
o Return: Returns a range type object.

o 1 parameter form: range(stop)

Trinh Hung Cuong - Applied Calculus for IT - 501031 5/13


Ton Duc Thang University
Faculty of Information Technology
o 2 parameter form: range(start, stop)

o 3 parameter form: range(start, stop, step)

https://cs.stanford.edu/people/nick/py/python-range.html
- in Keyword
o used to check if a value is present in a sequence (list, range, string etc.).
o used to iterate through a sequence in a for loop

Trinh Hung Cuong - Applied Calculus for IT - 501031 6/13


Ton Duc Thang University
Faculty of Information Technology
5. Python for loops
- A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string):

arr = [7, 3, 2, 10]


for x in arr:
print(x)

for i in range( len(arr) ):


print( arr[i] )

- To loop through a set of code a specified number of times, we can use the range() function:
for i in range(5):
print("Hello world!")

- The break statement


With the break statement we can stop the loop before it has looped through all the items:

Trinh Hung Cuong - Applied Calculus for IT - 501031 7/13


Ton Duc Thang University
Faculty of Information Technology
- The continue statement
With the continue statement we can stop the current iteration of the loop, and continue with the
next:

- Nested Loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each
iteration of the "outer loop":

- Practice examples:

#Print each even number in the array


arr = [7, 3, 2, 10, 5, 0]
for x in arr:
if x % 2 == 0:
print(x)

#Print each even number between 0 and 10 (both included)


for x in range(11):
if x % 2 == 0:
print("ex2", x)

Trinh Hung Cuong - Applied Calculus for IT - 501031 8/13


Ton Duc Thang University
Faculty of Information Technology

Exercise 1
Write a Python program to print odd numbers between 50 and 100.

Exercise 2
Write a Python program to print the integer numbers which are divisible by 7 and multiple of 5,
between 1500 and 2700 (both included).

Exercise 3
Write a Python program to prints all the integer numbers from 0 to 20 except 3 and 16. Note : Use
'continue' statement.

Exercise 4
Write a Python program to to count the number of even and odd numbers from a series of
numbers.
Sample numbers : numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Output :
Number of even numbers : 5
Number of odd numbers : 4

Exercise 5
Write a Python program to calculate the following expression:
1 2 3 99
𝑀 = + + + ⋯+
2 3 4 100

6. Python Tuples
- Tuples are used to store multiple items in a single variable.
- A tuple is a collection which is ordered and unchangeable.
- Tuples are written with round brackets.

https://www.w3schools.com/python/python_tuples.asp

Trinh Hung Cuong - Applied Calculus for IT - 501031 9/13


Ton Duc Thang University
Faculty of Information Technology
7. Python NumPy
7.1 NumPy Introduction
In Python we have lists that serve the purpose of arrays, but they are slow to process. NumPy aims to
provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy.
7.2 Installation of NumPy
If you have Python and PIP already installed on a system, install it using this command:

python -m pip install numpy


If these commands fails, then use a python distribution that already has NumPy installed like,
Anaconda, Spyder etc.
NumPy is usually imported under the np alias. In Python alias are an alternate name for referring to
the same thing. Create an alias with the as keyword while importing:

Now the NumPy package can be referred to as np instead of numpy.

7.3 Creating and accessing Numpy array


Create a NumPy ndarray object by using the array() function:

Trinh Hung Cuong - Applied Calculus for IT - 501031 10/


13
Ton Duc Thang University
Faculty of Information Technology
The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second
has index 1 etc.:

7.4 Arithmetic Operators


You can perform arithmetic operations on these arrays. For example, if you add the arrays, the
arithmetic operator will work element-wise. The output will be an array of the same dimension.
import numpy as np

array1 = np.array([10,20,30,40,50])
array2 = np.arange(5)

print(array1 + array2)
print(array1 - array2)
print(array1 * array2)
Trinh Hung Cuong - Applied Calculus for IT - 501031 11/
13
Ton Duc Thang University
Faculty of Information Technology
print(array1*2)
print(array2**2)
Source: https://www.pluralsight.com/guides/overview-basic-numpy-operations

7.5 numpy.arange funtions


arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per
the interval. The interval mentioned is half-opened i.e. [Start, Stop)
Parameters:
o start : [optional] start of interval range. By default start = 0
o stop : end of interval range
o step : [optional] step size of interval. By default step size = 1. For any output out, this
is the distance between two adjacent values, out[i+1] - out[i].
o dtype : type of output array
The advantage of numpy.arange() over the normal in-built range() function is that it allows us
to generate sequences of numbers that are not integers.

import numpy as np

# Printing all numbers from 1 to 2 in steps of 0.1


print(np.arange(1, 2, 0.1))

https://numpy.org/doc/stable/reference/generated/numpy.arange.html

Trinh Hung Cuong - Applied Calculus for IT - 501031 12/


13
Ton Duc Thang University
Faculty of Information Technology
import numpy as np

#Print each even number in the array


arr = np.array([7, 3, 2, 10, 5, 0])
for x in arr:
if x % 2 == 0:
print(x)

#Print each even number between 0 and 10 (both included)


for x in np.arange(11):
if x % 2 == 0:
print("ex2", x)

For more usages, visit the website: https://www.w3schools.com/python/numpy/default.asp

Exercise 6
Write a NumPy program to create an array with integer values ranging from 12 to 38.

Exercise 7
Write a NumPy program to print common values between two arrays.

8. References
- Python Tutorial on the W3schools website: https://www.w3schools.com/python/default.asp
- Python Tutorial on the Tutorials Point website:
https://www.tutorialspoint.com/python/index.htm

-- THE END --

Trinh Hung Cuong - Applied Calculus for IT - 501031 13/


13

You might also like