UNIVERSITÀ DI PADOVA. < 2014 March >

Similar documents
Strings. Chapter 6. Python for Everybody

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

Python - Variable Types. John R. Woodward

Strings. Chapter 6. Python for Informatics: Exploring Information

Introduction to Python

Variable and Data Type I

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

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

COLLEGE OF ENGINEERING, NASHIK-4

Variable and Data Type I

Python memento TI-Smart Grids

Advanced Algorithms and Computational Models (module A)

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

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

Getting Started Values, Expressions, and Statements CS GMU

Data Types and Conversion

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

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

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

ENGR 101 Engineering Design Workshop

CSCE 110 Programming I

PYTHON- AN INNOVATION

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

Variables, Expressions, and Statements

THIS CHAPTER DESCRIBES PYTHON S BUILT-IN OPERATORS as well as the precedence

UNIT- 3 Introduction to C++

What is Python? Developed by Guido van Rossum in the early1990s Named after Monty Python Available on eniac Available for download from

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

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Babu Madhav Institute of Information Technology, UTU 2015

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

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

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

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Python Class-Lesson1 Instructor: Yao

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

Java Basic Datatypees

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

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

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

CSC 1107: Structured Programming

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

A Java program contains at least one class definition.

L-System Fractal Generator: Language Reference Manual

Chapter 2. Lexical Elements & Operators

Real Python: Python 3 Cheat Sheet

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

And Parallelism. Parallelism in Prolog. OR Parallelism

Introduction to Python

CMPT 125: Lecture 3 Data and Expressions

2 nd Week Lecture Notes

Downloaded from Chapter 2. Functions

Operators. Java operators are classified into three categories:

Compound Data Types 1

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

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Built-in Types of Data

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

RUBY OPERATORS. Ruby Arithmetic Operators: Ruby Comparison Operators:

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.

Basics of Java Programming

The SPL Programming Language Reference Manual

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

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

JAVA Programming Fundamentals

TED Language Reference Manual

Visual C# Instructor s Manual Table of Contents

Language Reference Manual simplicity

BASIC ELEMENTS OF A COMPUTER PROGRAM

Variables, Constants, and Data Types

GraphQuil Language Reference Manual COMS W4115

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

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

DaMPL. Language Reference Manual. Henrique Grando

DEPARTMENT OF MATHS, MJ COLLEGE

Chapter 2 Getting Started with Python

Script language: Python Data structures

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

A variable is a name for a location in memory A variable must be declared

6. Data Types and Dynamic Typing (Cont.)

Python at Glance. a really fast (but complete) ride into the Python hole. Paolo Bellagente - ES3 - DII - UniBS

TCL - STRINGS. Boolean value can be represented as 1, yes or true for true and 0, no, or false for false.

HAWK Language Reference Manual

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

Table of Contents Date(s) Title/Topic Page #s. Abstraction

Getting Started with Python

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

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

Chapter 10: Creating and Modifying Text Lists Modules

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018

Full file at

MULTIPLE CHOICE. Chapter Seven

Introduction to TURING

STSCI Python Introduction. Class URL

STRINGS. We ve already introduced the string data type a few lectures ago. Strings are subtypes of the sequence data type.

1/31/2017. Expressions are Used to Perform Calculations. ECE 120: Introduction to Computing. Five Arithmetic Operators on Numeric Types

Data Handing in Python

Python Intro GIS Week 1. Jake K. Carr

Transcription:

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 to the eyes. Easy-to-maintain Interactive Mode: Support for functional and structured programming methods as well as OOP. Very high-level dynamic data types

If you want know more Information with respect to installation, documentation and so forth go to: https://www.python.org/

What is an operator? Python language supports the following types of operators: 1. Arithmetic Operators 2. Comparison Operators 3. Assignment Operators 4. Logical Operators 5. Membership Operators 6. Identity Operators

Assume variable a holds 10 and variable b holds 20, then: Operator 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 Multiplication - Multiplies values on either side of the operator Division - Divides left hand operand by right hand operand Modulus - Divides left hand operand by right hand operand and returns remainder Exponent - Performs exponential (power) calculation on operators Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed. a - b will give -10 a * b will give 200 b / a will give 2 b % a will give 0 a**b will give 10 to the power 20 9//2 is equal to 4 and 9.0//2.0 is equal to 4.0 Operator Description Example in not in Evaluates to true if it finds a variable in the specified sequence and false otherwise. Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y. x not in y, here not in results in a 1 if x is not a member of sequence y.

