Principles of Computing – UFCFA3-30-1

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Lists Introduction to Computing Science and Programming I.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Java Unit 9: Arrays Declaring and Processing Arrays.
Lists in Python.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
CS1022 Computer Programming & Principles Lecture 1.2 A brief introduction to Python.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Python Programing: An Introduction to Computer Science
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
String and Lists Dr. José M. Reyes Álamo.
10 - Python Dictionary John R. Woodward.
CS1022 Computer Programming & Principles
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
CS 100: Roadmap to Computing
JavaScript: Functions.
Engineering Innovation Center
CISC101 Reminders Quiz 2 this week.
Introduction to Python
Introduction to Python
Introduction to C++ Programming
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
CISC101 Reminders Slides have changed from those posted last night…
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data types Numeric types Sequence types float int bool list str
Coding Concepts (Data Structures)
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
Web DB Programming: PHP
String and Lists Dr. José M. Reyes Álamo.
Introduction to Programming
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Topics Sequences Introduction to Lists List Slicing
Python Primer 1: Types and Operators
CHAPTER 3: String And Numeric Data In Python
15-110: Principles of Computing
CISC101 Reminders Assignment 2 due today.
Topics Basic String Operations String Slicing
CHAPTER 4: Lists, Tuples and Dictionaries
Introduction to Computer Science
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Python Review
Topics Basic String Operations String Slicing
Introduction to Programming
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Introduction to Computer Science
Selamat Datang di “Programming Essentials in Python”
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Principles of Computing – UFCFA3-30-1 Week-8 Python Language Instructor : Mazhar H Malik Email : mazhar@gcet.edu.om Global College of Engineering and Technology

Python Language 1

Topics for Today Python Primer Python Introduction Installation/IDE uses Lists & its Operations Dictionary & its Operations String & its Operations Control Structure Looping Conditions Data Structure List Sets Dictionary 2

Why Python? Python is easy to use Python typically operates at a much higher level of abstraction. Syntax rules are very simple. Python to take one-fifth the time it would if coded in C or Java

Why Python? Example: – Python is expressive Expressive in this context means that a single line of Python code can do more than a single line of code in most other languages Example: In java int temp = var1; var1 = var2; var2 = temp; Python var2, var1 = var1, var2 1/17/2017 1

Why Python? Python is readable one can guess easily what’s happening in code #Perl version. sub pairwise_sum { my($arg1, $arg2) = @_; my(@result) = (); @list1 = @$arg1; @list2 = @$arg2; for($i=0; $i < length(@list1); $i++) { push(@result, $list1[$i] + $list2[$i]); } return(\@result); # Python version. def pairwise_sum(list1, list2): result = [] for i in range(len(list1)): result.append(list1[i] + list2[i]) return result

Why Python? Python is complete Python is cross-platform Python is free Python standard library comes with modules for handling email, web pages, databases, operating system calls, GUI development, and more. Python is cross-platform Python runs on many different platforms: Windows, Mac, Linux, UNIX, and so on. Python is free Python was originally, and continues to be, developed under the open source model, and it’s freely available. You can download and install practically any version of Python and use it to develop software for commercial or personal applications, and you don’t need to pay a dime.

Installing Python Installing Python is a simple matter, regardless of which platform you’re using. the most recent one can always be found at www.python.org.

command-line

The IDLE integrated development environment

Interactive and Programing Mode IDE: Integrated Development Environment

Comments For the most part, anything following a # symbol in a Python file is a comment and is disregarded by the language.

Variables and assignments

del statement The del statement deletes the variable.

Expressions Python supports arithmetic and similar expressions; these will be familiar to most readers. The following code calculates the average of 3 and 5, leaving the result in the variable z:

Strings You can use single quotes instead of double quotes. The following two lines do the same thing: x = "Hello, World" x = 'Hello, World'

Numbers Python offers four kinds of numbers: integers, floats, complex numbers, and Booleans.

Built-in numeric functions Python provides the following number- related functions as part of its core: abs, divmod, cmp, coerce, float, hex, int, long, max, min, oct, pow, round

Getting input from the user You can also use the input() function to get input from the user. Use the prompt string you want displayed to the user as input’s parameter:

Lists Lists are like arrays A list in Python is much the same thing as an array in Java or C or any other language. It’s an ordered collection of objects. You create a listd by enclosing a comma separated brackets, like so: Example x = [1, 2, 3] list of elements in square

List indices Elements can be extracted from a Python list using a notation like C’s array indexing. Like C and many other languages, Python starts counting from 0; asking for element 0 if indices are negative numbers, they indicate positions counting from the end of the list, with –1 being the last position in the list, –2 being the second-to-last position, and so forth.

List indices In thelist ["first", "second", "third", "fourth"], you can think of the indices as pointing like this:

Slicing in List enter list[index1:index2] to extract all items including index1 and up to (but not including) index2 into a new list.

Slicing in List When slicing a list, it’s also possible to leave out index1 or index2. Leaving out index1 means “go from the beginning of the list,” and leaving out index2 means “go to the end of the list”:

