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

Size: px
Start display at page:

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

Transcription

1 CS 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 operators 7) Assignment Operators 8) Built in functions 9) Input data 10) Functions 11) Built in libraries 12) Lists 13) Tuples 14) Maps 1

2 About Python High level language: Easy to program. Interpreted language Interactive and script mode You can write files with code and then execute them Objective oriented Let users create and manipulate data structures (objects). Example If you type 1 + 1, the interpreter replies 2 >>> Python Terminal Command line 2

3 First program Type: >>>print Hello, World! Example of a print statement*. and have the same effect with text * In Python 3, print is a function, so the syntax is print( Hello, World ) Python GUI GUI Graphic User Interface Scripts You can write all your code in a file and then execute it. In the main window of python shell click on File>>New Window A new window opens, you can write all your code here, save it and execute it. Shortcut for new window: ctrl + n Shortcut for run script: F5 3

4 Variables A variable is a name that refers to a value. >>> message = Hi robotics class >>> n = 9 >>> pi = >>>print message Hi robotics class >>>print n 17 >>>print pi Variables names and keywords If you give a variable an illegal name, you get a syntax error: >>> 76trombones = big parade SyntaxError: invalid syntax >>>more@ = SyntaxError: invalid syntax >>>class = Advance programming SyntaxError: invalid syntax 4

5 Values and Types Hello, World! is a String If you aren t sure what type a value has, the interpreter can tell you: Floating-point >>> type( Hello, World! ) <type str > >>> type(17) <type int > >>> type( ) <type float > Strings Text between and are considered strings. But, what happened to the next codes? >>>print Hello, World! >>>print Hi, I m the professor >>>print And he said Hi everybody 5

6 Strings Text between and are considered strings. But, what happened to the next codes? >>>print Hello, World! >>>print Hi, I m the professor >>>print And he said Hi everybody Strings >>>print Hi I m Gerardo So in this case we need to rewrite the code to: >>>print Hi I m Gerardo What about the second example? >>>print "He said, "Aren't can't shouldn't wouldn't."" Strings When we have complex use of (double commas) and (simple commas) and when we want to write larger strings we can use (three simple commas at the beginning and end of each string) to solve this problem, for example: >>>print He said, "Aren't can't shouldn't wouldn't. 6

7 Strings An alternative to is using backslash (\) before each quotation mark within the string. This is called escaping. Escaping strings can make them harder to read, so it s probably better to use multiline strings. Some examples: >>>print 'He said, "Aren\'t can\'t shouldn\'t wouldn\'t." >>>print "He said, \"Aren't can't shouldn't wouldn't.\"" Embedding Values in Strings If you want to display a message using the contents of a variable, you can embed values in a string using %s, which is like a marker for a value that you want to add later. For example: >>>score = 100 >>>message = I scored %s points >>>print (message % score) I scored 100 points Embedding Values in Strings Other examples: >>>text = Hi %s, how are you? >>>name1 = Gerardo >>>name2 = Rachel >>>print (text % name1) Hi Gerardo, how are you? >>>print (text % name2) Hi Rachel, how are you? 7

8 Embedding Values in Strings Other examples: >>>nums = What did the number %s say to the number %s? Nice belt!! >>>print (nums % (0,8)) What did the number 0 say to the number 8? Nice belt!! Strings can be subscripted (indexed) Like C string index starts in zero. Examples: >>>text = abcdef >>>print text[0] a >>>print text[2:4] cd >>>print text[2:] cdef But Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error. >>> x = 1234 >>>x[0] = "2" TypeError: 'str' object does not support item assignment However, creating a new string with the combined content is easy and efficient: >>>text = abcdef >>>print x + text[2] xc >>>print xyz + text[3:] xyzdef 8

9 Negative index Indices may be negative numbers, to start counting from the right. For example: >>>text = abcdef >>>print text[-1] f >>>print text[-2] e >>>print text[-2:] ef >>>print text[:-2] abcd Size of a string The built-in function len() returns the length of a string. Example: >>>text = abcdef >>>print len(text) 6 9

