Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Computer Programming http://profs.info.uaic.ro/~grigoras/Geo [email protected] Why Python? • Teaching introductory GIS programming to geographers using an open source Python approach ( Journal of Geography in Higher EducationVolume 40, 2016 Issue 1) ! Computer programming is not commonly taught to geographers as a part of geographic information system (GIS) courses, but the advent of NeoGeography, big data and open GIS means that programming skills are becoming more important. ! These laboratories use core spatial concepts that are relevant for all areas of geographic study, and use an open source Python approach that has wider logistical and pedagogical benefits. 2 Why Python? • Python for ArcGIS ( http://resources.arcgis.com/en/communities/python/ ) • Free GIS Programming Tutorials: Learn How to Code (http://gisgeography.com/free-gis-programming-tutorials/ ) ! Python has been a standard language in GIS because Esri and open source tend to gravitate toward it. Of all GIS programming languages, many consider it to be the frontrunner. • Python for ArcGIS ( http://desktop.arcgis.com/en/analytics/python/ ) ! Perform spatial analysis, data management, data conversion, and map automation and production using Python with ArcGIS for Desktop or ArcGIS for Server. 3 Bibliography • • • • • • • https://www.python.org/ https://wiki.python.org/moin/BeginnersGuide https://docs.python.org/2/tutorial/ https://www.python.org/downloads/ https://wiki.python.org/moin/IntroductoryBooks http://it-ebooks.info/read/304/ https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ index.html • https://docs.python.org/2/library/idle.html • https://www.tutorialspoint.com/python3/ 4 Evaluare • 50% Laborator • 50% Test scris 5 Short History - Computers Ancient era: Abacus • Abacus: 7 New calculating tools • John Napier's calculating tables from around 1680: 8 Mechanical calculators • Pascal's calculator. Pascal invented his machine in 1642. • He built twenty of these machines (called Pascal's Calculator or Pascaline) in the following ten years. 9 Punched card data processing • 1801: Joseph-Marie Jacquard developed a loom in which the pattern being woven was controlled by punched cards. • 1880: the American Herman Hollerith invented data storage on punched cards that could then be read by a machine • 1911: Computing Tabulating Recording Company (CTR) formed by the merger of the Tabulating Machine Company and three other companies. In 1924 renamed International Business Machines (IBM). • 1920: electro-mechanical tabulating machines could add, subtract and print accumulated totals. • 1935: IBM punched card systems were used to process records of 26 million workers. 10 First general-purpose computing device • Charles Babbage, (26 December 1791 – 18 October 1871) was an English polymath. He was a mathematician, philosopher, inventor and mechanical engineer, who is best remembered now for originating the concept of a programmable computer. • 1822: the difference engine, made to compute values of polynomial functions. 11 First general-purpose computing device • 1843: Babbage worked to design a more complex machine called the Analytical Engine • Ada Lovelace - the first computer programmer - is credited with developing an algorithm for the Analytical Engine to calculate a sequence of Bernoulli numbers. 12 Analog computers • 1872: The first modern analog computer was a tidepredicting machine, invented by Sir William Thomson, later Lord Kelvin • 1927: the differential analyzer built by H. L. Hazen and Vannevar Bush at MIT 13 Electromechanical computers • 1939: German engineer Konrad Zuse created Z2 one of the earliest examples of an electromechanical relay computer. • 1941: Zuse followed his earlier machine up with the Z3, the world's first working electromechanical programmable, fully automatic digital computer. 14 Electronic data processing • 1942: John Vincent Atanasoff and Clifford E. Berry of Iowa State University developed and tested the Atanasoff–Berry Computer (ABC) • This design was also all-electronic, and used about 300 vacuum tubes, with capacitors fixed in a mechanically rotating drum for memory 15 The electronic programmable computer • Colossus was the world's first electronic digital computer that was programmable. The Colossus computers were developed for British codebreakers during World War II to help in the cryptanalysis of the Lorenz cipher • Colossus Mark 1, was shown to be working in December 1943 and was operational at Bletchley Park by 5 February 1944. An improved Colossus Mark 2 that used shift registers to quintuple the speed, first worked on 1 June 1944, just in time for the Normandy Landings. Ten Colossi were in use by the end of the war. • A functioning replica of a Colossus computer was completed in 2007 and is on display at The National Museum of Computing at Bletchley Park. 16 Colossus rebuild 17 The stored-program computer • The theoretical basis for the stored-program computer had been laid by Alan Turing in his 1936 paper. In 1945 Turing joined the National Physical Laboratory and began work on developing an electronic stored-program digital computer. His 1945 report ‘Proposed Electronic Calculator’ was the first specification for such a device. 18 The stored-program computer • the Manchester Mark 1 at the University of Manchester. Work began in August 1948, and the first version was operational by April 1949 • the EDSAC (Electronic Delay Storage Automatic Calculator) designed and constructed by Maurice Wilkes and his team at the University of Cambridge Mathematical Laboratory in 1949. • ENIAC (Electronic Numerical Integrator And Computer) inventors John Mauchly and J. Presper Eckert proposed the EDVAC's (Electronic Discrete Variable Automatic Computer) construction in August 1944, and design work for the EDVAC commenced at the University of Pennsylvania's Moore School of Electrical Engineering, before the ENIAC was fully operational. 19 Commercial computers • The first commercial computer was the Ferranti Mark 1, built by Ferranti and delivered to the University of Manchester in February 1951 • In June 1951, the UNIVAC I (Universal Automatic Computer) was delivered to the U.S. Census Bureau. Remington Rand sold 46 machines at more than US$1 million each ($9.09 million as of 2014) • IBM introduced a smaller, more affordable computer in 1954 that proved very popular. The IBM 650 weighed over 900 kg, the attached power supply weighed around 1350 kg and both were held in separate cabinets of roughly 1.5 meters by 0.9 meters by 1.8 meters. It cost US$500,000 ($4.39 million as of 2014) 20 • In 1951, British scientist Maurice Wilkes developed the concept of microprogramming • By 1954, magnetic core memory was rapidly displacing most other forms of temporary storage • IBM introduced the first disk storage unit, the IBM 350 RAMAC (Random Access Method of Accounting and Control) in 1956. • From 1955 onwards transistors replaced vacuum tubes in computer designs • A second generation computer, the IBM 1401, captured about one third of the world market. IBM installed more than ten thousand 1401s between 1960 and 1964. 21 Post-1960: third generation • Integrated Circuit: Kilby (Texas Instruments) recorded his initial ideas concerning the integrated circuit in July 1958, successfully demonstrating the first working integrated example on 12 September 1958 • IBM System/360 in 1964. It was the first family of computers designed to cover the complete range of applications, from small to large, both commercial and scientific. • April 1975 at the Hannover Fair, Olivetti presented the P6060, the world's first personal computer with built-in floppy disk 22 Minicomputers • The term "minicomputer" developed in the 1960s to describe the smaller computers that became possible with the use of transistors and core memory technologies, minimal instructions sets and less expensive peripherals • Digital Equipment Corporation's (DEC) 12-bit PDP-8, which was built using discrete transistors and cost from US$16,000 upwards when launched in 1964 23 PC • An early use of the term "personal computer" appeared in a November 3, 1962, New York Times article reporting John W. Mauchly's vision of future computing as detailed at a recent meeting of the American Institute of Industrial Engineers. Mauchly stated, "There is no reason to suppose the average boy or girl cannot be master of a personal computer” • Six years later a manufacturer took the risk of referring to their product this way, when Hewlett-Packard advertised their "Powerful Computing Genie" as "The New Hewlett-Packard 9100A personal computer” • Over the next seven years the phrase had gained enough recognition that when Byte magazine published its first edition, it referred to its readers as "[in] the personal computing field” and Creative Computing defined the personal computer as a "non(time)shared system containing sufficient processing power and storage capabilities to satisfy the needs of an individual user. 24 PC - The beginnings • Simon was a project developed by Edmund Berkeley and presented in a thirteen articles series issued in RadioElectronics magazine, from October 1950. The Simon represented the first experience of building an automatic simple digital computer, for educational purposes. In 1950, it was sold for US$600 • The IBM 610 was designed between 1948 and 1957 by John Lentz at the Watson Lab at Columbia University as the Personal Automatic Computer (PAC) and announced by IBM as the 610 Auto-Point in 1957. With a price tag of $55,000, only 180 units were produced. 25 PC - The beginnings • The Programma 101 was the first commercially produced "desktop computer” designed and produced by the Italian company Olivetti and presented at the 1965 New York World's Fair. Over 44,000 units were sold worldwide; in the US its cost at launch was $3,200. • The Soviet MIR series of computers was developed from 1965 to 1969 in a group headed by Victor Glushkov. • The Kenbak-1 is considered by the Computer History Museum to be the world's first personal computer. It was designed and invented by John Blankenbaker of Kenbak Corporation in 1970, and was first sold in early 1971. The system first sold for US$750. 26 PC - The beginnings • The Xerox Alto, developed at Xerox PARC in 1973, was the first computer to use a mouse, the desktop metaphor, and a graphical user interface (GUI), concepts first introduced by Douglas Engelbart while at International. It was the first example of what would today be recognized as a complete personal computer. 27 PC - The beginnings • Three machines, the Apple II, PET 2001 and TRS-80 were all released in 1977, eventually selling millions of machines. 28 The IBM PC • IBM responded to the success of the Apple II with the IBM PC, released in August, 1981. 29 Apple Lisa and Macintosh • In 1983 Apple Computer introduced the first mass-marketed microcomputer with a graphical user interface, the Lisa. • Apple launched the Macintosh in 1984, the first successful mass-market mouse-driven computer with a graphical user interface or 'WIMP' (Windows, Icons, Menus, and Pointers). Based on the Motorola 68000 microprocessor, the Macintosh included many of the Lisa's features at a price of US$2,495. 30 PC clones • In 1985, the Atari ST, also based on the Motorola 68000 microprocessor, was introduced with the first color GUI in the Atari TOS. In 1986, the 32-bit Intel 80386 microprocessor was released, and the first '386-based PCcompatible was the Compaq Deskpro 386. 31 1990s and 2000s • In the early 1990s, the CD-ROM became an industry standard, and by the mid-1990s one was built into almost all desktop computers, and towards the end of the 1990s, in laptops as well. • In 1994, Apple introduced the Power Macintosh series of high-end professional desktop computers for desktop publishing and graphic designers. • In the late 1990s CD-R and later, rewritable CD-RW drives were included instead of standard CD ROM drives • Since the late 1990s, many more personal computers started shipping that included USB (Universal Serial Bus) ports for easy plug and play connectivity to devices 32 1990s and 2000s • In 2001, 125 million personal computers were shipped in comparison to 48,000 in 1977 • More than 500 million PCs were in use in 2002 and one billion personal computers had been sold worldwide since mid-1970s till this time • About 81.5 percent of PCs shipped had been desktop computers, 16.4 percent laptops and 2.1 percent servers • United States had received 38.8 percent (394 million) of the computers shipped, Europe 25 percent and 11.7 percent had gone to Asia-Pacific region, the fastest-growing market as of 2002 33 Programming Languages Short History Early history • 1842-1843: Ada Lovelace translated the memoir of Italian mathematician Luigi Menabrea about Charles Babbage's newest proposed machine, the Analytical Engine. • 1880: Herman Hollerith realized that he could encode information on punch cards • Alonzo Church was able to express the lambda calculus in a formulaic way. • The Turing machine was an abstraction of the operation of a tape-marking machine 35 First programming languages • An early high-level programming language to be designed for a computer was Plankalkül, developed for the German Z3 by Konrad Zuse between 1943 and 1945 • John Mauchly's Short Code, proposed in 1949, was one of the first high-level languages ever developed for an electronic computer. • The first code and compiler was developed in 1952 for the Mark 1 computer at the University of Manchester and is considered to be the first compiled high-level programming language • The second autocode was developed for the Mark 1 by R. A. Brooker in 1954 and was called the "Mark 1 Autocode". 36 First programming languages • FLOW-MATIC, Grace Hopper in the US. It was developed for the UNIVAC I at Remington Rand during the period from 1955 until 1959. Flow-Matic was a major influence in the design of COBOL(1958) • The language Fortran was developed at IBM in the mid 1950s, and became the first widely used high-level general purpose programming language. • LISP (1958), invented by John McCarthy • ALGOL 60 Report (the "ALGOrithmic Language"), ALGOL 68 • 1960 - Simula, the first language designed to support object-oriented programming. 37 Fundamental paradigms • • • • • • • • • • • 1960 1968 1969 1970 1970 1972 1972 1972 1973 1975 1978 - Simula, object-oriented programming. – Logo - B (forerunner to C) – Pascal – Forth – C, systems programming language – Smalltalk, complete object-oriented language. – Prolog - first logic programming language – ML - functional programming language – Scheme - SQL (a query language, later extended) 38 Modules, Performance • • • • • • • • • • • 1980 1983 1984 1984 1985 1986 1986 1987 1988 1988 1989 - C++ (as C with classes, renamed in 1983) – Ada - Common Lisp - MATLAB – Eiffel - Objective-C – Erlang – Perl – Tcl – Mathematica - FL (Backus) 39 1990s: the Internet age • • • • • • • • • • • • • 1990 1991 1991 1993 1993 1994 1995 1995 1995 1995 1995 1996 1997 – Haskell – Python - Visual Basic – Ruby – Lua - CLOS (part of ANSI Common Lisp) - Ada 95 – Java - Delphi (Object Pascal) – JavaScript – PHP – WebDNA – Rebol • 1999 – D 40 Current trends • Increasing support for functional programming • Constructs to support concurrent and distributed programming • Component-oriented software development • Metaprogramming, reflection or access to the abstract syntax tree • Integration with databases, including XML and relational databases • XML for graphical interface (XUL, XAML) • Open source as a developmental philosophy for languages, including the GNU compiler collection and recent languages such as Python, Ruby, and Squeak. • AOP or Aspect Oriented Programming 41 Current trends • • • • • • • • • • • • 2000 – ActionScript 2001 - C# 2001 - Visual Basic .NET 2002 - F# 2003 - Groovy 2003 - Scala 2007 – Clojure 2009 – Go 2011 – Dar 2012 – Rust 2014 – Swift http://en.wikipedia.org/wiki/ List_of_programming_languages 42 Python! • Created in 1991 by Guido van Rossum ! I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus). • https://gvanrossum.github.io ! I am the author of the Python programming language. ! In January 2013 I joined Dropbox. I work on various Dropbox products and have 50% for my Python work, no strings attached. Previously, I have worked for Google, Elemental Security, Zope Corporation, BeOpen.com, CNRI, CWI, and SARA. 43 Python! • Useful as a scripting language ! script: A small program meant for one-time use ! Targeted towards small to medium sized projects • Used by: ! Google, Yahoo!, Youtube ! Many Linux distributions ! Games and apps (e.g. Eve Online) 44 Python! • Python is a multi-paradigm programming language: ! object-oriented programming and structured programming are fully supported ! there are a number of language features which support functional programming and aspect-oriented programming (including by metaprogramming and by magic methods). ! many other paradigms are supported using extensions, including design by contract and logic programming. • Python uses dynamic typing • An important feature of Python is dynamic name resolution (late binding), which binds method and variable names during program execution. 45 Python! • The core philosophy of the language is summarized by the aphorisms : ! ! ! ! ! Beautiful is better than ugly Explicit is better than implicit Simple is better than complex Complex is better than complicated Readability counts 46 Installing Python https://www.python.org/downloads/ Windows: • Download Python from http:// www.python.org • Install Python. • Run Idle from the Start Menu. Mac OS X: • Python is already installed. • Open a terminal and run python or run Idle from Finder. Linux: • Chances are you already have Python installed. To check, run python from the terminal. • If not, install from your distribution's package system. 47 Interpreted Languages • interpreted ! Not compiled like Java ! Code is written and then directly executed by an interpreter ! Type commands into interpreter and see immediate results Java: Python: Code Compiler Code Runtime Environment Computer Interpreter Computer 48 The Python Interpreter • Allows you to type commands one-at-a-time and see results • A great way to explore Python's syntax ! Repeat previous command: Alt+P ! https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ index.html 49 Our First Python Program • Python does not have a main method like Java ! The program's main code is just written directly in the file • Python statements do not end with semicolons hello.py 1 print("Hello, world!") 50 Python Identifiers • A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). • Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python. 51 Naming conventions • Class names start with an uppercase letter. All other identifiers start with a lowercase letter. • Starting an identifier with a single leading underscore indicates that the identifier is private. • Starting an identifier with two leading underscores indicates a strongly private identifier. • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name. 52 Reserved Words and exec not as finally or assert for pass break from print class global raise continue if return def import try del in del elif is with else lambda yield except 53 Lines and Indentation • Python doesn't use braces({}) to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. • The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. • Example: if True:! print ("True")! else:! print ("False") 54 An error if True:! print ("Answer")! print ("True")! else:! print "(Answer")! print ("False") 55 Multi-Line Statements • Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example: total = item_one + \! item_two + \! item_three! • Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example: days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] 56 Quotation in Python • Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal: word = 'word’! sentence = "This is a sentence.”! paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" 57 Comments in Python • A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them. # First comment! print ("Hello, Python!") # second comment! name = "Madisetti" # This is again comment 58 Waiting for the User • The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action input("\n\nPress the enter key to exit.")! • Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. Press the enter key to exit.! ''! >>>! 59 Assigning Values to Variables • Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. • The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. counter = 100 # An integer assignment! miles = 1000.0 name = "John" print (counter)! print (miles)! print (name) # A floating point! # A string! 60 Multiple Assignment • Python allows you to assign a single value to several variables simultaneously. For example: a = b = c = 1! a, b, c = 1, 2, "john”! • Variables can change (they are variable!) x = 1.343 ! X = 2 ! x = 10 + 4! x = -3! 61 Standard Data Types • The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. • Python has five standard data types: ! ! ! ! ! Numbers String List Tuple Dictionary 62 Python Numbers • Number data types store numeric values. Number objects are created when you assign a value to them. For example: var1 = 1! var2 = 10! • You can also delete the reference to a number object by using the del statement. The syntax of the del statement is: del var1[,var2[,var3[....,varN]]]]! del var! del var_a, var_b 63 Python Numbers • Python supports four different numerical types: ! int (signed integers) ! float (floating point real values) ! complex (complex numbers) int 10 100 -786 080 -0490 float 0.0 15.20 -21.9 32.3+e18 -90. complex 3.14j 45.j 9.322e-36j .876j -.6545+0J 64 Python Strings • Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. • Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string str = print print print print print print 'Hello World!’! (str) # (str[0]) # (str[2:5]) # (str[2:]) # (str * 2) # (str + "TEST") Prints complete string! Prints first character of the string! Prints characters from 3rd to 5th! Prints string from 3rd character! Prints string two times! # Prints concatenated string 65 Python Lists • A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. • The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list • The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. 66 Python Lists list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]! tinylist = [123, 'john']! print (list) # Prints complete list! print (list[0]) # Prints first element of the list! print (list[1:3]) # Prints elements starting from 2nd till 3rd : [786, 2.23]! print (list[2:]) # Prints elements starting from 3rd element: [2.23, 'john', 70.200000000000003]! print (tinylist * 2) # Prints list two times! print (list + tinylist) # Prints concatenated lists 67 Python Tuples • A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. • The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. • Tuples can be thought of as read-only lists. 68 tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )! tinytuple = (123, 'john')! print (tuple) # Prints complete tuple! print (tuple[0]) # Prints first element of the tuple! print (tuple[1:3]) # Prints elements starting from 2nd till 3rd: (786, 2.23) ! print (tuple[2:]) # Prints elements starting from 3rd element! print (tinytuple * 2) # Prints tuple two times! print (tuple + tinytuple) # Prints concatenated tuple 69 >>> tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )! >>> list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]! >>> list[2] = 1000! >>> list! ['abcd', 786, 1000, 'john', 70.2]! >>> tuple[2] = 1000! Traceback (most recent call last):! File "<pyshell#13>", line 1, in <module>! tuple[2] = 1000! TypeError: 'tuple' object does not support item assignment! 70 Python Dictionary • Python's dictionaries consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. • Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). • Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered. 71 Python Dictionary dict = {}! dict['one'] = "This is one”! dict[2] = "This is two”! tinydict = {'name': 'john','code':6734, 'dept’:'sales'}! print (dict['one']) # Prints value for 'one' key! print (dict[2]) # Prints value for 2 key! print (tinydict) # Prints complete dictionary! print (tinydict.keys()) # Prints all the keys! print (tinydict.values()) # Prints all the values! This is one! This is two! {'dept': 'sales', 'code': 6734, 'name': 'john'}! ['dept', 'code', 'name']! ['sales', 6734, 'john'] 72 Data Type Conversion • To convert between types, you simply use the type name as a function. Function Description int(x [,base]) Converts x to an integer. Base specifies the base if x is a string. float(x) Converts x to a floating-point number. complex(real [,imag]) Creates a complex number. str(x) Converts object x to a string representation. str(x) Converts object x to a string representation. repr(x) Converts object x to an expression string. eval(str) Evaluates a string and returns an object. tuple(s) Converts s to a tuple. list(s) Converts s to a list. 73 Data Type Conversion • There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value. Function set(s) dict(d) frozenset(s) chr(x) unichr(x) ord(x) hex(x) oct(x) Description Converts s to a set. Creates a dictionary. d must be a sequence of (key,value) tuples. Converts s to a frozen set. Converts an integer to a character. Converts an integer to a Unicode character. Converts a single character to its integer value. Converts an integer to a hexadecimal string. Converts an integer to an octal string. 74 Types of Operator • Python language supports the following types of operators: ! ! ! ! ! ! ! Arithmetic Operators Comparison (Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators 75 Python Arithmetic Operators • Assume variable a holds 10 and variable b holds 21: Operator + Addition - Subtraction * Multiplication / Division % Modulus ** Exponent // Floor Division Description Adds values on either side Subtracts right operand from left Multiplies values on either side Divides left hand right hand Divides and returns remainder Performs exponential (power) The result is the quotient Example a + b = 31 a – b = -11 a * b = 210 b / a = 2.1 b%a=1 a**b =10^2 9//2 = 4 9.0//2.0 = 4.0 -11//3 = -4 -11.0//3 = -4.0 76 Python Comparison Operators • These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators. • Assume variable a holds 10 and variable b holds 20: ! ! ! ! ! ! (a == b) is not true. (a!= b) is true. (a > b) is not true. (a < b) is true. (a >= b) is not true. (a <= b) is true. 77 Python Assignment Operators • • • • • • • • c c c c c c c c =a+b += a -= a *= a /= a %= a **= a //= a assigns value of a + b into c is equivalent to c = c + a is equivalent to c = c – a is equivalent to c = c * a is equivalent to c = c / a is equivalent to c = c % a is equivalent to c = c ** a is equivalent to c = c // a 78 Python Bitwise Operators • Bitwise operator works on bits and performs bit by bit operation. >>> a = 60 >>> b = 13 >>> bin(a) '0b111100' >>> bin(b) '0b1101’ ! a = 0011 1100 b = 0000 1101 • • • • (a & b) = 12 (means 0000 1100) (a|b) = 61 (means 0011 1101) (a ^ b) = 49 (means 0011 0001) (~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number. • a << 2 = 240 (means 1111 0000) • a >> 2 = 15 (means 0000 1111) 79 Python Logical Operators >>> a = True >>> b = False >>> a and b False >>> a or b True >>> not a False 80 Python Membership Operators • Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators: ! in Evaluates to true if it finds a variable in the specified sequence and false otherwise. ! not in Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. >>> list = [1, 2, 3, 4, 5 ] >>> a=10 >>> b=20 >>> a in list False >>> b not in list True 81 Python Identity Operators • Identity operators compare the memory locations of two objects. There are two Identity operators: ! is ! is not Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. >>> a = 20 >>> b = 20 >>> id(a) 4297624544 >>> id(b) 4297624544 >>> c = 30 >>> id(c) 4297624864 >>> a is b True >>> a is c False 82 Python Operators Precedence Operator ** ~+* / % // +>> << & ^| <= < > >= <> == != = %= /= //= -= += *= **= is is not in not in not or and 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 Identity operators Membership operators Logical operators 83 Using Python as a Calculator >>> 4 >>> 20 >>> 5.0 >>> 1.6 2+2 50 - 5*6 (50 - 5*6) / 4 8 / 5 # division always returns a floating point number 84 Using Python as a Calculator >>> 17 / 3 # classic division returns a float 5.666666666666667 >>> >>> 17 // 3 # floor division discards the fractional part 5 >>> 17 % 3 # the % operator returns the remainder of the division 2 >>> 5 * 3 + 2 # result * divisor + remainder 17 85 Using Python as a Calculator >>> 5 ** 2 # 5 squared 25 >>> 2 ** 7 # 2 to the power of 7 128 >>> 55**55 524744532468751923546122657597368049278513737089035 272057324643668607677682302892208099365234375 >>> width = 20 >>> height = 5 * 9 >>> width * height 900 86 Using Python as a Calculator • In interactive mode, the last printed expression is assigned to the variable _. >> 5+75 80 >>> _ 80 >>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06 87 Strings • Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result >>> 'spam eggs' # single quotes 'spam eggs’ >>> 'doesn\'t' # use \' to escape the single quote... "doesn't” >>> "doesn't" # ...or use double quotes instead "doesn't” >>> '"Yes," he said.’ ’"Yes," he said.’ >>> "\"Yes,\" he said.” '"Yes," he said.’ >>> '"Isn\'t," she said.’ '"Isn\'t," she said.' 88 Strings • If you want to concatenate variables or a variable and a literal, use +: • Strings can be indexed (subscripted), with the first character having index 0. >>> >>> >>> >>> 'P’ >>> 'n' prefix = 'Py’ prefix + 'thon''Python’ word = 'Python’ word[0] # character in position 0 word[5] # character in position 5 89 Strings >>> word[-1] # last character 'n’ >>> word[-2] # second-last character 'o’ >>> word[-6] 'P’ >>> word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py’ >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho’ >>> word[:2] + word[2:] 'Python’ >>> word[:4] + word[4:] 'Python' 90 Lists >>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25] >>> squares[0] # indexing returns the item 1 >>> squares[-1] 25 >>> squares[-3:] # slicing returns a new list [9, 16, 25] >>> squares[:] [1, 4, 9, 16, 25] 91 List concatenation >>> squares + [36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] • Unlike strings, which are immutable, lists are a mutable type: cubes = [1, 8, 27, 65, 125] # something's wrong here >>> 4 ** 3 # the cube of 4 is 64, not 65! 64 >>> cubes[3] = 64 # replace the wrong value >>> cubes [1, 8, 27, 64, 125] 92 append >>> cubes.append(216) # add the cube of 6 >>> cubes.append(7 ** 3) # and the cube of 7 >>> cubes [1, 8, 27, 64, 125, 216, 343] >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> letters ['a', 'b', 'c', 'd', 'e', 'f', 'g'] >>> # replace some values >>> letters[2:5] = ['C', 'D', 'E'] >>> letters ['a', 'b', 'C', 'D', 'E', 'f', 'g'] 93 Nested lists >>> a = ['a', 'b', 'c'] >>> n = [1, 2, 3] >>> x = [a, n] >>> x [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b' 94 Decision Making • Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise. • Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value. • Python programming language provides following types of decision making statements: ! if statement ! if … else statement ! nested if statements 95 IF Statement • The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison: if expression: ! statement(s) • if the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. In Python, statements in a block are uniformly indented after : symbol. If boolean expression evaluates to FALSE, then the first set of code after the end of block is executed 96 IF Statement 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!")! 1 - Got a true expression value! 100! Good bye! 97 IF…ELSE Statement • An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value if expression:! statement(s)! else:! statement(s) 98 IF…ELSE Statement amount=int(input("Enter amount: "))! if amount<1000:! discount=amount*0.05! print ("Discount",discount)! else:! discount=amount*0.10! print ("Discount",discount)! print ("Net payable:",amount-discount)! Enter amount: 600! Discount 30.0! Net payable: 570.0! Enter amount: 1200! Discount 120.0! Net payable: 1080.0 99 The elif Statement • The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. if expression1:! statement(s)! elif expression2:! statement(s)! elif expression3:! statement(s)! else: statement(s) 100 The elif Statement amount=int(input("Enter amount: "))! if amount<1000:! discount=amount*0.05! print ("Discount",discount)! elif amount<5000:! discount=amount*0.10! print ("Discount",discount)! else:! discount=amount*0.15! print ("Discount",discount) ! print ("Net payable:",amount-discount) 101 The elif Statement Enter amount: 600! Discount 30.0! Net payable: 570.0! Enter amount: 3000! Discount 300.0! Net payable: 2700.0! Enter amount: 6000! Discount 900.0! Net payable: 5100.0 102 Loops • In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. • A loop statement allows us to execute a statement or group of statements multiple times. • Python programming language provides following types of loops: ! while loop ! for loop ! nested loops 103 while Loop Statement • A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. while expression:! statement(s) • Here, statement(s) may be a single statement or a block of statements with uniform indent. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. • When the condition becomes false, program control passes to the line immediately following the loop. 104 while Loop Statement count = 0! while (count < 5):! print ('The count is:', count)! count = count + 1! print ("Good bye!")! The count The count The count The count The count Good bye! is: is: is: is: is: 0! 1! 2! 3! 4! 105 for Loop Statement • The for statement in Python has the ability to iterate over the items of any sequence, such as a list or a string. for iterating_var in sequence:! statements(s) • if a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted. 106 for Loop Statement for letter in 'Python':! # traversal of a string sequence! print ('Current Letter :', letter)! print()! fruits = ['banana', 'apple', 'mango']! for fruit in fruits:! # traversal of List sequence! print ('Current fruit :', fruit)! print ("Good bye!") 107 for Loop Statement • The built-in function range() is the right function to iterate over a sequence of numbers. It generates an iterator of arithmetic progressions. >>> range(5)! range(0, 5)! >>> list(range(5))! [0, 1, 2, 3, 4]! >>> for var in list(range(5)):print(var)! 0! 1! 2! 3! 4! >>> for var in (range(5)):print(var)! 0! 1! 2! 3! 4! 108 fruits = ['banana', 'apple', 'mango']! for index in range(len(fruits)):! print ('Current fruit :', fruits[index])! print ("Good bye!")! Current fruit : banana! Current fruit : apple! Current fruit : mango! Good bye! 109 Nested loops • Python programming language allows to use one loop inside another loop. for iterating_var in sequence:! for iterating_var in sequence:! statements(s)! statements(s)! while expression:! while expression:! statement(s)! statement(s) 110 for i in range(1,11):! for j in range(1,11):! k=i*j! print (k, end=' ')! print()! 1 2 3 4 5 6 7 8 9 10 ! 2 4 6 8 10 12 14 16 18 20! 3 6 9 12 15 18 21 24 27 30 ! 4 8 12 16 20 24 28 32 36 40 ! 5 10 15 20 25 30 35 40 45 50 ! 6 12 18 24 30 36 42 48 54 60 ! 7 14 21 28 35 42 49 56 63 70 ! 8 16 24 32 40 48 56 64 72 80 ! 9 18 27 36 45 54 63 72 81 90 ! 10 20 30 40 50 60 70 80 90 100 111 Loop Control Statements • Loop control statements change execution from its normal sequence. • When execution leaves a scope, all automatic objects that were created in that scope are destroyed. • Python supports the following control statements: ! break statement ! continue statement ! pass statement 112 break statement • The break statement is used for premature termination of current loop. After abandoning the loop, execution at the next statement is resumed: 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!") 113 Using else Statement with Loops • Python supports to have an else statement associated with a loop statement • If the else statement is used with a for loop, the else block is executed only if for loops terminates normally (and not by encountering break statement). • If the else statement is used with a while loop, the else statement is executed when the condition becomes false. 114 Examples no=int(input('any number: '))! numbers=[11,33,55,39,55,75,37,21,23,41,13]! for num in numbers:! if num==no:! print ('number found in list')! break! else:! print ('number not found in list')! any number: 33! number found in list! any number: 22! number not found in list 115 Examples numbers=[11,33,55,39,55,75,37,21,23,41,13]! for num in numbers:! if num%2==0:! print ('the list contains an even number')! break! else:! print ('the list does not contain even number')! the list does not contain even number 116 continue statement • The continue statement in Python returns the control to the beginning of current loop. • When encountered, the loop starts next iteration without executing remaining statements in the current iteration. • The continue statement can be used in both while and for loops. 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!") 117 pass Statement • The pass statement is a null operation; nothing happens when it executes. • It is used when a statement is required syntactically but you do not want any command or code to execute. for letter in 'Python':! if letter == 'h':! pass! print ('This is pass block')! print ('Current Letter :', letter)! print ("Good bye!") 118