Introduction to Python

Size: px
Start display at page:

Download "Introduction to Python"

Transcription

1 Introduction to Python Reading assignment: Perkovic text, Ch. 1 and

2 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions directly into interactive shell (or load them from a file) Wherever you want your program to start, type this into the interactive shell (or in a file that is loaded into the shell)

3 Python Download and run We will use v Downloads the Python language, plus an interactive shell called idle To run: type idle into Search programs and files You can type Python expressions directly into the idle window Or, you can open a file window by clicking New file under the File menu, or Ctrl-o To load Python code from a file, hit F5 key

4 Algebraic expressions The Python interactive shell can be used to evaluate algebraic expressions 14//3 is the quotient when 14 is divided by 3 and 14%3 is the remainder 2**3 is 2 to the 3 rd power abs(), min(), and max() are functions abs() takes a number as input and returns its absolute value min() (resp., max()) take an arbitrary number of inputs and return the smallest (resp., largest ) among them >>> >>> >>> >>> 7-5 >>> 2 2*(3+1) 8 >>> 2*(3+1) >>> 8 5/2 2.5 >>> 5/2 >>> 2.5 5//2 2 >>> 5//2 >>> 2 14//3 >>> 4 14//3 4 >>> 14%3 >>> 2 14%3 2 >>> 2**3 >>> 8 2**3 8 >>> min(3, 2, 4) >>> 2 abs(-3.2) 3.2 >>> min(23,41,15,24) 15 >>> max(23,41,15,24) 41

5 Operator precedence Introduction to Computing Using Python In algrabraic expressions that use more than one operator, Python must have some way to determine the order in which operators are applied. For example: >>> * 5 (is it 25 or 17?) It s 17, because * has higher precedence than + In other words * is computed first You can always override precedence by using parentheses

6 Functions Introduction to Computing Using Python A function is a sequence of simple statements that is given a name Many functions are built in to the Python language Examples: abs, min, max When you call a function, you must place parentheses after it; e.g., abs(-4) NOT abs -4

7 Functions Introduction to Computing Using Python Functions are often passed parameters which are pieces of information a function needs to run Example: >>> abs(-3) 3 Different functions take different numbers of parameters. For example:

8 Functions abs takes one parameter Introduction to Computing Using Python >>> abs(-1) 1 min takes one or more parameters >>> min(2,1) 1 >>> min(4, 2, 6) 2 Some take no parameters >>> import time >>> time.time()

9 Comments Introduction to Computing Using Python When you write non-trivial code, it is important to comment it. Comment symbol is # Anything on a line that is after # will be ignored by the computer

10 Comments Comments are used to make code more understandable for people (including you) Introduction to Computing Using Python Example: x = * radius * radius # compute the area of a circle Don t overcomment: y = 3 # set the value of y to 3 Even the first example of a comment might not be necessary

11 Boolean expressions In addition to algebraic expressions, Python can evaluate Boolean expressions Boolean expressions evaluate to or False Boolean expressions often involve arithmetic comparison operators <, >, ==,!=, <=, and >= In an expression containing algebraic and comparison operators: Algebraic operators are evaluated first Comparison operators are evaluated next >>> 2 < 3 >>> 2 > 3 False >>> 2 == 3 False >>> 2!= 3 >>> 2 <= 3 >>> 2 >= 3 False >>> 2+4 == 2*(9/3)

12 Logical operators Logical operators can also be used in Boolean expressions - and, or, not In a an expression containing algebraic, comparison, and Boolean operators: Algebraic operators are evaluated first Comparison operators are evaluated next Boolean operators are evaluated last >>> 2<3 and 3<4 >>> 4==5 and 3<4 False >>> False and False >>> and >>> 4==5 or 3<4 >>> False or >>> False or False False >>> not(3<4) False >>> not() False >>> not(false) >>> 4+1==5 or 4-1<4

