SlideShare a Scribd company logo
Python 3.x:
Quick Syntax Guide
Mohammed Zuhair Al-Taie
Big Data Centre - Universiti Teknologi Malaysia - 2016
python 3.x quick syntax guide
Python is a general-purpose, and multi-paradigm dynamic object
oriented programming language.
Python is a simple, portable, open source, and powerful
programming language
It allows to work quickly and integrate more effectively.
Named for the British comedy group Monty Python
Python can be described as:
An interpreted language, which means it is processed at runtime by the
interpreter,
Interactive, which means it is possible to use Python prompt to interact
directly with the interpreter,
Object oriented-based language, and
A beginner’s language, which means it is a great option for beginner
programmers who want to develop applications.
Language Overview
python 3.x quick syntax guide
The first version of Python code (0.9.0) was published by Guido Van
Rossum
in February 1991
at the CWI (Centrum Wiskunde & Informatica) in the Netherlands, Amsterdam.
It was derived from ABC programming language,
ABC is a general-purpose programming language that had been developed at the CWI.
Although today Python is maintained by a core development team at the
institute, Van Rossum still holds a vital role in directing its progress.
Language History
python 3.x quick syntax guide
Python has many uses. For example:
Web development  Django, TurboGears, and Plone,
Communicating with databases  MongoDB, MySQL, PostgreSQL,
and Oracle,
Desktop GUI  GTK+, QT, Tk, etc.
Scientific computing  Scipy, Scientific Python, etc.
Network programming  Twisted,
Software development  SCons, Buildbot, Roundup, etc. and (vii)
games and 3D graphics  PyGame, PyKyra, etc.
Language Uses
python 3.x quick syntax guide
One of Python’s greatest strengths is
size and scope of its standard library
the other open-source libraries
Libraries: mathematical functions, scientific computations, graphics,
machine learning, XML parsing, downloading Webpages, etc.
In fact, designing a small core language with a large standard library and
an easily extensible was the idea of Van Rossum at the very beginning.
Language Greatest Strength
python 3.x quick syntax guide
Everything in Python is represented as an object (e.g. integers, lists,
strings, functions, modules, classes, etc.) or by relations between objects.
Each object gets an identity, a type and a value.
Although Python is object oriented and everything in the language is
object, it also supports
procedural, functional, aspect-oriented, design by contract, and logic
programming styles of programming.
This is useful when implementing machine learning algorithms as it allows for
the use of the most suitable programming style for each case.
Multi-Approach Language
python 3.x quick syntax guide
Python differs from other high level languages (e.g. C, C++,
or Java) in that
The code written in dynamically typed languages such as Python tends
to be shorter than in C, C++, or Java.
No pointers are used
No prior compilation to bytecode is required as it can be directly
interpreted.
Python and C/C++/Java
python 3.x quick syntax guide
Python files have extension .py
Indentation is used instead of braces in Python to delimit blocks.
The number of spaces is variable, but all statements within the same block must be
indented the same amount.
Basic data types:
numbers (i.e. integer, float, and complex),
Boolean, and
sequences (i.e. strings, lists, dictionaries, and tuples).
The header line for compound statements, such as if, while, def, and class
should be terminated with a colon ( : ).
Python Syntax
python 3.x quick syntax guide
The semicolon ( ; ) is optional at the end of statement.
print is a keyword for giving output to a console or a file.
print can take multiple arguments separated by comma (; ). Ex: print(“Hello Python!”)
To reading from keyboard: name = input(“enter your name”).
The method returns a line of user input as a string.
Comments:
Single line comment (#) and
Multiple lines comment(‘’’____‘’’’).
help(<obj>) provides help/documentation for the object using pydoc.help.
dir(<obj>) lists the attributes/methods available for that object.
attributes/methods starting with “/” are internal attributes/methods and
should not be used unless you know what you are doing. dir() returns
names in current scope
Python Syntax
python 3.x quick syntax guide
A variable can refer to any Data Type (like Tuple, List, Dictionary, Int,
String, Complex, or any other object).
They are references to allocated memory.
No prior type declaration is required for variables.
Python is dynamically typed
The declaration happens automatically when value is assigned to a variable.
Variables can change type, simply by assigning them a new value of a
different type.
Python allows to assign a single value to several variables simultaneously.
It is also possible to assign multiple objects to multiple variables.
Python Variables
python 3.x quick syntax guide
Numbers in Python are immutable objects.
Immutability means that objects cannot change their values.
Ex: 1234, 3.1415, 3+4j.
The three built-in data types for numbers in Python3 are:
integers,
floating-point numbers, and
complex numbers that consist of two parts: real and imaginary.
Common number functions include int(x), float(x), abs(x), exp(x),
log(x), pow(x,y), and sqrt(x).
Python Numbers
python 3.x quick syntax guide
Strings are contiguous set of characters in between quotation marks.
Example: myStr = “This is Python 3.x quick syntax guide”.
Python strings are immutable objects (i.e. cannot change their values).
There is no “character” data type in python
To update an existing string, we can (re)assign a variable to another
string.
Strings of length one character are treated as normal strings (i.e. no type
character is used in Python syntax)
To denote strings:
Single ('),
double (")
triple (''' or """)
Python Strings
python 3.x quick syntax guide
String indexes start at 0 and work their way from -1 at the end.
Common string operators include (+) for concatenation, (*) for
repetition, ([ ]) for slicing, ([:]) for range slicing, and (in) to check
membership.
Special characters can be inserted by using the escape character “”
Common string methods include str.count(sub, beg=0, end=len(str)),
str.isalpha(), str.isdigit(), str.lower(), str.upper(), str.replace(old, new),
str.split(str = ‘ ‘), str.strip(), str.title().
Common string functions include str(x) to convert x to a string, and
len(string) to find the total length of the string.
Python Strings
python 3.x quick syntax guide
A list is an ordered group of items or elements.
List elements do not have to be of the same type. There can have nesting of lists one inside other.
A list contains items separated by commas and enclosed within square brackets.
Ex: myList = [1, [2, 'three'], 4]
Python Lists are mutable objects which means that they CAN change their values.
List indexes like strings start at 0 and work their way from -1 at the end.
They can be extended at right end.
Lists can have sublists as elements and these sublists may contain other sublists.
Lists operations include slicing ([ ] and [:]), concatenation (+), repetition (*), and
membership (in).
Common list functions include len(list), max(list), min(list), list(tuple).
Common list methods include list.append(obj), list.insert(index, obj),
list.count(obj), list.index(obj), list.remove(obj), list.sort(), list.reverse(), list.pop().
Python Lists
python 3.x quick syntax guide
Tuple is an immutable ordered sequence of items. Immutable means
cannot be changed once it has been declared. Tuples can be considered as
constant array.
A tuple contains items separated by commas and enclosed in parentheses.
Ex: myTuple = (1, 'spam', 4, 'U').
There can have nesting of tuples one inside other.
A Tuple can be updated by (re)assigning a variable to another tuple.
Sometimes tuples are preferred over lists
if we want faster processing and we want to protect data against accidental changes.
Tuple operations include slicing ([ ] and [:]), concatenation (+),
repetition (*), and membership (in).
A tuple with a single value must include a comma, e.g. t = (17, )
Python Tuples
python 3.x quick syntax guide
Dictionaries are containers which store items in key/value pairs.
Python Dictionaries are mutable objects that can change their values.
They are kind of hash table type which consist of key-value pairs of unordered
elements.
Keys must be immutable data types, usually numbers or strings, and values can be any arbitrary
Python object.
A dictionary is enclosed by curly braces ({ }), the items are separated by
commas, and each key is separated from its value by a colon (:).
Ex: {'food': 'spam', 'taste': 'yum'}
Dictionary’s values can be assigned and accessed using square braces ([]) with a
key to obtain its value.
Common dictionary methods include dict.keys(), dict.values(), dict.items(),
dict.get(key, default = None), dict.has_key(key), dict.update(dict2), dict.clear()
To iterate over dictionary: for key, value in a_dictionary.items(): print key, value
Python Dictionaries
python 3.x quick syntax guide
Conditionals are used to control the flow of execution of program
If statements are powerful decision making statements.
Syntax: [if expression: statement(s)], [if expression: statement(s); else: statement(s)],
[if expression1: statement(s); elif expression2: statement(s); else: statement(s)].
True and False are Boolean objects of class 'bool' and they are
immutable.
Python assumes any non-zero and non-null values as True,
otherwise it is False value.
Python does not provide switch or case statements.
Python Conditionals
python 3.x quick syntax guide
Looping is the process of repeatedly executing a block of statements.
The For-loop. It iterates through a list of values.
Example: [for x in X: print(“current letter is :”, x)].
In Python, the For-loops may have the optional “else” clause.
The While-loop: while is used for repeated execution of a block of code
till a condition holds true.
Syntax: [while condition: statement(s)].
The While-else clause. The optional else clause runs only if the loop
exits normally (not by break).
Syntax: while condition: statement(s); else: statement(s).
Python Loops
python 3.x quick syntax guide
Loop control statements:
break: terminates the loop statement and transfers execution to the statement
that comes immediately after the loop,
continue: causes the loop to skip the remainder of its body and retest its
condition, and
pass: used when a statement is required syntactically but we do not want any
command or code to be executed.
range(N) generates a list of numbers [0, 1, …., N-1].
Example: range(i, j, k) where “i" is the start, “j” is the stop condition and “k” is the step
condition.
List Comprehensions. Normal use of for" loop is to iterate and build a
new list. List comprehensions simplifies the above task.
Syntax: [ <expression> for <target> in <iterable> <condiction> ]
Python Loops
python 3.x quick syntax guide
A function is a group of statements that executes on request.
Syntax: def function_name(parameters): "function_docstring";
function_statements; return [expression].
A function is defined using the keyword def followed by function name and
parameters
In Python functions are also objects.
Function return type is not required.
If function does not return any value, default value of None is returned.
A function can take another function name as argument and return a
function name (as in functional programming languages).
Python Functions
python 3.x quick syntax guide
Basic types of functions: built-in functions e.g. dir(), len(), and abs();
and user-defined functions created with the ‘def’ keyword.
Four types of argument are used with Python functions:
required arguments, where arguments are passed to the function in the correct
positional order,
keyword argument, where Python function call can identify the arguments by
the parameter name,
default arguments, where the argument has a default value in the function
declaration. The default value is used when no value is provided in the function
call.
Variable-length arguments: are used when we want to process unspecified
additional argument. An asterisk (*) is used before the variable name.
It is recommended that all functions have documentation along with the
function definition.
Python Functions
python 3.x quick syntax guide
Python’s file is a built-in type in Python.
It allows access to files in an Operating System independent manner.
File opening. For file opening, the following expression is used fileObject
= open(file_name [, access_mode][, buffering]).
Common access modes include “r” to open a file for reading only, “w” to
open a file for writing only, “a” to open a file for appending, “r+” to open a
file for reading and writing, “w+” to open a file for writing and reading,
“a+” to open a file for reading and writing where new data is added at the
end, and “b” to open a file in binary mode.
Closing a file. To close a file in Python, use fileObject.close(). The close()
method flushes any unwritten data and closes the file object.
This method is invoked when the program does not need the file anymore.
File Handling in Python
python 3.x quick syntax guide
File renaming and deleting. Python “os” module provides methods to
rename and delete files.
Ex: import os; os.rename(“old_name.txt”, “new_name.txt”) or os.remove(file_name).
Reading a File. To read a file, you can use fileObject.read([count]).
Different formats for reading:
the read() method reads the whole file at once,
the readline() method reads one line each time from the file, and
the readlines() method reads all lines from the file in a list.
Writing in a File. The write() method writes any string in a file. The file
should be open.
File Handling in Python
python 3.x quick syntax guide
Common exceptions in Python: NameError - TypeError - IndexError -
KeyError – Exception.
An empty except statement can catch any type of exception.
Finally clause is always executed before finishing try statements.
Exception Handling in Python
python 3.x quick syntax guide
A module is a file with Python code that contains definitions for functions,
classes and variables.
Modules help grouping related code for better code understanding.
Any python file (.py) can work as a module.
If the file is written to execute when invoked, it is executed when
imported.
Modules can be executed by using import statement.
Ex. import module1, module2, module3 …
Python’s from statement can be used to import specific attributes from a
module.
Ex: from module1 import name1, name3, name3 …
import * statement can be used to import all names from a module.
Ex: from module1 import *
Python Modules
python 3.x quick syntax guide
A class is a set of attributes that characterize any object of the class.
The attributes are data members (class variables and instance variables) and methods.
Constructor method: first method __init__() is called class constructor
or initialization method that Python calls when a new instance of this class
is created.
Creating classes: class class_name: class_body
Creating objects: obj1 = class_name(args)
Python Classes
python 3.x quick syntax guide
Ad

More Related Content

What's hot (20)

Datatypes in c
Datatypes in cDatatypes in c
Datatypes in c
CGC Technical campus,Mohali
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
PriyankaC44
 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slides
rfojdar
 
For Loops and Nesting in Python
For Loops and Nesting in PythonFor Loops and Nesting in Python
For Loops and Nesting in Python
primeteacher32
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
MAHALAKSHMI P
 
Python Decision Making And Loops.pdf
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdf
NehaSpillai1
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ayshwarya Baburam
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
Rajendran
 
Introduction python
Introduction pythonIntroduction python
Introduction python
Jumbo Techno e_Learning
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
University of Technology
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
AnirudhaGaikwad4
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and comments
Nilimesh Halder
 
Theory of Computation Lecture Notes
Theory of Computation Lecture NotesTheory of Computation Lecture Notes
Theory of Computation Lecture Notes
FellowBuddy.com
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
RaginiJain21
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
Dipankar Achinta
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
Edureka!
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
PriyankaC44
 
Full Python in 20 slides
Full Python in 20 slidesFull Python in 20 slides
Full Python in 20 slides
rfojdar
 
For Loops and Nesting in Python
For Loops and Nesting in PythonFor Loops and Nesting in Python
For Loops and Nesting in Python
primeteacher32
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
MAHALAKSHMI P
 
Python Decision Making And Loops.pdf
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdf
NehaSpillai1
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
Rajendran
 
Lesson 03 python statement, indentation and comments
Lesson 03   python statement, indentation and commentsLesson 03   python statement, indentation and comments
Lesson 03 python statement, indentation and comments
Nilimesh Halder
 
Theory of Computation Lecture Notes
Theory of Computation Lecture NotesTheory of Computation Lecture Notes
Theory of Computation Lecture Notes
FellowBuddy.com
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
RaginiJain21
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
Dipankar Achinta
 

Viewers also liked (20)

24 Sata - Ne zaboravi titlove prezentacija (IT Showoff)
24 Sata - Ne zaboravi titlove prezentacija (IT Showoff)24 Sata - Ne zaboravi titlove prezentacija (IT Showoff)
24 Sata - Ne zaboravi titlove prezentacija (IT Showoff)
IT Showoff
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
Luigi De Russis
 
April '16 - Recruiting, Onboarding & Mobile
April '16 - Recruiting, Onboarding & MobileApril '16 - Recruiting, Onboarding & Mobile
April '16 - Recruiting, Onboarding & Mobile
Dana S. White
 
Expo tpc ef extraordinarios
Expo tpc ef extraordinariosExpo tpc ef extraordinarios
Expo tpc ef extraordinarios
Andreea C. Silva M
 
Deel 6 transport en verwerking
Deel 6   transport en verwerkingDeel 6   transport en verwerking
Deel 6 transport en verwerking
Sealer bvba
 
Wiki Presentation
Wiki PresentationWiki Presentation
Wiki Presentation
Beth Kanter
 
MS Society
MS SocietyMS Society
MS Society
Beth Kanter
 
Deel 2 natuursteen sedimentgesteente
Deel 2   natuursteen sedimentgesteenteDeel 2   natuursteen sedimentgesteente
Deel 2 natuursteen sedimentgesteente
Sealer bvba
 
Deel 8 composiet en bescherming
Deel 8   composiet en beschermingDeel 8   composiet en bescherming
Deel 8 composiet en bescherming
Sealer bvba
 
Deel 1 waarom beschermen
Deel 1   waarom beschermenDeel 1   waarom beschermen
Deel 1 waarom beschermen
Sealer bvba
 
20151215 Company Profile Denkfaktur
20151215 Company Profile Denkfaktur20151215 Company Profile Denkfaktur
20151215 Company Profile Denkfaktur
Sabine Kopsch
 
UK Networked Nonprofit
UK Networked NonprofitUK Networked Nonprofit
UK Networked Nonprofit
Beth Kanter
 
Measuring the Networked Nonprofit - Session 2
Measuring the Networked Nonprofit - Session 2Measuring the Networked Nonprofit - Session 2
Measuring the Networked Nonprofit - Session 2
Beth Kanter
 
2. evaluacion de vulnerabilidades
2.  evaluacion de vulnerabilidades2.  evaluacion de vulnerabilidades
2. evaluacion de vulnerabilidades
Jose Peña
 
Facilitating data discovery & sharing among agricultural scientific networks
Facilitating data discovery & sharing among agricultural scientific networksFacilitating data discovery & sharing among agricultural scientific networks
Facilitating data discovery & sharing among agricultural scientific networks
Nikos Manouselis
 
EFY 2016 - Temple Prep for Teens, pt.2
EFY 2016 - Temple Prep for Teens, pt.2EFY 2016 - Temple Prep for Teens, pt.2
EFY 2016 - Temple Prep for Teens, pt.2
Ben Bernards
 
Thwglobal presentation
Thwglobal presentationThwglobal presentation
Thwglobal presentation
Devi Lal Verma
 
Alaska PRSA
Alaska PRSAAlaska PRSA
Alaska PRSA
Beth Kanter
 
derecho constitucional comparado
derecho constitucional comparadoderecho constitucional comparado
derecho constitucional comparado
Sneak Soliben Comander
 
24 Sata - Ne zaboravi titlove prezentacija (IT Showoff)
24 Sata - Ne zaboravi titlove prezentacija (IT Showoff)24 Sata - Ne zaboravi titlove prezentacija (IT Showoff)
24 Sata - Ne zaboravi titlove prezentacija (IT Showoff)
IT Showoff
 
AmI 2015 - Python basics
AmI 2015 - Python basicsAmI 2015 - Python basics
AmI 2015 - Python basics
Luigi De Russis
 
April '16 - Recruiting, Onboarding & Mobile
April '16 - Recruiting, Onboarding & MobileApril '16 - Recruiting, Onboarding & Mobile
April '16 - Recruiting, Onboarding & Mobile
Dana S. White
 
Deel 6 transport en verwerking
Deel 6   transport en verwerkingDeel 6   transport en verwerking
Deel 6 transport en verwerking
Sealer bvba
 
Wiki Presentation
Wiki PresentationWiki Presentation
Wiki Presentation
Beth Kanter
 
Deel 2 natuursteen sedimentgesteente
Deel 2   natuursteen sedimentgesteenteDeel 2   natuursteen sedimentgesteente
Deel 2 natuursteen sedimentgesteente
Sealer bvba
 
Deel 8 composiet en bescherming
Deel 8   composiet en beschermingDeel 8   composiet en bescherming
Deel 8 composiet en bescherming
Sealer bvba
 
Deel 1 waarom beschermen
Deel 1   waarom beschermenDeel 1   waarom beschermen
Deel 1 waarom beschermen
Sealer bvba
 
20151215 Company Profile Denkfaktur
20151215 Company Profile Denkfaktur20151215 Company Profile Denkfaktur
20151215 Company Profile Denkfaktur
Sabine Kopsch
 
UK Networked Nonprofit
UK Networked NonprofitUK Networked Nonprofit
UK Networked Nonprofit
Beth Kanter
 
Measuring the Networked Nonprofit - Session 2
Measuring the Networked Nonprofit - Session 2Measuring the Networked Nonprofit - Session 2
Measuring the Networked Nonprofit - Session 2
Beth Kanter
 
2. evaluacion de vulnerabilidades
2.  evaluacion de vulnerabilidades2.  evaluacion de vulnerabilidades
2. evaluacion de vulnerabilidades
Jose Peña
 
Facilitating data discovery & sharing among agricultural scientific networks
Facilitating data discovery & sharing among agricultural scientific networksFacilitating data discovery & sharing among agricultural scientific networks
Facilitating data discovery & sharing among agricultural scientific networks
Nikos Manouselis
 
EFY 2016 - Temple Prep for Teens, pt.2
EFY 2016 - Temple Prep for Teens, pt.2EFY 2016 - Temple Prep for Teens, pt.2
EFY 2016 - Temple Prep for Teens, pt.2
Ben Bernards
 
Thwglobal presentation
Thwglobal presentationThwglobal presentation
Thwglobal presentation
Devi Lal Verma
 
Ad

Similar to Python 3.x quick syntax guide (20)

PYTHON PPT.pptx python is very useful for day to day life
PYTHON PPT.pptx python is very useful for day to day lifePYTHON PPT.pptx python is very useful for day to day life
PYTHON PPT.pptx python is very useful for day to day life
NaitikSingh33
 
Introduction on basic python and it's application
Introduction on basic python and it's applicationIntroduction on basic python and it's application
Introduction on basic python and it's application
sriram2110
 
CPPDS Slide.pdf
CPPDS Slide.pdfCPPDS Slide.pdf
CPPDS Slide.pdf
Fadlie Ahdon
 
1-Introduction to Python, features of python, history of python(1).pptx
1-Introduction to Python, features of python, history of python(1).pptx1-Introduction to Python, features of python, history of python(1).pptx
1-Introduction to Python, features of python, history of python(1).pptx
MAHESWARIS55
 
AI_2nd Lab.pptx
AI_2nd Lab.pptxAI_2nd Lab.pptx
AI_2nd Lab.pptx
MohammedAlYemeni1
 
1. python programming
1. python programming1. python programming
1. python programming
sreeLekha51
 
python1.ppt
python1.pptpython1.ppt
python1.ppt
arivukarasi2
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
Chariza Pladin
 
Python Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdfPython Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
faithxdunce63732
 
Presentation on basics of python
Presentation on basics of pythonPresentation on basics of python
Presentation on basics of python
NanditaDutta4
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
kavinilavuG
 
Programming in Civil Engineering_UNIT 2_NOTES
Programming in Civil Engineering_UNIT 2_NOTESProgramming in Civil Engineering_UNIT 2_NOTES
Programming in Civil Engineering_UNIT 2_NOTES
Rushikesh Kolhe
 
Chapter - 2.pptx
Chapter - 2.pptxChapter - 2.pptx
Chapter - 2.pptx
MikialeTesfamariam
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
RojaPriya
 
Python Programming for problem solving.pptx
Python Programming for problem solving.pptxPython Programming for problem solving.pptx
Python Programming for problem solving.pptx
NishaM41
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
Tiji Thomas
 
Top Most Python Interview Questions.pdf
Top Most Python Interview Questions.pdfTop Most Python Interview Questions.pdf
Top Most Python Interview Questions.pdf
Datacademy.ai
 
ENGLISH PYTHON.ppt
ENGLISH PYTHON.pptENGLISH PYTHON.ppt
ENGLISH PYTHON.ppt
GlobalTransLogistics
 
PYTHON PPT.pptx python is very useful for day to day life
PYTHON PPT.pptx python is very useful for day to day lifePYTHON PPT.pptx python is very useful for day to day life
PYTHON PPT.pptx python is very useful for day to day life
NaitikSingh33
 
Introduction on basic python and it's application
Introduction on basic python and it's applicationIntroduction on basic python and it's application
Introduction on basic python and it's application
sriram2110
 
1-Introduction to Python, features of python, history of python(1).pptx
1-Introduction to Python, features of python, history of python(1).pptx1-Introduction to Python, features of python, history of python(1).pptx
1-Introduction to Python, features of python, history of python(1).pptx
MAHESWARIS55
 
1. python programming
1. python programming1. python programming
1. python programming
sreeLekha51
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
Chariza Pladin
 
Python Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdfPython Interview Questions PDF By ScholarHat.pdf
Python Interview Questions PDF By ScholarHat.pdf
Scholarhat
 
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docxCS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
CS 360 LAB 3 STRINGS, FUNCTIONS, AND METHODSObjective The purpos.docx
faithxdunce63732
 
Presentation on basics of python
Presentation on basics of pythonPresentation on basics of python
Presentation on basics of python
NanditaDutta4
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
kavinilavuG
 
Programming in Civil Engineering_UNIT 2_NOTES
Programming in Civil Engineering_UNIT 2_NOTESProgramming in Civil Engineering_UNIT 2_NOTES
Programming in Civil Engineering_UNIT 2_NOTES
Rushikesh Kolhe
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
RojaPriya
 
Python Programming for problem solving.pptx
Python Programming for problem solving.pptxPython Programming for problem solving.pptx
Python Programming for problem solving.pptx
NishaM41
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
Tiji Thomas
 
Top Most Python Interview Questions.pdf
Top Most Python Interview Questions.pdfTop Most Python Interview Questions.pdf
Top Most Python Interview Questions.pdf
Datacademy.ai
 
Ad

More from Universiti Technologi Malaysia (UTM) (11)

A self organizing communication model for disaster risk management
A self organizing communication model for disaster risk managementA self organizing communication model for disaster risk management
A self organizing communication model for disaster risk management
Universiti Technologi Malaysia (UTM)
 
Spark Working Environment in Windows OS
Spark Working Environment in Windows OSSpark Working Environment in Windows OS
Spark Working Environment in Windows OS
Universiti Technologi Malaysia (UTM)
 
Python networkx library quick start guide
Python networkx library quick start guidePython networkx library quick start guide
Python networkx library quick start guide
Universiti Technologi Malaysia (UTM)
 
Social media with big data analytics
Social media with big data analyticsSocial media with big data analytics
Social media with big data analytics
Universiti Technologi Malaysia (UTM)
 
Predicting the relevance of search results for e-commerce systems
Predicting the relevance of search results for e-commerce systemsPredicting the relevance of search results for e-commerce systems
Predicting the relevance of search results for e-commerce systems
Universiti Technologi Malaysia (UTM)
 
Scientific theory of state and society parities and disparities between the p...
Scientific theory of state and society parities and disparities between the p...Scientific theory of state and society parities and disparities between the p...
Scientific theory of state and society parities and disparities between the p...
Universiti Technologi Malaysia (UTM)
 
Nation building current trends of technology use in da’wah
Nation building current trends of technology use in da’wahNation building current trends of technology use in da’wah
Nation building current trends of technology use in da’wah
Universiti Technologi Malaysia (UTM)
 
Flight MH370 community structure
Flight MH370 community structureFlight MH370 community structure
Flight MH370 community structure
Universiti Technologi Malaysia (UTM)
 
Visualization of explanations in recommender systems
Visualization of explanations in recommender systemsVisualization of explanations in recommender systems
Visualization of explanations in recommender systems
Universiti Technologi Malaysia (UTM)
 
Explanations in Recommender Systems: Overview and Research Approaches
Explanations in Recommender Systems: Overview and Research ApproachesExplanations in Recommender Systems: Overview and Research Approaches
Explanations in Recommender Systems: Overview and Research Approaches
Universiti Technologi Malaysia (UTM)
 
Factors disrupting a successful implementation of e-commerce in iraq
Factors disrupting a successful implementation of e-commerce in iraqFactors disrupting a successful implementation of e-commerce in iraq
Factors disrupting a successful implementation of e-commerce in iraq
Universiti Technologi Malaysia (UTM)
 
A self organizing communication model for disaster risk management
A self organizing communication model for disaster risk managementA self organizing communication model for disaster risk management
A self organizing communication model for disaster risk management
Universiti Technologi Malaysia (UTM)
 
Scientific theory of state and society parities and disparities between the p...
Scientific theory of state and society parities and disparities between the p...Scientific theory of state and society parities and disparities between the p...
Scientific theory of state and society parities and disparities between the p...
Universiti Technologi Malaysia (UTM)
 
Explanations in Recommender Systems: Overview and Research Approaches
Explanations in Recommender Systems: Overview and Research ApproachesExplanations in Recommender Systems: Overview and Research Approaches
Explanations in Recommender Systems: Overview and Research Approaches
Universiti Technologi Malaysia (UTM)
 
Factors disrupting a successful implementation of e-commerce in iraq
Factors disrupting a successful implementation of e-commerce in iraqFactors disrupting a successful implementation of e-commerce in iraq
Factors disrupting a successful implementation of e-commerce in iraq
Universiti Technologi Malaysia (UTM)
 

Recently uploaded (20)

Process Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBSProcess Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBS
Process mining Evangelist
 
Automated Melanoma Detection via Image Processing.pptx
Automated Melanoma Detection via Image Processing.pptxAutomated Melanoma Detection via Image Processing.pptx
Automated Melanoma Detection via Image Processing.pptx
handrymaharjan23
 
AWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdfAWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdf
philsparkshome
 
problem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursingproblem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursing
vishnudathas123
 
Process Mining as Enabler for Digital Transformations
Process Mining as Enabler for Digital TransformationsProcess Mining as Enabler for Digital Transformations
Process Mining as Enabler for Digital Transformations
Process mining Evangelist
 
Mining a Global Trade Process with Data Science - Microsoft
Mining a Global Trade Process with Data Science - MicrosoftMining a Global Trade Process with Data Science - Microsoft
Mining a Global Trade Process with Data Science - Microsoft
Process mining Evangelist
 
Process Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulenProcess Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulen
Process mining Evangelist
 
Lagos School of Programming Final Project Updated.pdf
Lagos School of Programming Final Project Updated.pdfLagos School of Programming Final Project Updated.pdf
Lagos School of Programming Final Project Updated.pdf
benuju2016
 
Sets theories and applications that can used to imporve knowledge
Sets theories and applications that can used to imporve knowledgeSets theories and applications that can used to imporve knowledge
Sets theories and applications that can used to imporve knowledge
saumyasl2020
 
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdfZ14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Fariborz Seyedloo
 
Process Mining Machine Recoveries to Reduce Downtime
Process Mining Machine Recoveries to Reduce DowntimeProcess Mining Machine Recoveries to Reduce Downtime
Process Mining Machine Recoveries to Reduce Downtime
Process mining Evangelist
 
CS-404 COA COURSE FILE JAN JUN 2025.docx
CS-404 COA COURSE FILE JAN JUN 2025.docxCS-404 COA COURSE FILE JAN JUN 2025.docx
CS-404 COA COURSE FILE JAN JUN 2025.docx
nidarizvitit
 
L1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptxL1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptx
38NoopurPatel
 
Voice Control robotic arm hggyghghgjgjhgjg
Voice Control robotic arm hggyghghgjgjhgjgVoice Control robotic arm hggyghghgjgjhgjg
Voice Control robotic arm hggyghghgjgjhgjg
4mg22ec401
 
Ann Naser Nabil- Data Scientist Portfolio.pdf
Ann Naser Nabil- Data Scientist Portfolio.pdfAnn Naser Nabil- Data Scientist Portfolio.pdf
Ann Naser Nabil- Data Scientist Portfolio.pdf
আন্ নাসের নাবিল
 
Chapter 6-3 Introducingthe Concepts .pptx
Chapter 6-3 Introducingthe Concepts .pptxChapter 6-3 Introducingthe Concepts .pptx
Chapter 6-3 Introducingthe Concepts .pptx
PermissionTafadzwaCh
 
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
disnakertransjabarda
 
How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?
Process mining Evangelist
 
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
muhammed84essa
 
HershAggregator (2).pdf musicretaildistribution
HershAggregator (2).pdf musicretaildistributionHershAggregator (2).pdf musicretaildistribution
HershAggregator (2).pdf musicretaildistribution
hershtara1
 
Process Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBSProcess Mining and Official Statistics - CBS
Process Mining and Official Statistics - CBS
Process mining Evangelist
 
Automated Melanoma Detection via Image Processing.pptx
Automated Melanoma Detection via Image Processing.pptxAutomated Melanoma Detection via Image Processing.pptx
Automated Melanoma Detection via Image Processing.pptx
handrymaharjan23
 
AWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdfAWS Certified Machine Learning Slides.pdf
AWS Certified Machine Learning Slides.pdf
philsparkshome
 
problem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursingproblem solving.presentation slideshow bsc nursing
problem solving.presentation slideshow bsc nursing
vishnudathas123
 
Process Mining as Enabler for Digital Transformations
Process Mining as Enabler for Digital TransformationsProcess Mining as Enabler for Digital Transformations
Process Mining as Enabler for Digital Transformations
Process mining Evangelist
 
Mining a Global Trade Process with Data Science - Microsoft
Mining a Global Trade Process with Data Science - MicrosoftMining a Global Trade Process with Data Science - Microsoft
Mining a Global Trade Process with Data Science - Microsoft
Process mining Evangelist
 
Process Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulenProcess Mining at Dimension Data - Jan vermeulen
Process Mining at Dimension Data - Jan vermeulen
Process mining Evangelist
 
Lagos School of Programming Final Project Updated.pdf
Lagos School of Programming Final Project Updated.pdfLagos School of Programming Final Project Updated.pdf
Lagos School of Programming Final Project Updated.pdf
benuju2016
 
Sets theories and applications that can used to imporve knowledge
Sets theories and applications that can used to imporve knowledgeSets theories and applications that can used to imporve knowledge
Sets theories and applications that can used to imporve knowledge
saumyasl2020
 
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdfZ14_IBM__APL_by_Christian_Demmer_IBM.pdf
Z14_IBM__APL_by_Christian_Demmer_IBM.pdf
Fariborz Seyedloo
 
Process Mining Machine Recoveries to Reduce Downtime
Process Mining Machine Recoveries to Reduce DowntimeProcess Mining Machine Recoveries to Reduce Downtime
Process Mining Machine Recoveries to Reduce Downtime
Process mining Evangelist
 
CS-404 COA COURSE FILE JAN JUN 2025.docx
CS-404 COA COURSE FILE JAN JUN 2025.docxCS-404 COA COURSE FILE JAN JUN 2025.docx
CS-404 COA COURSE FILE JAN JUN 2025.docx
nidarizvitit
 
L1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptxL1_Slides_Foundational Concepts_508.pptx
L1_Slides_Foundational Concepts_508.pptx
38NoopurPatel
 
Voice Control robotic arm hggyghghgjgjhgjg
Voice Control robotic arm hggyghghgjgjhgjgVoice Control robotic arm hggyghghgjgjhgjg
Voice Control robotic arm hggyghghgjgjhgjg
4mg22ec401
 
Chapter 6-3 Introducingthe Concepts .pptx
Chapter 6-3 Introducingthe Concepts .pptxChapter 6-3 Introducingthe Concepts .pptx
Chapter 6-3 Introducingthe Concepts .pptx
PermissionTafadzwaCh
 
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
indonesia-gen-z-report-2024 Gen Z (born between 1997 and 2012) is currently t...
disnakertransjabarda
 
How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?How to Set Up Process Mining in a Decentralized Organization?
How to Set Up Process Mining in a Decentralized Organization?
Process mining Evangelist
 
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
CERTIFIED BUSINESS ANALYSIS PROFESSIONAL™
muhammed84essa
 
HershAggregator (2).pdf musicretaildistribution
HershAggregator (2).pdf musicretaildistributionHershAggregator (2).pdf musicretaildistribution
HershAggregator (2).pdf musicretaildistribution
hershtara1
 

Python 3.x quick syntax guide

  • 1. Python 3.x: Quick Syntax Guide Mohammed Zuhair Al-Taie Big Data Centre - Universiti Teknologi Malaysia - 2016
  • 2. python 3.x quick syntax guide Python is a general-purpose, and multi-paradigm dynamic object oriented programming language. Python is a simple, portable, open source, and powerful programming language It allows to work quickly and integrate more effectively. Named for the British comedy group Monty Python Python can be described as: An interpreted language, which means it is processed at runtime by the interpreter, Interactive, which means it is possible to use Python prompt to interact directly with the interpreter, Object oriented-based language, and A beginner’s language, which means it is a great option for beginner programmers who want to develop applications. Language Overview
  • 3. python 3.x quick syntax guide The first version of Python code (0.9.0) was published by Guido Van Rossum in February 1991 at the CWI (Centrum Wiskunde & Informatica) in the Netherlands, Amsterdam. It was derived from ABC programming language, ABC is a general-purpose programming language that had been developed at the CWI. Although today Python is maintained by a core development team at the institute, Van Rossum still holds a vital role in directing its progress. Language History
  • 4. python 3.x quick syntax guide Python has many uses. For example: Web development  Django, TurboGears, and Plone, Communicating with databases  MongoDB, MySQL, PostgreSQL, and Oracle, Desktop GUI  GTK+, QT, Tk, etc. Scientific computing  Scipy, Scientific Python, etc. Network programming  Twisted, Software development  SCons, Buildbot, Roundup, etc. and (vii) games and 3D graphics  PyGame, PyKyra, etc. Language Uses
  • 5. python 3.x quick syntax guide One of Python’s greatest strengths is size and scope of its standard library the other open-source libraries Libraries: mathematical functions, scientific computations, graphics, machine learning, XML parsing, downloading Webpages, etc. In fact, designing a small core language with a large standard library and an easily extensible was the idea of Van Rossum at the very beginning. Language Greatest Strength
  • 6. python 3.x quick syntax guide Everything in Python is represented as an object (e.g. integers, lists, strings, functions, modules, classes, etc.) or by relations between objects. Each object gets an identity, a type and a value. Although Python is object oriented and everything in the language is object, it also supports procedural, functional, aspect-oriented, design by contract, and logic programming styles of programming. This is useful when implementing machine learning algorithms as it allows for the use of the most suitable programming style for each case. Multi-Approach Language
  • 7. python 3.x quick syntax guide Python differs from other high level languages (e.g. C, C++, or Java) in that The code written in dynamically typed languages such as Python tends to be shorter than in C, C++, or Java. No pointers are used No prior compilation to bytecode is required as it can be directly interpreted. Python and C/C++/Java
  • 8. python 3.x quick syntax guide Python files have extension .py Indentation is used instead of braces in Python to delimit blocks. The number of spaces is variable, but all statements within the same block must be indented the same amount. Basic data types: numbers (i.e. integer, float, and complex), Boolean, and sequences (i.e. strings, lists, dictionaries, and tuples). The header line for compound statements, such as if, while, def, and class should be terminated with a colon ( : ). Python Syntax
  • 9. python 3.x quick syntax guide The semicolon ( ; ) is optional at the end of statement. print is a keyword for giving output to a console or a file. print can take multiple arguments separated by comma (; ). Ex: print(“Hello Python!”) To reading from keyboard: name = input(“enter your name”). The method returns a line of user input as a string. Comments: Single line comment (#) and Multiple lines comment(‘’’____‘’’’). help(<obj>) provides help/documentation for the object using pydoc.help. dir(<obj>) lists the attributes/methods available for that object. attributes/methods starting with “/” are internal attributes/methods and should not be used unless you know what you are doing. dir() returns names in current scope Python Syntax
  • 10. python 3.x quick syntax guide A variable can refer to any Data Type (like Tuple, List, Dictionary, Int, String, Complex, or any other object). They are references to allocated memory. No prior type declaration is required for variables. Python is dynamically typed The declaration happens automatically when value is assigned to a variable. Variables can change type, simply by assigning them a new value of a different type. Python allows to assign a single value to several variables simultaneously. It is also possible to assign multiple objects to multiple variables. Python Variables
  • 11. python 3.x quick syntax guide Numbers in Python are immutable objects. Immutability means that objects cannot change their values. Ex: 1234, 3.1415, 3+4j. The three built-in data types for numbers in Python3 are: integers, floating-point numbers, and complex numbers that consist of two parts: real and imaginary. Common number functions include int(x), float(x), abs(x), exp(x), log(x), pow(x,y), and sqrt(x). Python Numbers
  • 12. python 3.x quick syntax guide Strings are contiguous set of characters in between quotation marks. Example: myStr = “This is Python 3.x quick syntax guide”. Python strings are immutable objects (i.e. cannot change their values). There is no “character” data type in python To update an existing string, we can (re)assign a variable to another string. Strings of length one character are treated as normal strings (i.e. no type character is used in Python syntax) To denote strings: Single ('), double (") triple (''' or """) Python Strings
  • 13. python 3.x quick syntax guide String indexes start at 0 and work their way from -1 at the end. Common string operators include (+) for concatenation, (*) for repetition, ([ ]) for slicing, ([:]) for range slicing, and (in) to check membership. Special characters can be inserted by using the escape character “” Common string methods include str.count(sub, beg=0, end=len(str)), str.isalpha(), str.isdigit(), str.lower(), str.upper(), str.replace(old, new), str.split(str = ‘ ‘), str.strip(), str.title(). Common string functions include str(x) to convert x to a string, and len(string) to find the total length of the string. Python Strings
  • 14. python 3.x quick syntax guide A list is an ordered group of items or elements. List elements do not have to be of the same type. There can have nesting of lists one inside other. A list contains items separated by commas and enclosed within square brackets. Ex: myList = [1, [2, 'three'], 4] Python Lists are mutable objects which means that they CAN change their values. List indexes like strings start at 0 and work their way from -1 at the end. They can be extended at right end. Lists can have sublists as elements and these sublists may contain other sublists. Lists operations include slicing ([ ] and [:]), concatenation (+), repetition (*), and membership (in). Common list functions include len(list), max(list), min(list), list(tuple). Common list methods include list.append(obj), list.insert(index, obj), list.count(obj), list.index(obj), list.remove(obj), list.sort(), list.reverse(), list.pop(). Python Lists
  • 15. python 3.x quick syntax guide Tuple is an immutable ordered sequence of items. Immutable means cannot be changed once it has been declared. Tuples can be considered as constant array. A tuple contains items separated by commas and enclosed in parentheses. Ex: myTuple = (1, 'spam', 4, 'U'). There can have nesting of tuples one inside other. A Tuple can be updated by (re)assigning a variable to another tuple. Sometimes tuples are preferred over lists if we want faster processing and we want to protect data against accidental changes. Tuple operations include slicing ([ ] and [:]), concatenation (+), repetition (*), and membership (in). A tuple with a single value must include a comma, e.g. t = (17, ) Python Tuples
  • 16. python 3.x quick syntax guide Dictionaries are containers which store items in key/value pairs. Python Dictionaries are mutable objects that can change their values. They are kind of hash table type which consist of key-value pairs of unordered elements. Keys must be immutable data types, usually numbers or strings, and values can be any arbitrary Python object. A dictionary is enclosed by curly braces ({ }), the items are separated by commas, and each key is separated from its value by a colon (:). Ex: {'food': 'spam', 'taste': 'yum'} Dictionary’s values can be assigned and accessed using square braces ([]) with a key to obtain its value. Common dictionary methods include dict.keys(), dict.values(), dict.items(), dict.get(key, default = None), dict.has_key(key), dict.update(dict2), dict.clear() To iterate over dictionary: for key, value in a_dictionary.items(): print key, value Python Dictionaries
  • 17. python 3.x quick syntax guide Conditionals are used to control the flow of execution of program If statements are powerful decision making statements. Syntax: [if expression: statement(s)], [if expression: statement(s); else: statement(s)], [if expression1: statement(s); elif expression2: statement(s); else: statement(s)]. True and False are Boolean objects of class 'bool' and they are immutable. Python assumes any non-zero and non-null values as True, otherwise it is False value. Python does not provide switch or case statements. Python Conditionals
  • 18. python 3.x quick syntax guide Looping is the process of repeatedly executing a block of statements. The For-loop. It iterates through a list of values. Example: [for x in X: print(“current letter is :”, x)]. In Python, the For-loops may have the optional “else” clause. The While-loop: while is used for repeated execution of a block of code till a condition holds true. Syntax: [while condition: statement(s)]. The While-else clause. The optional else clause runs only if the loop exits normally (not by break). Syntax: while condition: statement(s); else: statement(s). Python Loops
  • 19. python 3.x quick syntax guide Loop control statements: break: terminates the loop statement and transfers execution to the statement that comes immediately after the loop, continue: causes the loop to skip the remainder of its body and retest its condition, and pass: used when a statement is required syntactically but we do not want any command or code to be executed. range(N) generates a list of numbers [0, 1, …., N-1]. Example: range(i, j, k) where “i" is the start, “j” is the stop condition and “k” is the step condition. List Comprehensions. Normal use of for" loop is to iterate and build a new list. List comprehensions simplifies the above task. Syntax: [ <expression> for <target> in <iterable> <condiction> ] Python Loops
  • 20. python 3.x quick syntax guide A function is a group of statements that executes on request. Syntax: def function_name(parameters): "function_docstring"; function_statements; return [expression]. A function is defined using the keyword def followed by function name and parameters In Python functions are also objects. Function return type is not required. If function does not return any value, default value of None is returned. A function can take another function name as argument and return a function name (as in functional programming languages). Python Functions
  • 21. python 3.x quick syntax guide Basic types of functions: built-in functions e.g. dir(), len(), and abs(); and user-defined functions created with the ‘def’ keyword. Four types of argument are used with Python functions: required arguments, where arguments are passed to the function in the correct positional order, keyword argument, where Python function call can identify the arguments by the parameter name, default arguments, where the argument has a default value in the function declaration. The default value is used when no value is provided in the function call. Variable-length arguments: are used when we want to process unspecified additional argument. An asterisk (*) is used before the variable name. It is recommended that all functions have documentation along with the function definition. Python Functions
  • 22. python 3.x quick syntax guide Python’s file is a built-in type in Python. It allows access to files in an Operating System independent manner. File opening. For file opening, the following expression is used fileObject = open(file_name [, access_mode][, buffering]). Common access modes include “r” to open a file for reading only, “w” to open a file for writing only, “a” to open a file for appending, “r+” to open a file for reading and writing, “w+” to open a file for writing and reading, “a+” to open a file for reading and writing where new data is added at the end, and “b” to open a file in binary mode. Closing a file. To close a file in Python, use fileObject.close(). The close() method flushes any unwritten data and closes the file object. This method is invoked when the program does not need the file anymore. File Handling in Python
  • 23. python 3.x quick syntax guide File renaming and deleting. Python “os” module provides methods to rename and delete files. Ex: import os; os.rename(“old_name.txt”, “new_name.txt”) or os.remove(file_name). Reading a File. To read a file, you can use fileObject.read([count]). Different formats for reading: the read() method reads the whole file at once, the readline() method reads one line each time from the file, and the readlines() method reads all lines from the file in a list. Writing in a File. The write() method writes any string in a file. The file should be open. File Handling in Python
  • 24. python 3.x quick syntax guide Common exceptions in Python: NameError - TypeError - IndexError - KeyError – Exception. An empty except statement can catch any type of exception. Finally clause is always executed before finishing try statements. Exception Handling in Python
  • 25. python 3.x quick syntax guide A module is a file with Python code that contains definitions for functions, classes and variables. Modules help grouping related code for better code understanding. Any python file (.py) can work as a module. If the file is written to execute when invoked, it is executed when imported. Modules can be executed by using import statement. Ex. import module1, module2, module3 … Python’s from statement can be used to import specific attributes from a module. Ex: from module1 import name1, name3, name3 … import * statement can be used to import all names from a module. Ex: from module1 import * Python Modules
  • 26. python 3.x quick syntax guide A class is a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods. Constructor method: first method __init__() is called class constructor or initialization method that Python calls when a new instance of this class is created. Creating classes: class class_name: class_body Creating objects: obj1 = class_name(args) Python Classes
  • 27. python 3.x quick syntax guide
  翻译: