Programming in Python 3

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

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

Scripting Languages. Python basics

Variables, Constants, and Data Types

Chapter 2 Getting Started with Python

Getting Started with Python

Full file at

Python Unit

Fundamentals of Programming (Python) Getting Started with Programming

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

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

ENGR 101 Engineering Design Workshop

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

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

Python memento TI-Smart Grids

Reserved Words and Identifiers

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

Visual C# Instructor s Manual Table of Contents

Introduction to Python Programming

Coral Programming Language Reference Manual

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Python in 10 (50) minutes

CSI33 Data Structures

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

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

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

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

The current topic: Python. Announcements. Python. Python

CSc 110, Spring Lecture 24: print revisited, tuples cont.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Part III Appendices 165

Python for Non-programmers

CS 115 Lecture 4. More Python; testing software. Neil Moore

Typescript on LLVM Language Reference Manual

Full file at C How to Program, 6/e Multiple Choice Test Bank

Python Programming Exercises 1

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

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Starting. Read: Chapter 1, Appendix B from textbook.

3. Java - Language Constructs I

Python for Informatics

ML 4 A Lexer for OCaml s Type System

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

Programming with C++ Language

Java Bytecode (binary file)

Python Working with files. May 4, 2017

UNIT- 3 Introduction to C++

Language Reference Manual

MEIN 50010: Python Flow Control

Advanced Algorithms and Computational Models (module A)

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

BoredGames Language Reference Manual A Language for Board Games. Brandon Kessler (bpk2107) and Kristen Wise (kew2132)

Outline. Data and Operations. Data Types. Integral Types

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

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Fundamental of Programming (C)

Computer System and programming in C

SCoLang - Language Reference Manual

Introduction to Bioinformatics

Babu Madhav Institute of Information Technology, UTU 2015

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Downloaded from Chapter 2. Functions

LOON. Language Reference Manual THE LANGUAGE OF OBJECT NOTATION. Kyle Hughes, Jack Ricci, Chelci Houston-Borroughs, Niles Christensen, Habin Lee

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Introduction to Python

Lecture 1. Types, Expressions, & Variables

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

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

Getting started with Java

Exercise: Using Numbers

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

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Primitive Data Types: Intro

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

VLC : Language Reference Manual

Some material adapted from Upenn cmpe391 slides and other sources

Title:[ Variables Comparison Operators If Else Statements ]

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CIS 110: Introduction to Computer Programming

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

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

Variable and Data Type I

The C++ Language. Arizona State University 1

EnableBasic. The Enable Basic language. Modified by Admin on Sep 13, Parent page: Scripting Languages

EL2310 Scientific Programming

Syntax and Variables

Cisco IOS Shell. Finding Feature Information. Prerequisites for Cisco IOS.sh. Last Updated: December 14, 2012

Lecture 2 Tao Wang 1

C++ Programming: From Problem Analysis to Program Design, Third Edition

Python Games. Session 1 By Declan Fox

Algorithms and Programming I. Lecture#12 Spring 2015

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

CSC326 Python Imperative Core (Lec 2)

File Handling in C. EECS 2031 Fall October 27, 2014

FRAC: Language Reference Manual

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

GNU ccscript Scripting Guide IV

OCR Pseudocode to Python

1 Truth. 2 Conditional Statements. Expressions That Can Evaluate to Boolean Values. Williams College Lecture 4 Brent Heeringa, Bill Jannen

Transcription:

Programming in Python 3

Programming transforms your computer from a home appliance to a power tool Al Sweigart, The invent with Python Blog

Programming Introduction Write programs that solve a problem using a set of computational steps Write programs/scripts that automate a repetitive task Write glue code that coordinates several other programs to achieve a task

Introduction Algorithms Algorithms Algorithms are the computational steps that the computer needs to follow to perform a function Computer programs implement algorithms

Algorithm: find max of 4 numbers a, b, c, d Let x represent the largest integer At the end of algorithm, x must be the largest of the 4 Introduction Algorithms 1. Assume a is the largest. i.e assign x value of a 2. If b greater than x, assign x value of b 3. If c greater than x, assign x value of c 4. If d greater than x, assign x value of d 5. Output value of x Computer implementation Requires 5 variables to store a,b,c,d and x. A comparison operation An assignment operation

Python Python is a high-level, general purpose programming language Elegant, readable syntax that is easy to learn A large collection of standard modules. Batteries included philosophy Allows a programmer to create programs that perform complex functions in less time and less lines of code than other languages

Python Versions Python The Python language has been steadily evolving with the addition of new language features The 2.x series gained wide acceptance and has a large base of existing scripts 2008: Python 3.0 was released in parallel with 2.6

Python 3 Python Python 3 aimed to clean up flaws in the Python language But this required changes that would make it backward incompatible Existing 2.x code will not run in Python 3 without modification Python 2.7 is the last release of the 2.x interpreter support will end in 2020 Python 3 represents the future of the language But you will most likely encounter existing code written in 2.x We will learn Python 3 in this course

Python Versions Python Most Linux distributions have both Python 2.7 and 3.x installed side by side $ python --version Python 2.7.12 $ python3 --version Python 3.5.2

Interactive Interpreter Python Python provides a shell interface to the interpreter Much like the Bash shell Each line entered is executed by the interpreter Running the Python interpreter without any arguments starts an interactive session $ python3 Python 3.5.2 (default, Jul 5 2016, 12:43:10) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> prompt indicates that the interpreter is ready to accept Python statements

Python Interactive Interpreter The interpreter prints output after each statement is executed Suitable for doing quick tests and trying out Python Our first line of code >>> print('hello, World') Hello, World >>>

Documentation can be accessed with the help() built-in function Python Getting Help >>> help(print) Help on built-in function print in module builtins: print(...) print(value,..., sep=' ', end='\n', file=sys.stdout, flush=false) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.

Variables Variables in Python are created with the an assignment statement A variable in Python is simply an identifier >>> largest = 0 >>> In this case the name largest is a reference to an object in memory holding a 0 integer value The name largest is said to be bound to the integer object 0 0 largest

Reassigning a variable to another value causes it to be bound to a new object 0 Variables >>> largest = 0 >>> largest = 'aeiou' >>> largest is now bound to a string object largest aeiou

Variables Python is a dynamically typed language The type() built-in function can tell us what is the type referenced by a variable >>> largest = 0 >>> type(largest) <class 'int'> >>> largest = 'aeiou' >>> type(largest) <class 'str'> >>>

Even a reassignment to a new value of the same type creates a new object 0 Variables >>> largest = 0 >>> largest = -12 >>> type(largest) <class 'int'> >>> Now the name largest is a reference to an object in memory holding a -12 integer value largest -12

Expressions Literals Whatever appears on the right side of an assignment is an expression i.e., expression evaluates to an object with a value. And the assignment operation binds a variable name to that object One of the simplest expressions are literals In the previous examples 0 is an integer literal and 'aeiou' is a string literal

Expressions Integer Literals Integer literals in Python can additionally be input in Hexadecimal, Octal and Binary notation Hexadecimal is a numeral system with 16 symbols Numerals are 0 1 2 3 4 5 6 7 8 9 A B C D E F Prefixed with 0x Octal has 8 symbols Prefixed with 0o Binary has 2 symbols: 0 and 1 Prefixed with 0b print() function accepts variables as arguments And multiple arguments separated by commas >>> a = -63 >>> b = -0x3F >>> c = -0o77 >>> d = -0b00111111 >>> print(a,b,c,d) -63-63 -63-63

Floating point numbers are the computer approximation of real numbers Expressions Floating Point Literals >>> f = 3.14159 >>> type(f) <class 'float'> >>> print(f) 3.14159 Scientific notation also supported Note: # character begins a comment Everything from the # to the end of the line ignored by interpreter >>> f = 1.3e-9 # same as 1.3x10 ⁹ >>> type(f) <class 'float'> >>> print(f) 1.3e-09

Expressions Complex numbers consist of a real part and an imaginary part Each of which is a float type Imaginary unit uses symbol j (rather than i) Complex Literals >>> cnum = 2+3j >>> type(cnum) <class 'complex'> >>>

Expressions Attributes The complex type has two attributes real imag Attributes are accessed using the. (dot) operator >>> print(cnum.real) 2.0 >>> print(cnum.imag) 3.0 >>> type(cnum.real) <class 'float'> >>>

Boolean type takes either of two values True or False Expressions Bool Type >>> mybool = True >>> type(mybool) <class 'bool'> >>> mybool = False >>> type(mybool) <class 'bool'>

An str type represents a sequence of characters Characters of a string can be enclosed in either single or double quotes A single quote can be present unescaped in a double quoted string and vice versa Expressions String Literals >>> mystr = 'a string' >>> type(mystr) <class 'str'> >>> mystr = "it's a word" >>> print(mystr) it's a word >>> mystr = 'won't work with single quotes' File "<stdin>", line 1 mystr = 'won't work with single quotes' ^ SyntaxError: invalid syntax

Expressions String literals can be implicitly concatenated Allows us to split long strings across lines in scripts String Literals >>> mystr = 'supercalifrag' 'ilisticexpialidocious' >>> print(mystr) supercalifragilisticexpialidocious

Triple quotes preserve newlines In the interactive interpreter, is the secondary prompt Interpreter expects continuation lines Expressions String Literals >>> mypara = """This is a multi-line... string. Each line in the... paragraph is separated by a... newline character""" >>> print(mypara) This is a multi-line string. Each line in the paragraph is separated by a newline character

Expressions Python 3 has full native support for Unicode Unicode defines a standard for how text of most of the world s writing systems is represented and stored on computers String Literals >>> myname = 'ഇർഷ ദ ബഷ ർ' >>> print(myname) ഇർഷ ദ ബഷ ർ >>>