Slicing in List Omitting both indices makes a new list that goes from the beginning to the end of the original list; that is, it copies the list. This is useful when you wish to make a copy that you can modify, without affecting the original list:

Modifying lists You can use list index notation to modify a list as well as to extract an element from it.

Modifying lists Slice notation can be used here too. Saying something like lista[index1:index2] = listb causes all elements of lista between index1 and index2 to be replaced with the elements in listb. listb can have more or fewer elements than are removed from lista, in which case the length of lista will be altered. You can use slice assignment to do a number of different things, as shown here:

Append, Extend Appending a single element to a list is such a common operation that there’s a special append method to do it: The extend method is like the append method, except that it allows you to add one list to another:

Insert insert is used as a method of lists and takes two additional arguments; the first is the index position in the list where the new element should be inserted, and the second is the new element itself:

The del statement The del statement is the preferred method of deleting list items or slices. It doesn’t do anything that can’t be done with slice assignment, but it’s usually easier to remember and easier to read:

removes remove looks for the first instance of a given value in a list and removes that value from the list:

Sorting lists Lists can be sorted using the built-in Python sort method:

List membership with the in operator It’s easy to test if a value is in a list using the in operator, which returns a Boolean value. You can also use the converse, the not in operator:

Min/Max You can use min and max to find the smallest and largest elements in a list

List search with index If you wish to find where in a list a value can be found (rather than wanting to know only if the value is in the list), use the index method.

List matches with count count also searches through a list, looking for a given value, but it returns the number of times that value is found in the list rather than positional information:

Summary of list operations

Summary of list operations

Nested lists Lists can be nested. One application of this is to represent two-dimensional matrices. The members of these can be referred to using two-dimensional indices. Indices for these work as follows:

Strings strings can be considered sequences of characters which means you can use index or slice notation:

The split and join string methods join takes a list of strings and puts them together to form a single string with the original string between each element.

The split and join string methods split returns a list of substrings in the string By default, split splits on any whitespace, not just a single space character, but you can also tell it to split on a particular sequence by passing it an optional argument:

Modifying strings with list manipulations

index Returns the location of substring in text

Excercise Write a Program that input a name and and print in abbreviated form Eg. Kamrn Ahmed K. Ahmed

Replace Replaces the first occurrence with other one. of substring

upper Convert into upper case

Title Capitalize the string

Excercise Write a Program that input a name convert into capital, lower and upper Case. Eg. Kamrn ahmed Kamran Ahmed KAMRAN AHMED kamran ahmed

Range function

Comprehension

Looping

Exercise Write a program that print EVEN numbers (2-20)

Home-Work Write a program to generate Fibonacci series

Fibonacci series – Home Work

While Loop – Table

Exercise Write a program to produce following output

For Loop

For Loop

The for loop with range function Sometimes you need to loop with explicit indices (to use the position at which values occur in a list). You can use the range command together with the len command on lists to generate a sequence of indices for use by the for loop.

For Loop

For Loop output?

For Loop output?

Comprehension

String operations

Today’s Class Topic Assignments Python Dictionary and Sets Probabilistic Algorithms (GA) Research Paper Titled “Genetic Algorithm Implementation in Python” Assignments Write code of basic Genetic Algorithm in Python with reference of above research paper. Last Date: Two Weeks 65 –

Python Dictionary 66

Dictionary

Dictionary

Dictionary

Dictionary

Dictionary

Dictionary

Dictionary

Accessing Values in Dictionary Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. 74

Updating Dictionary You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example 75

Updating Dictionary What about concatenating dictionaries, like we did with lists? There is something similar for dictionaries: the update method update() merges the keys and values of one dictionary into another, overwriting values of the same key: 76

Delete Dictionary Elements you can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the del statement. Following is a simple example − 77

Iterating over a Dictionary 78

Iterating over a Dictionary 79

Dictionaries from Lists Now we will create a dictionary, which assigns a dish to a country, of course according to the common prejudices. For this purpose we need the function zip(). The name zip was well chosen, because the two lists get combined like a zipper. 80

Dictionaries from Lists 81

Sets in Python The data tpye "set", which is a collection type, has been part of Python since version 2.4. A set contains an unordered collection of unique and immutable objects. The set data type is, as the name implies, a Python implementation of the sets as they are known from sets mathematics. This explains, why unlike lists or tuples can't have multiple occurrences of the same element. 82

Creating Sets 83

Set from List We can pass a list to the built-in set function, as we can see in the following: 84

Frozensets Frozensets are like sets except that they cannot be changed, i.e. they are immutable: 85

Set Operations 86

add(element) 87

clear 88

copy 89

difference 90

Difference Update 91

discard(el) 92

remove 93

intersection(s) 94

issubset() 95

issuperset() 96

pop 97

Useful Modules, Packages and Libraries

Useful Modules, Packages and Libraries

Useful Modules, Packages and Libraries

Useful Modules, Packages and Libraries

Useful Modules, Packages and Libraries

Useful Modules, Packages and Libraries

Useful Modules, Packages and Libraries

GUI

WxPython

Boa Constructor - wxPython GUI Builder

Visual Python for 3D graphics

Development Game

Plotting

Thank You

References http://www.python-course.eu/ 112