13 Exercise Translate the following into Python algebraic or Boolean expressions and then evaluate them: a) The total of 14.99, 27.95, and b) The area of a rectangle of length 20 and width 15 c) 2 to the 10 th power d) The minimum of 3, 1, 8, -2, 5, -3, and 0 e) 3 equals 4-2 f) The value of 17//5 is 3 g) The value of 17%5 is 3 h) 284 is even i) 284 is even and 284 is divisible by 3 j) 284 is even or 284 is divisible by 3 >>> >>> 20* >>> 2** >>> min(3, 1, 8, -2, 5, -3, 0) -3 >>> 3 == 4-2 False >>> 17//5 == 3 >>> 17%5 == 3 False >>> 284%2 == 0 >>> 284%2 == 0 and 284%3 == 0 False >>> 284%2 == 0 or 284%3 == 0

14 Variables and assignments Just as in algebra, a value can be assigned to a variable, such as x When variable x appears inside an expression, it evaluates to its assigned value A variable (name) does not exist until it is assigned The assignment statement has the format >>> x = 3 >>> x 3 >>> 4*x 12 >>> y Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> y NameError: name 'y' is not defined >>> y = 5*x 15 >>> y 15 <variable> = <expression> <expression> is evaluated first, and the resulting value is assigned to variable <variable>

15 Naming rules Variable names can contain these characters: a through z A through Z the underscore character _ digits 0 through 9 Names cannot start with a digit For a multiple-word name, use either the underscore as the delimiter or camelcase capitalization Short and meaningful names are ideal >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> new_temp = 23 >>> newtemp = 23 >>> counter = 0 >>> temp = 1 >>> price = 2 >>> age = 3

16 Strings In addition to number and Boolean values, Python supports string values "Hello, 'Hello, World!' World!" >>> 'Hello, World!' 'Hello, World!' >>> s = 'rock' >>> t = 'climbing' >>> A string value is represented as a sequence of characters enclosed within quotes A string value can be assigned to a variable String values can be manipulated using string operators and functions

17 Usage x in s String operators x not in s s + t s * n, n * s s[i] len(s) Explanation x is a substring of s x is not a substring of s Concatenation of s and t Concatenation of n copies of s Character at index i of s (function) Length of string s To view all operators, use the help() tool >> help(str) Help on class str in module builtins: class str(object) str(object= )-> str... >>> 'Hello, World!' 'Hello, World!' >>> s = 'rock' >>> t = 'climbing' >>> s == 'rock' >>> s!= t >>> s < t False >>> s > t >>> s + t 'rockclimbing' >>> s + ' ' + t 'rock climbing' >>> 5 * s 'rockrockrockrockrock' >>> 30 * '_' ' ' >>> 'o' in s >>> 'o' in t False >>> 'bi' in t >>> len(t) 8

18 Exercise Write Python expressions involving strings s1, s2, and s3 that correspond to: a) 'll' appears in s3 b) the blank space does not appear in s1 c) the concatenation of s1, s2, and s3 d) the blank space appears in the concatenation of s1, s2, and s3 e) the concatenation of 10 copies of s3 f) the total number of characters in s1, s2, and s3 combined >>> s1 >>> s1 'good' 'good' >>> s2 >>> s2 'bad' 'bad' >>> s3 >>> s3 'silly' 'silly' >>> >>> 'll' in s3 >>> ' ' not in s1 >>> s1 + s2 + s3 'goodbadsilly >>> ' ' in s1 + s2 + s3 False >>> 10*s3 'sillysillysillysillysillysillysillysillysillysilly' >>> len(s1+s2+s3) 12 >>>

19 Index and indexing operator The index of an item in a sequence is its position with respect to the first item The first item has index 0, The second has index 1, The third has index 2, The indexing operator [] takes a s = ' A p p l e ' nonnegative index i and returns a string consisting of the single character at index i s[0] = s[1] = s[2] = s[3] = s[4] = 'A' 'p' 'p' 'l' 'e' >>> s = 'Apple' >>> s[0] 'A' >>> s[1] 'p' >>> s[4] 'e'

20 Negative index A negative index is used to specify a position with respect to the end The last item has index -1, The second to last item has index -2, The third to last item has index -3, s = s[-1] = s[-2] = s[-5] = ' A p p l e ' 'A' 'l' 'e' >>> s = 'Apple' >>> s[-1] 'e' >>> s[-2] 'l' >>> s[-5] 'A'

