Programming in Python

Size: px
Start display at page:

Download "Programming in Python"

Transcription

1 Programming in Python Project Future (Fall 2017) Yanqiao ZHU Camp School of Software Engineering, Tongji University

2 Outline 1 Getting Started Setting Up Environment Editing Python 2 Introduction to Python Language Introduction Features 3 Basic Syntax First Python Program Python Identifiers Lines and Indentation Comments Command-Line Arguments Code Checked at Runtime 4 Data Types and Operators Variables Built-in Types Basic Operators 5 Control Statements Branches Loops 6 Functions 7 Modules 8 Exceptions 9 Further More Getting Help Built-in Documentation

3 Getting Started Python Set Up Python is free and open source, available for all operating systems from pythonorg In particular we want a Python install where you can do two things: Run an existing python program, such as hellopy Run the Python interpreter interactively, so you can type code right at it

4 Getting Started Python on Linux and macos Most operating systems other than Windows already have Python installed by default To check that Python is installed, open the terminal and type python in the terminal to run the Python interpreter interactively: sxkdz:~$ python Python 361 ( default, Mar , 16: 49: 06) [ GCC 421 Compatible Apple LLVM 800 ( clang )] on darwin Type "help", "copyright", "credits" or "license" for more information >>> print(' Hello, world ') Hello, world Listing 11: First Run

5 Getting Started Python on Windows 1 Go to the download page, select a version (the legacy version is 2x, the newest version is 361) 2 Run the Python installer, taking all the defaults This will install Python in the root directory and set up some file associations To run the Python interpreter interactively, select the Run command from the Start menu, and type python this will launch Python interactively in its own window

6 Getting Started Exit Interactive-Mode Python On Windows, use Ctrl + Z to represent EOF (End-of-File) and exit On all other operating systems, EOF is represented by + D or Ctrl + D

7 Getting Started Editing Python A Python program is just a text file that you edit directly As above, you should have a command line open, where you can type python hellopy Alice to run whatever you are working on At the command line prompt, just hit the key to recall previously typed commands without retyping them You want a text editor with a little understanding of code and indentation There are many good free ones: 1 Notepad++ (free and open source, Windows only) 2 Visual Studio Code with Python or MagicPython extension (free and open source, cross platform) 3 PyCharm (professional, cross platform, free for students) 4 Thonny (official recommended, free, cross platform)

8 Introduction to Python Language Introduction Python is a clear and powerful object-oriented programming language, comparable to Perl, Ruby, Scheme, or Java Python is a dynamic, interpreted (bytecode-compiled) language There are no type declarations of variables, parameters, functions, or methods in source code This makes the code short and flexible, and you lose the compile-time type checking of the source code Python tracks the types of all values at runtime and flags code that does not make sense as it runs

9 Introduction to Python Notable Features Easy-to-learn: has an elegant syntax, few keywords and somple structure Easy-to-read: Python code is clearly defined and visible to the eyes Ideal for prototype development and other ad-hoc programming tasks, without compromising maintainability A board standard library: supports many common programming tasks such as connecting to web servers, searching text with regular expressions, reading and modifying files Extendable: can add new modules implemented in a compiled language such as C or C++ Cross-platform compatible

10 Introduction to Python Features at Programming-Language Level A variety of basic data types are available Python supports object-oriented programming with classes and multiple inheritance Code can be grouped into modules and packages The language supports raising and catching exceptions, resulting in cleaner error handling

11 Introduction to Python Features at Programming-Language Level (cont) Data types are strongly and dynamically typed Mixing incompatible types (eg attempting to add a string and a number) causes an exception to be raised, so errors are caught sooner Python contains advanced programming features such as generators and list comprehensions Python s automatic memory management frees you from having to manually allocate and free memory in your code

12 Basic Syntax First Python Program There re two ways of programming in Python: Interactive Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the prompt like Listing 11 Script Mode Programming Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished When the script is finished, the interpreter is no longer active

13 Basic Syntax First Python Program (cont) Let us write a simple Python program in a script Python files have extension py Type the following source code in a hellopy file: 1 #!/usr/bin/python3 2 3 print(" Hello, Python!") Listing 31: First Python Program We assume that you have Python interpreter available in /usr/bin directory

14 Basic Syntax First Python Program (cont) Now, try to run this program as follows: $ chmod +x hello py $ / hello py Listing 32: Modify the Property of the Script and Run This produces the following result: Hello, Python! Listing 33: Result of the Script

