Introduction to Python

Similar documents
1ο Φροντιστήριο Τεχνητής Νοημοσύνης. Διαδικαστικά και εισαγωγή στην Python

Compound Data Types 1

Some material adapted from Upenn cmpe391 slides and other sources

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CSC326 Python Sequences i. CSC326 Python Sequences

Senthil Kumaran S

Data Structures. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

ECS15, Lecture 14. Reminder: how to learn Python. Today is the final day to request a regrade of the midterm. Topic 4: Programming in Python, cont.

MUTABLE LISTS AND DICTIONARIES 4

Python. Karin Lagesen.

Python Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다. PythonBasics

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]

Accelerating Information Technology Innovation

Why Python? Introduction into Python. Introduction: Remarks. Where to get Python and Learn More?

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Lecture 7: Python s Built-in. in Types and Basic Statements

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

18.1. CS 102 Unit 18. Python. Mark Redekopp

Programming in Python

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Data Science Python. Anaconda. Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas.

Topic 7: Lists, Dictionaries and Strings

STA141C: Big Data & High Performance Statistical Computing

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

6. Data Types and Dynamic Typing (Cont.)

Lists How lists are like strings

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

LECTURE 1. Getting Started with Python

Accelerating Information Technology Innovation

Python Programming: Lecture 2 Data Types

Part III Appendices 165

Introduction to Python Programming

The current topic: Python. Announcements. Python. Python

Python Tutorial. CSE 3461: Computer Networking

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

Python Basics. Lecture and Lab 5 Day Course. Python Basics

def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food

Fundamentals of Programming (Python) Getting Started with Programming

Download Python from Any version will do for this class

CIS192 Python Programming. Robert Rand. August 27, 2015

Programming to Python

(2½ hours) Total Marks: 75

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Introduction to Python

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France

UNIVERSITÀ DI PADOVA. < 2014 March >

Physics 514 Basic Python Intro

CIS192: Python Programming

Python for Non-programmers

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

Types, lists & functions

Introduction to Python

Programming Fundamentals and Python

Play with Python: An intro to Data Science

Here n is a variable name. The value of that variable is 176.

Advanced Python. Executive Summary, Session 1

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Getting Started with Python

Introduction to Python (All the Basic Stuff)

Lists. There are several ways to create a new list; the simplest is to enclose the elements in square brackets ( [ and ]):

Abstract Data Types Chapter 1

Python Tutorial. Day 1

Introduction to Python

COMP 204: Sets, Commenting & Exceptions

Strengthen Your Python Foundations

Beyond Blocks: Python Session #1

MEIN 50010: Python Introduction

Python and Bioinformatics. Pierre Parutto

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

AI Programming CS S-02 Python

CS Summer 2013

Course Title: Python + Django for Web Application

Script language: Python Data structures

Sequences and iteration in Python

Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.

Babu Madhav Institute of Information Technology, UTU 2015

The Pyth Language. Administrivia

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

A Little Python Part 1. Introducing Programming with Python

Python Crash-Course. C. Basso. Dipartimento di Informatica e Scienze dell Informazione Università di Genova. December 11, 2007

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

Python for ArcGIS. Lab 1.

Python at Glance. a really fast (but complete) ride into the Python hole. Paolo Bellagente - ES3 - DII - UniBS

For strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table.

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

Transcription:

Introduction to Python

Development Environments what IDE to use? 1. PyDev with Eclipse 2. Sublime Text Editor 3. Emacs 4. Vim 5. Atom 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows) 10.BlueFish (Linux)

Python Version Python Version 2.7.x Download Link : https://www.python.org/downloads/

Python Interactive Shell % python Python 2.6.6 (r266:84292, Nov 21 2013, 10:50:32) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. You can type things directly into a running Python session name Andrew name 'Andrew' >>> print "Hello", name Hello Andrew