21 Exercise String s is defined to be 'abcdefgh' Write expressions using s and the indexing operator [] that return the following strings: a) 'a' b) 'c' c) 'h' d) 'f' >>> s = 'abcdefgh' >>> s[0] 'a' >>> s[2] 'c' >>> s[7] 'h' >>> s[-1] 'h' >>> s[-3] 'f' >>>

22 Lists In addition to number, Boolean, and string values, Python supports lists [ 0 ' a, n1 t ',, 2 '', tbw a3 o t,', 4,' tc h5 or, d e' 6 e,,',' 7 d, [ o4 g 8, ',,' f9 i', ve e l10] k ' ]' A comma-separated sequence of items enclosed within square brackets The items can be numbers, strings, and even other lists >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] 'elk ] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>

23 List operators and functions Like strings, lists can be manipulated with operators and functions Usage x in lst x not in lst lst + lstb lst*n, n*lst lst[i] len(lst) min(lst) max(lst) sum(lst) Explanation x is an item of lst x is not an item of lst Concatenation of lst and lstb Concatenation of n copies of lst Item at index i of lst Number of items in lst Minimum item in lst Maximum item in lst Sum of items in lst >>> lst = [1, 2, 3] >>> lstb = [0, 4] >>> 4 in lst False >>> 4 not in lst >>> lst + lstb [1, 2, 3, 0, 4] >>> 2*lst [1, 2, 3, 1, 2, 3] >>> lst[0] 1 >>> lst[1] 2 >>> lst[-1] 3 >>> len(lst) 3 >>> min(lst) 1 >>> max(lst) 3 >>> sum(lst) 6 >>> help(list...

24 Lists are mutable, strings are not Lists can be modified; they are said to be mutable pets = ['ant', 'bat', 'cod', 'cow', 'dog', 'elk'] Strings can t be modified; they are said to be immutable pet = 'cod' Introduction to Computing Using Python >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] 'elk ] >>> pet = 'cod' >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> pet[2] = 'w' >>> Traceback (most recent call last): File "<pyshell#155>", line 1, in <module> pet[2] = 'w' TypeError: 'str' object does not support item assignment >>> The elements can be numbers, strings, and even other lists