The following table lists all operators from highest precedence to lowest: Operator Description ** Exponentiation (raise to the power) ~ + - Complement, unary plus and minus * / % // Multiply, divide, modulo and floor division + - Addition and subtraction >> << Right and left bitwise shift <= < > >= Comparison operators <> ==!= Equality operators = %= /= //= -= += *= **= Assignment operators in not in not or and Membership operators Logical operators

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. #!/usr/bin/python counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print counter print miles print name While running this program, this will produce the following result: 100 1000.0 John DASDC

Python has five standard data types: 1-Numbers 2-String 3-List 4-Tuple 5-Dictionary

Python supports different numerical types: int / float / complex (complex numbers) Number data types store numeric values. They are immutable data types which means that changing the value of a number data type results in a newly allocated object. You can also delete the reference to a number object by using the del statement. var1 = 1 var2 = 10 del var del var_a, var_b

Strings in are identified as a contiguous set of characters in between quotation marks. Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) The plus ( + ) sign is the string concatenation operator The asterisk ( * ) is the repetition operator #!/usr/bin/python str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string This will produce the following result: Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST

Creating a strings is as simple as assigning a value to a variable. var1 = 'Hello World!' var2 = "Python Programming"

Following table is a list of escape or non-printable characters that can be represented with backslash notation. \b 0x08 Backspace \e 0x1b Escape \n 0x0a Newline \r 0x0d Carriage return \s 0x20 Space \t 0x09 Tab \v 0x0b Vertical tab \x Character x \xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

Assume string variable a holds 'Hello' and variable b holds 'Python', then: Operator Description + * [] [ : ] in not in Concatenation - Adds values on either side of the operator Repetition - Creates new strings, concatenating multiple copies of the same string Slice - Gives the character from the given index Range Slice - Gives the characters from the given range Membership - Returns true if a character exists in the given string Membership - Returns true if a character does not exist in the given string % Format - Performs String formatting Example a + b will give HelloPython a*2 will give -HelloHello a[1] will give e a[1:4] will give ell H in a will give 1 M not in a will give 1

#!/usr/bin/python print "My name is %s and weight is %d kg!" % ('Zara', 21) When the above code is executed, it produces the following result: My name is Zara and weight is 21 kg! Format Symbol Conversion %s string conversion via str() prior to formatting %i signed decimal integer %d signed decimal integer %f floating point real number

Raw strings don't treat the backslash as a special character at all #!/usr/bin/python print 'C:\\nowhere' When the above code is executed, it produces the following result: C:\nowhere Now let's make use of raw string. We would put expression in r'expression' as follows: #!/usr/bin/python print r'c:\\nowhere' When the above code is executed, it produces the following result: C:\\nowhere

As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r. #!/usr/bin/python print u'hello, world!' When the above code is executed, it produces the following result: Hello, world!

A string is a sequence of characters A string literal uses quotes 'Hello' or Hello For strings, + means concatenate When a string contains numbers, it is still a string We can convert numbers in a string into a number using int() >>> str1 = "Hello >>> str2 = 'there' >>> bob = str1 + str2 >>> print bob Hellothere >>> str3 = '123' >>> str3 = str3 + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module>typeerror: cannot concatenate 'str' and 'int' objects >>> x = int(str3) + 1 >>> print x 124

We prefer to read data in using strings and then parse and convert the data as we need This gives us more control over error situations and/or bad user input Raw input numbers must be converted from strings >>> name = raw_input('enter:') Enter:Chuck >>> print name Chuck >>> apple = raw_input('enter:') Enter:100 >>> x = apple 10 Traceback (most recent call last): File "<stdin>", line 1, in <module>typeerror: unsupported operand type(s) for -: 'str' and 'int' >>> x = int(apple) 10 >>> print x 90

We can get at any single character in a string using an index specified in square brackets The index value must be an integer and starts at zero The index value can be an expression that is computed b 0 a 1 n 2 a 3 n 4 a 5 >>> fruit = 'banana' >>> letter = fruit[1] >>> print letter a >>> n = 3 >>> w = fruit[n - 1] >>> print w n

You will get a python error if you attempt to index beyond the end of a string. So be careful when constructing index values and slices >>> zot = 'abc' >>> print zot[5] Traceback (most recent call last): File "<stdin>", line 1, in <module>indexerror: string index out of range >>>

There is a built-in function len that gives us the length of a string b 0 a 1 n 2 a 3 n 4 a 5 >>> fruit = 'banana' >>> print len(fruit) 6

