CSE488_Lab2_PythonWorld
CSE488_Lab2_PythonWorld
Objectives:
Introduce the main properties of Python language
Introduce the basics of Python:
o Variables and datatypes
o Arithmetic Operators
o Loops
o If statement
o Data structures
List
Tuples
Dictionaries
o Function definition
o Class definition
Extending Python using packages
Python Basics
Python is a high-level, dynamically typed multiparadigm programming language.
Python code is often said to be almost like pseudocode, since it allows you to express
very powerful ideas in very few lines of code while being very readable. This tutorial
gives you an overview of the entire Python world. First you will read a description of the
Python language and its unique characteristics. You’ll see where to start, what an
interpreter is, and how to begin writing the first lines of code in Python. Then you are
presented with some new, more advanced, forms of interactive writing with respect to
the shells, such as IPython and IPython Notebook.
This language can be characterized by a series of adjectives:
Interpreted
Portable
Object-oriented
Interactive
Interfaced
Open source
Easy to understand and use
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #02: Python Basics
Interpreter Vs Compiler
print(type(var1))
print(type(var2))
print(type(var3))
<class 'int'>
<class 'float'>
<class 'str'>
Spaces are not allowed in variable names, but underscores can be used to
separate words in variable names. For example, user_name works, but user name
will cause errors.
Avoid using Python keywords and function names as variable names; that is, do
not use words that Python has reserved for a particular programmatic purpose,
such as the word if.
Variable names should be short but descriptive. For example, name is better than
n, student_name is better than s_n, and name_length is better than
length_of_persons_name.
Be careful when using the lowercase letter l and the uppercase letter O because
they could be confused with the numbers 1 and 0.
Arithmetic operations
Common arithmetic operations such as +, -, /, and * can be used as usual in Python.
Other operators such as:
exponent operator ** performs exponential (power) calculation on operators.
Modulus operator % divides left hand operand by right hand operand and returns
remainder.
Floor Division // - The division of operands where the result is the quotient in
which the digits after the decimal point are removed. But if one of the operands
is negative, the result is floored, i.e., rounded away from zero (towards negative
infinity)
print(4**3) #Perform power calculation
Lists
The type list is a data structure that contains a number of objects in a precise order to
form a sequence to which elements can be added and removed. Each item is marked
with a number corresponding to the order of the sequence, called the index.
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #02: Python Basics
numbers = [1, 2, 3, 4]
print(numbers)
elements= ['chair', 'desk', 'wall']
print(elements)
[1, 2, 3, 4]
['chair', 'desk', 'wall']
If you want to access the individual elements, it is sufficient to specify the index in
square brackets (the first item in the list has 0 as its index):
elements[0]
'chair'
If you are using negative indices instead, this means you are considering the last item in
the list and gradually moving to the first.
numbers[-2]
3
You can create a list of numbers using the range function which take arguments as
(start, end, step)
numbers = list(range(5))
print(numbers)
even_numbers = list(range(2,11,2))
print(even_numbers)
[0, 1, 2, 3, 4]
[2, 4, 6, 8, 10]
Note that the upper limit of the range is not included into the list as the range function
exclude the final element from the list.
elements.insert(1,"fan")
print(elements)
[0, 1, 2, 3, 4, 5]
['chair', 'fan', 'desk', 'wall']
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #02: Python Basics
There are many methods to remove items form the list in python, each one has its own
properties.
- You can use del method to delete item from the list if you know its index.
- Another method is pop which removes the item from the list and return it as an output
of the function.
- Function remove is used when you want to remove item using its value not its index.
del numbers[1]
print(numbers)
[0, 2, 3, 4, 5]
last_item = numbers.pop()
print(last_item)
print(numbers)
second_item = numbers.pop(1)
print(second_item)
print(numbers)
5
[0, 2, 3, 4]
2
[0, 3, 4]
print(elements)
elements.remove('chair')
print(elements)
['chair', 'fan', 'desk', 'wall']
['fan', 'desk', 'wall']
for i in range(3):
print(animals[i].upper()+ " would make a great pet")
Note that the indentation is essential in python code. In Python indentation plays an
integral role in the implementation of the code, by dividing it into logical blocks.
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #02: Python Basics
for i in range(3):
print(animals[i].upper() + " would make a great pet")
List Comprehension
A list comprehension allows you to generate this same list in just one line of code. A list
comprehension combines the for loop and the creation of new elements into one line,
and automatically appends each new element.
squares= [value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Slicing a List
You can also work with a specific group of items in a list, which Python calls a slice. To
make a slice, you specify the index of the first and last elements you want to work with.
As with the range() function, Python stops one item before the second index you
specify. To output the first three elements in a list, you would request indices 0 through
3, which would return elements 0, 1, and 2.
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[0:3] #Items of index 0 to 2
['cairo', 'rome', 'paris']
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[1:4] #Items of index 1 to 3
['rome', 'paris', 'london']
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[:4] #Items from the beginning to index 3
['cairo', 'rome', 'paris', 'london']
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[2:] #Items from the index 2 to the end of list
['paris', 'london', 'madrid']
cities = ['cairo', 'rome', 'paris', 'london', 'madrid']
cities[-3:] #Last three items
['paris', 'london', 'madrid']
Tuples
Lists work well for storing sets of items that can change throughout the life of a
program. The ability to modify lists is particularly important when you’re working with
a list of users on a website or a list of characters in a game. However, sometimes you’ll
want to create a list of items that cannot change. Tuples allow you to do just that.
Python refers to values that cannot change as immutable, and an immutable list is
called a tuple.
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #02: Python Basics
A tuple looks just like a list except you use parentheses instead of square brackets. Once
you define a tuple, you can access individual elements by using each item’s index, just as
you would for a list.
dimensions = (400, 50)
print(dimensions[0])
print(dimensions[1])
400
50
dimensions[0] = 200
--------------------------------------------------------------------------
-
<ipython-input-24-dbb7433ce5e9> in <module>
----> 1 dimensions[0] = 200
The code tried to change the value of the first dimension, but Python returned a type
error. Basically, because we’re trying to alter a tuple, which can’t be done to that type of
object, Python tells us we can’t assign a new value to an item in a tuple. If you want to
change a value in tuple you have to define a new tuple and assign it to the same variable
as follows:
dimensions = (250,50)
print(dimensions[0])
print(dimensions[1])
If Statement
The following short example shows how if tests let you respond to special situations
correctly. Imagine you have a list of cars and you want to print out the name of each car.
Car names are proper names, so the names of most cars should be printed in title case.
However, the value 'bmw' should be printed in all uppercase. The following code loops
through a list of car names and looks for the value 'bmw'. Whenever the value is 'bmw',
it’s printed in uppercase instead of title case:
cars = ['audi', 'bmw', 'subaru', 'toyota']
for var in cars:
if var == 'bmw':
print(var.upper())
else:
print(var.title())
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #02: Python Basics
else if statements
age = 20
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
Your admission cost is $10.
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #02: Python Basics
Dictionaries
The type dictionary, defined also as dicts, is a data structure in which each particular
value is associated with a particular label, called a key. A dictionary in Python is a
collection of key-value pairs. Each key is connected to a value, and you can use a key to
access the value associated with that key. A key’s value can be a number, a string, a list,
or even another dictionary. In fact, you can use any object that you can create in Python
as a value in a dictionary.
In Python, a dictionary is wrapped in braces, {}, with a series of key-value pairs inside
the braces, Every key is connected to its value by a colon, and individual key-value pairs
are separated by commas. You can store as many key-value pairs as you want in a
dictionary.
user = {'name':'William', 'age':25, 'city':'London'}
user['name']
'William'
The previous example involved storing different kinds of information about one object.
You can also use a dictionary to store one kind of information about many objects. For
example, say you want to poll a number of people and ask them what their favorite
color is. A dictionary is useful for storing the results of a simple poll, like this:
favorite_colors = {
'Mohamed': 'blue',
'Sarah': 'orange',
'Ali': 'green',
'Ahmed': 'blue',
}
print(favorite_colors)
{'Mohamed': 'blue', 'Sarah': 'orange', 'Ali': 'green', 'Ahmed': 'blue'}
two variables. This code would work just as well if you had used abbreviations for the
variable names, like this:
for key,value in favorite_colors.items():
print(key + "'s favorite color is " +value)
Mohamed's favorite color is blue
Sarah's favorite color is orange
Ali's favorite color is green
Ahmed's favorite color is blue
The same can be done to loop through dictionary values when keys are not needed:
for color in favorite_colors.values():
print(color)
blue
orange
green
blue
William
Mark
Function definition
def greet_user(username):
"""Display a simple greeting."""
print("Hello, " + username.title() + "!")
greet_user('jesse')
Hello, Jesse!
def average(x):
return sum(x)/len(x)
average([1, 2, 3, 4])
2.5
if loud:
print('HELLO, {}'.format(name.upper()))
else:
print('Hello, {}!'.format(name))
hello('Bob')
hello('Fred', loud=True)
Hello, Bob!
HELLO, FRED
Class definition
class Greeter:
# Constructor
def __init__(self, name):
self.name = name # Create an instance variable
# Instance method
def greet(self, loud=False):
if loud:
print('HELLO, {}!'.format(self.name.upper()))
else:
print('Hello, {}'.format(self.name))
Mechatronics Engineering and Automation Program
CSE488: Computational Intelligence
Lab #02: Python Basics
NumPy
This library, whose name means numerical Python, constitutes the core of many other
Python libraries that have originated from it. Indeed, NumPy is the foundation library
for scientific computing in Python since it provides data structures and high-performing
functions that the basic package of the Python cannot provide. In fact, NumPy defines a
specific data structure that is an N-dimensional array defined as ndarray. This package
provides some features that will be added to the standard Python: - Ndarray: A
multidimensional array much faster and more efficient than those provided by the basic
package of Python. - Element-wise computation: A set of functions for performing this
type of calculation with arrays and mathematical operations between arrays. - Reading-
writing datasets: A set of tools for reading and writing data stored in the hard disk. -
Integration with other languages such as C, C++, and FORTRAN: A set of tools to
integrate code developed with these programming languages.
Pandas
This package provides complex data structures and functions specifically designed to
make the work on them easy, fast, and effective. This package is the core of data analysis
in Python. The fundamental concept of this package is the DataFrame, a two-
dimensional tabular data structure with row and column labels.
matplotlib
This package is the Python library that is currently most popular for producing plots
and other data visualizations in 2D. Since data analysis requires visualization tools, this
is the library that best suits this purpose.