Introduction to Python

Similar documents
Python Programming Exercises 1

The current topic: Python. Announcements. Python. Python

Getting Started with Python

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

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

MEIN 50010: Python Flow Control

Scripting Languages. Python basics

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

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

Fundamentals of Programming (Python) Getting Started with Programming

Python for Non-programmers

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Some material adapted from Upenn cmpe391 slides and other sources

Programming in Python 3

Algorithms and Programming I. Lecture#12 Spring 2015

Python for Informatics

Built-in Types of Data

Senthil Kumaran S

Introduction to Python - Part I CNV Lab

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

A Little Python Part 1. Introducing Programming with Python

Python Programming, bridging course 2011

Downloaded from Chapter 2. Functions

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Programming for Engineers in Python. Autumn

Python 1: Introduction to Python 1 / 19

Session 1: Introduction to Python from the Matlab perspective. October 9th, 2017 Sandra Diaz

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Programming for Engineers in Python. Recitation 1

CSI33 Data Structures

Table of Contents EVALUATION COPY

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Functions. Python Part 3

Python for C programmers

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Python. Sarwan Singh Assistant Director(S) NIELIT Chandigarh. Education is the kindling of a flame, not the filling of a vessel.

Introduction to Python. Dmytro Karpenko Research Infrastructure Services Group, Department for Research Computing, USIT, UiO

Python Workshop. January 18, Chaitanya Talnikar. Saket Choudhary

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Introduction to Python

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

And Parallelism. Parallelism in Prolog. OR Parallelism

Physics 514 Basic Python Intro

>>> * *(25**0.16) *10*(25**0.16)

Introduction to Python

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

CS 115 Lecture 8. Selection: the if statement. Neil Moore

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

SOFT 161. Class Meeting 1.6

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

CIS192: Python Programming

CSCE 110 Programming I

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Conditionals and Recursion. Python Part 4

61A Lecture 3. Friday, September 5

Introduction to VTK and Python. Filip Malmberg Uppsala universitet

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Variables, expressions and statements

Variable and Data Type I

ENGR 101 Engineering Design Workshop

Conditional Expressions and Decision Statements

Computer Lab 1: Introduction to Python

Introduction to Python

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

Introduction to Python

ENGR (Socolofsky) Week 02 Python scripts

CS Advanced Unix Tools & Scripting

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Algorithms and Data Structures

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

Python. Karin Lagesen.

Introduction to Python, Cplex and Gurobi

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

cs1114 REVIEW of details test closed laptop period

Getting started with programming For geospatial data analysis. Robert Hijmans UC Davis

Script language: Python Data and files

Large-Scale Networks

Introduction to programming with Python

CMSC 201 Computer Science I for Majors

Introduction to Python

CS1 Lecture 3 Jan. 22, 2018

A simple interpreted language

Lecture 3: Functions & Modules

Python for Bioinformatics Fall 2014

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

The float type and more on variables FEB 6 TH 2012

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Act like a code monkey Coding Basics

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Not-So-Mini-Lecture 6. Modules & Scripts

Lecture 3. Strings, Functions, & Modules

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

Lecture 3. Functions & Modules

PROGRAMMING FUNDAMENTALS

Transcription:

Introduction to Python CB2-101 Introduction to Scientific Computing November 11 th, 2014 Emidio Capriotti http://biofold.org/emidio Division of Informatics Department of Pathology

Python Python high-level programming language. Its design philosophy emphasizes code readability, and allows programmers to express concepts in few lines of code. Python is an object-oriented language supporting imperative and functional programming. Object-oriented programming that represents concepts as "objects" that have data fields (attributes) and associated procedures known as methods. Python implementation was started at the end of 1989 by Guido van Rossum. Python 2.0 was released in 2000, with new features including a full garbage collector and support for Unicode.

The interpreter The interpreter can be accessed typing python in the shell emidio-imac:data emidio$ python Python 2.7.6 (default, Nov 23 2013, 23:57:52) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> To exit from the interpreter environment Ctrl+D or exit() The interactive interpreter: ipython emidio-imac:data emidio$ ipython-2.7 Python 2.7.6 (default, Nov 23 2013, 23:57:52) Type "copyright", "credits" or "license" for more information. IPython 0.13.1 -- An enhanced Interactive Python.? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. In [1]:

