Introduction to Python

Similar documents
Python memento TI-Smart Grids

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

Python - Variable Types. John R. Woodward

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

UNIVERSITÀ DI PADOVA. < 2014 March >

Introduction to Python

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

COLLEGE OF ENGINEERING, NASHIK-4

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

Senthil Kumaran S

What is Python? Developed by Guido van Rossum in the early1990s Named after Monty Python Available on eniac Available for download from

Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.

And Parallelism. Parallelism in Prolog. OR Parallelism

Variable and Data Type I

PYTHON- AN INNOVATION

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

Variable and Data Type I

ENGR 101 Engineering Design Workshop

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

Chapter 2 Getting Started with Python

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

Advanced Algorithms and Computational Models (module A)

UNIT-III. All expressions involving relational and logical operators will evaluate to either true or false

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

GE8151- PROBLEM SOLVING AND PYTHON PROGRAMMING Question Bank

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

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

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

Introduction to Python for Plone developers

S206E Lecture 19, 5/24/2016, Python an overview

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Short, Unique and Mysterious

LECTURE 1. Getting Started with Python

DaMPL. Language Reference Manual. Henrique Grando

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

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

D R S H YA M N C H AW D A

VLC : Language Reference Manual

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

Babu Madhav Institute of Information Technology, UTU 2015

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

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

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

Key Differences Between Python and Java

Python Intro GIS Week 1. Jake K. Carr

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

Introduction to Bioinformatics

The current topic: Python. Announcements. Python. Python

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

CSCE 110 Programming I

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

DECODE SPECIAL OPERATOR, FORMAT OPERATOR CONTENTS TRIPLE QUOTES. IS a-to-z METHODS REPLACE L E N G T H E X P A N D T A B S ENC0D3

STSCI Python Introduction. Class URL

Financial Accounting Tutorial

Basics of Java Programming

DEPARTMENT OF MATHS, MJ COLLEGE

Python Tutorial. Day 1

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

PHY224 Practical Physics I Python Review Lecture 1 Sept , 2013

Revision of Basics of Python

Python. Department of Computer Science And Engineering. European University Cyprus

Coral Programming Language Reference Manual

Data Types and Conversion

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates

JAVA Programming Fundamentals

CIS192: Python Programming

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Python for ArcGIS. Lab 1.

Python Input, output and variables

Basic Syntax - First Program 1

Introduction to Python: Data types. HORT Lecture 8 Instructor: Kranthi Varala

Introduction to Programming

An introduction to Python

String Processing CS 1111 Introduction to Programming Fall 2018

VALLIAMMAI ENGINEERING COLLEGE

Variables and Values

Accelerating Information Technology Innovation

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

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Some material adapted from Upenn cmpe391 slides and other sources

2 nd Week Lecture Notes

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

L-System Fractal Generator: Language Reference Manual

Accelerating Information Technology Innovation

Built-in Types of Data

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

TCL - STRINGS. Boolean value can be represented as 1, yes or true for true and 0, no, or false for false.

Jython. secondary. memory

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

Transcription:

Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1

Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code is typically 3-5 times shorter than equivalent Java code, it is often 5-10 times shorter than equivalent C++ code) 2

Why Python? GitHub Archive data reveals that Python repositories, on average, receive the most pull requests of any programming language 3

Python Histrory Python is a high-level, interpreted, interactive and object-oriented scripting language. Python was developed by Guido Van Rossum Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk and Unix shell and other scripting languages. 4

Python Features Interpreted languages compiled languages Interactive mode and script mode Easy to lean and use A board standard library Portable Extendable Support OOP, Databases, GUI Programming 5

Installation of Python Python Official Website : http://www.python.org/ Windows and unix installation Set up Path Environment variables IDE for Python: IDLE 6