Expressions Bytes Literals Like str, bytes is a sequence type A bytes type represents a sequence of 8-bit bytes Therefore each element represents an integer between 0 and 255 inclusive Byte literal syntax like strings but prefixed with a b Elements can be represented by ASCII characters for values 0-127 and/or hexadecimal digits: \x00-\xff for value 0-255 >>> bvar = b'abc' >>> type(bvar) <class 'bytes'> >>> print(bvar) b'abc' >>>

Types Seen So Far Types Review Numeric Types int float complex bool Sequence Types str bytes

Operators Operations on Numeric Types Types Operators All familiar operations available for numeric types Numeric literals along with operators are expressions: They return an object that can be bound to a name >>> a = 2 + 1 * 5 >>> print(a) 7 >>>

Operators follow precedence rules Use of parenthesis can make evaluation order explicit Operators Arithmetic >>> a = (2 + 1) * 5 >>> print(a) 15 >>> Other operators include Raise to the power: ** Modulo: % >>> print(2**4) 16 >>> >>> print(13%10) 3 >>>

In expressions where arithmetic operators are applied between two numeric values that are not of the same type The less general type is converted to the more general one Operators Generality increases in the order bool -> int -> float -> complex Numeric Type Conversion >>> type(2 + 3) <class 'int'> >>> type(2 + 3.5) <class 'float'> >>> type(3.5 + (2+1j)) <class 'complex'> >>>

Division Operators Python 3 has two division operators: / and // // The floor division operator Operators Division >>> a = 8 // 3 >>> print(a) 2 >>> a = -3.4 // 2 >>> print(a) -2.0 // rounds towards negative infinity

Division Operators Operators / Performs true division Division >>> a = 8 / 3 >>> print(a) 2.6666666666666665 >>> a = -3.4 / 2 >>> print(a) -1.7 >>>

Comparison Operators Numeric types Return a value of type bool Operators are <, >, <=, >=,!=, == Operators Comparison >>> print(1 < 2) True >>> a = 123 >>> print(a == 12.2) False >>>

Comparison Operators Numeric types Operators Be wary of comparing floating point values directly Comparison >>> a = 0.1 + 0.1 + 0.1 >>> print(a == 0.3) False >>>

Comparison operators can be chained Operators Comparison >>> a = 1 >>> b = 2 >>> c = 3 >>> print(a < b < c) True >>> print(a < b and b < c) #Functionally identical True

Boolean Operators Numeric types Operators Logical Operators: and, or, not and >>> print(true and True) True >>> print(true and False) False >>> print(false and True) False >>> print(false and False) False

Boolean Operators Numeric types or Operators Logical >>> print(true or True) True >>> print(true or False) True >>> print(false or True) True >>> print(false or False) False

Boolean Operators Numeric types Operators not Logical >>> print(not True) False >>> print(not False) True

if statement Execute one or more statements based on the boolean value of an expression Operators Conditional Statement if <expression>: statement-1 statement-2 statement1, statement2, are executed if boolean conversion of expression has value True

Operators Indentation in Python Statement block begins with a clause that ends in colon : Suite of statements to be executed are at the same indentation level: indentation mandatory in Python if <expression>: statement-1 statement-2 statement-3 statement-4 Statements 1-3 are conditionally executed statement4 is executed unconditionally statement4 is outside the if block

Operators Indentation in Python Nested statement block adds a level of indentation if <expr-1>: statement-1 if <expr-2>: statement-2 statement-3 statement-4 statement-1, statement-3 executed if expr-1 is True statement-2 executed if expr-1 and expr-2 are True statement-4 executed regardless of expr-1 or expr-2

Algorithm: find maximum of 4 number a, b, c, d Let x represent the largest integer At the end of algorithm, x must be the largest of the 4 Introduction Algorithms 1. Assume a is the largest. i.e assign x value of a 2. If b greater than x, assign x value of b 3. If c greater than x, assign x value of c 4. If d greater than x, assign x value of d 5. Output value of x Computer implementation Requires 5 variables to store a,b,c,d and x. A comparison operation An assignment operation

Implementation Program written into a file Operators Largest Number Algorithm a = -12 b = 22 c = 2.222 d = -22.00001 x = a if b > x: x = b if c > x: x = c if d > x: x = d print(x) $ python3 largest.py 22

else and elif clauses Operators >>> a = 23 >>> if a % 2 == 0:... print("a is even")... else:... print("a is odd")... a is odd

else and elif clauses Nested if and else Operators if char == 'a': print("char is 'a'") else: if char == 'b': print("char is 'b'") else: if char == 'c': print("char is 'c'") else: print("none of the above")

else and elif clauses Using elif Operators if char == 'a': print("char is 'a'") elif char == 'b': print("char is 'b'") elif char == 'c': print("char is 'c'") else: print("none of the above")