15 Basic Syntax First Python Program (cont) Shebang The first line in Listing 31 is called Shebang Under Unix-like operating systems, when a script with a shebang is run as a program, the program loader parses the rest of the script s initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script A valid shebang begins with number sign and exclamation mark (#!) and is at the beginning of a script chmod in Listing 32 is to make the script file executable

16 Basic Syntax 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 does not allow punctuation characters such $, and % within identifiers Python is a case sensitive programming language Thus, Foobar and foobar are two different identifiers in Python

17 Basic Syntax Python Identifiers (cont) Here are naming conventions for Python identifiers: 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

18 Basic Syntax Variable Names Since Python variables don t have any type spelled out in the source code, it s extra helpful to give meaningful names to your variables to remind yourself of what s going on So use: name if it s a single name names if it s a list of names tuples if it s a list of tuples In general, Python prefers the underscore method but guides developers to defer to camelcasing if integrating into existing Python code that already uses that style Readability counts

19 Basic Syntax Reserved Words Table 31 shows the Python keywords These are reserved words and can t be used as constant or variable or any other identifier names All the Python keywords contain lowercase letters only auto del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass with def finally in print yield Table 31: Python Reserved Words

20 Basic Syntax Lines and Indentation Python provides no 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 A logical block of statements such as the ones that make up a function should all have the same indentation, set in from the indentation of their parent function or if or whatever If one of the lines in a group has a different indentation, it is flagged as a syntax error

21 Basic Syntax Lines and Indentation (cont) Avoid using TAB s as they greatly complicate the indentation scheme A common question beginners ask is, How many spaces should I indent? According to the official Python style guide (PEP 8), you should indent with 4 spaces (Fact: Google s internal style guideline dictates indenting by 2 spaces)

22 Basic Syntax 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: 1 foo = bar_one + \ 2 bar_two + \ 3 bar_three Listing 34: A Multi-line Statement Statements contained within the [], {}, or () brackets do not need to use the line continuation character

23 Basic Syntax Using Blank Lines A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it In an interactive interpreter session, you must enter an empty physical line to terminate a multi-line statement

24 Basic Syntax Multiple Statements on a Single Line The semicolon (;) allows multiple statements on the single line given that neither statement starts a new code block Here is a sample snip using the semicolon: 1 import sys; x = 'foo'; sys stdout write(x + '\n ') Listing 35: Multiple Statements on a Single Line

25 Basic Syntax Comments 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 1 #!/usr/bin/python3 2 3 # First comment 4 print " Hello, Python!" # Second comment Listing 36: Comments in Python

26 Basic Syntax Command-Line Arguments Here s another simple hellopy program differed from Listing 31: 1 #!/usr/bin/python3 2 3 # import sys modules 4 import sys 5 def main(): 6 print ' Hello there', sys argv[1] 7 # Command line args are in sys argv[1], 8 # sys argv[0] is the script name itself 9 10 # Standard boilerplate to call the main() 11 # function to begin the program 12 if name == ' main ': 13 main() Listing 37: Another hellopy

27 Basic Syntax Command-Line Arguments (cont) Running this program from the command line looks like: $ / hello py SXKDZ Hello there SXKDZ Listing 38: Result of Another hellopy The outermost statements in a Python file, or module, do its one-time setup those statements run from top to bottom the first time the module is imported somewhere, setting up its variables and functions A Python module can be run directly as above python hellopy SXKDZ or it can be imported and used by some other module

28 Basic Syntax Command-Line Arguments (cont) When a Python file is run directly, the special variable name is set to main Therefore, it s common to have the boilerplate if name == shown above to call a main() function when the module is run directly, but not when the module is imported by some other module In a standard Python program, the list sysargv contains the command-line arguments in the standard way with sysargv[0] being the program itself, sysargv[1] the first argument, and so on If you know about argc, or the number of arguments, you can simply request this value with len(sysargv) In general, len() can tell you how long a string is, the number of elements in lists and tuples, and the number of key-value pairs in a dictionary

29 Basic Syntax Code Checked at Runtime Python does very little checking at compile time, deferring almost all type, name, etc checks on each line until that line runs Suppose the above main() calls repeat() like this: 1 def main(): 2 if name == ' Guido': 3 print repeeeet(name) + '!!!' 4 else: 5 print repeat( name) Listing 39: A Python Script with Obvious Errors

30 Basic Syntax Code Checked at Runtime (cont) The if-statement in Listing 39 contains an obvious error, where the repeat() function is accidentally typed in as repeeeet() But this code compiles and runs fine so long as the name at runtime is not Guido Only when a run actually tries to execute the repeeeet() will it notice that there is no such function and raise an error This just means that when you first run a Python program, some of the first errors you see will be simple typos like this

31 Data Types and Operators 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 For example: 1 counter = 100 # An integer assignment 2 miles = # A floating point assignment 3 name = " John" # A string assignment Listing 41: Variable Assignments

32 Data Types and Operators Multiple Assignments Python allows you to assign a single value or multiple values to several variables simultaneously For example: 1 a, b, c = 1 2 d, e, f = 2, 3, " john" Listing 42: Multiple Assignments In Listing 42, an integer object is created with the value 1, and all three variables a, b, c are assigned to the same memory location Then, two integer objects with values 2 and 3 are assigned to variables d and e respectively, and one string object with the value "john" is assigned to the variable f

33 Data Types and Operators Built-in Types The data stored in memory can be of many types Python has five built-in data types: number string list tuple dictionary

34 Data Types and Operators Numbers Number data types store numeric values Number objects are created when you assign a value to them Python supports four different numerical types: int (signed integers) long (long integers, they can also be represented in octal and hexadecimal) Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1 Python displays long integers with an uppercase L float (floating point real values) complex (complex numbers)

35 Data Types and Operators Strings Python has a built-in string class named str with many handy features String literals can be enclosed by either double or single quotes, although single quotes are more commonly used Backslash escapes work the usual way within both single and double quoted literals The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator Python strings are immutable which means they cannot be changed after they are created Since strings can t be changed, we construct new strings as we go to represent computed values So for example the expression ('hello' + 'there') takes in the 2 strings 'hello' and 'there' and builds a new string 'hellothere'

36 Data Types and Operators Strings (cont) Characters in a string can be accessed using the standard [ ] syntax, and Python uses zero-based indexing, so if str = 'hello' then str[1] = 'e' If the index is out of bounds for the string, Python raises an error Python does not have a separate character type Instead an expression like s[8] returns a string of length 1 containing the character With that string, the operators ==, <=, all work as you would expect, so mostly you don t need to know that Python does not have a separate scalar char type

37 Data Types and Operators Strings (cont) The handy slice syntax also works to extract any substring from a string The len(string) function returns the length of a string The [ ] syntax and the len() function actually work on any sequence type strings, lists, etc Python tries to make its operations work consistently across different types

38 Data Types and Operators Strings (cont) For example: 1 #!/usr/bin/python3 2 str = " Hello World!" 3 print( str) # Prints complete string 4 print( str[0]) # Prints first character of the string 5 print( str[2:5]) # Prints characters starting from 3rd to 5th 6 print( str[2:]) # Prints string starting from 3rd character 7 print( str * 2) # Prints string two times 8 print( str + " TEST")# Prints concatenated string Listing 43: String Representations

39 Data Types and Operators Strings (cont) Listing 43 produces the following result: Hello World! H llo llo World! Hello World! Hello World! Hello World! TEST Listing 44: Result of String Representations

40 Data Types and Operators Quotations 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: 1 word = ' word' 2 sentence = " This is a sentence" 3 paragraph = ''' This is a paragraph It is 4 made up of multiple lines and sentences''' Listing 45: String Literals in Python

41 Data Types and Operators String Methods Here are some of the most common string methods A method is like a function, but it runs on an object If the variable s is a string, then the code slower() runs the lower() method on that string object and returns the result Object-Oriented Programming Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods A feature of objects is that an object s procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of this or self)