25 List methods len()and sum() are examples of functions that can be called with a list input argument; they can also be called on other type of input argument(s) There are also functions that are called on a list; such functions are called list methods (note the different syntax). Two of these methods are append and remove Later we will discuss in more detail what the difference is between a method and a function >>> lst = [1, 2, 3] >>> lst len(lst) = [1, 2, 3] >>> 3 len(lst) 3 >>> sum(lst) >>> 6 sum(lst) 6 >>> lst.append(7) >>> lst [1, 2, 3, 7] >>> lst.remove(3) ` >>> lst [1, 2, 7]

26 Usage List methods lst.append(item) lst.count(item) lst.index(item) lst.pop() lst.remove(item) lst.reverse( ) lst.sort( ) Explanation adds item to the end of lst returns the number of times item occurs in lst Returns index of (first occurrence of) item in lst Removes and returns the last item in lst Removes (the first occurrence of) item from lst Reverses the order of items in lst Sorts the items of lst in increasing order Methods append(), remove(), reverse(), and sort() do not return any value; they, along with method pop(), modify list lst >>> lst = [1, 2, 3] >>> lst.append(7) >>> lst.append(3) >>> lst [1, 2, 3, 7, 3] >>> lst.count(3) 2 >>> lst.remove(2) >>> lst [1, 3, 7, 3] >>> lst.reverse() >>> lst [3, 7, 3, 1] >>> lst.index(3) 0 >>> lst.sort() >>> lst [1, 3, 3, 7] >>> lst.remove(3) >>> lst [1, 3, 7] >>> lst.pop() 7 >>> lst [1, 3]

27 Exercise List lst is a list of prices for an item at different online retailers lst = [159.99, , , , ] a) You found another retailer selling the item for $160.00; add this price to list lst b) Compute the number of retailers selling the item for $ c) Find the minimum price in lst d) Using c), find the index of the minimum price in list lst e) Using c) remove the minimum price from list lst f) Sort list lst in increasing order >>> lst = [159.99, , , , ] >>> lst.append(160.00) >>> lst.count(160.00) 2 >>> min(lst) >>> lst.index(128.83) 3 >>> lst.remove(128.83) >>> lst [159.99, 160.0, , , 160.0] >>> lst.sort() >>> lst [159.99, 160.0, 160.0, , ] >>>

28 Objects and classes A class is a kind of data (int, list, str, ) An object is a particular value associated with a class (3, [1, 2, 3], abc ) All values in Python are objects Unlike many other programming languages An object s type determines what values it can have and how it can be manipulated Terminology: object X is of type int = object X belongs to class int

29 Values of number types An object s type determines what values it can have and how it can be manipulated An object of type int can be any integer number value (with no decimal point) Another type for numbers is called float. Any number with a decimal point is a float. >>> 3 3 >>> type(3) <class 'int'> >>> >>> type(3.) <class 'float'> >>> type(3.0) <class 'float'>

30 Input from a user Function for user input: input(prompt) where prompt is a string Example (assume the user enters Hello ) >>> inp = input( Enter a word: ) (user types Hello) >>> inp + was your input Hello was your input The user s input is always interpreted as a string Example (the user enters 1 ) >>> x = input( Enter a number: ) (user types 1) >>> x * 2 11

31 Output to a user Function: print(<output>) where <output> is a string For example: >>> print( Hello world ) Hello world

32 .py Files You can write Python statements in a file To start a new file, type Ctrl-n (hole down the Ctrl key and type n) Or, to open an existing file, Ctrl-o File name should end in.py To execute the code, hit F5 Example: Compose a file that, when loaded, will ask the user to enter 3 numbers, and prints the sum.

33 Example program Compose a file that, when loaded, will ask the user to enter 3 numbers, and prints the sum. (user input is in red) >>> Enter a number: 1 Enter a number: 2 Enter a number: 3 The sum is 6 Does anyone s program print The sum is 123

34 Conversion of types To change a string into an integer: int(<string>) For example: >>> int( 3 ) 3 Example (the user enters 1 ) >>> x = int(input( Enter a number )) >>> x * 2 2

35 Example program x = int(input( Enter a number: )) y = int(input( Enter a number: )) z = int(input( Enter a number: )) print( The sum is + (x + y + z))

36 Conversion of types, continued What if you want to print something that isn t a string? The str function does this >>> str(1) 1 For example: >>> int( 3 ) 3 >>> int( 3 ) + 2 5

37 Example using str Assume user types 3 >>> x = int(input( Enter an integer )) >>> y = x + 2 >>> print(x + ' plus 2 is ' + y) Traceback (most recent call last): File "<pyshell#58>", line 1, in <module> print(x + ' plus 2 is ' + y) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print(str(x) + plus 2 is + str(y)) is 5

38 Special characters If a string contains a \, then the character after that is interpreted differently Example: \n means a newline >>> print( abc\ndef ) abc def ( \ is an escape character within print function)

39 Special characters, continued \t : tab character >>> print( abc\tdef ) abc def However: >>> abc\ndef abc\ndef ( \ is an escape character within print function)

40 Homework assignment 1 See D2L Dropbox

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

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

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

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

Impera've Programming

Impera've Programming Impera've Programming Python Programs Interac)ve Input/Output One- Way and Two- Way if Statements for Loops User- Defined Func)ons Assignments Revisited and Parameter Passing Python program line1 = 'Hello

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

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

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

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

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

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators 1 Professor: Sana Odeh odeh@courant.nyu.edu Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators Review What s wrong with this line of code? print( He said Hello ) What s wrong with

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

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

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore CS 115 Data Types and Arithmetic; Testing Taken from notes by Dr. Neil Moore Statements A statement is the smallest unit of code that can be executed on its own. So far we ve seen simple statements: Assignment:

More information

6. Data Types and Dynamic Typing (Cont.)

6. Data Types and Dynamic Typing (Cont.) 6. Data Types and Dynamic Typing (Cont.) 6.5 Strings Strings can be delimited by a pair of single quotes ('...'), double quotes ("..."), triple single quotes ('''...'''), or triple double quotes ("""...""").

More information

Python Input, output and variables

Python Input, output and variables Today s lecture Python Input, output and variables Lecture 22 COMPSCI111/111G SS 2016! What is Python?! Displaying text on screen using print()! Variables! Numbers and basic arithmetic! Getting input from

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

Lecture 4: Basic I/O

Lecture 4: Basic I/O Lecture 4: Basic I/O CS1068+ Introductory Programming in Python Dr Kieran T. Herley Department of Computer Science University College Cork 2017-2018 KH (21/09/17) Lecture 4: Basic I/O 2017-2018 1 / 20

More information

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

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016 Python Input, output and variables Lecture 22 COMPSCI111/111G SS 2016 Today s lecture u What is Python? u Displaying text on screen using print() u Variables u Numbers and basic arithmetic u Getting input

More information

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

CS 115 Lecture 4. More Python; testing software. Neil Moore CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement

More information

Lecture 3. Input, Output and Data Types

Lecture 3. Input, Output and Data Types Lecture 3 Input, Output and Data Types Goals for today Variable Types Integers, Floating-Point, Strings, Booleans Conversion between types Operations on types Input/Output Some ways of getting input, and

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

Getting Started Values, Expressions, and Statements CS GMU

Getting Started Values, Expressions, and Statements CS GMU Getting Started Values, Expressions, and Statements CS 112 @ GMU Topics where does code go? values and expressions variables and assignment 2 where does code go? we can use the interactive Python interpreter

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

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

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

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

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

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018 Python Input, output and variables Lecture 23 COMPSCI111/111G SS 2018 1 Today s lecture What is Python? Displaying text on screen using print() Variables Numbers and basic arithmetic Getting input from

More information

Expressions and Variables

Expressions and Variables Expressions and Variables Expressions print(expression) An expression is evaluated to give a value. For example: 2 + 9-6 Evaluates to: 5 Data Types Integers 1, 2, 3, 42, 100, -5 Floating points 2.5, 7.0,

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

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

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

Python Programming. Introduction Part II

Python Programming. Introduction Part II Python Programming Introduction Part II Type Conversion One data type > another data type Example: int > float, int > string. >>> a = 5.5 >>> b = int(a) >>> print(b) 5 >>>> print(a) 5.5 Conversion from

More information

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han Lab 1: Course Intro, Getting Started with Python IDLE Ling 1330/2330 Computational Linguistics Na-Rae Han Objectives Course Introduction http://www.pitt.edu/~naraehan/ling1330/index.html Student survey

More information

Question 1. Part (a) Simple Syntax [1 mark] Circle add_ints(), because it is missing arguments to the function call. Part (b) Simple Syntax [1 mark]

Question 1. Part (a) Simple Syntax [1 mark] Circle add_ints(), because it is missing arguments to the function call. Part (b) Simple Syntax [1 mark] Note to Students: This file contains sample solutions to the term test together with the marking scheme and comments for each question. Please read the solutions and the marking schemes and comments carefully.

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

Built-in Types of Data

Built-in Types of Data Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),

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

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ 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

More information

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

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

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

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1 Review Midterm Exam 1 Review Midterm Exam 1 Exam on Monday, October 7 Data Types and Variables = Data Types and Variables Basic Data Types Integers Floating Point Numbers Strings Data Types and Variables

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

BASIC ELEMENTS OF A COMPUTER PROGRAM

BASIC ELEMENTS OF A COMPUTER PROGRAM BASIC ELEMENTS OF A COMPUTER PROGRAM CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING LOGO Contents 1 Identifier 2 3 Rules for naming and declaring data variables Basic data types 4 Arithmetic operators

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

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

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

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

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

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 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

Python Class-Lesson1 Instructor: Yao

Python Class-Lesson1 Instructor: Yao Python Class-Lesson1 Instructor: Yao What is Python? Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

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

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

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d. Gaddis: Starting Out with Python, 2e - Test Bank Chapter Two MULTIPLE CHOICE 1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical

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

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

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

Final Exam(sample), Fall, 2014

Final Exam(sample), Fall, 2014 Final Exam(sample), Fall, 2014 Date: Dec 4 th, 2014 Time: 1.25 hours (1.00 a.m. 2:15 p.m.) Total: 100 points + 20 bonus Problem 1 T/F 2 Choice 3 Output Points 16 16 48 4 Programming 20 5 Bonus 20 Total

More information

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

Not-So-Mini-Lecture 6. Modules & Scripts Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything

More information

Topic 2: Introduction to Programming

Topic 2: Introduction to Programming Topic 2: Introduction to Programming 1 Textbook Strongly Recommended Exercises The Python Workbook: 12, 13, 23, and 28 Recommended Exercises The Python Workbook: 5, 7, 15, 21, 22 and 31 Recommended Reading

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

More information

Basic Python Revision Notes With help from Nitish Mittal

Basic Python Revision Notes With help from Nitish Mittal Basic Python Revision Notes With help from Nitish Mittal HELP from Documentation dir(module) help() Important Characters and Sets of Characters tab \t new line \n backslash \\ string " " or ' ' docstring

More information

Script language: Python Data structures

Script language: Python Data structures Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015 Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

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

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Contents 1 Introduction...2 2 Lexical Conventions...2 3 Types...3 4 Syntax...3 5 Expressions...4 6 Declarations...8 7 Statements...9

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

Chapter 2. Lexical Elements & Operators

Chapter 2. Lexical Elements & Operators Chapter 2. Lexical Elements & Operators Byoung-Tak Zhang TA: Hanock Kwak Biointelligence Laboratory School of Computer Science and Engineering Seoul National Univertisy http://bi.snu.ac.kr The C System

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

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

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

University of Texas at Arlington, TX, USA

University of Texas at Arlington, TX, USA Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,

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

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions Grace Murray Hopper Expressions Eric Roberts CSCI 121 January 30, 2018 Grace Hopper was one of the pioneers of modern computing, working with

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

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

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

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 Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 11 Part 1 Instructor: Long Ma The Department of Computer Science Chapter 11 Data Collections Objectives: To understand the

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

Lab 4: Sequence Types Lists, Tuples, Strings

Lab 4: Sequence Types Lists, Tuples, Strings CSE/IT 107 NMT Department of Computer Science and Engineering Programming is learned by writing programs. The purpose of computing is insight, not numbers. Brian Kernighan Richard Hamming, 1962 From our

More information

Programming for Engineers in Python. Autumn

Programming for Engineers in Python. Autumn Programming for Engineers in Python Autumn 2011-12 Plan Administration: Course site Homework submission guidelines Working environment Python: Variables Editor vs. shell Homework 0 Python Cont. Conditional

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 11 Part 1 The Department of Computer Science Objectives Chapter 11 Data Collections To understand the use of lists (arrays)

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

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

Introduction to: Computers & Programming: Review prior to 1 st Midterm Introduction to: Computers & Programming: Review prior to 1 st Midterm Adam Meyers New York University Summary Some Procedural Matters Summary of what you need to Know For the Test and To Go Further in

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

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

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

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

Name Feb. 14, Closed Book/Closed Notes No electronic devices of any kind! 3. Do not look at anyone else s exam or let anyone else look at yours!

Name Feb. 14, Closed Book/Closed Notes No electronic devices of any kind! 3. Do not look at anyone else s exam or let anyone else look at yours! Name Feb. 14, 2018 CPTS 111 EXAM #1 Closed Book/Closed Notes No electronic devices of any kind! Directions: 1. Breathe in deeply, exhale slowly, and relax. 2. No hats or sunglasses may be worn during the

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

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

More information

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 3 Jan. 18, 2019 CS1 Lecture 3 Jan. 18, 2019 Office hours for Prof. Cremer and for TAs have been posted. Locations will change check class website regularly First homework assignment will be available Monday evening, due

More information