Notes Indentation Multiple statements on the single line Semicolon ( ; ) Multi-line statement Continuation character (\) Exception: {}, (), [] Example: total = a + \ b + \ c Comment (#) 7

Variables Definition Name Type Value Scope Life Time Location 8

Python Identifiers Identifiers: A name used to identify a variable, function, class, module or other object. How to select name: Start with a letter a to z or an underscore followed by zero or more letters, underscores and digits (0 to 9). Punctuation Case sensitive Reserved Words: Such as: Class, def, if, while,. 9

Data Type Standard Data Type: Number Boolean String List Tuple Dictionary 10

Numbers Numbers: Integer: 23, -3, -0x260 Long: 51924361L, 0x122L Float: 32.3+e18, -90.0, 1.2 Complex: 3.14j, 3e+26J Using Python as a Calculator >>> 2+2 4 11

String String: set of characters in between quotation marks. Quotation marks: Single, Double, Triple str2 = 'Hello World!' str1 = ''Hello World!'' longstr = """This is a paragraph. It is made up of multiple lines and sentences.""" Slice operator: [] or [:] 12

String Slice operator: [] or [:] print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string 13

LIST List: A sequence data type. It is similar to array but all items can be of different data type. Mylist = [ 'abc', 86, 0.23, python', 73.2 ] list2 = [ 1, 2] print Mylist # Prints complete list print Mylist[0] # Prints first element of the list print Mylist[1:3] # Prints elements starting from 2nd till 3rd print Mylist[2:] # Prints elements starting from 3rd element print list2 * 2 # Prints list two times print Mylist + list2 # Prints concatenated lists 14

Tuple Tuple: A sequence data type. It is similar to list but Tuple cannot be updated. MyTuple = ('abc', 86, 0.23, python', 73.2 ) tuple2 = (1, 2) print MyTuple # Prints complete tuple print MyTuple[0] # Prints first element of the tuple print MyTuple[1:3] # Prints elements starting from 2nd till 3rd print MyTuple[2:] # Prints elements starting from 3rd element print tuple2 * 2 # Prints tuple two times print MyTuple + tuple2 # Prints concatenated tuples 15

Dictionary Dictionary: It is a kind of hash table type. dict = {} dict['one'] = "This is one" dict[2] = "This is two tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] print dict[2] print tinydict print tinydict.keys() print tinydict.values() # Prints value for 'one' key # Prints value for 2 key # Prints complete dictionary # Prints all the keys # Prints all the values # Prints concatenated tuples 16

Basic Operators Different types of operators: Arithmetic Operators Comparison (i.e., Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators 17

Operator Precedence Operator Description ** Exponentiation (raise to the power) ~ + - Complement, unary plus and minus * / % // Multiply, divide, modulo and floor division + - Addition and subtraction >> << Right and left bitwise shift & Bitwise 'AND' ^ Bitwise exclusive `OR' and regular `OR' <= < > >= Comparison operators <> ==!= Equality operators = %= /= //= -= += *= **= Assignment operators is, is not in, not in Not, or, and Identity operators Membership operators Logical operators 18

Decision Making True:. any non-zero and non-null values False:. zero or null If statement If else statement Nested if statement 19

If Statement if expression: statement(s) var1 = 100 if var1: print "1 - Got a true expression value" print var1 var2 = 0 if var2: print "2 - Got a true expression value" print var2 print "Good bye!" 20

If else Statement if expression: statement(s) else: statement(s) var1 = 100 if var1: print "true expression value" print var1 else: print " false expression value" print var1 21

elif Statement if expression1: statement(s) elif expression2: statement(s) else: statement(s) 22 var = 100 if var == 200: print "1 - Got a true expression value" print var elif var == 150: print "2 - Got a true expression value" print var2 elif var == 100: print "3 - Got a true expression value" print var else: print "4 - Got a false expression value" print var print "Good bye!"

Nested If Statement if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else: statement(s) elif expression4: statement(s) else: statement(s) var = 100 if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: print "Expression value is less than 50 else: print "Could not find true expression" print "Good bye!" 23

LOOP While Loop For Loop Nested Loop 24

While Loop while expression: statement(s) count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!" 25

For Loop for iterating_var in sequence: statements(s) for letter in 'Python': # First Example print 'Current Letter :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # Second Example print 'Current fruit :', fruit print "Good bye!" 26

Using ELSE with loop else statement is used with a for loop else statement is used with a while loop count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5" 27

Nested Loop for iterating_var in sequence: for iterating_var in sequence: statements(s) statements(s) while expression: while expression: statement(s) statement(s) 28

Loop Control Statement Break Continue Pass 29

Break for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :', letter var = 10 # Second Example while var > 0: print 'Current variable value :', var var = var -1 if var == 5: break print "Good bye!" 30

Continue for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :', letter var = 10 # Second Example while var > 0: var = var -1 if var == 5: continue print 'Current variable value :', var print "Good bye!" 31

Scape Characters Backslash Notation Description \a Bell or alert \\ Backslash \ Double quote \n Newline \r Carriage return \ Single quote \t Tab 32

String String Operators: +, *, [], [:], IN, Not IN, r/r, % Example: print r"\n" print "My name is %s and weight is %d kg!" % ('Zara', 21) Formatting symbol: %c character %i signed decimal integer %d signed decimal integer %f %E floating point real number exponential notation (with UPPERcase 'E') 33

String >>> pi = 3.14159 >>> print(" pi = %1.2f " % pi) pi = 3.14 >>> print(" pi = %d " % pi) pi = 3 >>> print(" pi = %E " % pi) pi= 3.141590E+00 34

String s Methods find(str, beg=0 end=len(string)) index(str, beg=0, end=len(string)) islower() isupper() capitalize() replace(old, new [, count]) rfind(str, beg=0,end=len(string)) rindex( str, beg=0, end=len(string)) join(seq) str = "-"; seq = ("a", "b", "c"); print str.join( seq ); 35

Function Benefit of using function Bulit-in Function User Define Function Defining a Function def functionname([param1,[param2, ]]) : body return [expression] Calling a Function Parameters & arguments Order of Parameters & arguments 36

Function Define a Function: def printme( str ): print < +str+ > return Calling a Function: printme( Hello ) printme( Book ): 37

Passing Parameters Call by Value Call by Reference Call by object Call by Object Reference Call by Sharing 38

Examples (Parameters) # Function definition def changeme( mylist ): mylist = [1,2,3,4]; print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist 39

Examples (Parameters) # Function definition def changeme( mylist ): mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist 40

Passing Parameters Call by object Immutable String, Integer, Tuple Call by Value (They can't be changed within the function) Mutable Call by object Two cases: Can be Changed Unchanged 41

Examples (Parameters) # Function definition def r_demo(x): print "x=",x," id=",id(x) x=42 print "x=",x," id=",id(x) # Now you can call r_demo function >>> x = 9 >>> id(x) 41902552 >>> r_demo(x) x= 9 id= 41902552 x= 42 id= 41903752 >>> id(x) 41902552 42