42 Data Types and Operators String Methods (cont) slower(), supper() returns the lowercase or uppercase version of the string sstrip() returns a string with whitespace removed from the start and end sisalpha()/sisdigit()/sisspace() tests if all the string chars are in the various character classes sstartswith('other'), sendswith('other') tests if the string starts or ends with the given other string sfind('other') searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found

43 Data Types and Operators String Methods (cont) sreplace('old', 'new') returns a string where all occurrences of 'old' have been replaced by 'new' ssplit('delim') returns a list of substrings separated by the given delimiter The delimiter is not a regular expression, it s just text 'aaa,bbb,ccc'split(',') -> ['aaa', 'bbb', 'ccc'] As a convenient special case ssplit() (with no arguments) splits on all whitespace chars sjoin(list) opposite of split(), joins the elements in the given list together using the string as the delimiter, eg '---'join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

44 Data Types and Operators Slices The slice syntax is a handy way to refer to sub-parts of sequences typically strings and lists The slice s[start:end] is the elements beginning at start and extending up to but not including end Suppose we have s = "Hello": Hello Figure 41: Subscripts of String Slices

45 Data Types and Operators Slices (cont) The standard zero-based index numbers give easy access to chars near the start of the string As an alternative, Python uses negative numbers to give easy access to the chars at the end of the string as shown in Figure 41: s[-1] = 'o', s[-2] = 'l', and so on Negative index numbers count back from the end of the string It is a neat truism of slices that for any index n, s[:n] + s[n:] == s This works even for n negative or out of bounds Or put another way s[:n] and s[n:] always partition the string into two string parts, conserving all the characters