10 Arithmetic Operators Assume variable a holds 10 and variable b holds 20, then: Op. Description Example + Addition - Adds values on either side of the operator a + b will give 30 - Subtraction - Subtracts right hand operand from left hand operand a - b will give -10 * Multiplication - Multiplies values on either side of the operator a * b will give 200 / Division - Divides left hand operand by right hand operand b / a will give 2 *Parentheses () can be used for grouping. Arithmetic Operators Assume variable a holds 10 and variable b holds 20, then: Op. Description Example % Modulus - Divides left hand operand by right hand operand and b % a will give 0 returns remainder ** Exponent - Performs exponential (power) calculation on operators a**b will give 10 to the power 20 // Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0 Examples with strings Operations with strings Try: >>> print (10 * abc ) >>> text1 = "abc" >>> text2 = "def" >>> print text1 + text2 + "!" 10

11 Examples with strings Answer >>> print (10 * 'abc') abcabcabcabcabcabcabcabcabcabc >>> text1 = "abc" >>> text2 = "def" >>> print text1 + text2 + "! abcdef! Examples with integers and floats Try: >>> print >>> print 10+4/2 >>> print 10/3 >>> print 10.0/3 >>> print 10/3.0 >>> print 10+2/4 Examples with integers and floats Answer >>> print >>> print 10+4/2 12 >>> print 10/3 3 >>> print 10.0/ >>> print 10/ >>> print 10+2/

12 Other examples The equal sign ('=') is used to assign a value to a variable. Afterwards, no result is displayed >>> width = 200 >>> height = 400 >>> print width + height 600 >>> x = y = z = 0 >>> print x, y, z >>> a,b = 5, 9 >>> print a,b 5 9 While loop We can write an initial sub-sequence of the Fibonacci series as follows: Fibonacci series: The sum of two elements defines the next Indentation is important and it s done by a tab or 4 spaces >>> a,b = 0,1 >>> while b < 10: print b, a,b = b, a+b Test your program with and without the comma 12

13 If statements Besides the while statement just introduced, Python knows the usual control flow statements known from other languages, with some twists. Perhaps the most well-known statement type is the if statement. For example: File: 01-if-statements.py For statements For loops are traditionally used when you have a piece of code which you want to repeat n number of times. Examples: >>>for x in range (0,3): print x, >>>for j in range(10): print j, >>>for i in range(5, 50, 10): print i, For statements Other examples: 02-for-statements.py 13

14 break statements The break statement, like in C, breaks out of the smallest enclosing for or while loop. for i in range (100): if i == 10: break print i, continue statement Continue works different, inside a loop you can skip some code and go directly to the next iteration. For example: for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :', letter continue statement Other example: var = 10 # Second Example while var > 0: var = var -1 if var == 5: continue print 'Current variable value :', var 14

15 Comparison Operators Assume variable a holds 10 and variable b holds 20, then: Op. Description Example == Checks if the value of two operands are equal or not, if yes then condition (a == b) is not true. becomes true.!= Checks if the value of two operands are equal or not, if values are not equal (a!= b) is true. then condition becomes true. <> Checks if the value of two operands are equal or not, if values are not equal (a <> b) is true. This is then condition becomes true. similar to!= operator. Continue Comparison Operators Assume variable a holds 10 and variable b holds 20, then: Op. Description Example > Checks if the value of left operand is greater than the value of right (a > b) is not true. operand, if yes then condition becomes true. < Checks if the value of left operand is less than the value of right operand, if (a < b) is true. yes then condition becomes true. >= Checks if the value of left operand is greater than or equal to the value of (a >= b) is not true. right operand, if yes then condition becomes true. <= Checks if the value of left operand is less than or equal to the value of right (a <= b) is true. operand, if yes then condition becomes true. 15