Rules for naming variables A variable name have to start with a letter start with a number >>> 2name=True File "<stdin>", line 1 2name=True ^ SyntaxError: invalid syntax<type 'bool'> A variable can not be one of the 31 python keyword >>> print= Hello world File "<stdin>", line 1 print= Hello world ^ SyntaxError: invalid syntax A variable can not contain illegal characters >>> you*=1 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'you' is not defined

Basic variable types The simplest type of variable in programming is the boolean >>> bit=true >>> type(bit) <type 'bool'> The simplest numeric variable is integer >>> inum=1 >>> type(inum) <type 'int'> More complex numeric variable is float >>> fnum=1.5 >>> type(fnum) <type 'float'> In python character variable does not exist. >>> text= Hello World >>> type(text) <type 'str'>

String variables In low level program languages the string is not a basic variable. It is actually a group of concatenated characters. In programming languages such as fortran the length of a string is fix. In python a string can assume any length and it do not need to be declared. Python provides built-in functions for dealing with string >>> text= Hello world >>> print len(text) 12 >>> print text[0] H >>> print text[-1] >>> print text[2:5] llo

Convert variable types In python variables are not explicitly declared and are defined instantiation. Variable types can be converted. This procedure is referred as variable casting. In python changing the variable type can be a source of error. Few example about how to modify variable type >>> fnum=5.6 >>> int(fnum) 5 >>> inum=4 >>> float(inum) 4.0 >>> text= 1024 >>> int(text) 1024

Standard operators The standard operators for numeric variables are: >>> 2+2 4 >>> 2-2 0 >>> 2*3 6 >>> 7/2 3 >>>7%2 1 >>>2**3 8 Some of these operators works also for strings >>> a + b ab >>> 2* a aa

Function Function is a set of statements to perform a task. def name(list of variables): statements The function consists of two parts: the header and the body. The header contains the name and the list of variables The body contains the set of statements and is indented The order of the statements defines the flow of execution. A function can not be called before it has been defined Example write a function that write a name. >>> def print_name(name): print My name is,name >>> print_name( Emidio ) My name is Emidio

Compose functions Write the a function that calculate the square value of a given n >>> def square(x): return x**2 >>> square(3) 9 The function can composed and we can calculate Python as built-in functions such as: >>> square(square(3)) 81 abs(x) pow(x,n) max(x,y) min(x,y) - absolute value - power x**n - maximum between x,y - minimum between x,y

Import function Functions and variables can imported from a python script Define the following polynomial functions in poly.py script k=2 def square(x): return x**2 def cubic (x) return pow(x,3) Import the functions square and cubic and variable k >>> from poly import square, cubic, k Calculate the value of kx**-x**2 with x=2 >>> x=2 >>> k*cubic(x)-square(x) 12

if and operators Basic structure of if in python. Also elif can be used. if (condition 1): do something 1 elif (condition 2): do something 2 else: do something 3 Standard operators are ==, =, >, >=, <, <= that can be combined with and, or, not Write a function that check names for length and first characters >>> def check_name(name,name_len,letter): if (len(name>=name_len and name[0]==letter): return True else: return False >>> print chech_name( Goofy,5, G ) True

for and while loops Basic structure of the for and while loop in python. for i in list: do something # Indentation is needed while (condition): do something # Indentation is needed Build a function that takes a text variable and print all the letters >>> def print_for_letters(text): for i in text: print i >>> def print_while_letters(text): i=0 while i<len(text): print text[i] i+=1

Use the while loop Exercise 1 Write a function that takes in input a string and a character and find the position in the string that first match the character >>> def find(text, character): i=0 while i<len(text) if text[i]==character: return i else: i+=1 return -1 >>> def find( Goofy, o ) 1 The function find() returns same result >>> Goofy.find( o )

Important modules The module sys access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. >>> import sys >>> sys.argv[0] The module math provide standard mathematics functions >>> import math >>> math.pi 3.141592653589793 >>> math.sqrt(2) >>> 1.4142135623730951

Exercise 2 Write the first python script to address the following problems 1. Count the number of vowels. The script takes in input a string and print the number of vowels 2. Write similar script that takes in input a string and a character and calculates the number matching characters. Use the function upper() to compare string in uppercase >>> text= abc text.upper() ABC Include sys.argv[2] variable to provide the character. import sys sys.argv[2]