46 Data Types and Operators String % Python has a printf()-like facility to put together a string The % operator takes a printf()-type format string on the left: %d int %s string %f/%g floating point and the matching values in a tuple on the right: 1 # add parens to make the long - line work: 2 text = ("%d little pigs come out or I'll %s and %s and %s" % 3 (3, 'huff', 'puff', 'blow down')) Listing 46: String %

47 Data Types and Operators Lists Lists are the most versatile of Python s compound data types 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 as well, with indexes starting at 0 in the beginning of the list and working their way to end -1

48 Data Types and Operators Lists (cont) For example: 1 #!/usr/bin/python3 2 list = [' abcd', 786, 223, ' john', 702] 3 tinylist = [123, ' john'] 4 print( list) # Prints complete list 5 print( list[0]) # Prints first element of the list 6 print( list [1:3]) # Prints elements starting from 2nd till 3rd 7 print( list[2:]) # Prints elements starting from 3rd element 8 print( tinylist * 2) # Prints list two times 9 print( list + tinylist) 10 # Prints concatenated lists Listing 47: Lists Representations

49 Data Types and Operators Lists (cont) Listing 47 produces the following result: [' abcd ', 786, 223, 'john ', 702] abcd [786, 223] [223, 'john ', 702] [123, 'john ', 123, 'john '] [' abcd ', 786, 223, 'john ', 702, 123, 'john '] Listing 48: Result of Lists Representations

50 Data Types and Operators Lists (cont) Assignment with an = on lists does not make a copy Instead, assignment makes the two variables point to the one list in memory 1 colors = ['red', 'blue', 'green'] 2 b = colors ## Does not copy the list Listing 49: References of Lists colors b 'red' 'blue' 'green' Figure 42: Illustration of the Memory Space

51 Data Types and Operators List Methods Here are some common list methods: listappend(elem) adds a single element to the end of the list Common error: does not return the new list, just modifies the original listinsert(index, elem) inserts the element at the given index, shifting elements to the right listextend(list2) adds the elements in list2 to the end of the list Using + or += on a list is similar to using extend() listindex(elem) searches for the given element from the start of the list and returns its index Throws a ValueError if the element does not appear (use in to check without a ValueError)

52 Data Types and Operators List Methods (cont) listremove(elem) searches for the first instance of the given element and removes it (throws ValueError if not present) listsort() sorts the list in place listreverse() reverses the list in place listpop(index) removes and returns the element at the given index Returns the rightmost element if index is omitted (roughly the opposite of append())

53 Data Types and Operators Tuples A tuple is a fixed size grouping of elements, such as an (x, y) co-ordinate Tuples are like lists, except they are immutable and do not change size (tuples are not strictly immutable since one of the contained elements could be mutable) Unlike lists, tuples are enclosed within parentheses Tuples play a sort of struct role in Python a convenient way to pass around a little logical, fixed size bundle of values For example, if I wanted to have a list of 3-d coordinates, the natural python representation would be a list of tuples, where each tuple is size 3 holding one (x, y, z) group

54 Data Types and Operators Tuples (cont) To create a size-1 tuple, the lone element must be followed by a comma: 1 tuple = ('hi',) ## size -1 tuple Listing 410: A Size-1 Tuple The comma is necessary to distinguish the tuple from the ordinary case of putting an expression in parentheses In some cases you can omit the parenthesis and Python will see from the commas that you intend a tuple

55 Data Types and Operators Tuples (cont) The following code is invalid with tuple, because it is not allowed to update a tuple Similar case is possible with lists: 1 #!/usr/bin/python3 2 3 tuple = (' abcd', 786, 223, ' john', 702) 4 list = [' abcd', 786, 223, ' john', 702] 5 tuple[2] = 1000 # Invalid syntax with tuple 6 list[2] = 1000 # Valid syntax with list Listing 411: Invalid Tuple Operations

56 Data Types and Operators Dictionaries Python s efficient key/value hash table structure is called a dict The contents of a dict can be written as a series of key:value pairs within braces { }, eg, dict = {key1:value1, key2:value2, } Looking up or setting a value in a dict uses square brackets, eg, dict['foo'] looks up the value under the key 'foo' Strings, numbers, and tuples work as keys, and any type can be a value Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable) Looking up a value which is not in the dict throws a KeyError use in to check if the key is in the dict, or use dictget(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case)

57 Data Types and Operators Dictionaries (cont) For example: 1 dict = {} 2 dict['a'] = 'alpha' 3 dict['g'] = 'gamma' 4 print( dict) 5 ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma '} 6 print(dict['a']) ## Simple lookup: 'alpha' 7 dict['a'] = 6 ## Put new key/ value into dict 8 'a' in dict ## True 9 ## print(dict['z ']) ## Throws KeyError 10 if 'z' in dict: 11 print( dict['z']) ## Avoid KeyError 12 print( dict get('z')) ## None ( avoid KeyError) Listing 412: An Example Using Dict

