The document provides an introduction to the Python programming language. It discusses that Python is an open source, general purpose language that is object oriented, procedural, and functional. It also notes that Python has a great interactive environment and batteries included standard library. The document then covers technical issues like installing Python, running Python programs, and commonly used Python modules like NumPy, Matplotlib, and PyFITS. It concludes with an overview of the basics of Python including data types, operators, comments, and understanding reference semantics.
The document discusses alternatives to Java for enterprise application development, focusing on the Fantom programming language. It provides an introduction to Fantom's features such as closures, functional programming support, static and dynamic typing, portability, and meta-programming capabilities. Examples demonstrate Fantom code for classes, inheritance, concurrency, and web development. Resources for learning more about Fantom are also listed.
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
- web development (server-side),
- software development,
- mathematics,
- system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
- Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
- what we learn:
1- Python Install.
2- Python Comments.
3- Python Variables.
4- Python Data Types.
5- Python Numbers.
Simple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETLRomain Dorgueil
Simple Data Engineering in Python 3.5+ using Bonobo ETL, with real world example using Django2 and DBPedia.
https://www.bonobo-project.org/
Presentation from Pycon.DE 2017 in Karlsruhe
A quick tour of the basic concepts in Apache Storm. The talk is meant to be accessible to beginners who have no prior experience with distributed computing, Clojure, or Apache Storm.
This talk was given at the September 28, 2015 meeting of Vancouver Functional Programmers, hosted at Unbounce.
This document provides an introduction to the Python programming language over 30 minutes. It covers basic Python concepts like variables, data types, conditionals, loops, functions, imports, strings, lists, tuples, sets, dictionaries, and classes. Code examples are provided to demonstrate how to use these features. The document encourages learners to continue learning Python through online documentation and resources.
Basic Python Programming: Part 01 and Part 02Fariz Darari
This document discusses basic Python programming concepts including strings, functions, conditionals, loops, imports and recursion. It begins with examples of printing strings, taking user input, and calculating areas of shapes. It then covers variables and data types, operators, conditional statements, loops, functions, imports, strings, and recursion. Examples are provided throughout to demonstrate each concept.
Daniel Greenfeld gave a presentation titled "Intro to Python". The presentation introduced Python and covered 21 cool things that can be done with Python, including running Python anywhere, learning Python quickly, introspecting Python objects, working with strings, lists, generators, sets and dictionaries. The presentation emphasized Python's simplicity, readability, extensibility and how it can be used for a wide variety of tasks.
The document discusses alternatives to Java for enterprise application development, focusing on the Fantom programming language. It provides an introduction to Fantom's features such as closures, functional programming support, static and dynamic typing, portability, and meta-programming capabilities. Examples demonstrate Fantom code for classes, inheritance, concurrency, and web development. Resources for learning more about Fantom are also listed.
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
- web development (server-side),
- software development,
- mathematics,
- system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
- Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
- what we learn:
1- Python Install.
2- Python Comments.
3- Python Variables.
4- Python Data Types.
5- Python Numbers.
Simple Data Engineering in Python 3.5+ — Pycon.DE 2017 Karlsruhe — Bonobo ETLRomain Dorgueil
Simple Data Engineering in Python 3.5+ using Bonobo ETL, with real world example using Django2 and DBPedia.
https://www.bonobo-project.org/
Presentation from Pycon.DE 2017 in Karlsruhe
A quick tour of the basic concepts in Apache Storm. The talk is meant to be accessible to beginners who have no prior experience with distributed computing, Clojure, or Apache Storm.
This talk was given at the September 28, 2015 meeting of Vancouver Functional Programmers, hosted at Unbounce.
This document provides an introduction to the Python programming language over 30 minutes. It covers basic Python concepts like variables, data types, conditionals, loops, functions, imports, strings, lists, tuples, sets, dictionaries, and classes. Code examples are provided to demonstrate how to use these features. The document encourages learners to continue learning Python through online documentation and resources.
Basic Python Programming: Part 01 and Part 02Fariz Darari
This document discusses basic Python programming concepts including strings, functions, conditionals, loops, imports and recursion. It begins with examples of printing strings, taking user input, and calculating areas of shapes. It then covers variables and data types, operators, conditional statements, loops, functions, imports, strings, and recursion. Examples are provided throughout to demonstrate each concept.
Daniel Greenfeld gave a presentation titled "Intro to Python". The presentation introduced Python and covered 21 cool things that can be done with Python, including running Python anywhere, learning Python quickly, introspecting Python objects, working with strings, lists, generators, sets and dictionaries. The presentation emphasized Python's simplicity, readability, extensibility and how it can be used for a wide variety of tasks.
Gnuplot is a freely available command-line based interactive plotting program that was originally developed in 1986. It can plot functions, data from files, and its commands can be used in scripts. Gnuplot supports various output formats including PNG, LaTeX, and can interface with LaTeX to produce publication quality plots in documents. It allows customization of plots including labels, titles, keys and multiplot layouts.
EuroPython 2016 - Do I Need To Switch To GolangMax Tepkeev
Nowadays, there is a lot of buzz about Go. It happened so that for the last 6 months I’ve been mostly programming Go, and frankly speaking I fell in love with this language.
We’ll first do a quick review of the language. Go doesn’t have some language constructs, for example classes and exceptions and at first it may seem hard to write proper Go code, but in practice the language is so easy that I will try to teach you the basics and most important concepts of the language. We’ll further discuss differences and similarities in Go and Python and dive into the cool features of Go.
Finally we’ll talk about why popularity of Go is raising so fast and try to answer the most important question: Do I need to switch to Go ?
This document contains the notes from a session exploring different Protostar format string vulnerability exercises. It summarizes the steps taken to exploit each level by overwriting memory addresses or the GOT table to modify program behavior. For level 3, it took trying multiple payloads before discovering you need to target each byte of the memory address separately due to it being multibyte.
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
If you're absolutely new to Python, and to programming in general, this is the place to start!
Here's the breakdown: by the end of this workshop, you'll have Python downloaded onto your personal machine; have a general idea of what Python can help you do; be pointed in the direction of some excellent practice materials; and have a basic understanding of the syntax of the language.
Please don't forget to bring your laptop!
Audience: "Python 101" is geared toward individuals who are new to programming. If you've had some programming experience (shell scripting, MATLAB, Ruby, etc.), then you'll probably want to check out the more intermediate workshop, "Python 101++".
- The document discusses loading, cleaning, and saving data in R. It focuses on using data from a slots machine experiment.
- Students are instructed to load various data files into R, including slots.csv and movies.csv, and to clean the slots.txt file.
- The document covers working with different data types like factors and strings, and using functions like read.csv(), write.csv(), and save() to import and export data.
Python is a versatile, object-oriented programming language that can be used for web development, data analysis, and more. It has a simple syntax and is easy to read and learn. Key features include being interpreted, dynamically typed, supporting functional and object-oriented programming. Common data types include numbers, strings, lists, dictionaries, tuples, and files. Functions and classes can be defined to organize and reuse code. Regular expressions provide powerful string manipulation. Python has a large standard library and is used widely in areas like GUIs, web scripting, AI, and scientific computing.
This document provides a cheat sheet for Python basics. It begins with an introduction to Python and its advantages. It then covers key Python data types like strings, integers, floats, lists, tuples, and dictionaries. It explains how to define variables, functions, conditional statements, and loops. The document also demonstrates built-in functions, methods for manipulating common data structures, and other Python programming concepts in a concise and easy to understand manner.
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
This document provides an overview of biological databases and SQL. It discusses different data levels in biological research like primary data, derived data, and interpreted data. It also summarizes some popular biological databases like Ensembl, ArrayExpress, and PharmGKB and whether they support direct SQL querying. The document then provides definitions for key database concepts like database, table, record, and query. It also describes different data types in SQL like numeric, string, date/time types and large object types. It discusses keys, integrity rules, and referential integrity in database design.
Using the Arrow Library to increase the Functional Programming potential of the Kotlin Language. Presented to the Cork Java Users Group and Cork Functional Programmers on 1st May 2018
Presentation on using the Arrow library for enhanced Functional Programming in the Kotlin Language. Delivered at the Northern Ireland Developer Conference 2018.
The document discusses various data structures including stacks, queues, binary heaps, and binary indexed trees. It provides descriptions of each data structure, their common operations like push(), pop(), and top(), as well as discussing their time complexities and providing C++ code examples for implementation. It also gives examples of applications for each data structure.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/1e4UMbN.
Gilad Bracha explains how to distinguish FP hype from reality and to apply key ideas of FP in non-FP languages, separating the good parts of FP from its unnecessary cultural baggage. Filmed at qconsf.com.
Gilad Bracha is the creator of the Newspeak programming language and a software engineer at Google where he works on Dart. Previously, he was a VP at SAP Labs, a Distinguished Engineer at Cadence, and a Computational Theologist and Distinguished Engineer at Sun. He is co-author of the Java Language Specification, and a researcher in the area of object-oriented programming languages.
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
Industry - Program analysis and verification - Type-preserving Heap Profiler ...ICSM 2011
Paper: Type-preserving Heap Profiler for C++
Authors: József Mihalicza, Zoltán Porkoláb and Ábel Gábor
Session: "Industry Track Session 4: Program analysis and Verification"
Functions, Exception, Modules and Files
Functions: Difference between a Function and a Method, Defining a Function, Calling a Function, Returning Results from a Function, Returning Multiple Values from a Function, Functions are First Class Objects, Pass by Object Reference, Formal and Actual Arguments, Positional Arguments, Keyword Arguments, Default Arguments, Variable Length Arguments, Local and Global Variables, The Global Keyword, Passing a Group of Elements to a Function, Recursive Functions, Anonymous Functions or Lambdas (Using Lambdas with filter() Function, Using Lambdas with map() Function, Using Lambdas with reduce() Function), Function Decorators, Generators, Structured Programming, Creating our Own Modules in Python, The Special Variable __name__
Exceptions: Errors in a Python Program (Compile-Time Errors, Runtime Errors, Logical Errors),Exceptions, Exception Handling, Types of Exceptions, The Except Block, The assert Statement, UserDefined Exceptions, Logging the Exceptions
20%
Files: Files, Types of Files in Python, Opening a File, Closing a File, Working with Text Files Containing Strings, Knowing Whether a File Exists or Not, Working with Binary Files, The with Statement, Pickle in Python, The seek() and tell() Methods, Random Accessing of Binary Files, Random Accessing of Binary Files using mmap, Zipping and Unzipping Files, Working with Directories, Running Other Programs from Python Program
This document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It also covers topics like functions, modules, files, and classes in Python.
This document provides an overview of learning Python in three hours. It covers Python's history, installing and running Python, basic data types like integers, floats and strings. It also discusses sequence types like lists, tuples and strings, and how lists are mutable while tuples are immutable. The document includes examples of basic syntax like assignment, conditionals, functions and modules. It provides guidance on naming conventions and discusses the Python interpreter, editors and development environments.
This document provides an overview of the Python programming language. It discusses Python's history and key features such as being an interpreted, object-oriented, and functional language. The document also covers installing Python, running Python scripts and programs, basic datatypes like integers and strings, sequence types like lists and tuples, and other basic concepts like functions, variables, and flow control.
Gnuplot is a freely available command-line based interactive plotting program that was originally developed in 1986. It can plot functions, data from files, and its commands can be used in scripts. Gnuplot supports various output formats including PNG, LaTeX, and can interface with LaTeX to produce publication quality plots in documents. It allows customization of plots including labels, titles, keys and multiplot layouts.
EuroPython 2016 - Do I Need To Switch To GolangMax Tepkeev
Nowadays, there is a lot of buzz about Go. It happened so that for the last 6 months I’ve been mostly programming Go, and frankly speaking I fell in love with this language.
We’ll first do a quick review of the language. Go doesn’t have some language constructs, for example classes and exceptions and at first it may seem hard to write proper Go code, but in practice the language is so easy that I will try to teach you the basics and most important concepts of the language. We’ll further discuss differences and similarities in Go and Python and dive into the cool features of Go.
Finally we’ll talk about why popularity of Go is raising so fast and try to answer the most important question: Do I need to switch to Go ?
This document contains the notes from a session exploring different Protostar format string vulnerability exercises. It summarizes the steps taken to exploit each level by overwriting memory addresses or the GOT table to modify program behavior. For level 3, it took trying multiple payloads before discovering you need to target each byte of the memory address separately due to it being multibyte.
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
If you're absolutely new to Python, and to programming in general, this is the place to start!
Here's the breakdown: by the end of this workshop, you'll have Python downloaded onto your personal machine; have a general idea of what Python can help you do; be pointed in the direction of some excellent practice materials; and have a basic understanding of the syntax of the language.
Please don't forget to bring your laptop!
Audience: "Python 101" is geared toward individuals who are new to programming. If you've had some programming experience (shell scripting, MATLAB, Ruby, etc.), then you'll probably want to check out the more intermediate workshop, "Python 101++".
- The document discusses loading, cleaning, and saving data in R. It focuses on using data from a slots machine experiment.
- Students are instructed to load various data files into R, including slots.csv and movies.csv, and to clean the slots.txt file.
- The document covers working with different data types like factors and strings, and using functions like read.csv(), write.csv(), and save() to import and export data.
Python is a versatile, object-oriented programming language that can be used for web development, data analysis, and more. It has a simple syntax and is easy to read and learn. Key features include being interpreted, dynamically typed, supporting functional and object-oriented programming. Common data types include numbers, strings, lists, dictionaries, tuples, and files. Functions and classes can be defined to organize and reuse code. Regular expressions provide powerful string manipulation. Python has a large standard library and is used widely in areas like GUIs, web scripting, AI, and scientific computing.
This document provides a cheat sheet for Python basics. It begins with an introduction to Python and its advantages. It then covers key Python data types like strings, integers, floats, lists, tuples, and dictionaries. It explains how to define variables, functions, conditional statements, and loops. The document also demonstrates built-in functions, methods for manipulating common data structures, and other Python programming concepts in a concise and easy to understand manner.
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
This document provides an overview of biological databases and SQL. It discusses different data levels in biological research like primary data, derived data, and interpreted data. It also summarizes some popular biological databases like Ensembl, ArrayExpress, and PharmGKB and whether they support direct SQL querying. The document then provides definitions for key database concepts like database, table, record, and query. It also describes different data types in SQL like numeric, string, date/time types and large object types. It discusses keys, integrity rules, and referential integrity in database design.
Using the Arrow Library to increase the Functional Programming potential of the Kotlin Language. Presented to the Cork Java Users Group and Cork Functional Programmers on 1st May 2018
Presentation on using the Arrow library for enhanced Functional Programming in the Kotlin Language. Delivered at the Northern Ireland Developer Conference 2018.
The document discusses various data structures including stacks, queues, binary heaps, and binary indexed trees. It provides descriptions of each data structure, their common operations like push(), pop(), and top(), as well as discussing their time complexities and providing C++ code examples for implementation. It also gives examples of applications for each data structure.
Video and slides synchronized, mp3 and slide download available at URL http://bit.ly/1e4UMbN.
Gilad Bracha explains how to distinguish FP hype from reality and to apply key ideas of FP in non-FP languages, separating the good parts of FP from its unnecessary cultural baggage. Filmed at qconsf.com.
Gilad Bracha is the creator of the Newspeak programming language and a software engineer at Google where he works on Dart. Previously, he was a VP at SAP Labs, a Distinguished Engineer at Cadence, and a Computational Theologist and Distinguished Engineer at Sun. He is co-author of the Java Language Specification, and a researcher in the area of object-oriented programming languages.
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
Industry - Program analysis and verification - Type-preserving Heap Profiler ...ICSM 2011
Paper: Type-preserving Heap Profiler for C++
Authors: József Mihalicza, Zoltán Porkoláb and Ábel Gábor
Session: "Industry Track Session 4: Program analysis and Verification"
Functions, Exception, Modules and Files
Functions: Difference between a Function and a Method, Defining a Function, Calling a Function, Returning Results from a Function, Returning Multiple Values from a Function, Functions are First Class Objects, Pass by Object Reference, Formal and Actual Arguments, Positional Arguments, Keyword Arguments, Default Arguments, Variable Length Arguments, Local and Global Variables, The Global Keyword, Passing a Group of Elements to a Function, Recursive Functions, Anonymous Functions or Lambdas (Using Lambdas with filter() Function, Using Lambdas with map() Function, Using Lambdas with reduce() Function), Function Decorators, Generators, Structured Programming, Creating our Own Modules in Python, The Special Variable __name__
Exceptions: Errors in a Python Program (Compile-Time Errors, Runtime Errors, Logical Errors),Exceptions, Exception Handling, Types of Exceptions, The Except Block, The assert Statement, UserDefined Exceptions, Logging the Exceptions
20%
Files: Files, Types of Files in Python, Opening a File, Closing a File, Working with Text Files Containing Strings, Knowing Whether a File Exists or Not, Working with Binary Files, The with Statement, Pickle in Python, The seek() and tell() Methods, Random Accessing of Binary Files, Random Accessing of Binary Files using mmap, Zipping and Unzipping Files, Working with Directories, Running Other Programs from Python Program
This document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It also covers topics like functions, modules, files, and classes in Python.
This document provides an overview of learning Python in three hours. It covers Python's history, installing and running Python, basic data types like integers, floats and strings. It also discusses sequence types like lists, tuples and strings, and how lists are mutable while tuples are immutable. The document includes examples of basic syntax like assignment, conditionals, functions and modules. It provides guidance on naming conventions and discusses the Python interpreter, editors and development environments.
This document provides an overview of the Python programming language. It discusses Python's history and key features such as being an interpreted, object-oriented, and functional language. The document also covers installing Python, running Python scripts and programs, basic datatypes like integers and strings, sequence types like lists and tuples, and other basic concepts like functions, variables, and flow control.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It explains key concepts like variable assignment, conditional statements, functions, modules and packages. The document also compares mutable lists and immutable tuples, and covers common list operations.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It explains key concepts like variable assignment, basic operations, slicing of sequences, and how lists are mutable but tuples are immutable. The document is intended to teach Python fundamentals in about three hours.
This document provides an overview of the Python programming language. It discusses Python's history and key features such as being object-oriented, scalable, and functional from the beginning. It also covers installing Python, running Python programs, basic datatypes like integers and strings, sequence types like lists and tuples, and other basic concepts like functions, comments, and whitespace.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It explains key concepts like variable assignment, basic operations, slicing of sequences, and how lists are mutable but tuples are immutable. The document is intended to teach Python fundamentals in about three hours.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It explains key concepts like variable assignment, basic operations, slicing of sequences, and how lists are mutable but tuples are immutable. The document is intended to teach Python fundamentals in about three hours.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It explains key concepts like variable assignment, conditional statements, functions, modules and packages. The document also compares mutable lists and immutable tuples, and covers common list operations.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It explains key concepts like variable assignment, conditional statements, functions, modules and packages. The document also compares mutable lists and immutable tuples, and covers common list operations.
This document provides an overview of the Python programming language. It discusses Python's history and key features such as being an interpreted, object-oriented, and functional language. The document also covers installing Python, running Python scripts and programs, basic datatypes like integers and strings, sequence types like lists and tuples, and other basic concepts like functions, variables, and flow control.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It explains key concepts like variable assignment, basic operations, slicing of sequences, and how lists are mutable but tuples are immutable. The document is intended to teach Python fundamentals in about three hours.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, and lists. It also covers Python concepts like functions, modules, conditionals, loops, classes and objects.
The document provides an overview of the Python programming language. It discusses Python's history and key features such as being scalable, object oriented, and functional. It also covers installing Python, running Python programs, basic datatypes like integers and strings, sequence types like lists and tuples, and other basic concepts like functions, variables, and control flow.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists, and tuples. It explains that lists are mutable while tuples are immutable. The document also covers topics like functions, modules, control flow, and the Python interpreter.
Python is an interpreted, object-oriented programming language similar to PERL, that has gained popularity because of its clear syntax and readability.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.
The document provides an overview of the Python programming language. It discusses Python's history, how to install and run Python, basic data types like integers, floats, strings, lists and tuples. It explains key Python concepts like variable assignment, conditional statements, functions, modules and packages. The document also compares mutable lists and immutable tuples, and covers common list operations.
This document provides an overview of learning Python in three hours. It covers installing and running Python, basic data types like integers, floats and strings. It also discusses sequence types like lists, tuples and strings, including accessing elements, slicing, and using operators like + and *. The document explains basic syntax like comments, indentation and naming conventions. It provides examples of simple functions and scripts.
Discovering the Best Indian Architects A Spotlight on Design Forum Internatio...Designforuminternational
India’s architectural landscape is a vibrant tapestry that weaves together the country's rich cultural heritage and its modern aspirations. From majestic historical structures to cutting-edge contemporary designs, the work of Indian architects is celebrated worldwide. Among the many firms shaping this dynamic field, Design Forum International stands out as a leader in innovative and sustainable architecture. This blog explores some of the best Indian architects, highlighting their contributions and showcasing the most famous architects in India.
Explore the essential graphic design tools and software that can elevate your creative projects. Discover industry favorites and innovative solutions for stunning design results.
ARENA - Young adults in the workplace (Knight Moves).pdfKnight Moves
Presentations of Bavo Raeymaekers (Project lead youth unemployment at the City of Antwerp), Suzan Martens (Service designer at Knight Moves) and Adriaan De Keersmaeker (Community manager at Talk to C)
during the 'Arena • Young adults in the workplace' conference hosted by Knight Moves.
Architectural and constructions management experience since 2003 including 18 years located in UAE.
Coordinate and oversee all technical activities relating to architectural and construction projects,
including directing the design team, reviewing drafts and computer models, and approving design
changes.
Organize and typically develop, and review building plans, ensuring that a project meets all safety and
environmental standards.
Prepare feasibility studies, construction contracts, and tender documents with specifications and
tender analyses.
Consulting with clients, work on formulating equipment and labor cost estimates, ensuring a project
meets environmental, safety, structural, zoning, and aesthetic standards.
Monitoring the progress of a project to assess whether or not it is in compliance with building plans
and project deadlines.
Attention to detail, exceptional time management, and strong problem-solving and communication
skills are required for this role.
International Upcycling Research Network advisory board meeting 4Kyungeun Sung
Slides used for the International Upcycling Research Network advisory board 4 (last one). The project is based at De Montfort University in Leicester, UK, and funded by the Arts and Humanities Research Council.
1. Introduction to Python
Heavily based on presentations by
Matt Huenerfauth (Penn State)
Guido van Rossum (Google)
Richard P. Muller (Caltech)
...
Monday, October 19, 2009
2. • Open source general-purpose language.
• Object Oriented, Procedural, Functional
• Easy to interface with C/ObjC/Java/Fortran
• Easy-ish to interface with C++ (via SWIG)
• Great interactive environment
• Downloads: http://www.python.org
• Documentation: http://www.python.org/doc/
• Free book: http://www.diveintopython.org
Python
Monday, October 19, 2009
3. 2.5.x / 2.6.x / 3.x ???
• “Current” version is 2.6.x
• “Mainstream” version is 2.5.x
• The new kid on the block is 3.x
You probably want 2.5.x unless you are starting from
scratch. Then maybe 3.x
Monday, October 19, 2009
5. Binaries
• Python comes pre-installed with Mac OS X and
Linux.
• Windows binaries from http://python.org/
• You might not have to do anything!
Monday, October 19, 2009
6. The Python Interpreter
• Interactive interface to Python
% python
Python 2.5 (r25:51908, May 25 2007, 16:14:04)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
• Python interpreter evaluates inputs:
>>> 3*(7+2)
27
• Python prompts with ‘>>>’.
• To exit Python:
• CTRL-D
Monday, October 19, 2009
7. Running Programs on UNIX
% python filename.py
You could make the *.py file executable and add the
following #!/usr/bin/env python to the top to make it
runnable.
Monday, October 19, 2009
8. Batteries Included
• Large collection of proven modules included in the
standard distribution.
http://docs.python.org/modindex.html
Monday, October 19, 2009
9. numpy
• Offers Matlab-ish capabilities within Python
• Fast array operations
• 2D arrays, multi-D arrays, linear algebra etc.
• Downloads: http://numpy.scipy.org/
• Tutorial: http://www.scipy.org/
Tentative_NumPy_Tutorial
Monday, October 19, 2009
10. matplotlib
• High quality plotting library.
• Downloads: http://matplotlib.sourceforge.net/
#!/usr/bin/env python
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green',
alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=1)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$mathrm{Histogram of IQ:} mu=100, sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
Monday, October 19, 2009
14. Custom Distributions
• Python(x,y): http://www.pythonxy.com/
• Python(x,y) is a free scientific and engineering development
software for numerical computations, data analysis and data
visualization
• Sage: http://www.sagemath.org/
• Sage is a free open-source mathematics software system
licensed under the GPL. It combines the power of many existing
open-source packages into a common Python-based interface.
Monday, October 19, 2009
17. A Code Sample
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
Monday, October 19, 2009
18. Enough to Understand the Code
• Assignment uses = and comparison uses ==.
• For numbers + - * / % are as expected.
• Special use of + for string concatenation.
• Special use of % for string formatting (as with printf in C)
• Logical operators are words (and, or, not)
not symbols
• The basic printing command is print.
• The first assignment to a variable creates it.
• Variable types don’t need to be declared.
• Python figures out the variable types on its own.
Monday, October 19, 2009
19. Basic Datatypes
• Integers (default for numbers)
z = 5 / 2 # Answer is 2, integer division.
• Floats
x = 3.456
• Strings
• Can use “” or ‘’ to specify.
“abc” ‘abc’ (Same thing.)
• Unmatched can occur within the string.
“matt’s”
• Use triple double-quotes for multi-line strings or strings than contain both ‘
and “ inside of them:
“““a‘b“c”””
Monday, October 19, 2009
20. Whitespace
Whitespace is meaningful in Python: especially
indentation and placement of newlines.
• Use a newline to end a line of code.
• Use when must go to next line prematurely.
• No braces { } to mark blocks of code in Python…
Use consistent indentation instead.
• The first line with less indentation is outside of the block.
• The first line with more indentation starts a nested block
• Often a colon appears at the start of a new block.
(E.g. for function and class definitions.)
Monday, October 19, 2009
21. Comments
• Start comments with # – the rest of line is ignored.
• Can include a “documentation string” as the first line of any
new function or class that you define.
• The development environment, debugger, and other tools use
it: it’s good style to include one.
def my_function(x, y):
“““This is the docstring. This
function does blah blah blah.”””
# The code would go here...
Monday, October 19, 2009
22. Assignment
• Binding a variable in Python means setting a name to hold a
reference to some object.
• Assignment creates references, not copies
• Names in Python do not have an intrinsic type. Objects have
types.
• Python determines the type of the reference automatically based on the
data object assigned to it.
• You create a name the first time it appears on the left side of
an assignment expression:
! x = 3
• A reference is deleted via garbage collection after any names
bound to it have passed out of scope.
Monday, October 19, 2009
23. Accessing Non-Existent Names
• If you try to access a name before it’s been properly created
(by placing it on the left side of an assignment), you’ll get an
error.
>>> y
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevel-
y
NameError: name ‘y' is not defined
>>> y = 3
>>> y
3
Monday, October 19, 2009
24. Multiple Assignment
• You can also assign to multiple names at the same time.
>>> x, y = 2, 3
>>> x
2
>>> y
3
Monday, October 19, 2009
25. Naming Rules
• Names are case sensitive and cannot start with a number.
They can contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
• There are some reserved words:
and, assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if,
import, in, is, lambda, not, or, pass, print, raise,
return, try, while
Monday, October 19, 2009
27. Understanding Reference Semantics
• Assignment manipulates references
—x = y does not make a copy of the object y references
—x = y makes x reference the object y references
• Very useful; but beware!
• Example:
>>> a = [1, 2, 3] # a now references the list [1, 2, 3]
>>> b = a # b now references what a references
>>> a.append(4) # this changes the list a references
>>> print b # if we print what b references,
[1, 2, 3, 4] # SURPRISE! It has changed…
Why??
Monday, October 19, 2009
28. Understanding Reference Semantics II
• There is a lot going on when we type:
x = 3
• First, an integer 3 is created and stored in memory
• A name x is created
• An reference to the memory location storing the 3 is then
assigned to the name x
• So: When we say that the value of x is 3
• we mean that x now refers to the integer 3
Type: Integer
Data: 3
Name: x
Ref: <address1>
name list memory
Monday, October 19, 2009
29. Understanding Reference Semantics III
• The data 3 we created is of type integer. In Python, the
datatypes integer, float, and string (and tuple) are
“immutable.”
• This doesn’t mean we can’t change the value of x, i.e. change
what x refers to …
• For example, we could increment x:
>>> x = 3
>>> x = x + 1
>>> print x
4
Monday, October 19, 2009
30. Understanding Reference Semantics IV
• If we increment x, then what’s really happening is:
1. The reference of name x is looked up.
2. The value at that reference is retrieved.
Type: Integer
Data: 3Name: x
Ref: <address1>
>>> x = x + 1
Monday, October 19, 2009
31. Understanding Reference Semantics IV
• If we increment x, then what’s really happening is:
1. The reference of name x is looked up.
2. The value at that reference is retrieved.
3. The 3+1 calculation occurs, producing a new data element 4 which is
assigned to a fresh memory location with a new reference.
Type: Integer
Data: 3Name: x
Ref: <address1>
Type: Integer
Data: 4
>>> x = x + 1
Monday, October 19, 2009
32. Understanding Reference Semantics IV
• If we increment x, then what’s really happening is:
1. The reference of name x is looked up.
2. The value at that reference is retrieved.
3. The 3+1 calculation occurs, producing a new data element 4 which is
assigned to a fresh memory location with a new reference.
4. The name x is changed to point to this new reference.
Type: Integer
Data: 3Name: x
Ref: <address1>
Type: Integer
Data: 4
>>> x = x + 1
Monday, October 19, 2009
33. Understanding Reference Semantics IV
• If we increment x, then what’s really happening is:
1. The reference of name x is looked up.
2. The value at that reference is retrieved.
3. The 3+1 calculation occurs, producing a new data element 4 which is
assigned to a fresh memory location with a new reference.
4. The name x is changed to point to this new reference.
5. The old data 3 is garbage collected if no name still refers to it.
Name: x
Ref: <address1>
Type: Integer
Data: 4
>>> x = x + 1
Monday, October 19, 2009
34. Assignment 1
• So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print x # No effect on x, still ref 3.
3
Monday, October 19, 2009
35. Assignment 1
• So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print x # No effect on x, still ref 3.
3
Type: Integer
Data: 3
Name: x
Ref: <address1>
Monday, October 19, 2009
36. Assignment 1
• So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print x # No effect on x, still ref 3.
3
Type: Integer
Data: 3
Name: x
Ref: <address1>
Name: y
Ref: <address1>
Monday, October 19, 2009
37. Assignment 1
• So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print x # No effect on x, still ref 3.
3
Type: Integer
Data: 3
Name: x
Ref: <address1>
Type: Integer
Data: 4
Name: y
Ref: <address1>
Monday, October 19, 2009
38. Assignment 1
• So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print x # No effect on x, still ref 3.
3
Type: Integer
Data: 3
Name: x
Ref: <address1>
Type: Integer
Data: 4
Name: y
Ref: <address2>
Monday, October 19, 2009
39. Assignment 1
• So, for simple built-in datatypes (integers, floats, strings),
assignment behaves as you would expect:
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print x # No effect on x, still ref 3.
3
Type: Integer
Data: 3
Name: x
Ref: <address1>
Type: Integer
Data: 4
Name: y
Ref: <address2>
Monday, October 19, 2009
40. Assignment 2
• For other data types (lists, dictionaries, user-defined types), assignment
works differently.
• These datatypes are “mutable.”
• When we change these data, we do it in place.
• We don’t copy them into a new memory address each time.
• If we type y=x and then modify y, both x and y are changed.
>>> x = 3 x = some mutable object
>>> y = x y = x
>>> y = 4 make a change to y
>>> print x look at x
3 x will be changed as well
immutable mutable
Monday, October 19, 2009
41. a
1 2 3
b
a
1 2 3
b
4
a = [1, 2, 3]
a.append(4)
b = a
a 1 2 3
Why? Changing a Shared List
Monday, October 19, 2009
42. Our surprising example surprising no more...
• So now, here’s our code:
>>> a = [1, 2, 3] # a now references the list [1, 2, 3]
>>> b = a # b now references what a references
>>> a.append(4) # this changes the list a references
>>> print b # if we print what b references,
[1, 2, 3, 4] # SURPRISE! It has changed…
Monday, October 19, 2009
44. Sequence Types
1. Tuple
• A simple immutable ordered sequence of items
• Items can be of mixed types, including collection types
2. Strings
• Immutable
• Conceptually very much like a tuple
3. List
• Mutable ordered sequence of items of mixed types
Monday, October 19, 2009
45. Similar Syntax
• All three sequence types (tuples, strings, and lists)
share much of the same syntax and functionality.
• Key difference:
• Tuples and strings are immutable
• Lists are mutable
• The operations shown in this section can be
applied to all sequence types
• most examples will just show the operation
performed on one
Monday, October 19, 2009
46. Sequence Types 1
• Tuples are defined using parentheses (and commas).
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
• Lists are defined using square brackets (and commas).
>>> li = [“abc”, 34, 4.34, 23]
• Strings are defined using quotes (“, ‘, or “““).
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
Monday, October 19, 2009
47. Sequence Types 2
• We can access individual members of a tuple, list, or string
using square bracket “array” notation.
• Note that all are 0 based…
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> tu[1] # Second item in the tuple.
‘abc’
>>> li = [“abc”, 34, 4.34, 23]
>>> li[1] # Second item in the list.
34
>>> st = “Hello World”
>>> st[1] # Second character in string.
‘e’
Monday, October 19, 2009
48. Positive and negative indices
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Positive index: count from the left, starting with 0.
>>> t[1]
‘abc’
Negative lookup: count from right, starting with –1.
>>> t[-3]
4.56
Monday, October 19, 2009
49. Slicing: Return Copy of a Subset 1
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Return a copy of the container with a subset of the original
members. Start copying at the first index, and stop copying
before the second index.
>>> t[1:4]
(‘abc’, 4.56, (2,3))
You can also use negative indices when slicing.
>>> t[1:-1]
(‘abc’, 4.56, (2,3))
Monday, October 19, 2009
50. Slicing: Return Copy of a Subset 2
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
Omit the first index to make a copy starting from the beginning
of the container.
>>> t[:2]
(23, ‘abc’)
Omit the second index to make a copy starting at the first index
and going to the end of the container.
>>> t[2:]
(4.56, (2,3), ‘def’)
Monday, October 19, 2009
51. Copying the Whole Sequence
To make a copy of an entire sequence, you can use [:].
>>> t[:]
(23, ‘abc’, 4.56, (2,3), ‘def’)
Note the difference between these two lines for mutable
sequences:
>>> list2 = list1 # 2 names refer to 1 ref
# Changing one affects both
>>> list2 = list1[:] # Two independent copies, two refs
Monday, October 19, 2009
52. The ‘in’ Operator
• Boolean test whether a value is inside a container:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not in t
False
• For strings, tests for substrings
>>> a = 'abcde'
>>> 'c' in a
True
>>> 'cd' in a
True
>>> 'ac' in a
False
• Be careful: the in keyword is also used in the syntax of
for loops and list comprehensions.
Monday, October 19, 2009
53. The + Operator
• The + operator produces a new tuple, list, or string whose
value is the concatenation of its arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> “Hello” + “ ” + “World”
‘Hello World’
Monday, October 19, 2009
54. The * Operator
• The * operator produces a new tuple, list, or string that
“repeats” the original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> “Hello” * 3
‘HelloHelloHello’
Monday, October 19, 2009
56. Tuples: Immutable
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment
You can’t change a tuple.
You can make a fresh tuple and assign its reference to a previously used
name.
>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)
Monday, October 19, 2009
57. Lists: Mutable
>>> li = [‘abc’, 23, 4.34, 23]
>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]
• We can change lists in place.
• Name li still points to the same memory reference when we’re
done.
• The mutability of lists means that they aren’t as fast as tuples.
Monday, October 19, 2009
58. Operations on Lists Only 1
>>> li = [1, 11, 3, 4, 5]
>>> li.append(‘a’) # Our first exposure to method syntax
>>> li
[1, 11, 3, 4, 5, ‘a’]
>>> li.insert(2, ‘i’)
>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
Monday, October 19, 2009
59. The extend method vs the + operator.
• + creates a fresh list (with a new memory reference)
• extend operates on list li in place.
>>> li.extend([9, 8, 7])
>>>li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7]
Confusing:
• Extend takes a list as an argument.
• Append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12]]
Monday, October 19, 2009
60. Operations on Lists Only 3
>>> li = [‘a’, ‘b’, ‘c’, ‘b’]
>>> li.index(‘b’) # index of first occurrence
1
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove first occurrence
>>> li
[‘a’, ‘c’, ‘b’]
Monday, October 19, 2009
61. Operations on Lists Only 4
>>> li = [5, 2, 6, 8]
>>> li.reverse() # reverse the list *in place*
>>> li
[8, 6, 2, 5]
>>> li.sort() # sort the list *in place*
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
Monday, October 19, 2009
62. Tuples vs. Lists
• Lists slower but more powerful than tuples.
• Lists can be modified, and they have lots of handy operations we can
perform on them.
• Tuples are immutable and have fewer features.
• To convert between tuples and lists use the list() and tuple()
functions:
li = list(tu)
tu = tuple(li)
Monday, October 19, 2009
64. Dictionaries: A Mapping type
• Dictionaries store a mapping between a set of keys
and a set of values.
• Keys can be any immutable type.
• Values can be any type
• A single dictionary can store values of different types
• You can define, modify, view, lookup, and delete
the key-value pairs in the dictionary.
Monday, October 19, 2009
65. Using dictionaries
>>> d = {‘user’:‘bozo’, ‘pswd’:1234}
>>> d[‘user’]
‘bozo’
>>> d[‘pswd’]
1234
>>> d[‘bozo’]
Traceback (innermost last):
File ‘<interactive input>’ line 1, in ?
KeyError: bozo
>>> d = {‘user’:‘bozo’, ‘pswd’:1234}
>>> d[‘user’] = ‘clown’
>>> d
{‘user’:‘clown’, ‘pswd’:1234}
>>> d[‘id’] = 45
>>> d
{‘user’:‘clown’, ‘id’:45, ‘pswd’:1234}
>>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}
>>> del d[‘user’] # Remove one.
>>> d
{‘p’:1234, ‘i’:34}
>>> d.clear() # Remove all.
>>> d
{}
>>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}
>>> d.keys() # List of keys.
[‘user’, ‘p’, ‘i’]
>>> d.values() # List of values.
[‘bozo’, 1234, 34]
>>> d.items() # List of item tuples.
[(‘user’,‘bozo’), (‘p’,1234), (‘i’,34)]
Monday, October 19, 2009
67. Functions
• def creates a function and assigns it a name
• return sends a result back to the caller
• Arguments are passed by assignment
• Arguments and return types are not declared
def <name>(arg1, arg2, ..., argN):
! <statements>
! return <value>
def times(x,y):
! return x*y
Monday, October 19, 2009
68. Passing Arguments to Functions
• Arguments are passed by assignment
• Passed arguments are assigned to local names
• Assignment to argument names don't affect the
caller
• Changing a mutable argument may affect the caller
def changer (x,y):
! x = 2! ! ! # changes local value of x only
! y[0] = 'hi'!! # changes shared object
Monday, October 19, 2009
69. Optional Arguments
• Can define defaults for arguments that need not be
passed
def func(a, b, c=10, d=100):
! print a, b, c, d
>>> func(1,2)
1 2 10 100
>>> func(1,2,3,4)
1,2,3,4
Monday, October 19, 2009
70. Gotchas
• All functions in Python have a return value
• even if no return line inside the code.
• Functions without a return return the special value
None.
• There is no function overloading in Python.
• Two different functions can’t have the same name, even if they
have different arguments.
• Functions can be used as any other data type.
They can be:
• Arguments to function
• Return values of functions
• Assigned to variables
• Parts of tuples, lists, etc
Monday, October 19, 2009
72. Examples
if x == 3:
print “X equals 3.”
elif x == 2:
print “X equals 2.”
else:
print “X equals something else.”
print “This is outside the ‘if’.”
x = 3
while x < 10:
if x > 7:
x += 2
continue
x = x + 1
print “Still in the loop.”
if x == 8:
break
print “Outside of the loop.”
assert(number_of_players < 5)
for x in range(10):
if x > 7:
x += 2
continue
x = x + 1
print “Still in the loop.”
if x == 8:
break
print “Outside of the loop.”
Monday, October 19, 2009
74. Why Use Modules?
• Code reuse
• Routines can be called multiple times within a program
• Routines can be used from multiple programs
• Namespace partitioning
• Group data together with functions used for that data
• Implementing shared services or data
• Can provide global data structure that is accessed by multiple
subprograms
Monday, October 19, 2009
75. Modules
• Modules are functions and variables defined in
separate files
• Items are imported using from or import
from module import function
function()
import module
module.function()
• Modules are namespaces
• Can be used to organize variable names, i.e.
atom.position = atom.position - molecule.position
Monday, October 19, 2009
77. What is an Object?
• A software item that contains variables and
methods
• Object Oriented Design focuses on
• Encapsulation:
—dividing the code into a public interface, and a private implementation
of that interface
• Polymorphism:
—the ability to overload standard operators so that they have appropriate
behavior based on their context
• Inheritance:
—the ability to create subclasses that contain specializations of their
parents
Monday, October 19, 2009
78. Example
class atom(object):
! def __init__(self,atno,x,y,z):
! ! self.atno = atno
! ! self.position = (x,y,z)
! def symbol(self): # a class method
! ! return Atno_to_Symbol[atno]
! def __repr__(self): # overloads printing
! ! return '%d %10.4f %10.4f %10.4f' %
! ! ! (self.atno, self.position[0],
! ! ! self.position[1],self.position[2])
>>> at = atom(6,0.0,1.0,2.0)
>>> print at
6 0.0000 1.0000 2.0000
>>> at.symbol()
'C'
Monday, October 19, 2009
79. Atom Class
• Overloaded the default constructor
• Defined class variables (atno,position) that are
persistent and local to the atom object
• Good way to manage shared memory:
• instead of passing long lists of arguments, encapsulate some of
this data into an object, and pass the object.
• much cleaner programs result
• Overloaded the print operator
• We now want to use the atom class to build
molecules...
Monday, October 19, 2009
80. Molecule Class
class molecule:
! def __init__(self,name='Generic'):
! ! self.name = name
! ! self.atomlist = []
! def addatom(self,atom):
! ! self.atomlist.append(atom)
! def __repr__(self):
! ! str = 'This is a molecule named %sn' % self.name
! ! str = str+'It has %d atomsn' % len(self.atomlist)
! ! for atom in self.atomlist:
! ! ! str = str + `atom` + 'n'
! ! return str
Monday, October 19, 2009
81. Using Molecule Class
>>> mol = molecule('Water')
>>> at = atom(8,0.,0.,0.)
>>> mol.addatom(at)
>>> mol.addatom(atom(1,0.,0.,1.))
>>> mol.addatom(atom(1,0.,1.,0.))
>>> print mol
This is a molecule named Water
It has 3 atoms
8 0.000 0.000 0.000
1 0.000 0.000 1.000
1 0.000 1.000 0.000
• Note that the print function calls the atoms print
function
• Code reuse: only have to type the code that prints an atom
once; this means that if you change the atom specification, you
only have one place to update.
Monday, October 19, 2009
82. Inheritance
class qm_molecule(molecule):
def addbasis(self):
self.basis = []
for atom in self.atomlist:
self.basis = add_bf(atom,self.basis)
• __init__, __repr__, and __addatom__ are taken
from the parent class (molecule)
• Added a new function addbasis() to add a basis set
• Another example of code reuse
• Basic functions don't have to be retyped, just inherited
• Less to rewrite when specifications change
Monday, October 19, 2009
83. Overloading
class qm_molecule(molecule):
def __repr__(self):
! ! str = 'QM Rules!n'
! ! for atom in self.atomlist:
! ! ! str = str + `atom` + 'n'
! ! return str
• Now we only inherit __init__ and addatom from the
parent
• We define a new version of __repr__ specially for
QM
Monday, October 19, 2009
84. Adding to Parent Functions
• Sometimes you want to extend, rather than
replace, the parent functions.
class qm_molecule(molecule):
! def __init__(self,name="Generic",basis="6-31G**"):
! ! self.basis = basis
! ! super(qm_molecule, self).__init__(name)
Monday, October 19, 2009
85. Public and Private Data
• In Python anything with two leading underscores
is private
__a, __my_variable
• Anything with one leading underscore is semi-
private, and you should feel guilty accessing this
data directly.
_b
• Sometimes useful as an intermediate step to making data
private
Monday, October 19, 2009
87. File I/O, Strings, Exceptions...
fileptr = open(‘filename’)
somestring = fileptr.read()
for line in fileptr:
print line
fileptr.close()
>>> a = 1
>>> b = 2.4
>>> c = 'Tom'
>>> '%s has %d coins worth a total of $%.02f' % (c, a, b)
'Tom has 1 coins worth a total of $2.40'
>>> try:
... 1 / 0
... except:
... print('That was silly!')
... finally:
... print('This gets executed no matter what')
...
That was silly!
This gets executed no matter what
Monday, October 19, 2009