16 Assignment Operators Assume variable a holds 10 and variable b holds 20, then: Op. Description Example = Simple assignment operator, Assigns values from right side operands c = a + b will assign to left side operand value of a + b into c += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a -= Subtract AND assignment operator, It subtracts right operand from the c -= a is equivalent to left operand and assign the result to left operand c = c - a *= Multiply AND assignment operator, It multiplies right operand with the c *= a is equivalent to left operand and assign the result to left operand c = c * a Assignment Operators Assume variable a holds 10 and variable b holds 20, then: Op. Description Example /= Divide AND assignment operator, It divides left operand with the right c /= a is equivalent to operand and assign the result to left operand c = c / a %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a **= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division and assigns a value, Performs floor division on operators c //= a is equivalent to and assign value to the left operand c = c // a 16

17 Bitwise Operators Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows Op. Description Example & Binary AND Operator copies a bit to the result if it (a & b) will give 12 which is 0000 exists in both operands Binary OR Operator copies a bit if it exists in either (a b) will give 61 which is 0011 operand ^ Binary XOR Operator copies the bit if it is set in one (a ^ b) will give 49 which is 0011 operand but not both Bitwise Operators Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows Op. Description Example ~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~a ) will give -61 which is in 2's complement form due to a signed binary number. << Binary Left Shift Operator. The left operands value is moved a << 2 will give 240 which is left by the number of bits specified by the right operand >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15 which is

18 Function range() It generates lists containing arithmetic progressions. Some examples: >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] Creates a list of numbers, this function only works in Python 2.x, for python 3.x: >>> mylist = list(range(4)) [0, 1, 2, 3] We will learn about lists later Function len() Len() function returns the length of a string or array. Like for example: >>> text = abcdef >>> print len(text) 6 >>> nums = [2,3,7,8,10] >>> print len(nums) 5 Another example What s going to be printed? >>> items = [ leds, motors, raspberry pi, buttons ] >>> for j in range(len(items)): print j, items[j] 18

19 abs() Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned. >>> abs(-100.2) >>> abs(3+2j) str() Convert to string. Try this! >>> age = 28 >>> print I m + age + years old Did it work? str() Now try this >>> age = 28 >>> print I m + str(age) + years old I m 28 years old How else can be programmed? 19

20 int() Returns an integer from a floating point number or string (must be number character). >>> x = 20 >>> y = int(x) >>> print y 20 >>> type(y) <type 'int'> float() Convert a string or a number to floating point. If the argument is a string, it must contain a possibly signed decimal or floating point number. >>> x = >>> y = float(x) >>> print y >>> type(y) <type float'> bool() Converts to a Boolean value. Returns false if no value or cero value is entered, true otherwise. >>> bool() False >>> bool(9) True >>> bool("0") True >>> bool("") False 20

21 bin() Returns a string with the binary representantion of a number >>> bin(7) 111 >>> bin( 8 ) 1000 ord() Returns ascii value of a char. >>> ord( A ) 65 Quick exercises A while loop can be used anywhere a for loop is used: i = 0 while i < 10: print(i) i = i + 1 # This is the same as: for i in range(10): print(i) 21

22 Input data With Python you can ask the user to type some data. Use command: raw_input Example: 03-input-data.py Tip: Using raw_input you get a string, so if you need to convert to int use int() function. 22

23 Project 1: Temperature converter Convert temperature between C, F and K C F Display a menu with all the options, user must select which option desires Ask for the temperature Display result Project 2: Factorial numbers Create a program that displays factorial number of a given number (do not use any library, write your own code). Numbers must be in range of 1 to 10, otherwise alert user. Project 3: Prime numbers Create a program that can tell you which number is prime from a range of 2 to

24 Other Projects Encrypt text: 04-encrypt.py and 05-get-text.py Defining a function To define a function use def name (parameters). For example: >>> def in_to_cm(in): cm = in*2.54 print cm Open 06-def.py file for more examples 24