58 Data Types and Operators Dictionaries (cont) keys 'foo1' 'foo2' 'foo3' values 'bar1' 'bar2' 'bar3' dict Figure 43: Illustration of the Dict Memory Space

59 Data Types and Operators Dictionaries (cont) The methods dictkeys() and dictvalues() return lists of the keys or values explicitly There s also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary Strategy Note From a performance point of view, the dictionary is one of your greatest tools, and you should use it where you can as an easy way to organize data For example, you might read a log file where each line begins with an IP address, and store the data into a dict using the IP address as the key, and the list of lines where it appears as the value Once you ve read in the whole file, you can look up any IP address and instantly see its list of lines The dictionary takes in scattered data and makes it into something coherent

60 Data Types and Operators Dictionary Formatting The % operator works conveniently to substitute values from a dict into a string by name: 1 hash = {} 2 hash['word'] = 'garfield' 3 hash[' count'] = 42 4 s = 'I want %( count)d copies of %( word)s' % hash # %d for int, %s for string 5 # 'I want 42 copies of garfield' Listing 413: An Example of Dict Formatting

61 Data Types and Operators Data Type Conversion Sometimes, you may need to perform conversions between the built-in types To convert between types, you simply use the type name as a function 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

62 Data Type Conversion (cont) Data Types and Operators Function int(x [,base]) long(x [,base]) float(x) str(x) tuple(s) list(s) dict(d) Description Converts x to an integer base specifies the base if x is a string Converts x to a long integer base specifies the base if x is a string Converts x to a floating-point number Converts object x to a string representation Converts s to a tuple Converts s to a list Creates a dictionary d must be a sequence of (key,value) tuples Table 41: Some Useful Type Conversion Functions