Lists A compound data type: [5, "Hello", "there", 9.8] [5, "Hello", "there", [1, AI ] ] Use len() to get the length of a list >>> fruits = [ Apple", Banana", Olive"] >>> len(fruits) 3

Use [ ] to index items in the list fruits = [ Apple, Banana ] fruits Apple fruits Banana fruits Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range fruits [-1] Banana' fruits [-2] Apple [0] is the first item. [1] is the second item. Out of range values raise an exception. Negative values go backwards from the last element.

Strings share many features with lists smiles = "C(=N N)N.C(=O O O smiles 'C' smiles smiles[-1] O smiles Use slice notation to get a substring N smiles[10:-4] 'C(=O

String Methods: find, split smiles = "C(=N N)N.C(=O O O smiles.find O smiles.find Use find to find the start of a substring. smiles.find Start looking at position 10. - Find returns -1 if it couldn t find a match. smiles.split Split the string into parts with. as delimiter. 'C(=N N N', 'C(=O O O

String operators: in, not in if "Br" in Brother : print "contains! else: print doesn t contain email_address = tberis if @ not in email_address: email_address += @di.uoa.gr

Lists are mutable - some useful methods fruits = ["Apple", "Banana", "Olive"] fruits.append("strawberry") fruits [ Apple, Banana, Olive, Strawberry ] del fruits ['Banana', 'Olive', 'Strawberry'] #remove an element fruits.reverse() ['Strawberry', 'Olive', 'Banana'] #reverse the elements in a list fruits.sort() ['Banana', 'Olive', 'Strawberry'] #in place sort based of ASCII codes

Tuples: sort of an immutable list yellow = (255, 255, 0) # r, g, b yellow 255 yellow yellow Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment

Zipping lists together names [ Themis, Nikos, Despoina ] gender [ Male, Male, Female ] zip(names, gender) [( Themis, Male ), ( Nikos, Male ), ( Despoina, Female )]

Dictionaries Dictionaries are lookup tables. They map from a key to a value. symbol_to_name = { "H": "hydrogen", He helium "Li": "lithium", "C": "carbon O oxygen "N": "nitrogen" } Duplicate keys are not allowed Duplicate values are just fine

Dictionary Key access >>> symbol_to_name = {"H": "hydrogen, He helium "Li": "lithium,"c": "carbon O oxygen "N": "nitrogen } >>> symbol_to_name["c"] Get the value for a given key 'carbon' >>> Z" in symbol_to_name Test if the key exists( in only checks the keys, not the values.) False >>> symbol_to_name[ Z"] [] lookup failures raise an exception. Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: Z' >>> symbol_to_name.get("p", "unknown") Use.get() if you want to return a default value. 'unknown' >>> symbol_to_name.get("c", "unknown") 'carbon >>> symbol_to_name["cu"] = copper Insert a new item >>> symbol_to_name["c"] = calcium Update single item

Keys can be any immutable value Numbers, strings, tuples are valid (immutable). Lists, dictionaries, sets are not valid (mutable). A set is an unordered collection with no duplicate elements. nobel_prize_winners = { (1979, "physics"): ["Glashow", "Salam", "Weinberg"], chemistry Hodgkin biology McClintock

Some useful dictionary methods >>> symbol_to_name = {"H": "hydrogen, He helium "Li": "lithium,"c": carbon O oxygen "N": "nitrogen } >>> symbol_to_name.keys() ['C', 'H O N Li He >>> symbol_to_name.values() ['carbon', 'hydrogen', 'oxygen', 'nitrogen', 'lithium', 'helium'] >>> symbol_to_name.update( {"P": "phosphorous", "S": "sulfur"} ) >>> symbol_to_name.items() [('C', 'carbon H hydrogen O oxygen N nitrogen P phosphorous S sulfur Li lithium He helium >>> del symbol_to_name['c'] >>> symbol_to_name {'H': 'hydrogen', 'O': 'oxygen', 'N': 'nitrogen', 'Li': 'lithium', 'He': 'helium'}

Control Flow Things that are False The boolean value False The numbers 0 (integer), 0.0 (float) The empty string "". The empty list [], empty dictionary {} and empty set set(). Things that are True The boolean value True All non-zero numbers. Any string containing at least one character. A non-empty data structure.

Control flow: if statement x = int(raw_input("please enter #:")) if x print 'Negative number' elif x print 'Zero' elif x print One' else: print 'More than one no switch case statements in python

Control flow: for a = ['cat', 'window', 'defenestrate'] for x in a: print x, len(x) no arithmetic progression, but range(10) # à [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(2,10,2) # à [2, 4, 6, 8] for i in range(len(a)): print i, a[i] break and continue like C and Java

User-defined functions def fib(n): """Print a Fibonacci series up to n.""" a b while b < n: print b a b b a+b fib(30)

File Manipulation

List Comprehension Construct lists in an alternative way

Classes class Person: def init (self, first, last): self.firstname = first self.lastname = last def get_fullname(self): return self.firstname + + self.lastname class Employee(Person): instances = 0 Class / static variables def init (self, first, last, afm): Person. init (self, first, last) self.afm = afm Employee.instances += 1 def get_employee(self): return self.get_fullname() + + self.afm employee1 = Employee( themis, beris, 123 ) Creates an instance of Employee employee2 = Employee( nikos, karalis, 456 ) Creates another instance of Employee print employee1.get_employee() print employee2.instances print employee1.instances == employee2.instances It will always be True