>>> fruit = 'banana' >>> x = len(fruit) >>> print x 6 A function is some stored code that we use. A function takes some input and produces an output. 'banana' (a string) len() function 6 (a number)

>>> fruit = 'banana' >>> x = len(fruit) >>> print x 6 A function is some stored code that we use. A function takes some input and produces an output. 'banana' (a string) def len(inp): blah blah for x in y: blah blah 6 (a number)

M o n t y P y t h o n 0 1 2 3 4 5 6 7 8 9 10 11 We can also look at any continuous section of a string using a colon operator The second number is one beyond the end of the slice - up to but not including >>> s = 'Monty Python' >>> print s[0:4] Mont >>> print s[6:7] P >>> print s[6:20] Python If the second number is beyond the end of the string, it stops at the end

M o n t y P y t h o n 0 1 2 3 4 5 6 7 8 9 10 11 If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string respectively >>> s = 'Monty Python' >>> print s[:2] Mo >>> print s[8:] thon >>> print s[:] Monty Python

When the + operator is applied to strings, it means "concatenation" >>> a = 'Hello' >>> b = a + 'There' >>> print b HelloThere >>> c = a + ' ' + 'There' >>> print c Hello There >>>

The in keyword can also be used to check to see if one string is "in" another string The in expression is a logical expression and returns True or False and can be used in an if statement >>> fruit = 'banana >>> 'n' in fruit True >>> 'm' in fruit False >>> 'nan' in fruit True >>> if 'a' in fruit :... print 'Found it!... Found it! >>>

if word == 'banana': print 'All right, bananas.' if word < 'banana': print 'Your word,' + word + ', comes before banana. elif word > 'banana': print 'Your word,' + word + ', comes after banana. else: print 'All right, bananas.'

Python has a number of string functions which are in the string library These functions are already built into every string - we invoke them by appending the function to the string variable These functions do not modify the original string, instead they return a new string that has been altered >>> greet = 'Hello Bob >>> zap = greet.lower() >>> print zap hello bob >>> print greet Hello Bob >>> print 'Hi There'.lower() hi there >>>

str.capitalize() str.title(width[]) str.join() str.find(sub[, start[, end]]) str.replace(old, new[, count]) str.lower() str.rstrip([chars]) str.upper()

We use the find() function to search for a substring within another string find() finds the first occurrence of the substring If the substring is not found, find() returns -1 Remember that string position starts at zero b 0 a 1 n 2 a 3 n 4 a 5 >>> fruit = 'banana' >>> pos = fruit.find('na') >>> print pos 2 >>> aa = fruit.find('z') >>> print aa -1

You can make a copy of a string in lower case or upper case Often when we are searching for a string using find() - we first convert the string to lower case so we can search a string regardless of case >>> greet = 'Hello Bob' >>> nnn = greet.upper() >>> print nnn HELLO BOB >>> www = greet.lower() >>> print www hello bob >>>

The replace() function is like a search and replace operation in a word processor It replaces all occurrences of the search string with the replacement string >>> greet = 'Hello Bob' >>> nstr = greet.replace('bob','jane') >>> print nstr Hello Jane >>> nstr = greet.replace('o','x') >>> print nstr HellX BXb >>>

Sometimes we want to take a string and remove whitespace at the beginning and/or end lstrip() and rstrip() to the left and right only strip() Removes both begin and ending whitespace >>> greet = ' Hello Bob ' >>> greet.lstrip() 'Hello Bob ' >>> greet.rstrip() ' Hello Bob' >>> greet.strip() 'Hello Bob' >>>

>>> line = 'Please have a nice day >>> line.startswith('please') True >>> line.startswith('p') False

Sometimes, you may Data need to Type perform Conversion: conversions between the built-in types. To convert between types, you simply use the type name as a function. Function int(x) long(x ) float(x) complex(real,imag) str(x) tuple(s) list(s) set(s) dict(d) hex(x) Description Converts x to an integer. Converts x to a long integer Converts x to a floating-point number. Creates a complex number. Converts object x to a string representation. Converts s to a tuple. Converts s to a list. Converts s to a set. Creates a dictionary. Converts an integer to a hexadecimal string.

REFERENCES 1. http://www.tutorialspoint.com/index.htm 2. http://docs.python.org/2/library/stdtypes.html 3. http://docs.python.org/lib/string-methods.html

Contact Website: http://www.math.unipd.it/~hossein/fereidooni.htm E-mail: hossein@math.unipd.it Skype: fereidooni1983