63 Data Types and Operators Basic Operators Operators are the constructs which can manipulate the value of operands Python language supports the following types of operators: Arithmetic Operators Comparison (Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators

64 Data Types and Operators Arithmetic Operators Basic arithmetic operators are the following: + (Addition) Adds values on either side of the operator - (Subtraction) Subtracts right hand operand from left hand operand * (Multiplication) Multiplies values on either side of the operator / (Division) Divides left hand operand by right hand operand % (Modulus) Divides left hand operand by right hand operand and returns remainder ** (Exponent) Performs exponential (power) calculation on operators

65 Arithmetic Operators (cont) Data Types and Operators // (Floor Division) The division of operands where the result is the quotient in which the digits after the decimal point are removed But if one of the operands is negative, the result is floored, ie, rounded away from zero (towards negative infinity): 9//2 = 4 90//20 = 40 11//3 = 4 110//3 = 40

66 Data Types and Operators Comparison Operators These operators compare the values on either sides of them and decide the relation among them They are also called Relational operators == If the values of two operands are equal, then the condition becomes true!= If values of two operands are not equal, then condition becomes true <> If values of two operands are not equal, then condition becomes true This is similar to!= operator

67 Data Types and Operators Comparison Operators (cont) > If the value of left operand is greater than the value of right operand, then condition becomes true < If the value of left operand is less than the value of right operand, then condition becomes true >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true

68 Data Types and Operators Assignment Operators Assignment operators are quite like C Python supports = as the basic assignment operator and also adding-assignment operator += Apparently, there re 7 corresponding assignment operators along with their arithmetic operators Value stored in computer memory An assignment binds name to value Retrieve value associated with name or variable by invoking the name

69 Data Types and Operators Bitwise Operators Bitwise operator works on bits and performs bit by bit operation Assume if a = 60 and b = 13 Now in binary format they will be as follows: a = ( ) 2 b = ( ) 2 a&b = a b = aˆb = a =

70 Data Types and Operators Identity Operators Identity operators compare the memory locations of two objects There are two Identity operators explained below: Operator Description Example 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 x is y results in True if id(x) equals to id(y) x is not y results in True if id(x) doesn t equal to id(y) Table 42: Identity Operators

71 Data Types and Operators The Deleting Operator The del operator does deletions In the simplest case, it can remove the definition of a variable, as if that variable had not been defined It can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary 1 var = 6 2 del var # var no more 3 list = ['a', 'b', 'c', 'd'] 4 del list[0] ## Delete first element 5 del list[-2:] ## Delete last two elements 6 print(list) ## ['b'] 7 dict = {'a':1, 'b':2, 'c':3} 8 del dict['b'] ## Delete 'b' entry 9 print(dict) ## {'a':1, 'c ':3} Listing 414: An Example Using del

72 Control Statements if Statement Python does not use {} to enclose blocks of code for branches, loops, functions, etc Instead, Python uses the colon (:) and indentation/whitespace to group statements The boolean test for an if does not need to be in parenthesis, and it can have elif and else clauses Mnemonic The word elif is the same length as the word else

73 Control Statements if Statement (cont) Any value can be used as an if-test The zero values all count as false: None, 0, empty string, empty list, empty dictionary There is also a Boolean type with two values: True and False (converted to an int, these are 1 and 0) Python has the usual comparison operations: ==,!=, <, <=, >, >= Unlike Java and C, == is overloaded to work correctly with strings The boolean operators are the spelled out words and, or, not (Python does not use the C-style &&,,!)

74 Control Statements if Statement (cont) Here s what the code might look like for a policeman pulling over a speeder: 1 if speed >= 80: 2 print(' License and registration please') 3 if mood == ' terrible' or speed >= 100: 4 print('you have the right to remain silent') 5 elif mood == 'bad' or speed >= 90: 6 print("i'm going to have to write you a ticket") 7 write_ticket() 8 else: 9 print(" Let's try to keep it under 80 ok?") Listing 51: An Example Using if Statement

75 Control Statements if Statement (cont) If the code is short, you can put the code on the same line after :, like this (this also applies to functions, loops, etc): 1 if speed >= 80: print('you are so busted') 2 else: print(' Have a nice day') Listing 52: A Shorter Example Using if Statement

76 Control Statements in Statement The in construct on its own is an easy way to test if an element appears in a list (or other collection) value in collection tests if the value is in the collection, returning True/False 1 list = ['larry', 'curly', 'moe'] 2 if ' curly' in list: 3 print('yay') Listing 53: An Example Using in Statement

77 Control Statements Ranged Loops Python s for and in constructs are extremely useful The for construct for var in list is an easy way to look at each element in a list (or other collection) Do not add or remove from the list during iteration For example: 1 squares = [1, 4, 9, 16] 2 sum = 0 3 for num in squares: 4 sum += num 5 print(sum) ## 30 Listing 54: Ranged Loops

78 Control Statements Range Generating The range(n) function yields the numbers 0, 1,, n 1, and range(a, b) returns a, a+1,, b 1 up to but not including the last number The combination of the for-loop and the range() function allow you to build a traditional numeric for loop: 1 # Generates the Numbers from 0 through 99 2 for i in range (100): 3 print(i) Listing 55: An Example of range() Function There is a variant xrange() which avoids the cost of building the whole list for performance sensitive cases

79 Control Statements while Loop Python also has the standard while-loop, and the break and continue statements work as in C++ and Java, altering the course of the innermost loop The above for/in loops solves the common case of iterating over every element in a list, but the while loop gives you total control over the index numbers Here s a while loop which accesses every 3rd element in a list: 1 ## Access every 3rd element in a list 2 i = 0 3 while i < len(a): 4 print(a[i]) 5 i = i + 3 Listing 56: An Example of while Loop

80 Functions Defining a Function A function is a block of organized, reusable code that is used to perform a single, related action Functions provide better modularity for your application and a high degree of code reusing The def keyword defines the function with its parameters within parentheses and its code indented The first line of a function can be a documentation string (docstring) that describes what the function does Variables defined in the function are local to that function The return statement can take an argument, in which case that is the value returned to the caller

81 Functions Defining a Function (cont) 1 # Defines a " repeat" function that takes 2 arguments 2 def repeat(s, exclaim): 3 """ 4 Returns the string 's' repeated 3 times 5 If exclaim is true, add exclamation marks 6 """ 7 8 result = s * 3 9 if exclaim: 10 result = result + '!!!' 11 return result Listing 61: Function Definitions

82 Modules More on Modules and their Namespaces Suppose you ve got a module binkypy which contains a def foo() The fully qualified name of that foo function is binkyfoo In this way, various Python modules can name their functions and variables whatever they want, and the variable names won t conflict module1foo is different from module2foo In the Python vocabulary, we d say that binky, module, and module2 each have their own namespaces, which as you can guess are variable name-to-object bindings

83 Modules More on Modules and their Namespaces (cont) For example, we have the standard sys module that contains some standard system facilities, like the argv list, and exit() function With the statement import sys you can then access the definitions in the sys module and make them available by their fully-qualified name, eg sysexit() 1 import sys 2 3 # Now can refer to sys xxx facilities 4 sys exit(0) Listing 71: Importing sys Module

84 Modules More on Modules and their Namespaces (cont) There is another import form that looks like this: from sys import argv, exit That makes argv and exit() available by their short names; however, we recommend the original form with the fully-qualified names because it s a lot easier to determine where a function or attribute came from There are many modules and packages which are bundled with a standard installation of the Python interpreter, so you don t have to do anything extra to use them These are collectively known as the Python Standard Library You can find the documentation of all the Standard Library modules and packages at

85 Exceptions Exceptions An exception represents a runtime error that halts the normal execution at a particular line and transfers control to error handling code This section just introduces the most basic uses of exceptions For example a runtime error might be that a variable used in the program does not have a value (ValueError), or a file open operation error because that a does not exist (IOError) See exception docs for more useful information

86 Exceptions Exceptions (cont) Without any error handling code, a runtime exception just halts the program with an error message That s a good default behavior, and you ve seen it many times You can add a try/except structure to your code to handle exceptions, like this: 1 try: 2 f = open( filename, 'ru') 3 text = f read() 4 fclose() 5 except IOError: 6 ## Control jumps directly to here if any of the above lines throws IOError 7 sys stderr write(' problem reading:' + filename) Listing 81: An Example Handling Exceptions

87 Exceptions Exceptions (cont) The try: section includes the code which might throw an exception The except: section holds the code to run if there is an exception If there is no exception, the except: section is skipped (that is, that code is for error handling only, not the normal case for the code) You can get a pointer to the exception object itself with syntax except IOError, e: (e points to the exception object)

88 Further More Getting Help There are a variety of ways to get help for Python The official Python docs site has high quality docs The official Tutor mailing list specifically designed for those who are new to Python and/or programming Many questions (and answers) can be found on StackOverflow and Quora Use the help() and dir() functions

89 Further More The help() and dir() Function Inside the Python interpreter, the help() function pulls up documentation strings for various modules, functions, and methods These doc strings are similar to Java s javadoc The dir() function tells you what the attributes of an object are Below are some ways to call help() and dir() from the interpreter: help(len) help string for the built-in len() function; note that it s len not len(), which is a call to the function dir(sys) dir() is like help() but just gives a quick list of its defined symbols, or attributes help(sysexit) help string for the exit() function in the sys module

90 The help() and dir() Function (cont) Further More help('xyz'split) help string for the split() method for string objects You can call help() with that object itself or an example of that object, plus its attribute For example, calling help('xyz'split) is the same as calling help(strsplit) help(list) help string for list objects dir(list) displays list object attributes, including its methods help(listappend) help string for the append() method for list objects

91 Credit and References Credit and References s Python Class by Nick Parlante Python Official Beginners Guide Massachusetts Institute of Technology 60001: Introduction to Computer Science and Programming in Python

92 Copyright Information Copyright Except as otherwise noted, the content is under the Creative Commons Attribution-ShareAlike License 30 cb a, and code samples are licensed under the Apache 20 License Java is a registered trademark of Oracle and/or its affiliates

Python - Variable Types. John R. Woodward

Python - Variable Types. John R. Woodward Python - Variable Types John R. Woodward Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

More information

COLLEGE OF ENGINEERING, NASHIK-4

COLLEGE OF ENGINEERING, NASHIK-4 Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING Important PYTHON Questions 1. What is Python? Python is a high-level, interpreted, interactive and object-oriented

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

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

S206E Lecture 19, 5/24/2016, Python an overview S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Global and local variables: differences between the two Global variable is usually declared at the start of the program, their

More information

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Basic Syntax - First Program 1

Basic Syntax - First Program 1 Python Basic Syntax Basic Syntax - First Program 1 All python files will have extension.py put the following source code in a test.py file. print "Hello, Python!";#hello world program run this program

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

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

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

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

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

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

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

UNIVERSITÀ DI PADOVA. < 2014 March >

UNIVERSITÀ DI PADOVA. < 2014 March > UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible

More information

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

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD PYTHON Varun Jain & Senior Software Engineer Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT CenturyLink Technologies India PVT LTD 1 About Python Python is a general-purpose interpreted, interactive,

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

Python memento TI-Smart Grids

Python memento TI-Smart Grids Python memento TI-Smart Grids Genoveva Vargas-Solar French Council of Scientific Research, LIG genoveva.vargas@imag.fr http://vargas-solar.com/data-centric-smart-everything/ * This presentation was created

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

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

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

Variable and Data Type I

Variable and Data Type I The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017 Variable is reserved

More information

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

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

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

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates Chapter 3 : Informatics Practices Class XI ( As per CBSE Board) Python Fundamentals Introduction Python 3.0 was released in 2008. Although this version is supposed to be backward incompatibles, later on

More information

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

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction ECE 364 Software Engineering Tools Lab Lecture 3 Python: Introduction 1 Introduction to Python Common Data Types If Statements For and While Loops Basic I/O Lecture Summary 2 What is Python? Python is

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2 Basic Concepts Computer Science Computer - Science - Programming history Algorithms Pseudo code 2013 Andrew Case 2 Basic Concepts Computer Science Computer a machine for performing calculations Science

More information

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

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

Lecture 2 Tao Wang 1

Lecture 2 Tao Wang 1 Lecture 2 Tao Wang 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common programming errors

More information

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

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

(CC)A-NC 2.5 by Randall Munroe Python

(CC)A-NC 2.5 by Randall Munroe Python http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional

More information

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

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Senthil Kumaran S

Senthil Kumaran S Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

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

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

Introduction to Python

Introduction to Python 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

More information

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON Table of contents 2 1. Learning Outcomes 2. Introduction 3. The first program: hello world! 4. The second program: hello (your name)! 5. More data types 6.

More information

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

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

What Version Number to Install

What Version Number to Install A Python Primer This chapter provides a quick overview of the Python language. The goal in this chapter is not to teach you the Python language excellent books have been written on that subject, such as

More information

Language Reference Manual

Language Reference Manual TAPE: A File Handling Language Language Reference Manual Tianhua Fang (tf2377) Alexander Sato (as4628) Priscilla Wang (pyw2102) Edwin Chan (cc3919) Programming Languages and Translators COMSW 4115 Fall

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Key Differences Between Python and Java

Key Differences Between Python and Java Python Python supports many (but not all) aspects of object-oriented programming; but it is possible to write a Python program without making any use of OO concepts. Python is designed to be used interpretively.

More information

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital PYTHON FOR MEDICAL PHYSICISTS Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital TUTORIAL 1: INTRODUCTION Thursday 1 st October, 2015 AGENDA 1. Reference list 2.

More information

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

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 Course Web Site http://www.nps.navy.mil/cs/facultypages/squire/cs2900 All course related materials will be posted

More information

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

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is

More information

Advanced Algorithms and Computational Models (module A)

Advanced Algorithms and Computational Models (module A) Advanced Algorithms and Computational Models (module A) Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 34 Python's built-in classes A class is immutable if each object of that class has a xed value

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

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

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

Learning Language. Reference Manual. George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104)