25 Other functions examples See files Random number In order to generate a random number we need to import the file random.py by writing on our code import random. There are several pre-defined functions for random numbers, but we are going to focus only in one, random.randint(). Example, generate 10 random numbers between zero and nine: >>> import random >>> for i in range(10): x = random.randint(0,9) print x, Find more information: 25

26 time.sleep() Python has a functions that let us read cpu time. First we need to import the file time by writing import time. Time has a lot of functions, but we are going to focus on sleep which can suspend the calling thread for any given seconds. Try the next example: >>> import time >>> print Hello, >>> time.sleep(3) >>> print World! Find more information: time.clock() This function will return time elapsed in seconds. Try: >>> import time >>> print time.clock() >>> time.sleep(3) >>> print time.clock() 26

27 Project 4: Guess number game This game have 3 modes. Mode 1: Guess a number between 0 and 9 in less than 3 tries Mode 2: Guess a number between 0 and 99 in les than 7 tries. Mode 3: Guess a number between 0 and 99 and display time that it takes to guess. Project 4: Guess number game Requirements: Display menu and ask for game mode (user input) Use functions Generate random number Use time.clock() for mode 3 to calculate the time that the user takes to guess the number 27

28 List Lists Are More Powerful than strings. List can contain different elements, and these elements may be strings. Example: >>> food = ['pizza', 'lasagna', 'Pasta'] >>> print food ['pizza', 'lasagna', 'Pasta'] >>> print food[2] Pasta List We can change an item. >>>food[2] = 'cannelloni' >>>print food ['pizza', 'lasagna', 'canellonni'] And print some items from the list, say item from 0 to 1 (number 2 not included. >>>print food[0:2] ['pizza, 'lasagna'] 28

29 Types of lists Numbers >>>numbers = [2,9,3,7] >>>print numbers [2, 9, 3, 7] Numbers and strings >>>numbers_and_strings = [1, "cpu", 3, "monitor"] >>>print numbers_and_strings [1, 'cpu', 3, 'monitor'] Types of lists List of lists >>> list_of_lists = [food, numbers] >>> print list_of_lists [['pizza', 'lasagna', 'canellonni'], [2, 9, 3, 7]] Operations with lists Adding items to a list: >>> food.append('pasta') >>> print food ['pizza', 'lasagna', 'canellonni', 'pasta'] Removing items from a list >>> del food[1] >>> print food ['pizza', 'canellonni', 'pasta'] 29

30 Operations with lists Adding two lists >>> new_list = food + numbers >>> print new_list ['pizza', 'canellonni', 'pasta', 2, 9, 3, 7] Multiply a list by a number. For example >>> print numbers*2 [2, 9, 3, 7, 2, 9, 3, 7] Tuples A tuple is like a list that uses parentheses, as in this example: >>> example = ('1', 4, 'r', 67) >>> print example ('1', 4, 'r', 67) >>> print example[2] R >>> print example[0:2] ('1', 4) The main difference between a tuple and a list is that a tuple cannot change once you ve created it. 30

31 Tuples Why would you use a tuple instead of a list? Basically because sometimes it is useful to use something that you know can never change. If you create a tuple with two elements inside, it will always have those two elements inside. Not in order Maps In Python, a map(also referred to as a dict, short for dictionary) is a collection of things, like lists and tuples. The difference between maps and lists or tuples is that each item in a map has a key and a corresponding value. key value For example: >>> colors = {'Gerardo' : 'blue', 'Rachel' : 'purple', 'Santiago' : 'red'} >>> print colors {'Santiago': 'red', 'Gerardo': 'blue', 'Rachel': 'purple'} >>> print colors['gerardo'] blue 31

32 Maps To delete a value in a map, use its key. For example: >>> del colors['gerardo'] >>> print colors {'Santiago': 'red', 'Rachel': 'purple'} To replace a value use its key too. >>> colors['santiago'] = 'orange' >>> print colors {'Santiago': 'orange', 'Rachel': 'purple'} Maps As you can see, working with maps is kind of like working with lists and tuples, except that you can t join maps with the plus operator (+) or use append attribute to add items. 32

33 Project 5: Memory game Show a sequence of numbers. First show one number and ask for it, then show the first and second number and ask for them, and so on. You will need to clear the screen so the player can t see the previous numbers. One way to do it its by printing a few blank lines. You can do this in a function. Project 5: Memory game Requirements: Use functions Generate ten random numbers and save them in an array. Use time.clock() for mode 3 to calculate the time that the user takes to guess the number 33

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

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

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

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

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

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

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

Decisions, Decisions. Testing, testing C H A P T E R 7

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.

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

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

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

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

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

More information

Lecture 1. Types, Expressions, & Variables

Lecture 1. Types, Expressions, & Variables Lecture 1 Types, Expressions, & Variables About Your Instructor Director: GDIAC Game Design Initiative at Cornell Teach game design (and CS 1110 in fall) 8/29/13 Overview, Types & Expressions 2 Helping

More information

Real Python: Python 3 Cheat Sheet

Real Python: Python 3 Cheat Sheet Real Python: Python 3 Cheat Sheet Numbers....................................... 3 Strings........................................ 5 Booleans....................................... 7 Lists.........................................

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

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

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

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

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

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

PYTHON- AN INNOVATION

PYTHON- AN INNOVATION PYTHON- AN INNOVATION As per CBSE curriculum Class 11 Chapter- 2 By- Neha Tyagi PGT (CS) KV 5 Jaipur(II Shift) Jaipur Region Python Introduction In order to provide an input, process it and to receive

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

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

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

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands Introduction Operators are the symbols which operates on value or a variable. It tells the compiler to perform certain mathematical or logical manipulations. Can be of following categories: Unary requires

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

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

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

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

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

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

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

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 5, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Introduction to the C language Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) The C language

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

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

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

JAVA Programming Fundamentals

JAVA Programming Fundamentals Chapter 4 JAVA Programming Fundamentals By: Deepak Bhinde PGT Comp.Sc. JAVA character set Character set is a set of valid characters that a language can recognize. It may be any letter, digit or any symbol

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

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

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

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

Funk Programming Language Reference Manual

Funk Programming Language Reference Manual Funk Programming Language Reference Manual Naser AlDuaij, Senyao Du, Noura Farra, Yuan Kang, Andrea Lottarini {nya2102, sd2693, naf2116, yjk2106, al3125} @columbia.edu 26 October, 2012 1 Introduction This

More information

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments Basics Objectives Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments 2 Class Keyword class used to define new type specify

More information

GraphQuil Language Reference Manual COMS W4115

GraphQuil Language Reference Manual COMS W4115 GraphQuil Language Reference Manual COMS W4115 Steven Weiner (Systems Architect), Jon Paul (Manager), John Heizelman (Language Guru), Gemma Ragozzine (Tester) Chapter 1 - Introduction Chapter 2 - Types

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

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one. http://www.tutorialspoint.com/go/go_operators.htm GO - OPERATORS Copyright tutorialspoint.com An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.

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

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

Java Programming Fundamentals. Visit for more.

Java Programming Fundamentals. Visit  for more. Chapter 4: Java Programming Fundamentals Informatics Practices Class XI (CBSE Board) Revised as per CBSE Curriculum 2015 Visit www.ip4you.blogspot.com for more. Authored By:- Rajesh Kumar Mishra, PGT (Comp.Sc.)

More information

Chapter 2 Working with Data Types and Operators

Chapter 2 Working with Data Types and Operators JavaScript, Fourth Edition 2-1 Chapter 2 Working with Data Types and Operators At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics

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

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

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

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

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

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

Python Day 3 11/28/16

Python Day 3 11/28/16 Python Day 3 11/28/16 Objectives Review Concepts Types of Errors Escape sequences String functions Find the Errors bookcost = int(input("how much is the book: ")) discount = float(input("what is the discount:

More information

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators Course Name: Advanced Java Lecture 2 Topics to be covered Variables Operators Variables -Introduction A variables can be considered as a name given to the location in memory where values are stored. One

More information

4. Inputting data or messages to a function is called passing data to the function.

4. Inputting data or messages to a function is called passing data to the function. Test Bank for A First Book of ANSI C 4th Edition by Bronson Link full download test bank: http://testbankcollection.com/download/test-bank-for-a-first-book-of-ansi-c-4th-edition -by-bronson/ Link full

More information

JAVA OPERATORS GENERAL

JAVA OPERATORS GENERAL JAVA OPERATORS GENERAL Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: Arithmetic Operators Relational Operators Bitwise Operators

More information

VLC : Language Reference Manual

VLC : Language Reference Manual VLC : Language Reference Manual Table Of Contents 1. Introduction 2. Types and Declarations 2a. Primitives 2b. Non-primitives - Strings - Arrays 3. Lexical conventions 3a. Whitespace 3b. Comments 3c. 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

9. Elementary Algebraic and Transcendental Scalar Functions

9. Elementary Algebraic and Transcendental Scalar Functions Scalar Functions Summary. Introduction 2. Constants 2a. Numeric Constants 2b. Character Constants 2c. Symbol Constants 2d. Nested Constants 3. Scalar Functions 4. Arithmetic Scalar Functions 5. Operators

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

More Programming Constructs -- Introduction

More Programming Constructs -- Introduction More Programming Constructs -- Introduction We can now examine some additional programming concepts and constructs Chapter 5 focuses on: internal data representation conversions between one data type and

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

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g. 1.3a Expressions Expressions An Expression is a sequence of operands and operators that reduces to a single value. An operator is a syntactical token that requires an action be taken An operand is an object

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Ceng 111 Fall 2015 Week 7a

Ceng 111 Fall 2015 Week 7a Ceng 111 Fall 2015 Week 7a Container data Credit: Some slides are from the Invitation to Computer Science book by G. M. Schneider, J. L. Gersting and some from the Digital Design book by M. M. Mano and

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

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

Outline. Data and Operations. Data Types. Integral Types

Outline. Data and Operations. Data Types. Integral Types Outline Data and Operations Data Types Arithmetic Operations Strings Variables Declaration Statements Named Constant Assignment Statements Intrinsic (Built-in) Functions Data and Operations Data and Operations

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

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

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

Python lab session 1

Python lab session 1 Python lab session 1 Dr Ben Dudson, Department of Physics, University of York 28th January 2011 Python labs Before we can start using Python, first make sure: ˆ You can log into a computer using your username

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

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program Overview - General Data Types - Categories of Words - The Three S s - Define Before Use - End of Statement - My First Program a description of data, defining a set of valid values and operations List of

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 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

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

More information

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

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University C Programming Notes Dr. Karne Towson University Reference for C http://www.cplusplus.com/reference/ Main Program #include main() printf( Hello ); Comments: /* comment */ //comment 1 Data Types

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

ANSI C Programming Simple Programs

ANSI C Programming Simple Programs ANSI C Programming Simple Programs /* This program computes the distance between two points */ #include #include #include main() { /* Declare and initialize variables */ double

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

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

Lecture 3. More About C

Lecture 3. More About C Copyright 1996 David R. Hanson Computer Science 126, Fall 1996 3-1 Lecture 3. More About C Programming languages have their lingo Programming language Types are categories of values int, float, char Constants

More information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

Information Science 1

Information Science 1 Information Science 1 Simple Calcula,ons Week 09 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 8 l Simple calculations Documenting

More information

Data Types and Conversion

Data Types and Conversion Data Types and Conversion CONTENTS A A Practicing with Data Types Data Type Conversion Operators Comparison Assignment Bitwise Logical Membership Identity Precedence of Operators A Practicing with Data

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

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information