Introduction to the Python programming language (version 2.x)
Ambient intelligence: technology and design
http://bit.ly/polito-ami
Politecnico di Torino, 2015
This document provides an introduction to Python programming concepts such as variables, data types, strings, lists, dictionaries, conditionals, loops, functions and modules. It covers Python basics like formatting, naming conventions and comments. Key concepts are explained through examples, such as how to define and modify variables and different data structures, perform string operations, take user input, and define reusable functions. The document is intended to teach Python fundamentals to new programmers.
Introduction to the Python programming language (version 3.x).
Ambient Intelligence
http://bit.ly/polito-ami
Politecnico di Torino, 2017
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
This document provides an overview of NumPy, the core library for scientific computing in Python. It discusses NumPy arrays, which provide a grid of values that are all of the same type and indexed by tuples of integers. NumPy arrays can be initialized from nested lists and accessed using square brackets. NumPy also provides functions to create arrays filled with zeros, ones, random values, or a constant. The document covers slicing NumPy arrays to extract subarrays, and integer array indexing to construct arbitrary arrays from another array's data. It demonstrates how slicing returns views into the original data, while integer indexing allows selecting elements in any order.
This document summarizes basic operations in Matlab and Python, including programming paradigms, object-oriented fundamentals, arrays/lists, cells/structures, functions, and loops. It provides examples of classes, objects, and inheritance in both languages. Examples are also given for arrays, lists, cells, structures, functions, and loops. The document outlines the key differences between Matlab and Python for arrays, lists, and cells/structures. It concludes with references used in preparing the content.
1. Python can be used to automate repetitive tasks like data entry, file processing, report generation etc. This saves time and reduces human errors.
2. Python has many libraries for machine learning, data analysis and visualization which can be used to analyze patent data, identify trends, cluster similar technologies etc.
3. Web scraping and web development frameworks like Django can be used to build internal tools and dashboards to manage workflows more efficiently.
4. Python scripts can be written to extract and process data from various sources, perform calculations, format reports in a standardized way reducing manual efforts.
This document provides an introduction to Python programming using PyCharm. It discusses downloading and installing Python and PyCharm, creating and running simple Python scripts that use print statements and variables, taking user input, and introducing conditional logic using if/else statements and while loops. Examples include printing ASCII art, basic math operations, and building a text-based choose your own adventure game. Further exercises are suggested to improve the game by adding dice rolls and more options.
Python is a high-level, interpreted programming language that is designed to be easy to read and write. It has a clear syntax using English keywords and its code is often shorter than languages like C++ and Java. Python is widely used for web development, software development, science, and machine learning. It has a large standard library and can be extended through modules. Some key data structures in Python include lists, tuples, and dictionaries.
Python quickstart for programmers: Python Kung Fuclimatewarrior
The document provides an overview of key Python concepts including data types, operators, control flow statements, functions, objects and classes. It discusses lists in depth, covering creation, iteration, searching and common list methods. It also briefly touches on modules, exceptions, inheritance and other advanced topics.
Introduction to Python Language and Data TypesRavi Shankar
This document provides information about the Python programming language. It discusses that Python was invented in the 1990s in the Netherlands by Guido van Rossum and was named after Monty Python. It is an open source, general-purpose, interpreted programming language that is widely used. The document then covers various Python implementations, popular Python editors and IDEs, tips for getting started with Python, basic syntax, data types, operators, and lists.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.
A slightly modified version of original "An introduction to Python
for absolute beginners" slides. For credits please check the second page. I used this presentation for my company's internal Python course.
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
This is the 3rd part of a multi-part series that teaches the basics of Python programming. It covers list and dict comprehensions, functions, modules and packages.
This document provides an overview of the basics of the Python programming language. It covers key Python concepts like types, expressions and variables, strings, input/output, lists and tuples, dictionaries, sets, conditions and branching, loops, functions, and objects and classes. The document defines each concept, provides examples, and explains how to use various Python features and functions related to each topic.
This document provides an introduction to the Python language and discusses Python data types. It covers how to install Python, interact with the Python interpreter through command line and IDLE modes, and learn basic Python parts like data types, operators, functions, and control structures. The document discusses numeric, string, and other data types in Python and how to manipulate them using built-in functions and operators. It also introduces Python library modules and the arcpy package for geoprocessing in ArcGIS.
This document provides an introduction and overview of various Python programming concepts including print statements, math operations, variables, selection using if/else statements, and iteration using while and for loops. Examples are given for basic "Hello World" programs, math calculations, variables, checking if a number is odd or even, and finding the largest of three numbers. Loops are demonstrated for printing ranges of numbers, calculating sums and factorials. The document also discusses data types and operations in Python.
This document provides an introduction to the Python programming language. It covers Python's background, syntax, types, operators, control flow, functions, classes, tools, and IDEs. Key points include that Python is a multi-purpose, object-oriented language that is interpreted, strongly and dynamically typed. It focuses on readability and has a huge library of modules. Popular Python IDEs include Emacs, Vim, Komodo, PyCharm, and Eclipse.
This document provides an agenda and overview for a Python training course. The agenda covers key Python topics like dictionaries, conditional statements, loops, functions, modules, input/output, error handling, object-oriented programming and more. The introduction section explains that Python is an interpreted, interactive and object-oriented language well-suited for beginners. It also outlines features like rapid development, automatic memory management and support for procedural and object-oriented programming. The document concludes by explaining Python's core data types including numbers, strings, lists, tuples and dictionaries.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins, philosophy, features, and uses. Key points covered include Python's simplicity, power, object-oriented approach, and wide portability. Examples are provided of basic Python syntax and constructs like strings, lists, functions, modules, and dictionaries.
The document provides an introduction to programming in Python. It discusses how Python can be used for web development, desktop applications, data science, machine learning, and more. It also covers executing Python programs, reading keyboard input, decision making and loops in Python, standard data types like numbers, strings, lists, tuples and dictionaries. Additionally, it describes functions, opening and reading/writing files, regular expressions, and provides examples of SQLite database connections in Python projects.
Here are the steps to solve this problem:
1. Convert both lists of numbers to sets:
set1 = {11, 2, 3, 4, 15, 6, 7, 8, 9, 10}
set2 = {15, 2, 3, 4, 15, 6}
2. Find the intersection of the two sets:
intersection = set1.intersection(set2)
3. The number of elements in the intersection is the number of similar elements:
similarity = len(intersection)
4. Print the result:
print(similarity)
The similarity between the two sets is 4, since they both contain the elements {2, 3, 4, 15}.
The document discusses dictionaries in Python. It explains that dictionaries are a mapping type that store key-value pairs, with keys being immutable types and values being any type. It provides examples of creating, accessing, updating, removing entries from, and accessing properties of dictionaries. It also covers functions, control flow statements like if/else and while loops, and list comprehensions.
This presentation covers Python most important data structures like Lists, Dictionaries, Sets and Tuples. Exception Handling and Random number generation using simple python module "random" also covered. Added simple python programs at the end of the presentation
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.
Python was created in 1980 by Guido Van Rossum. There are differences between Python versions 2.x and 3.x related to compatibility, understandability, maturity, and robustness. Some frameworks like Twisted and gevent have not yet migrated to Python 3.x, while others like NumPy, Django, Flask, CherryPy, Pyramid, PIL, cx_Freeze, and Py2exe have migrated. The document also includes code examples and information about a Python developer.
This document provides an overview and tutorial on the Python programming language. It introduces Python's main features like lists, dictionaries, functions, object-oriented programming and modules. The tutorial includes example code and explanations of Python concepts like data types, scope, exceptions, classes and inheritance. It also covers debugging tools and accessing Python's online documentation. The goal is to quickly teach the essentials of Python in a painless manner.
This document provides an introduction to Python programming using PyCharm. It discusses downloading and installing Python and PyCharm, creating and running simple Python scripts that use print statements and variables, taking user input, and introducing conditional logic using if/else statements and while loops. Examples include printing ASCII art, basic math operations, and building a text-based choose your own adventure game. Further exercises are suggested to improve the game by adding dice rolls and more options.
Python is a high-level, interpreted programming language that is designed to be easy to read and write. It has a clear syntax using English keywords and its code is often shorter than languages like C++ and Java. Python is widely used for web development, software development, science, and machine learning. It has a large standard library and can be extended through modules. Some key data structures in Python include lists, tuples, and dictionaries.
Python quickstart for programmers: Python Kung Fuclimatewarrior
The document provides an overview of key Python concepts including data types, operators, control flow statements, functions, objects and classes. It discusses lists in depth, covering creation, iteration, searching and common list methods. It also briefly touches on modules, exceptions, inheritance and other advanced topics.
Introduction to Python Language and Data TypesRavi Shankar
This document provides information about the Python programming language. It discusses that Python was invented in the 1990s in the Netherlands by Guido van Rossum and was named after Monty Python. It is an open source, general-purpose, interpreted programming language that is widely used. The document then covers various Python implementations, popular Python editors and IDEs, tips for getting started with Python, basic syntax, data types, operators, and lists.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.
A slightly modified version of original "An introduction to Python
for absolute beginners" slides. For credits please check the second page. I used this presentation for my company's internal Python course.
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
This is the 3rd part of a multi-part series that teaches the basics of Python programming. It covers list and dict comprehensions, functions, modules and packages.
This document provides an overview of the basics of the Python programming language. It covers key Python concepts like types, expressions and variables, strings, input/output, lists and tuples, dictionaries, sets, conditions and branching, loops, functions, and objects and classes. The document defines each concept, provides examples, and explains how to use various Python features and functions related to each topic.
This document provides an introduction to the Python language and discusses Python data types. It covers how to install Python, interact with the Python interpreter through command line and IDLE modes, and learn basic Python parts like data types, operators, functions, and control structures. The document discusses numeric, string, and other data types in Python and how to manipulate them using built-in functions and operators. It also introduces Python library modules and the arcpy package for geoprocessing in ArcGIS.
This document provides an introduction and overview of various Python programming concepts including print statements, math operations, variables, selection using if/else statements, and iteration using while and for loops. Examples are given for basic "Hello World" programs, math calculations, variables, checking if a number is odd or even, and finding the largest of three numbers. Loops are demonstrated for printing ranges of numbers, calculating sums and factorials. The document also discusses data types and operations in Python.
This document provides an introduction to the Python programming language. It covers Python's background, syntax, types, operators, control flow, functions, classes, tools, and IDEs. Key points include that Python is a multi-purpose, object-oriented language that is interpreted, strongly and dynamically typed. It focuses on readability and has a huge library of modules. Popular Python IDEs include Emacs, Vim, Komodo, PyCharm, and Eclipse.
This document provides an agenda and overview for a Python training course. The agenda covers key Python topics like dictionaries, conditional statements, loops, functions, modules, input/output, error handling, object-oriented programming and more. The introduction section explains that Python is an interpreted, interactive and object-oriented language well-suited for beginners. It also outlines features like rapid development, automatic memory management and support for procedural and object-oriented programming. The document concludes by explaining Python's core data types including numbers, strings, lists, tuples and dictionaries.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins, philosophy, features, and uses. Key points covered include Python's simplicity, power, object-oriented approach, and wide portability. Examples are provided of basic Python syntax and constructs like strings, lists, functions, modules, and dictionaries.
The document provides an introduction to programming in Python. It discusses how Python can be used for web development, desktop applications, data science, machine learning, and more. It also covers executing Python programs, reading keyboard input, decision making and loops in Python, standard data types like numbers, strings, lists, tuples and dictionaries. Additionally, it describes functions, opening and reading/writing files, regular expressions, and provides examples of SQLite database connections in Python projects.
Here are the steps to solve this problem:
1. Convert both lists of numbers to sets:
set1 = {11, 2, 3, 4, 15, 6, 7, 8, 9, 10}
set2 = {15, 2, 3, 4, 15, 6}
2. Find the intersection of the two sets:
intersection = set1.intersection(set2)
3. The number of elements in the intersection is the number of similar elements:
similarity = len(intersection)
4. Print the result:
print(similarity)
The similarity between the two sets is 4, since they both contain the elements {2, 3, 4, 15}.
The document discusses dictionaries in Python. It explains that dictionaries are a mapping type that store key-value pairs, with keys being immutable types and values being any type. It provides examples of creating, accessing, updating, removing entries from, and accessing properties of dictionaries. It also covers functions, control flow statements like if/else and while loops, and list comprehensions.
This presentation covers Python most important data structures like Lists, Dictionaries, Sets and Tuples. Exception Handling and Random number generation using simple python module "random" also covered. Added simple python programs at the end of the presentation
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.
Python was created in 1980 by Guido Van Rossum. There are differences between Python versions 2.x and 3.x related to compatibility, understandability, maturity, and robustness. Some frameworks like Twisted and gevent have not yet migrated to Python 3.x, while others like NumPy, Django, Flask, CherryPy, Pyramid, PIL, cx_Freeze, and Py2exe have migrated. The document also includes code examples and information about a Python developer.
This document provides an overview and tutorial on the Python programming language. It introduces Python's main features like lists, dictionaries, functions, object-oriented programming and modules. The tutorial includes example code and explanations of Python concepts like data types, scope, exceptions, classes and inheritance. It also covers debugging tools and accessing Python's online documentation. The goal is to quickly teach the essentials of Python in a painless manner.
The document provides an overview of the Python programming language. It discusses that Python is an interpreted, interactive, object-oriented language created by Guido van Rossum in the late 1980s. It describes Python as high-level, portable, and has an extensive standard library. The document then covers Python variables and data types, basic operators, and provides examples of Python code, including defining variables, strings, lists, tuples, and dictionaries.
This document discusses Python statements, code blocks, and indentation. It notes that statements in Python are typically written on individual lines, but can span multiple lines using line continuation characters or parentheses. Code blocks, like if/else statements and functions, are defined by indentation rather than brackets - any indented code will be executed as part of the code block. Indentation is significant in Python and code blocks must be indented consistently using spaces.
This document contains slides from a Python workshop presentation. It introduces Python, discussing its history, philosophy, features, and how to write Python code. Some key points covered include:
- Python was created in the late 1980s and named after Monty Python.
- It aims to have clear, readable syntax while also being powerful.
- Python code tends to be more concise than languages like Java and C++.
- It uses indentation rather than braces to define code blocks.
- Common data types like lists, dictionaries, and tuples are covered.
- Basic programming constructs like conditionals, loops, functions and file I/O are demonstrated.
(1) Python uses indentation rather than braces to indicate blocks of code for functions and control flow. All statements within a block must be indented the same amount.
(2) Python identifiers can consist of letters, numbers, and underscores but must start with a letter or underscore. Identifiers are case-sensitive.
(3) There are reserved words in Python that cannot be used as identifiers such as def, if, else, and, or, not, etc.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and optionally returning values. Strings are sequences of characters that can be manipulated using indexes and methods. Common string methods include upper() and concatenation using +.
This document introduces Python by discussing its history and design, how to install it, the Python command line interface including lists and modules, introduction to GUI programming frameworks like GTK and widgets, and exception handling. It encourages learning Python by suggesting creative projects like games, lists, and downloading data to get experience with the language.
This document provides an overview of Python basics including:
1. How to print and comment in Python code
2. Taking input and manipulating strings
3. Converting between data types and working with dates and times
4. Making decisions with conditional statements and loops
5. Working with lists, tuples, and dictionaries
6. Handling exceptions
Computers can be classified into four main categories based on their processing power and size: micro computers which use a microprocessor as the CPU, mini computers which are larger than micros but smaller than mainframes, mainframe computers which are the largest and most powerful, and super computers which are the fastest and most advanced systems currently available for processing large amounts of data and performing complex calculations.
This document provides an introduction and agenda for a workshop on Python 3 scripting. The introduction covers the presenter's background in Python and an overview of what Python is. The agenda outlines the goals of making Python ready on attendees' workstations, preparing them for Python 3, providing resources for learning Python 3, and a quiz. Basic topics to be covered include setting up Python, a "Hello world!" example, and doing basic practices with conditionals, loops, files, and networking. Attendees will do an exercise writing their first Python script to make an HTTP request. Study materials are recommended after the workshop.
Evolution and classification of computersAVINASH ANAND
A computer is a general purpose device that can be programmed to carry out arithmetic and logical operations. It consists of at least one processing element and some form of memory. The processing element performs operations and is controlled by a sequencing unit that can change the order of operations based on stored information. Peripheral devices allow information to be retrieved from an external source and results saved. A computer's processing unit executes instructions that make it read, manipulate, and store data, with conditional instructions changing the sequence as a function of the machine's state. Programmers developed user interfaces to accept human input and return results for human consumption.
Python was created in the late 1980s by Guido van Rossum and first released in 1991. It gained popularity and saw new releases in 2000 and 2008. Python is an open source, general purpose, interpreted, object-oriented programming language used widely for web development, science, and more due to its large community and support. Performance depends more on frameworks and architecture than language alone.
Computers can be classified in various ways, including by their operational principle, size and capability, and application. The main types are analog, digital, and hybrid computers. Analog computers use continuously variable aspects like electrical signals to model problems, while digital computers use discrete values (1s and 0s) to perform calculations and logical operations. Hybrid computers integrate aspects of both. Computers can also be classified by size as microcomputers, minicomputers, mainframes, or supercomputers, with each type varying in processing power and use. They are further divided by application into general purpose computers, which can perform many different tasks, and special purpose computers, which are dedicated to a single task.
Open source general-purpose. Multiplatform programming language
Object Oriented, Procedural, Functional
Easy to interface with C/ObjC/Java/Fortran
Easy to interface with C++ (via SWIG)
Great interactive environment
Python 'philosophy' emphasis readability, clarity and simplicity
The Interactive Interpreter
it is very easy to learn and understand.
Python is an open source, multi-paradigm programming language created by Guido van Rossum in 1991. It is high-level, readable, has automatic memory management and a large standard library. Python can be used across many operating systems and for web applications, games, scripting, data science, and more due to its various frameworks and commercial uses. While Python is popular for its readability and ease of use, it does have some disadvantages like being slow for memory intensive tasks.
The document classifies computers based on their function, size, and purpose. Analog computers represent data continuously, digital computers use discrete pulses or bits to represent data, and hybrid computers can process both analog and digital data. General purpose computers can perform a variety of tasks, while special purpose computers are designed for specific applications. Computers are also classified based on their size from largest to smallest as super computers, mainframes, mini computers, microcomputers, desktop computers, and pocket computers. Each type of computer has different features, capabilities, and purposes.
This document provides an overview of a tutorial on mastering Python 3 I/O. The tutorial will cover the reimplemented I/O system in Python 3, including text handling, formatting, binary data handling, the new I/O stack, system interfaces, and library design issues. It assumes some familiarity with how I/O works in Python 2 and will take a detailed tour of the changes in Python 3.
This document provides an agenda and overview for a Python tutorial presented over multiple sessions. The first session introduces Python and demonstrates how to use the Python interpreter. The second session covers basic Python data structures like lists, modules, input/output, and exceptions. An optional third session discusses unit testing. The document explains that Python is an easy to learn yet powerful programming language that supports object-oriented programming and high-level data structures in an interpreted, dynamic environment.
This document provides an overview of key Python concepts:
1. Modules allow organizing Python code into files and namespaces. The file name is the module name with a .py extension.
2. Python code is compiled into bytecode cache files (.pyc) for improved performance. These files are platform independent.
3. Advanced optimizations can be applied to bytecode with command line flags, but may affect program functionality in rare cases.
4. Standard modules provide useful functions like dir() to inspect modules and packages for organizing code. Input/output, strings, files and exceptions are also covered.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and returning values. Strings are sequences of characters that can be manipulated using indexes and methods. Common string methods include upper() and concatenation using +.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then tells the processor to execute the program. Functions allow code to be reused by defining operations that take in arguments and return values. Strings are sequences of characters that can be accessed by index and manipulated with methods like upper() that return new strings.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and returning values. Strings are sequences of characters that can be manipulated using indexes and methods. Common string methods include upper() and concatenation using +.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and returning values. Strings are sequences of characters that can be accessed by index and manipulated with methods like upper() that return new strings.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and returning values. Strings are sequences of characters that can be accessed by index and manipulated with methods like upper() that return new strings.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and returning values. Strings are sequences of characters that can be manipulated using indexes and methods. Common string methods include upper() and concatenation using +.
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.
- The document discusses Python programming concepts such as data types, variables, operators, and syntax. It provides examples of Python code for variables, comments, strings, numbers, and more.
- Python is a popular programming language used for web development, software development, mathematics, and more. It runs on different platforms and has a simple, readable syntax.
- Key features of Python include dynamic typing, automatic memory management, and an intuitive syntax that uses indentation rather than brackets.
This lecture covers functions and modules in Python. It discusses built-in functions, writing user-defined functions, function parameters and return values, and scope. It also discusses modules as a way to organize Python code and introduces some of Python's standard library modules like math and random. The key points are:
1) Functions allow for code reuse and abstraction by encapsulating repeatable processes. Built-in functions perform common tasks while user-defined functions can be created for custom tasks.
2) Functions are defined using def and have parameters to pass in inputs and return values to produce outputs. Variables inside functions have local scope while global variables can be accessed everywhere.
3) Modules help structure Python programs and provide
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language.
Make use of the PPT to have a better understanding of Python.
This document contains notes from a Python class covering functions, lists, strings, and their methods. It discusses built-in functions like len(), range(), and type conversions. It also covers control flow structures like if/else, for loops, exceptions, modules, and functions in more detail including defining functions, parameters, arguments, returning values, docstring, and variable scopes. Assignments include writing functions to process lists and check for palindromes in strings.
This document is a Python cheat sheet created by Mosh Hamedani to summarize the core concepts covered in his Python tutorial. It includes sections on variables, data types, operators, control flow, functions, classes, modules and the standard library. The author encourages readers to enroll in his Complete Python Programming Course if they want to become a Python expert.
This document provides an introduction to the Semantic Web and the technologies that enable it. It defines key concepts like resources, URIs, RDF, RDF Schema (RDFS), and the Web Ontology Language (OWL). It explains how these technologies allow data on the web to be represented and linked in a standardized, machine-readable way. Examples are provided to illustrate how RDF and OWL can be used to represent relationships between resources like books and authors. The document discusses how semantic technologies can help integrate and combine data from diverse sources on the web.
Build an application upon Semantic Web models. Brief overview of Apache Jena and OWL-API.
Semantic Web course
e-Lite group (https://elite.polito.it)
Politecnico di Torino, 2017
A guide and a process for creating OWL ontologies.
Semantic Web course
e-Lite group (https://elite.polito.it)
Politecnico di Torino, 2017
How to create a simple Telegram bot with Python 3.x.
Ambient Intelligence
http://bit.ly/polito-ami
Politecnico di Torino, 2017
AngularJS is a JavaScript framework for building frontend web applications. It is inspired by Model-View-Controller (MVC) pattern and uses HTML templating with two-way data binding. Key features include DOM manipulation, validation, routing, and reusable components. The document provides an overview of AngularJS concepts like directives, data binding, controllers, modules, dependency injection, and built-in services. It also demonstrates how to create custom directives and use routing and resources services.
The document provides an overview of ambient intelligence (AmI) and discusses related technology trends. It defines AmI as sensitive, intelligent, responsive, adaptive, ubiquitous and transparent systems that are able to sense and understand their environment in order to respond to the needs of people in an unobtrusive way. The document outlines some of the main research areas in AmI, including smart homes and notifications, and provides examples of university projects developing AmI technologies and applications.
PowerOnt: an ontology-based approach for power consumption estimation in Smar...Luigi De Russis
Presentation given at the 1st Cognitive Internet of Things Technologies (COIOTE 2014)
October 27, 2014, Rome, Italy
The paper is available on the PORTO open access repositor of Politecnico di Torino: http://porto.polito.it/2570936/
Interacting with Smart Environments - Ph.D. Thesis PresentationLuigi De Russis
This thesis explores approaches to improve interaction between users and smart environments. It presents several contributions that address challenges in key interaction areas and provide tools and applications loosely coupled with underlying intelligent systems. The contributions are validated through user testing and publications, and address challenges like eye-based interaction, interaction with ubiquitous devices, visual programming for end-users, and incentivizing energy consumption behaviors. Future work is proposed in areas like on-body interaction and using existing sensing and actuating devices in environments.
Living in Smart Environments - 3rd year PhD ReportLuigi De Russis
Luigi De Russis' third year evaluation summarizes his work on several projects related to interfaces, interaction and usability in smart environments. These include Applus.energie and Applus.climatique systems for monitoring energy consumption in buildings; the dWatch wearable notification device; and the GrAAL project to assist healthcare workers through ambient assisted living technologies. He also contributed to the open source Dog gateway platform and conducted user studies on visualizing energy data and controlling smart home devices through gaze interaction.
Short seminar about the Semantic Web for the "Artificial Intelligence" course at Politecnico di Torino (academic year 2012/2013)
An updated version is available at http://www.slideshare.net/luigidr/semantic-web-an-introduction
An overview on social network technologies: are they "typical" website? Or do they work in a different way? How many and what technologies do Facebook and Instagram use?
Presentation made for the Multimedia Languages and Environments course at Politecnico di Torino (academic year 2013/2014).
A brief overview about writing clean code. Presentation made for the Multimedia Languages and Environments course at Politecnico di Torino (academic year 2012/2013).
Living in Smart Environments - 2nd year PhD ReportLuigi De Russis
This document summarizes Luigi De Russis's research activities related to human-computer interaction in ambient intelligence environments. His main research focuses on gaze interaction, developing interfaces to incentivize energy efficient behavior, and rule-based activity delegation. Some of his other projects involve a wearable notification device called dWatch, a speech-driven home interface for people with disabilities, and frameworks for processing sensor data streams. He supervises several student projects and has published papers in relevant journals and conferences. Future work will include completing ongoing projects and evaluating interfaces in a living lab environment.
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingCeline George
The Accounting module in Odoo 17 is a complete tool designed to manage all financial aspects of a business. Odoo offers a comprehensive set of tools for generating financial and tax reports, which are crucial for managing a company's finances and ensuring compliance with tax regulations.
The *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responThe *nervous system of insects* is a complex network of nerve cells (neurons) and supporting cells that process and transmit information. Here's an overview:
Structure
1. *Brain*: The insect brain is a complex structure that processes sensory information, controls behavior, and integrates information.
2. *Ventral nerve cord*: A chain of ganglia (nerve clusters) that runs along the insect's body, controlling movement and sensory processing.
3. *Peripheral nervous system*: Nerves that connect the central nervous system to sensory organs and muscles.
Functions
1. *Sensory processing*: Insects can detect and respond to various stimuli, such as light, sound, touch, taste, and smell.
2. *Motor control*: The nervous system controls movement, including walking, flying, and feeding.
3. *Behavioral responses*: Insects can exhibit complex behaviors, such as mating, foraging, and social interactions.
Characteristics
1. *Decentralized*: Insect nervous systems have some autonomy in different body parts.
2. *Specialized*: Different parts of the nervous system are specialized for specific functions.
3. *Efficient*: Insect nervous systems are highly efficient, allowing for rapid processing and response to stimuli.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive in diverse environments.
The insect nervous system is a remarkable example of evolutionary adaptation, enabling insects to thrive
A measles outbreak originating in West Texas has been linked to confirmed cases in New Mexico, with additional cases reported in Oklahoma and Kansas. The current case count is 795 from Texas, New Mexico, Oklahoma, and Kansas. 95 individuals have required hospitalization, and 3 deaths, 2 children in Texas and one adult in New Mexico. These fatalities mark the first measles-related deaths in the United States since 2015 and the first pediatric measles death since 2003.
The YSPH Virtual Medical Operations Center Briefs (VMOC) were created as a service-learning project by faculty and graduate students at the Yale School of Public Health in response to the 2010 Haiti Earthquake. Each year, the VMOC Briefs are produced by students enrolled in Environmental Health Science Course 581 - Public Health Emergencies: Disaster Planning and Response. These briefs compile diverse information sources – including status reports, maps, news articles, and web content– into a single, easily digestible document that can be widely shared and used interactively. Key features of this report include:
- Comprehensive Overview: Provides situation updates, maps, relevant news, and web resources.
- Accessibility: Designed for easy reading, wide distribution, and interactive use.
- Collaboration: The “unlocked" format enables other responders to share, copy, and adapt seamlessly. The students learn by doing, quickly discovering how and where to find critical information and presenting it in an easily understood manner.
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetSritoma Majumder
Introduction
All the materials around us are made up of elements. These elements can be broadly divided into two major groups:
Metals
Non-Metals
Each group has its own unique physical and chemical properties. Let's understand them one by one.
Physical Properties
1. Appearance
Metals: Shiny (lustrous). Example: gold, silver, copper.
Non-metals: Dull appearance (except iodine, which is shiny).
2. Hardness
Metals: Generally hard. Example: iron.
Non-metals: Usually soft (except diamond, a form of carbon, which is very hard).
3. State
Metals: Mostly solids at room temperature (except mercury, which is a liquid).
Non-metals: Can be solids, liquids, or gases. Example: oxygen (gas), bromine (liquid), sulphur (solid).
4. Malleability
Metals: Can be hammered into thin sheets (malleable).
Non-metals: Not malleable. They break when hammered (brittle).
5. Ductility
Metals: Can be drawn into wires (ductile).
Non-metals: Not ductile.
6. Conductivity
Metals: Good conductors of heat and electricity.
Non-metals: Poor conductors (except graphite, which is a good conductor).
7. Sonorous Nature
Metals: Produce a ringing sound when struck.
Non-metals: Do not produce sound.
Chemical Properties
1. Reaction with Oxygen
Metals react with oxygen to form metal oxides.
These metal oxides are usually basic.
Non-metals react with oxygen to form non-metallic oxides.
These oxides are usually acidic.
2. Reaction with Water
Metals:
Some react vigorously (e.g., sodium).
Some react slowly (e.g., iron).
Some do not react at all (e.g., gold, silver).
Non-metals: Generally do not react with water.
3. Reaction with Acids
Metals react with acids to produce salt and hydrogen gas.
Non-metals: Do not react with acids.
4. Reaction with Bases
Some non-metals react with bases to form salts, but this is rare.
Metals generally do not react with bases directly (except amphoteric metals like aluminum and zinc).
Displacement Reaction
More reactive metals can displace less reactive metals from their salt solutions.
Uses of Metals
Iron: Making machines, tools, and buildings.
Aluminum: Used in aircraft, utensils.
Copper: Electrical wires.
Gold and Silver: Jewelry.
Zinc: Coating iron to prevent rusting (galvanization).
Uses of Non-Metals
Oxygen: Breathing.
Nitrogen: Fertilizers.
Chlorine: Water purification.
Carbon: Fuel (coal), steel-making (coke).
Iodine: Medicines.
Alloys
An alloy is a mixture of metals or a metal with a non-metal.
Alloys have improved properties like strength, resistance to rusting.
A measles outbreak originating in West Texas has been linked to confirmed cases in New Mexico, with additional cases reported in Oklahoma and Kansas. The current case count is 817 from Texas, New Mexico, Oklahoma, and Kansas. 97 individuals have required hospitalization, and 3 deaths, 2 children in Texas and one adult in New Mexico. These fatalities mark the first measles-related deaths in the United States since 2015 and the first pediatric measles death since 2003.
The YSPH Virtual Medical Operations Center Briefs (VMOC) were created as a service-learning project by faculty and graduate students at the Yale School of Public Health in response to the 2010 Haiti Earthquake. Each year, the VMOC Briefs are produced by students enrolled in Environmental Health Science Course 581 - Public Health Emergencies: Disaster Planning and Response. These briefs compile diverse information sources – including status reports, maps, news articles, and web content– into a single, easily digestible document that can be widely shared and used interactively. Key features of this report include:
- Comprehensive Overview: Provides situation updates, maps, relevant news, and web resources.
- Accessibility: Designed for easy reading, wide distribution, and interactive use.
- Collaboration: The “unlocked" format enables other responders to share, copy, and adapt seamlessly. The students learn by doing, quickly discovering how and where to find critical information and presenting it in an easily understood manner.
CURRENT CASE COUNT: 817 (As of 05/3/2025)
• Texas: 688 (+20)(62% of these cases are in Gaines County).
• New Mexico: 67 (+1 )(92.4% of the cases are from Eddy County)
• Oklahoma: 16 (+1)
• Kansas: 46 (32% of the cases are from Gray County)
HOSPITALIZATIONS: 97 (+2)
• Texas: 89 (+2) - This is 13.02% of all TX cases.
• New Mexico: 7 - This is 10.6% of all NM cases.
• Kansas: 1 - This is 2.7% of all KS cases.
DEATHS: 3
• Texas: 2 – This is 0.31% of all cases
• New Mexico: 1 – This is 1.54% of all cases
US NATIONAL CASE COUNT: 967 (Confirmed and suspected):
INTERNATIONAL SPREAD (As of 4/2/2025)
• Mexico – 865 (+58)
‒Chihuahua, Mexico: 844 (+58) cases, 3 hospitalizations, 1 fatality
• Canada: 1531 (+270) (This reflects Ontario's Outbreak, which began 11/24)
‒Ontario, Canada – 1243 (+223) cases, 84 hospitalizations.
• Europe: 6,814
*Metamorphosis* is a biological process where an animal undergoes a dramatic transformation from a juvenile or larval stage to a adult stage, often involving significant changes in form and structure. This process is commonly seen in insects, amphibians, and some other animals.
Understanding P–N Junction Semiconductors: A Beginner’s GuideGS Virdi
Dive into the fundamentals of P–N junctions, the heart of every diode and semiconductor device. In this concise presentation, Dr. G.S. Virdi (Former Chief Scientist, CSIR-CEERI Pilani) covers:
What Is a P–N Junction? Learn how P-type and N-type materials join to create a diode.
Depletion Region & Biasing: See how forward and reverse bias shape the voltage–current behavior.
V–I Characteristics: Understand the curve that defines diode operation.
Real-World Uses: Discover common applications in rectifiers, signal clipping, and more.
Ideal for electronics students, hobbyists, and engineers seeking a clear, practical introduction to P–N junction semiconductors.
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsesushreesangita003
what is pulse ?
Purpose
physiology and Regulation of pulse
Characteristics of pulse
factors affecting pulse
Sites of pulse
Alteration of pulse
for BSC Nursing 1st semester
for Gnm Nursing 1st year
Students .
vitalsign
2. Editing / Formatting
• Python programs are
text files
• The end of a line
marks the end of a
statement
• Comments:
– Inline comments start
with a #
3/12/2015 Python basics 2
print 1+1 #statement
# inline comment
3. Editing / Formatting
• Code blocks are
defined through
identation
– mandatory
– 4 spaces strategy
• Use 4 spaces for code
identation
• Configure the text
editor to replace tabs
with 4 spaces (default
in PyDev)
• Exploit automatic
identation
3/12/2015 Python basics 3
def print_name():
# this is a block
name = 'sheldon'
surname = 'cooper'
print name, surname
4 spaces
4 spaces
4 spaces
4 spaces
4. Keywords
• and
• del
• from
• not
• while
• as
• elif
• global
• or
• with
• assert
• else
• if
• pass
• yield
• break
• except
• import
• print
• class
• exec
3/12/2015 Python basics 4
• in
• raise
• continue
• finally
• is
• return
• def
• for
• lambda
• try
5. Numbers and math
3/12/2015 Python basics 5
Operator Description
+ plus Sum
- minus Subtraction
/ slash Floor division
* asterisk Multiplication
** double asterisk Exponentiation
% percent Remainder
< less-than Comparison
> greater-than Comparison
<= less-than-equal Comparison
>= greater-than-equal Comparison
6. Numbers and math
3/12/2015 Python basics 6
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
7. Order of operations
• PEMDAS
– Parenthesis
– Exponentiation
– Multiplication
– Division
– Addition
– Subtraction
• Same precedence
– Left to right execution
3/12/2015 Python basics 7
8. Naming conventions
• joined_lower
– for functions,
variables, attributes
• joined_lower or
ALL_CAPS
– for constants
• StudlyCaps
– for classes
3/12/2015 Python basics 8
#variables
my_variable = 12
my_second_variable = 'Hello!'
#functions
my_function(my_variable)
my_print(my_second_variable)
9. Variables
• Variable types are not
explicitly declared
• Runtime type-checking
• The same variable can
be reused for holding
different data types
3/12/2015 Python basics 9
#integer variable
a = 1
print a
#float variable
a = 2.345
print a
#re-assignment to string
a = 'my name'
print a
# double quotes could be
# used as well
a = "my name"
print a
10. More variables
• Actual type can be
checked through the
interpreter
• Check the first result,
what happened?
• Display 01,010,01010
• Display 08
• Octal numbering system?
3/12/2015 Python basics 10
12. Strings
• Defined by using quotes
– "first string"
– 'second string'
• Immutable
• Each character in a string is assigned a number
– the number is called index
• Mathematical operators cannot be applied
• Exceptions
– + : means concatenation
– * : means repetition
3/12/2015 Python basics 12
13. Strings
3/12/2015 Python basics 13
name = 'Anthony "Tony" Stark'
age = 45 # not a lie
height = 174 # cm
weight = 78 # kg
eyes = 'brown'
teeth = 'white'
hair = 'brown'
print "Let's talk about %s." % name
print "He's %d cm tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
14. Strings
3/12/2015 Python basics 14
name = 'Anthony "Tony" Stark'
age = 45 # not a lie
height = 174 # cm
weight = 78 # kg
eyes = 'brown'
teeth = 'white'
hair = 'brown'
print "Let's talk about %s." % name
print "He's %d cm tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
Specifiers
• %s, format strings
• %d, format numbers
• %r, raw representation
Tuple
15. More strings
3/12/2015 Python basics 15
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e
16. Escape sequences
• n
– Line feed + Carriage return
•
– Prints a «»
• We want to print «Hello»
– print "I said: "Hello" "
– Syntax error: no difference between quotes
• Solution: using escape sequences
– print "I said: “Hello" "
3/12/2015 Python basics 16
17. Getting input from people
• Asking questions
– We want to ask the user’s age
– We want to ask the user’s height
• The raw_input()function allows to read from
the console
3/12/2015 Python basics 17
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "You are %s years old, and you are about %s cm tall." % (age, height)
18. More input
3/12/2015 Python basics 18
height = int(raw_input("How tall are you? "))
name = raw_input("What's your name? ")
print type(height)
print type(name)
print("Hello %s, you are about %d tall" %(name, height) )
19. Command-line parameters
• Python scripts can receive launch parameters
– Placed just after the script name
– Any number
– Accessible through sys.argv
• sys
– Python module to handle system-level operations
• argv
– Argument variable
– for handling command-line parameters
3/12/2015 Python basics 19
20. Command-line parameters
3/12/2015 Python basics 20
from sys import argv
script, first, second, third = argv
print 'The script is called:', script
print 'Your first variable is:', first
print 'Your second variable is:', second
print 'Your third variable is:', third
21. Functions
• A function is a named sequence of statements
that performs a computation
– Definition first:
• specify the name and the sequence of statements
– Then usage:
• “call” the function by name
• Examples
– Type conversion functions
• int(‘32’) 32
• str(3.2479) ‘3.2479’
3/12/2015 Python basics 21
22. Math functions
• Located in the math module
3/12/2015 Python basics 22
import math
signal_power = 10.0
noise_power = 0.01
ratio = signal_power / noise_power
print "ratio:", ratio
decibels = 10 * math.log10(ratio)
print "decibels:", decibels
radians = 0.7
height = math.sin(radians)
print height
Function call
23. String functions
• len()
– Gets the length (the number of characters) of a
string
• lower()
– Gets rid of all the capitalization in a string
• upper()
– Transform a string in upper case
• str()
– Transform «everything» in a string
3/12/2015 Python basics 23
24. String functions: an example
3/12/2015 Python basics 24
course_name = 'Ambient Intelligence'
string_len = len(course_name)
print string_len # 20
print course_name.lower() # ambient intelligence
print course_name.upper() # AMBIENT INTELLIGENCE
pi = 3.14
print "the value of pi is around " + str(pi) without str()
it gives an error
25. New functions
• Can be defined by developers
• Typically used to group homogeneous code
portions
– i.e., code for accomplishing a well-defined operation
• Enable re-use
– Same operation can be re-used several times
• Defined using the keyword def
3/12/2015 Python basics 25
26. New functions
3/12/2015 Python basics 26
• Compute the area of a disk, given the radius
import math
def circle_area(radius):
return radius**2*math.pi
radius = raw_input('Please, insert the radiusn')
print 'Radius: ', radius
print 'Area: ', circle_area(radius) Function call
Function definition
27. Docstring
• Optional, multiline comment
• Explains what the function does
• Starts and ends with """ or '''
3/12/2015 Python basics 27
import math
def circle_area(radius):
'''Compute the circle area given its radius'''
return radius**2*math.pi
radius = raw_input('Please, insert the radiusn')
print 'Radius: ', radius
print 'Area: ', circle_area(radius)
28. Modules
• A way to logically organize the code
• They are files consisting of Python code
– they can define (and implement) functions, variables,
etc.
– typically, the file containing a module is called in the
same way
• e.g., the module math resides in a file named math.py
• We already met them
3/12/2015 Python basics 28
import math
from sys import argv
29. Importing modules
• import module_name
– allows to use all the items present in a module
3/12/2015 Python basics 29
import math
def circle_area(radius):
return radius**2*math.pi
…
Import the math module
Call the pi variable from
the math module
30. Importing modules
• from module_name import name
– it only imports name from the specified module
• from module_name import *
– it imports all names from a module
– do not use!
3/12/2015 Python basics 30
from math import pi
def circle_area(radius):
return radius**2*pi
…
Import pi from the math module
Use the pi variable
31. Playing with files
• Python script can read and write files
• First, open a file
– You can use the open() function
• Then, you can read or write it
– With read(), readline(), or write()
• Finally, remember to close the file
– You can use the close() function
3/12/2015 Python basics 31
32. Reading files
• Read a file taking its name from command line
3/12/2015 Python basics 32
from sys import argv
filename = argv[1]
txt = open(filename)
print “Here’s your file %r:", % filename
print txt.read()
print “nType the filename again:”
file_again = raw_input(“> ”)
txt_again = open(file_again)
print txt_again.read()
Open the file
Show the file content
33. Writing files
3/12/2015 Python basics 33
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "Opening the file..."
target = open(filename, 'w')
print "… truncating the file. Goodbye!"
target.truncate()
print "nNow I'm going to ask you for two lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("n")
target.write(line2)
target.write("n")
print "And finally, we close it."
target.close()
Open the file in write mode
Empties the file
Write a string to the file
34. Conditionals and control flow
• Control flow gives the ability to choose among
outcomes
– based off what else is happening in the program
• Comparators
– Equal to ==
– Not equal to !=
– Less than <
– Less than or equal to <=
– Greater than >
– Greater than or equal to >=
3/12/2015 Python basics 34
36. Boolean operators
• They are three:
– not
– and
– or
• Not evaluated from left to right
– not is evaluated first
– and is evaluated next
– or is evaluated last
3/12/2015 Python basics 36
37. Boolean operators: an example
3/12/2015 Python basics 37
print 2 == 1 and True # False
print 2 == 2 or True # True
print 10 >= 2 and 2 != 1 # True
print not True # False
print 10 > 5 and 10 == 10 or 5 < 2 # True
print not False and True # True
38. Conditional statement
• if is a statements that executes some code
after checking if a given expression is True
• Structure
if expression:
do something
3/12/2015 Python basics 38
people = 20
cats = 30
if people < cats:
print 'Too many cats! The world
is doomed!'
if people > cats:
print 'Not many cats! The world
is saved!'
39. More “if”
• Let’s try to “improve” the previous example
• Chained conditionals
– To express more than two possibilities
– Each condition is checked in order
3/12/2015 Python basics 39
people = 20
cats = 30
if people < cats:
print 'Too many cats! The world is doomed!'
elif people > cats:
print 'Not many cats! The world is saved!'
else:
print "We can’t decide.”
else if
40. Loops and lists
• Loop
– An easy way to do repetitive things
– A condition to start and stop the loop is required
– e.g., for and while loops
• List
– A datatype for storing multiple items
• a sequence of values
– You can assign items to a list in this way:
list_name = [item1, item2, …]
3/12/2015 Python basics 40
41. Loops and lists: an example
3/12/2015 Python basics 41
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print 'This is count %d' % number
# same as above
for fruit in fruits:
print 'A fruit of type: %s' % fruit
# we can go through mixed lists too
# notice that we have to use %r since we don't know what's in it
for i in change:
print 'I got %r' % i
Three lists
42. Loops and lists: an example
3/12/2015 Python basics 42
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print 'This is count %d' % number
# same as above
for fruit in fruits:
print 'A fruit of type: %s' % fruit
# we can go through mixed lists too
# notice that we have to use %r since we don't know what's in it
for i in change:
print 'I got %r' % i
Structure of a for loop
• for variable in collection:
• indent for the loop body
43. More “for”
3/12/2015 Python basics 43
# we can also build lists: start with an empty one…
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print 'Adding %d to the list.' % i
# append() is a function that lists understand
elements.append(i)
# now we can print them out
for i in elements:
print 'Element was: %d' % i
Empty list
Repeat 6 times
44. Lists
• Mutable
• Do not have a fixed length
– You can add items to a list at any time
• Accessible by index
3/12/2015 Python basics 44
letters = [‘a’, ‘b’, ‘c’]
letters.append(‘d’)
print letters # a, b, c, d
print letters[0] # a
print len(letters) # 4
letters[3] = ‘e’
print letters # a, b, c, e
45. More lists
• List concatenation
– with the + operator
• List slices
– to access a portion of a list
– with the [:] operator
3/12/2015 Python basics 45
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print c # 1, 2, 3, 4, 5, 6
c = [1, 2, 3, 4, 5, 6]
d = c[1:3] # d is [2, 3]
e = c[:3] # e is [1, 2, 3]
f = c[:] # f is a full copy of c
46. More lists
• List concatenation
– with the + operator
• List slices
– to access a portion of a list
– with the [:] operator
3/12/2015 Python basics 46
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print c # 1, 2, 3, 4, 5, 6
c = [1, 2, 3, 4, 5, 6]
d = c[1:3] # d is [2, 3]
e = c[:3] # e is [1, 2, 3]
f = c[:] # f is a full copy of c
works with string, too
47. List functions
• append()
– add a new element to the end of a list
– e.g., my_list.append(‘d’)
• sort()
– arrange the elements of the list from low to high
– e.g., from a to z, from 1 to infinite, etc.
• extend()
– takes a list as an argument and appends all its
elements
– e.g., first_list.extend(second_list)
3/12/2015 Python basics 47
48. Deleting elements from a list
• Several ways to delete elements from a list
• If you know the index of the element to
remove: pop()
– without providing an index, pop() delete the last
element
• If you know the element to remove (but not the
index): remove()
• To remove more than one element: del()
– with a slice index
• e.g., del my_list[5:8]
3/12/2015 Python basics 48
49. Strings vs. lists
• A string is a sequence of character, but a list of
character is not a string
• To convert a string into a list of characters: list()
– e.g., my_list = list(my_string)
• To break a string into separate words: split()
– split a list according to some delimiters (default:
space)
– e.g., my_list = my_string.split()
– The inverse function is join()
3/12/2015 Python basics 49
50. Copying lists
• What happens here?
3/12/2015 Python basics 50
fruits = ['apple', 'orange', 'pear', 'apricot']
print 'The fruits are:', fruits
favourite_fruits = fruits
print 'My favourite fruits are', favourite_fruits
# add a fruit to the original list
fruits.append(‘banana’)
print 'The fruits now are:', fruits
print 'My favourite fruits are', favourite_fruits
51. Copying lists
• What happens here?
3/12/2015 Python basics 51
fruits = ['apple', 'orange', 'pear', 'apricot']
print 'The fruits are:', fruits
favourite_fruits = fruits
print 'My favourite fruits are', favourite_fruits
# add a fruit to the original list
fruits.append(‘banana’)
print 'The fruits now are:', fruits
print 'My favourite fruits are', favourite_fruits
We do not make a copy of
the entire list, but we only
make a reference to it!
52. Copying lists
• How to make a full copy of a list?
• Various methods exist
– you can entirely slice a list
• favourite_fruits = fruits[:]
– you can create a new list from the existing one
• favourite_fruits = list(fruit)
– you can extend an empty list with the existing one
• favourite_fruits.extend(fruit)
• Prefer the list() method, when possible!
3/12/2015 Python basics 52
53. Dictionaries
• Similar to lists, but you can access values by
looking up a key instead of an index
– A key can be a string or a number
• Example
– A dictionary with 3 key-value pairs
dict = { ‘key1’ : 1, ‘key2’ : 2, ‘key3’ : 3 }
• Mutable, like lists
– They can be changed after their creation
3/12/2015 Python basics 53
54. Dictionaries: an example
3/12/2015 Python basics 54
# create a mapping of U.S. state to abbreviation
states = {
'Oregon' : 'OR',
'Florida' : 'FL',
'California' : 'CA'
}
print 'States:', states
print 'Is Oregon available?', 'Oregon' in states
# add some more states
states['New York'] = 'NY'
states['Michigan'] = 'MI'
# print two states
print "New York’s abbreviation is: ", states[‘New York’]
print "Florida’s abbreviation is: ", states[‘Florida’]
Create a dictionary with 3 key-value pairs
Add two more key-value pairs
55. More dictionaries
3/12/2015 Python basics 55
# states is a dictionary defined as before
# print every state abbreviation
for state, abbrev in states.items():
print "%s is abbreviated %s", % (state, abbrev)
# safely get an abbreviation of a state that might not be there
state = states.get('Texas', None) # None is the default
if not state:
print "Sorry, no Texas."
# get a state abbreviation with a default value
next_state = states.get('Massachusetts', 'Does Not Exist')
print "Massachusetts is abbreviated %s", % next_state
56. Dictionary functions
• len()
– dictionary length: the number of key-value pairs
• del()
– remove a key-value pair
• e.g., del my_dict[my_key]
• clear()
– remove all items from a dictionary
• keys() and values()
– return a copy of the dictionary’s list of key and value,
respectively
3/12/2015 Python basics 56
57. References and Links
• The Python Tutorial,
http://docs.python.org/2/tutorial/
• «Think Python: How to think like a computer
scientist», Allen Downey, Green Tea Press,
Needham, Massachusetts
• «Dive into Python 2», Mark Pilgrim
• «Learn Python the Hard Way», Zed Shaw
• «Learning Python» (5th edition), Mark Lutz, O'Reilly
• The Google Python course,
https://developer.google.com/edu/python
• Online Python Tutor, http://pythontutor.com
3/12/2015 Python basics 57
59. License
• This work is licensed under the Creative Commons “Attribution-
NonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0)” License.
• You are free:
– to Share - to copy, distribute and transmit the work
– to Remix - to adapt the work
• Under the following conditions:
– Attribution - You must attribute the work in the manner specified by the
author or licensor (but not in any way that suggests that they endorse you
or your use of the work).
– Noncommercial - You may not use this work for commercial purposes.
– Share Alike - If you alter, transform, or build upon this work, you may
distribute the resulting work only under the same or similar license to this
one.
• To view a copy of this license, visit
http://creativecommons.org/license/by-nc-sa/3.0/
3/12/2015 Version Control with Git 59