Learning Language. Reference Manual. George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104) Learning Language Reference Manual 1 George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104) A. Introduction Learning Language is a programming language designed

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

ARG! Language Reference Manual

ARG! Language Reference Manual ARG! Language Reference Manual Ryan Eagan, Mike Goldin, River Keefer, Shivangi Saxena 1. Introduction ARG is a language to be used to make programming a less frustrating experience. It is similar to C

More information

The current topic: Python. Announcements. Python. Python

The current topic: Python. Announcements. Python. Python The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

DaMPL. Language Reference Manual. Henrique Grando

DaMPL. Language Reference Manual. Henrique Grando DaMPL Language Reference Manual Bernardo Abreu Felipe Rocha Henrique Grando Hugo Sousa bd2440 flt2107 hp2409 ha2398 Contents 1. Getting Started... 4 2. Syntax Notations... 4 3. Lexical Conventions... 4

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Chapter 2 Getting Started with Python

Chapter 2 Getting Started with Python Chapter 2 Getting Started with Python Introduction Python Programming language was developed by Guido Van Rossum in February 1991. It is based on or influenced with two programming languages: 1. ABC language,

More information

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

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s Intro to Python Python Getting increasingly more common Designed to have intuitive and lightweight syntax In this class, we will be using Python 3.x Python 2.x is still very popular, and the differences

More information

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

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 1 Introduction to Python Agenda What is Python? and Why Python? Basic Syntax Strings User Input Useful

More information

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I ECE 364 Software Engineering Tools Laboratory Lecture 4 Python: Collections I 1 Lecture Summary Lists Tuples Sets Dictionaries Printing, More I/O Bitwise Operations 2 Lists list is a built-in Python data

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

More information

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

>>> * *(25**0.16) *10*(25**0.16) #An Interactive Session in the Python Shell. #When you type a statement in the Python Shell, #the statement is executed immediately. If the #the statement is an expression, its value is #displayed. #Lines

More information

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

Scripting Languages. Python basics

Scripting Languages. Python basics Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Language Reference Manual

Language Reference Manual ALACS Language Reference Manual Manager: Gabriel Lopez (gal2129) Language Guru: Gabriel Kramer-Garcia (glk2110) System Architect: Candace Johnson (crj2121) Tester: Terence Jacobs (tj2316) Table of Contents

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

CS112 Lecture: Primitive Types, Operators, Strings

CS112 Lecture: Primitive Types, Operators, Strings CS112 Lecture: Primitive Types, Operators, Strings Last revised 1/24/06 Objectives: 1. To explain the fundamental distinction between primitive types and reference types, and to introduce the Java primitive

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

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

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

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

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology Introduction to Python Part 1 Brian Gregor Research Computing Services Information Services & Technology RCS Team and Expertise Our Team Scientific Programmers Systems Administrators Graphics/Visualization

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information