I have prepared this document during my Python course from sololearn "Learn Python" course. This document contains fundamentals of python. Aimed for python beginners.
This document provides an overview, prerequisites, and table of contents for a tutorial on learning the Python programming language from scratch. It is designed for software programmers who want to learn Python. The tutorial will cover Python's history and features, setting up a local environment to run Python, basic syntax like variables, data types, operators, and decision making statements. It will also discuss how to get and install Python, set environment paths, run Python programs, and handle command line arguments. The content is copyrighted and users are prohibited from redistributing it without permission.
The document provides an overview of the Python programming language. It discusses Python's history, features, and environment setup. Python is an interpreted, interactive, object-oriented programming language created by Guido van Rossum in 1991. It includes high-level data structures, supports OOP and functional programming, and has a large standard library. The document also covers installing Python, running Python programs, basic syntax, variables, operators, and data types.
This document provides an overview and tutorial on the Python programming language. It discusses Python's history and features, how to set up the Python environment and get started with the language. It then covers Python's basic syntax, variable types, operators, and decision-making constructs like if/else statements. The tutorial is designed for beginners to help them learn Python programming from scratch.
This is a presentation which is an introduction to python language.
The presentation is contributed by me for educational purpose and this presentation is
Only introduction.
The Basic python data types and how to use python for Data Science,
NumPy is a library for working with multidimensional arrays and matrices in Python. It allows mathematical and logical operations on arrays to be performed. This tutorial explains the basics of NumPy, including its architecture, data types, array attributes, array creation, indexing and slicing, broadcasting, and array manipulation functions. The audience is those looking to learn the basics of NumPy, which is useful for algorithm developers. A basic understanding of Python is recommended.
The document acknowledges and thanks several people for their help and guidance in preparing the report. It thanks the professor and seminar for providing background information and inspiration for the topic. It also thanks the author's parents for financially supporting their studies and encouraging them to learn engineering.
This document provides a summary of a summer training report on Python and its libraries. It acknowledges those who provided guidance and support. It includes an introduction to the training institute, a table of contents outlining 6 chapters, and an introduction to the history and development of Python. It discusses Python's design as a scripting language and its use of object-oriented programming.
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Edureka!
( Python Training : https://www.edureka.co/python )
This Edureka “Python Programming" introduces you to Python by giving you enough reasons to learn it. It will then take you to its various fundamentals along with a practical demonstrating the various libraries such as Numpy, Pandas, Matplotlib and Seaborn. This video helps you to learn the below topics:
1. Why should you go for Python?
2. Introduction to Python Programming Language
3. How to work with Jupyter?
4. Python Programming Fundamentals: Operators & Data Types
5. Libraries: Numpy, Pandas, Matplotlib, Seaborn
Python programming | Fundamentals of Python programming KrishnaMildain
Basic Fundamentals of Python Programming.
What is Python, History of python, Advantages, Disadvantages, feature of python, scope, and many more.
Data Structure using Python, Object Oriented Programming using
Pandas is an open-source Python library that provides data structures and data analysis tools. It allows users to load, clean, manipulate, and visualize data in an efficient way. Pandas contains powerful data structures like Series (1D), DataFrame (2D), and Panel (3D). DataFrame is the most commonly used data structure, as it represents data as columns and rows like a spreadsheet or SQL table. Pandas enables fast and easy data analysis and is widely used in domains like finance, economics, and analytics.
Python is a high-level, interpreted programming language created by Guido van Rossum in 1991. It has gained popularity due to its clear syntax and readability. Companies prefer Python because it is easy to use, free and open-source, and has a large standard library. It can be used for a variety of tasks including web development, data analysis, and scientific computing.
This document describes building a basic calculator program in Python. It takes user input to select an arithmetic operation (add, subtract, multiply, divide) and two numbers. If/elif/else statements direct the program to call functions to perform the selected operation and display the result. While basic, this provides a starting point to create a more advanced calculator with additional features.
This document provides an introduction to the Python programming language. It discusses that Python is an interpreted, interactive, object-oriented scripting language that is designed to be highly readable. The document outlines Python's history and key features, including being easy to learn and use, having a broad standard library, and being portable. It also discusses popular implementations of Python like CPython and how organizations like Google, Yahoo, and NASA use Python for applications such as bioinformatics, simulations, games, and networking.
The document discusses the benefits and advantages of the Python programming language. Python is described as a high-level, easy to use language that can be used for general programming as well as mobile and web development. It has many advantages, such as being easy to learn and use, having a large standard library, and being cross-platform. Some disadvantages are that it requires more memory than languages like C/C++ and has limited database access.
This document provides an introduction to Python programming, including:
- Python was created in 1991 by Guido van Rossum as an interpreted and general-purpose programming language.
- It focuses on code readability and allows programmers to do coding in fewer steps than languages like Java or C++.
- Popular uses of Python include backend web development, data analysis, artificial intelligence, and scientific computing.
- Key advantages that make Python popular include being easy to learn and use, having a large standard library, and supporting multiple programming paradigms.
This document provides an overview of the Python programming language. It discusses Python's history, key features such as being easy to use, scalable, high-level, object-oriented, interpreted, and having a rich core library. It also covers Python's uses in areas like web development, databases, GUI programming, and more. The document is intended to introduce readers to Python and provide context for a book on making use of the language.
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on Python Tutorial covers all the basic knowledge of statistics and probability for Python.
Why Python for Statistics?
What is Probability?
Data and Distribution
Revisiting the Normal
Poker Prediction Use-Case
Check out our Python Tutorial Playlist: https://goo.gl/WsBpKe
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The document outlines the syllabus for a Python course, including introductions to data warehousing, Python itself, different modes in Python like file extensions and IDEs, data structures like sets and dictionaries, OS and exception handling modules, advanced topics like iterators and decorators, XML and multi-threading, web scraping, sequences and collections, lists and tuples, modules and packages, file handling, classes and objects, regular expressions, unit testing, web frameworks like Django, and GUI programming with Tkinter. The syllabus is designed to meet corporate requirements and covers many fundamental and advanced Python topics.
This document is a summer training report submitted by Manish Raghav to fulfill the requirements for a B.Tech degree in computer science engineering from K.R. Mangalam University. The report details a summer training completed at Ducat India Pvt Ltd where the student implemented object tracking using Python. The report includes an introduction to Python, NumPy and OpenCV libraries used for the project. It describes two object tracking methods - absolute difference method and Haar cascade classifier. Screenshots show objects like a phone and pen being tracked.
PYTHON CURRENT TREND APPLICATIONS- AN OVERVIEWEditorIJAERD
Python is a powerful high-level, interpreted, interactive, and object-oriented scripting language created by
Guido Van Rossum in late 1980’s. Python is a very suitable language for the beginner level programmers and supports
the development of a wide range of applications from simple text processing to www browsers to games developments.
One of the biggest reasons for Python’s rapid growth is the simplicity of its syntax. The language reads almost like plain
English, making it easy to write complex programs. In this paper we first analyze you to Python programming language
popularity and features. Moreover, this paper specifying applications areas where python can be applied and specially
analyzing web application frameworks which are using in Python programming language
Python, the Language of Science and Engineering for EngineersBoey Pak Cheong
A talk given in November 2016 at IEM Malaysia to engineers, who are new to Python, a broad perspective of what Python is, why it is important to learn it and how it can help in solving/visualization of engineering and scientific tasks and problems.
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...Edureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka tutorial on Installing Python on Windows Tutorial covers all the aspects of installing and setting up Python to write code in. It is pretty simple and straightforward to setup Python completely in Windows as shown.
Following topics are covered in this PPT:
Agenda
Introduction to Python
Popularity of Python
Why should you learn Python?
Installing Python
Python Development Environments
Conclusion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Instagram: https://www.instagram.com/edureka_lea...
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
This document provides an introduction to the Python programming language. It begins with an overview of Python's history and development timeline. It then discusses Python's key features such as being high-level, interpreted, object-oriented, and having extensive libraries. The document outlines Python's main programming paradigms and discusses its growing popularity. It provides details on getting started with Python, different integrated development environments (IDEs), and Python basics like variables, data types, operators, and input/output. The document also covers Python syntax and structures such as control flow, functions, classes, and exceptions handling.
This document provides an overview of the Python programming language. It discusses Python's history, features, and environment setup. Python is an interpreted, interactive, object-oriented programming language created by Guido van Rossum in 1991. It includes high-level data structures, supports object-oriented programming, and is extensible via modules. The document also covers installing Python, running Python programs, basic syntax, variables, operators, and input/output.
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
The document introduces Python modules and importing. It discusses three formats for importing modules: import somefile, from somefile import *, and from somefile import className. It describes commonly used Python modules like sys, os, and math. It also covers defining your own modules, directories for module files, object-oriented programming in Python including defining classes, creating and deleting instances, methods and self, accessing attributes and methods, attributes, inheritance, and redefining methods.
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.
object-oriented JavaScript is somewhat redundant, as the JavaScript language is completely object-oriented and is impossible to use otherwise.
Objects are the foundation of JavaScript. Virtually everything within the language is an object. Much of the power of the language is derived from this fact.
Design patterns are advanced object-oriented solutions to commonly occurring software problems. Patterns are about reusable designs and interactions of objects.
Java OOP Programming language (Part 1) - Introduction to JavaOUM SAOKOSAL
Java OOP Programming language (Part 1) - Introduction to Java
In this slide, you will the basic of Java. Where Java came from and how it evolves? And start your first Java app.
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
Learn Python Programming | Python Programming - Step by Step | Python for Beg...Edureka!
( Python Training : https://www.edureka.co/python )
This Edureka “Python Programming" introduces you to Python by giving you enough reasons to learn it. It will then take you to its various fundamentals along with a practical demonstrating the various libraries such as Numpy, Pandas, Matplotlib and Seaborn. This video helps you to learn the below topics:
1. Why should you go for Python?
2. Introduction to Python Programming Language
3. How to work with Jupyter?
4. Python Programming Fundamentals: Operators & Data Types
5. Libraries: Numpy, Pandas, Matplotlib, Seaborn
Python programming | Fundamentals of Python programming KrishnaMildain
Basic Fundamentals of Python Programming.
What is Python, History of python, Advantages, Disadvantages, feature of python, scope, and many more.
Data Structure using Python, Object Oriented Programming using
Pandas is an open-source Python library that provides data structures and data analysis tools. It allows users to load, clean, manipulate, and visualize data in an efficient way. Pandas contains powerful data structures like Series (1D), DataFrame (2D), and Panel (3D). DataFrame is the most commonly used data structure, as it represents data as columns and rows like a spreadsheet or SQL table. Pandas enables fast and easy data analysis and is widely used in domains like finance, economics, and analytics.
Python is a high-level, interpreted programming language created by Guido van Rossum in 1991. It has gained popularity due to its clear syntax and readability. Companies prefer Python because it is easy to use, free and open-source, and has a large standard library. It can be used for a variety of tasks including web development, data analysis, and scientific computing.
This document describes building a basic calculator program in Python. It takes user input to select an arithmetic operation (add, subtract, multiply, divide) and two numbers. If/elif/else statements direct the program to call functions to perform the selected operation and display the result. While basic, this provides a starting point to create a more advanced calculator with additional features.
This document provides an introduction to the Python programming language. It discusses that Python is an interpreted, interactive, object-oriented scripting language that is designed to be highly readable. The document outlines Python's history and key features, including being easy to learn and use, having a broad standard library, and being portable. It also discusses popular implementations of Python like CPython and how organizations like Google, Yahoo, and NASA use Python for applications such as bioinformatics, simulations, games, and networking.
The document discusses the benefits and advantages of the Python programming language. Python is described as a high-level, easy to use language that can be used for general programming as well as mobile and web development. It has many advantages, such as being easy to learn and use, having a large standard library, and being cross-platform. Some disadvantages are that it requires more memory than languages like C/C++ and has limited database access.
This document provides an introduction to Python programming, including:
- Python was created in 1991 by Guido van Rossum as an interpreted and general-purpose programming language.
- It focuses on code readability and allows programmers to do coding in fewer steps than languages like Java or C++.
- Popular uses of Python include backend web development, data analysis, artificial intelligence, and scientific computing.
- Key advantages that make Python popular include being easy to learn and use, having a large standard library, and supporting multiple programming paradigms.
This document provides an overview of the Python programming language. It discusses Python's history, key features such as being easy to use, scalable, high-level, object-oriented, interpreted, and having a rich core library. It also covers Python's uses in areas like web development, databases, GUI programming, and more. The document is intended to introduce readers to Python and provide context for a book on making use of the language.
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on Python Tutorial covers all the basic knowledge of statistics and probability for Python.
Why Python for Statistics?
What is Probability?
Data and Distribution
Revisiting the Normal
Poker Prediction Use-Case
Check out our Python Tutorial Playlist: https://goo.gl/WsBpKe
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The document outlines the syllabus for a Python course, including introductions to data warehousing, Python itself, different modes in Python like file extensions and IDEs, data structures like sets and dictionaries, OS and exception handling modules, advanced topics like iterators and decorators, XML and multi-threading, web scraping, sequences and collections, lists and tuples, modules and packages, file handling, classes and objects, regular expressions, unit testing, web frameworks like Django, and GUI programming with Tkinter. The syllabus is designed to meet corporate requirements and covers many fundamental and advanced Python topics.
This document is a summer training report submitted by Manish Raghav to fulfill the requirements for a B.Tech degree in computer science engineering from K.R. Mangalam University. The report details a summer training completed at Ducat India Pvt Ltd where the student implemented object tracking using Python. The report includes an introduction to Python, NumPy and OpenCV libraries used for the project. It describes two object tracking methods - absolute difference method and Haar cascade classifier. Screenshots show objects like a phone and pen being tracked.
PYTHON CURRENT TREND APPLICATIONS- AN OVERVIEWEditorIJAERD
Python is a powerful high-level, interpreted, interactive, and object-oriented scripting language created by
Guido Van Rossum in late 1980’s. Python is a very suitable language for the beginner level programmers and supports
the development of a wide range of applications from simple text processing to www browsers to games developments.
One of the biggest reasons for Python’s rapid growth is the simplicity of its syntax. The language reads almost like plain
English, making it easy to write complex programs. In this paper we first analyze you to Python programming language
popularity and features. Moreover, this paper specifying applications areas where python can be applied and specially
analyzing web application frameworks which are using in Python programming language
Python, the Language of Science and Engineering for EngineersBoey Pak Cheong
A talk given in November 2016 at IEM Malaysia to engineers, who are new to Python, a broad perspective of what Python is, why it is important to learn it and how it can help in solving/visualization of engineering and scientific tasks and problems.
5 Simple Steps To Install Python On Windows | Install Python 3.7 | Python Tra...Edureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka tutorial on Installing Python on Windows Tutorial covers all the aspects of installing and setting up Python to write code in. It is pretty simple and straightforward to setup Python completely in Windows as shown.
Following topics are covered in this PPT:
Agenda
Introduction to Python
Popularity of Python
Why should you learn Python?
Installing Python
Python Development Environments
Conclusion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Instagram: https://www.instagram.com/edureka_lea...
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
This document provides an introduction to the Python programming language. It begins with an overview of Python's history and development timeline. It then discusses Python's key features such as being high-level, interpreted, object-oriented, and having extensive libraries. The document outlines Python's main programming paradigms and discusses its growing popularity. It provides details on getting started with Python, different integrated development environments (IDEs), and Python basics like variables, data types, operators, and input/output. The document also covers Python syntax and structures such as control flow, functions, classes, and exceptions handling.
This document provides an overview of the Python programming language. It discusses Python's history, features, and environment setup. Python is an interpreted, interactive, object-oriented programming language created by Guido van Rossum in 1991. It includes high-level data structures, supports object-oriented programming, and is extensible via modules. The document also covers installing Python, running Python programs, basic syntax, variables, operators, and input/output.
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
The document introduces Python modules and importing. It discusses three formats for importing modules: import somefile, from somefile import *, and from somefile import className. It describes commonly used Python modules like sys, os, and math. It also covers defining your own modules, directories for module files, object-oriented programming in Python including defining classes, creating and deleting instances, methods and self, accessing attributes and methods, attributes, inheritance, and redefining methods.
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.
object-oriented JavaScript is somewhat redundant, as the JavaScript language is completely object-oriented and is impossible to use otherwise.
Objects are the foundation of JavaScript. Virtually everything within the language is an object. Much of the power of the language is derived from this fact.
Design patterns are advanced object-oriented solutions to commonly occurring software problems. Patterns are about reusable designs and interactions of objects.
Java OOP Programming language (Part 1) - Introduction to JavaOUM SAOKOSAL
Java OOP Programming language (Part 1) - Introduction to Java
In this slide, you will the basic of Java. Where Java came from and how it evolves? And start your first Java app.
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
This document provides an introduction to Python basics including:
- Python is simple to use, powerful due to extensive libraries, free and open source, and portable across operating systems.
- Python supports literal constants like strings ("Hello") and numbers (2.5), as well as variables to store values. Variables must start with a letter or underscore and can include letters, numbers and underscores.
- Python uses hash marks (#) for comments and whitespace is ignored. Multiple statements can be written on one line separated by semicolons.
Meetup Python Nantes - les tests en pythonArthur Lutz
Au programme :
• introduction aux tests unittaires
• lancer les tests : unittest de base, py.test, nose, pytest, etc.
• tox pour lancer les test dans des virtualenvs
• l'intégration continue avec python (jenkins, travis, etc.)
• les tests en prod : healthchecks au cœur de l'application
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Matt Harrison
I gave this presentation at Code Camp. As a data scientist and backcountry skier, I was interested in looking at fatal avalanche data. This covers scraping the data, analysis with Python, pandas and IPython Notebook. The final result is an infographic
Learning notes of r for python programmer (Temp1)Chia-Chi Chang
R has several basic data types including integers, numerics, characters, complexes, and logicals. Objects in R include vectors, matrices, lists, data frames, factors, and environments. Functions like length(), mode(), class(), and str() can provide properties of R objects. R supports control structures like if/else, for loops, while loops, and repeat loops. R also has rich graphics capabilities for creating plots, histograms and other visualizations using both base and lattice graphics. Common packages used with R include those for statistics, machine learning, and working with time series and financial data.
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
This document discusses various aspects of developing and distributing Python projects, including versioning, configuration, logging, file input, shell invocation, environment layout, project layout, documentation, automation with Makefiles, packaging, testing, GitHub, Travis CI, and PyPI. It recommends using semantic versioning, the logging module, parsing files with the file object interface, invoking shell commands with subprocess, using virtualenv for sandboxed environments, Sphinx for documentation, Makefiles to automate tasks, setuptools for packaging, and GitHub, Travis CI and PyPI for distribution.
This document discusses overloading stream insertion (<<) and extraction (>>) operators for user-defined classes like Complex. It shows how to define these operators as member functions or non-member friend functions to allow objects of the class to be written to or read from streams like cout and cin. It also briefly mentions overloading other binary operators like == and != for comparison.
This document provides instructions for installing Python and various Python libraries on Mac OS X. It describes downloading and installing Python from python.org. It also explains how to install pip and then use pip to install popular Python packages like NumPy, SciPy, Matplotlib, Scikit-learn, TensorFlow, Theano, PyGame, OpenCV, and Requests. The user is instructed to open Terminal and run pip3 install package_name to install these libraries for Python 3.X. Detailed steps are provided for compiling and installing OpenCV from source.
Python is a simple yet powerful programming language that can be used for a wide range of tasks. The document provides an introduction to Python, discussing why it is a good language to learn, its history and examples of common uses. It covers Python's syntax, data types, modules, object oriented programming and how to interface Python with databases and other languages. The goal is to illustrate Python's versatility and ease of use through examples.
This document provides an introduction and overview of Python including sections on syntax, lists and dictionaries, for loops, and implementation examples. The introduction covers that Python code is indented using whitespace rather than brackets, semicolons are optional, and data types do not need declaration. Lists are described as arrays that can hold different data types indexed by number, while dictionaries hold key-value pairs indexed by keys that can be numbers, strings, or other data types. For loops in Python iterate over each item in a list or dictionary without needing an explicit condition. The implementation section provides examples of using for loops over lists, creating and accessing a dictionary of fruits, and making lists of dictionaries to demonstrate Python concepts.
This document provides an introduction and overview of Python and the Flask web framework. It discusses key Python concepts like objects, references, memory management and data types. It also covers Flask topics like routing, templates, request objects, sessions and authentication. The document aims to give readers a high-level understanding of Python and how to build basic web applications with Flask.
Introduction to facebook java script sdk Yi-Fan Chu
This document provides an overview and tutorial on using the Facebook JavaScript SDK. It begins with essential knowledge on the Facebook developers website, Facebook apps, the JavaScript SDK and Graph API. It then covers technical details like downloading the SDK, login functions, the Graph API, sharing, and social plugins. The final section demonstrates implementation through checkpoints for setting up a basic app, login, fetching a user's profile picture and name, and enabling sharing and comments. The goal is to teach developers how to integrate Facebook login, access user data, and allow sharing through the JavaScript SDK.
This document provides an overview of the book "A Byte of Python" by Swaroop C H. The book aims to help readers learn the Python programming language, whether they are new to computers or experienced programmers. It covers topics like installing Python, basic syntax, variables, data types, control flow, functions, modules, object-oriented programming and exceptions. The book is intended as a guide for learning Python and is constantly being improved based on reader feedback. It is released under a Creative Commons license that allows copying and sharing with attribution.
This document provides an overview and tutorial for the Python programming language. It discusses Python's history and features, how to set up the Python environment and run Python programs, Python's basic syntax including variables, operators, and control flow structures, built-in data types like numbers, strings, lists, and dictionaries, and many Python functions and methods. The tutorial is designed for new Python programmers to learn the fundamentals of the language.
Python is a general-purpose, interpreted, interactive, object-oriented and high-level
programming language. Python was created by Guido van Rossum in the late eighties and
early nineties. Like Perl, Python source code is also now available under the GNU General
Public License (GPL).
This document provides an introduction to the Python programming language. It discusses installing Python and using the interpreter to run Python code. Basic Python syntax for arithmetic, variables, functions, loops, and lists are covered. The math module is demonstrated for importing common mathematical functions like square root and exponential. Defining custom functions is also explained. The goal is to teach Python for mathematical calculations and programming.
This document provides an introduction to the Python programming language. It discusses downloading and installing Python, using the Python interpreter to run calculations, defining functions, using files and scripts, different data types like strings and lists, expressions and operators, variables and assignment, decisions and loops. It also covers basic Python commands for comments, numbers, Boolean values, and built-in functions from the math module.
This document provides an overview and tutorial for Python 3. It discusses the key differences between Python 3 and Python 2, including changes to print statements, integer division, and exceptions. It also covers setting up a Python development environment, basic Python syntax like identifiers, comments, and data types. The tutorial is designed for programmers looking to upgrade their Python skills to version 3 and also serves as an introduction for learning Python from scratch.
This document provides an overview and tutorial for Python 3. It discusses the key differences between Python 3 and Python 2, how to set up the Python environment, basic Python syntax, variables, operators, and built-in data types. It also covers core programming concepts like decision making, loops, functions, modules, date/time handling, files I/O, and more. The tutorial is designed for programmers looking to learn or upgrade their skills to Python 3.
The document provides an overview of the features and functionality available in the Pi trading platform version 1.0.0.6. It describes the login process, market watch, order types, charting tools, technical indicators, account positions and balances that can be accessed. The document is a user manual that defines each section of the Pi menus and provides instructions on how to use the various trading and analysis tools within the platform.
Raspberry Pi: Python todo en uno para dummies por John Shovic parte 1.pdfSANTIAGO PABLO ALBERTO
This document is the table of contents for the book "Python All-in-One For Dummies". It outlines the book's 7 books and various chapters, which cover topics ranging from getting started with Python to building robots and doing data science. The table of contents provides the chapter titles and brief descriptions of the content included in each chapter. It also includes publishing information such as the copyright and ISBN numbers.
A Visual and Interactive Journey into Python Programming." Dive into captivating visuals and interactive exercises, perfect for beginners and intermediate programmers. Unleash your Python skills with this immersive eBook. Let the adventure begin!
You can get the full course here:
https://dejavucode.com/product/pure-python-accelerator-rapid-learning-for-quick-results/
This document provides an overview and tutorial on the Python programming language. It discusses Python's history and features, how to set up a Python environment and run Python programs, Python's basic syntax including variables, operators, control flow and functions. It also covers built-in data types like numbers, strings, lists, tuples and dictionaries, modules, files I/O, object-oriented programming concepts in Python and more. The tutorial is designed for programmers new to Python.
This document provides a manual for using XRumer software. It describes the main interface components including the main menu, project settings, links databases, reports, anonymity settings, and multi-threading settings. It also outlines the files structure including folders for links databases, logs, plugins, and projects. Various tools are described like links counting, post-processing, and blacklisting filters. The document provides guidance on setting up projects, links databases, proxy settings, and email activation for posting processes.
This document provides instructions for installing Sitecore Experience Platform 8.0, including:
- Outlining the system requirements for the Sitecore hosting environment and client
- Describing the installation process from the .exe or .zip file
- Explaining necessary post-installation steps like rebuilding the search index and configuring the Experience Database
- Providing supplementary instructions for server configuration in the appendix
The document guides the reader through preparing for, performing, and finalizing the Sitecore installation.
This document summarizes a presentation about OpenStack clouds on Ubuntu. It discusses that OpenStack is open source cloud infrastructure software that is popular with over 1200 developers. It is used by many large companies and supports various hypervisors and components like compute, storage, networking, identity management and more. The document also notes that Ubuntu has a close relationship with OpenStack as the preferred operating system and is commonly used on over 55% of public clouds.
This document provides an overview of the Thru REST API, including its design principles, security measures, data types, resources and endpoints. The API follows REST architectural style with stateless operations, accepts JSON and XML payloads, and supports side-by-side versioning. It utilizes common HTTP verbs and secures access via session identifiers. Error responses contain detailed codes and messages to assist clients. The reference guide describes the API's data structures, services and tools to access file, message and user account resources.
Dat 210 academic adviser ....tutorialrank.comladworkspaces
This document contains instructions and requirements for multiple assignments in the DAT 210 course. It includes instructions for weekly assignments involving writing programs in Python, Java, and Ruby to complete tasks like calculating sums, finding minimum values, and converting costs between currencies. It also includes discussion prompts for weekly discussions on topics like programming logic, object-oriented programming, and functional programming.
DAT 210 Education Specialist |tutorialrank.comladworkspaces
This document contains instructions and requirements for multiple assignments in the DAT 210 course. It includes instructions for weekly assignments involving writing programs in Python, Java, and Ruby to complete tasks like calculating sums, finding minimum values, and converting costs between currencies. It also includes discussion prompts for weekly topics like programming logic, object-oriented programming, and functional programming. Students are asked to submit working code and screenshots of outputs in ZIP files.
This package selection allows you to install additional packages that provide common server
tasks:
- OpenSSH Server: Secure shell server for remote login and secure communication between hosts.
- LAMP server: Installs packages to configure a basic LAMP (Linux, Apache, MySQL, PHP) web and
database server.
- Print server: Installs packages to configure a print server with CUPS.
- DNS server: Installs packages to configure a DNS server with Bind.
- Mail server: Installs packages to configure a mail server with Postfix, Dovecot and SpamAssassin.
Selecting one of these tasks installs the recommended packages for that role, saving time over
Writing Character driver (loadable module) in linuxRajKumar Rampelli
It covers the step by step approach on how to write a simple loadable character device driver in linux. What are Device files in linux detail. How user application interact with character driver using a device file.
It describes the MMC storage device driver functionality in Linux Kernel and it's role. It explains different type of storage devices available and how they are handled from MMC driver point of view. It describes eMMC (internal storage) device and SD (external storage) devices in details and SD protocol used for communicating with these devices in Linux.
Learn python in easy steps. This presentation will cover followings
1. Python basics
2. How to write a python code
3. Variable usage & their syntax
4. Strings handling
5. Files handling
6. How to use loops and others.
7. Python Vs C language.
Linux kernel has a special feature called Watchdog timer which would reset the system in case of any software faults | system hangs | or any application crashes after a timeout has reached.
This presentation gives an overview of Linux kernel block I/O susbsystem functionality, importance of I/O schedulers in Block layer. It also describes the different types of I/O Schedulers including the Deadline I/O scheduler, Anticipatory I/O Scheduler, Complete Fair queuing I/O scheduler and Noop I/O scheduler.
It provides details about what is Kernel, what is a Module and what is device driver. How device gets registered and how a storage volume gets mounted if it is inserted on android system. Details on Allocation of memory in Kernel.
This PPT shares some information on what is booting process and different stages in it. Importance of BIOS and BootROM. Steps involved for loading kernel into RAM. What is the importance of init RAM disk (initrd), when 1st user space application is started and who will create init process.
This ppt describes network security concepts and the role of cryptography. Difference in Symmetric Key Cryptography and Public Key Cryptography. Uses of Digital Certificates. What is the use of Digital Signature and how it ensure authenticity, Integrity and Non-repudiation. How security features should be ensured for any transactions using cryptography.
Tasklet vs work queues (Deferrable functions in linux)RajKumar Rampelli
Deferrable functions in linux is a mechanism to delay the execution of any piece of code later in the kernel context. Can be implemented using Tasklet and work queues
SQL is a language used to access and manipulate databases. It allows users to execute queries, retrieve, insert, update and delete data from databases. SQL injection occurs when malicious code is injected into an SQL query, which can compromise the security of a database. To prevent SQL injection, developers should validate all user input, escape special characters, limit database permissions, and configure databases to not display error information to users.
This ppt shows more details on Higher education (M.Tech/MS/MBA) role and its importance. B.E/B.Tech students should think twice before choosing next level (Higher studies or JOB). There are so many benefits with higher studies today. GATE is a All India entrance test used for admission for MS/MTECH/Phd in Indian Institute of Technologies (IITs). GRE entrance test is for admission in other countries.
This ppt will demonstrate the compilation process stages in C language. C compilation process has 4 stages. They are pre-processor, compiler, assembler and linker. Each stage has its own functionality. The final outcome of these stages would be a C executable file. GCC tool is used in linux platform to compile C code. And It will generate *.out files as an executable.
How to Create Quotation Templates Sequence in Odoo 18 SalesCeline George
In this slide, we’ll discuss on how to create quotation templates sequence in Odoo 18 Sales. Odoo 18 Sales offers a variety of quotation templates that can be used to create different types of sales documents.
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...EduSkills OECD
Deborah Nusche, Senior Analyst, OECD presents at the OECD webinar 'Trends Spotting: Strategic foresight for tomorrow’s education systems' on 5 June 2025. You can check out the webinar on the website https://oecdedutoday.com/webinars/ Other speakers included: Deborah Nusche, Senior Analyst, OECD
Sophie Howe, Future Governance Adviser at the School of International Futures, first Future Generations Commissioner for Wales (2016-2023)
Davina Marie, Interdisciplinary Lead, Queens College London
Thomas Jørgensen, Director for Policy Coordination and Foresight at European University Association
Parenting Teens: Supporting Trust, resilience and independencePooky Knightsmith
For more information about my speaking and training work, visit: https://www.pookyknightsmith.com/speaking/
SESSION OVERVIEW:
Parenting Teens: Supporting Trust, Resilience & Independence
The teenage years bring new challenges—for teens and for you. In this practical session, we’ll explore how to support your teen through emotional ups and downs, growing independence, and the pressures of school and social life.
You’ll gain insights into the teenage brain and why boundary-pushing is part of healthy development, along with tools to keep communication open, build trust, and support emotional resilience. Expect honest ideas, relatable examples, and space to connect with other parents.
By the end of this session, you will:
• Understand how teenage brain development affects behaviour and emotions
• Learn ways to keep communication open and supportive
• Explore tools to help your teen manage stress and bounce back from setbacks
• Reflect on how to encourage independence while staying connected
• Discover simple strategies to support emotional wellbeing
• Share experiences and ideas with other parents
Unit- 4 Biostatistics & Research Methodology.pdfKRUTIKA CHANNE
Blocking and confounding (when a third variable, or confounder, influences both the exposure and the outcome) system for Two-level factorials (a type of experimental design where each factor (independent variable) is investigated at only two levels, typically denoted as "high" and "low" or "+1" and "-1")
Regression modeling (statistical model that estimates the relationship between one dependent variable and one or more independent variables using a line): Hypothesis testing in Simple and Multiple regression models
Introduction to Practical components of Industrial and Clinical Trials Problems: Statistical Analysis Using Excel, SPSS, MINITAB®️, DESIGN OF EXPERIMENTS, R - Online Statistical Software to Industrial and Clinical trial approach
Different pricelists for different shops in odoo Point of Sale in Odoo 17Celine George
Price lists are a useful tool for managing the costs of your goods and services. This can assist you in working with other businesses effectively and maximizing your revenues. Additionally, you can provide your customers discounts by using price lists.
Ray Dalio How Countries go Broke the Big CycleDadang Solihin
A complete and practical understanding of the Big Debt Cycle. A much more practical understanding of how supply and demand really work compared to the conventional economic thinking. A complete and practical understanding of the Overall Big Cycle, which is driven by the Big Debt Cycle and the other major cycles, including the big political cycle within countries that changes political orders and the big geopolitical cycle that changes world orders.
How to Manage Upselling of Subscriptions in Odoo 18Celine George
Subscriptions in Odoo 18 are designed to auto-renew indefinitely, ensuring continuous service for customers. However, businesses often need flexibility to adjust pricing or quantities based on evolving customer needs.
HOW YOU DOIN'?
Cool, cool, cool...
Because that's what she said after THE QUIZ CLUB OF PSGCAS' TV SHOW quiz.
Grab your popcorn and be seated.
QM: THARUN S A
BCom Accounting and Finance (2023-26)
THE QUIZ CLUB OF PSGCAS.
RE-LIVE THE EUPHORIA!!!!
The Quiz club of PSGCAS brings to you a fun-filled breezy general quiz set from numismatics to sports to pop culture.
Re-live the Euphoria!!!
QM: Eiraiezhil R K,
BA Economics (2022-25),
The Quiz club of PSGCAS
*Order Hemiptera:*
Hemiptera, commonly known as true bugs, is a large and diverse order of insects that includes cicadas, aphids, leafhoppers, and shield bugs. Characterized by their piercing-sucking mouthparts, Hemiptera feed on plant sap, other insects, or small animals. Many species are significant pests, while others are beneficial predators.
*Order Neuroptera:*
Neuroptera, also known as net-winged insects, is an order of insects that includes lacewings, antlions, and owlflies. Characterized by their delicate, net-like wing venation and large, often prominent eyes, Neuroptera are predators that feed on other insects, playing an important role in biological control. Many species have aquatic larvae, adding to their ecological diversity.
How to Configure Vendor Management in Lunch App of Odoo 18Celine George
The Vendor management in the Lunch app of Odoo 18 is the central hub for managing all aspects of the restaurants or caterers that provide food for your employees.
Strengthened Senior High School - Landas Tool Kit.pptxSteffMusniQuiballo
Landas Tool Kit is a very helpful guide in guiding the Senior High School students on their SHS academic journey. It will pave the way on what curriculum exits will they choose and fit in.
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxArshad Shaikh
Diptera, commonly known as flies, is a large and diverse order of insects that includes mosquitoes, midges, gnats, and horseflies. Characterized by a single pair of wings (hindwings are modified into balancing organs called halteres), Diptera are found in almost every environment and play important roles in ecosystems as pollinators, decomposers, and food sources. Some species, however, are significant pests and disease vectors, transmitting diseases like malaria, dengue, and Zika virus.
Pests of Rice: Damage, Identification, Life history, and Management.pptxArshad Shaikh
Rice pests can significantly impact crop yield and quality. Major pests include the brown plant hopper (Nilaparvata lugens), which transmits viruses like rice ragged stunt and grassy stunt; the yellow stem borer (Scirpophaga incertulas), whose larvae bore into stems causing deadhearts and whiteheads; and leaf folders (Cnaphalocrocis medinalis), which feed on leaves reducing photosynthetic area. Other pests include rice weevils (Sitophilus oryzae) and gall midges (Orseolia oryzae). Effective management strategies are crucial to minimize losses.
How to Manage & Create a New Department in Odoo 18 EmployeeCeline George
In Odoo 18's Employee module, organizing your workforce into departments enhances management and reporting efficiency. Departments are a crucial organizational unit within the Employee module.
How to Manage & Create a New Department in Odoo 18 EmployeeCeline George
Introduction to Python - Running Notes
1. PYTHON
INTRODUCTION
[Type the abstract of the document here. The abstract is typically a short
summary of the contents of the document. Type the abstract of the
document here. The abstract is typically a short summary of the contents of
the document.]
Reference:
sololearn.com
2. PYTHON
Table of Contents
Python Introduction............................................................................................................................6
Python versions..............................................................................................................................6
Python console...............................................................................................................................6
Python functions ................................................................................................................................6
Python errors.....................................................................................................................................6
Python floats......................................................................................................................................7
Python numerical operations ..............................................................................................................7
__main__...........................................................................................................................................8
Command line arguments...................................................................................................................8
sys module.....................................................................................................................................8
getopt module................................................................................................................................9
getopt.getopt method.................................................................................................................9
Exception getopt.GetoptError......................................................................................................9
Example.................................................................................................................................10
Strings..............................................................................................................................................11
String formatting..........................................................................................................................11
String operations ..........................................................................................................................12
Variables..........................................................................................................................................12
Variable names:............................................................................................................................12
del statement...............................................................................................................................13
Special operators..............................................................................................................................13
if statements....................................................................................................................................13
elif (short form of else if)...............................................................................................................13
Boolean logic................................................................................................................................14
While loops......................................................................................................................................14
infinite loop..................................................................................................................................14
break...........................................................................................................................................14
continue.......................................................................................................................................14
3. operator precedence........................................................................................................................14
More on else statements ..................................................................................................................15
Else with loops..............................................................................................................................15
Else with try/except......................................................................................................................15
Lists.................................................................................................................................................15
Empty list.....................................................................................................................................16
Nested lists...................................................................................................................................16
Errors...........................................................................................................................................16
List operations..............................................................................................................................16
Assignment...............................................................................................................................16
Addition and Multiplication........................................................................................................16
in operator................................................................................................................................16
not operator.............................................................................................................................17
Loops........................................................................................................................................17
List slices......................................................................................................................................17
Negative indexing......................................................................................................................17
List comprehensions .....................................................................................................................18
List functions................................................................................................................................18
Sets.................................................................................................................................................19
Mathematical operations - union/intersection................................................................................19
Functions and modules.....................................................................................................................20
Arguments ...................................................................................................................................20
Return values ...............................................................................................................................21
Docstrings ....................................................................................................................................21
Modules.......................................................................................................................................21
Import certain functions............................................................................................................21
Standard Library...............................................................................................................................21
Exception Handling...........................................................................................................................22
Raising exception..........................................................................................................................23
Assertions........................................................................................................................................23
Files handling...................................................................................................................................23
Opening files - open()....................................................................................................................23
5. Matching pattern..........................................................................................................................34
re.search()....................................................................................................................................34
re.sub() - search & replace.............................................................................................................35
Metacharacters ............................................................................................................................35
. (dot) character........................................................................................................................35
^ and $ - start and end...............................................................................................................35
Character classes..........................................................................................................................35
^ character................................................................................................................................36
More Metacharacters ...................................................................................................................36
* character................................................................................................................................36
+ character................................................................................................................................36
? character................................................................................................................................36
Curly braces..............................................................................................................................36
Groups.........................................................................................................................................36
| character................................................................................................................................37
Named groups...........................................................................................................................37
Special Sequences ............................................................................................................................37
number - Backslash .....................................................................................................................37
d and D sequence.......................................................................................................................38
s and S sequence........................................................................................................................38
w and W sequence.....................................................................................................................38
A Sequence.................................................................................................................................38
b sequence .................................................................................................................................38
Email extraction ...............................................................................................................................38
Pythonicness & Packaging.................................................................................................................39
PEP- Python Enhancement Proposals.................................................................................................39
Packaging.........................................................................................................................................39
Setup.py.......................................................................................................................................40
Packaging for Users.......................................................................................................................40
Function arguments..........................................................................................................................40
*args............................................................................................................................................40
**kwargs – keyword arguments ....................................................................................................41
6. Major 3rd
party libraries ....................................................................................................................41
Django.........................................................................................................................................41
CherryPy and Flask........................................................................................................................41
BeautifulSoup...............................................................................................................................41
Matplotlib....................................................................................................................................41
NumPy.........................................................................................................................................41
SciPy............................................................................................................................................42
Panda3D ......................................................................................................................................42
List Vs Dictionary Vs TuplesVs Sets....................................................................................................42
itertools - standard library.................................................................................................................43
Python Vs C......................................................................................................................................43
Web scraping: webbrowser library ....................................................................................................44
Webbrowser.open()......................................................................................................................44
webbrowser.open_new(url)..........................................................................................................44
webbrowser.open_new_tab(url) ...................................................................................................44
webbrowser.get([name])...............................................................................................................44
7. Python !!!
PythonIntroduction
Pythonisa highlevel programminglanguagelikeC/C++/Javaetc.,itsapplicationsincludingweb
programming,scripting,scientificcomputingandartificial intelligence.
pythonisprocessedatruntime bythe interpreter.Noneedto compile pythonprogramsbefore
executingthemunlikeCprograms,where compilationstepismandatorybeforeexecutingit.
An Interpreterisaprogramthat runs scriptswritteninan interpretedlanguage suchasPython.
Pythonsource fileshave anextensionof .py
Python versions
There are three majorversionsof pythonwhichare 1.x,2.x and3.x. Both2.x and 3.x are currentlyused.
Python console
The pythonconsole isa program that allowsyouto enterone line of pythoncode,repeatedlyexecutes
that line,anddisplaysthe output.Thisisknownasa REPL - Read-Eval-Print-Loop.
To close a console,type inquit() orexit() andpressenter.
Pythonfunctions
Pythonfunction Usage
print("Hello") orprint('Hello') Printsthe message,producesthe output
quit() orexit() Close the console
input("Entersomethingplease:") Promptsthe use for input,andreturnswhatthey
enteras a stringwithcontentsautomatically
escaped.
Enter somethingplease:userentersncharacter!
o/p-> userentersncharacter!
int() Convertsgivennumberinstringformattointeger
int("2") + int("3") = 5
Similarlyfloat() andstr()
del variable_name del statementusedtoremove avariable from
program.
Pythonerrors
Type of error Example
ZeroDivisionError:divisionbyzero 11 / 0
TypeError:unsupportedoperandtype(s) 1 + "2"
8. For +:'int' and 'str'
TypeError:can't multiplysequence bynon-intof
type 'str' or 'float'
"s" * "s"
9.0 * "r"
SyntaxError:invalidsyntax >>>123abc = 7
1. When variable namesdon'tfollowrules.
2. When programuses++ or -- operators.
NameError:name 'var_name" is notdefined Whenprogram triestoaccess undefinedvariable
or a functionwhichisnotdefined
In Lists:
IndexError:
whentry toaccess out of boundvalues.
things="hai"
print(things[4])
In Lists:
TypeError:
whentry toaccess integerorfloat typesusing
index.
Num= 123
print(Num(2))
In Lists:
ValueError:
If the itemisnotin the listand tryingto getits
index.
ImportError Whentryingto access unavailablemodule
KeyError Tryingto index akeythat isn'tpart of the
dictionaryreturnsaKeyError.
Dictionary'sTypeError Whenmutable objectsare usedaskeys
RuntimeError:maximumrecursiondepth
exceeded
Oftenoccur whenforgottoimplementthe base
case of resusion.
AttributeError Tryingto access an attribute of an instance the
isn'tdefinedcausesthiserror.
Pythonfloats
A floatcan be addedto an integerbecause Pythonsilentlyconvertsthe integertoa float.However,this
implicitconversionisthe exceptionratherthanthe rule inPython.Youhave to convertvaluesmanually
if you wantto operate onthem.
Pythonnumerical operations
Operator Usage
+ , - , * , / Addition,subtraction,multiplication,division
1 + 2 = 3
1 + 2.2 = 3.2
2 * 3 = 6
2 * 3.2 = 6.4
4/2 = 2.0
5/2 = 2.5
** Exponentiation
2**5 = 32
9**(1/2) = 3.0
// Quotient(Floordivision)
9. 20//6 = 3
% Remainder(modulooperator)
1.25%0.5 = 0.25
Inplace operators
+= , -=, *=, %= and /=
a += 3 -> a = a + 3
__main__
Whena pythoninterpreterreadsasource file,itexecutesall of the code itfindsinthe file. Before
executingthe code,itdefinesafewspecial variables.
For example,if the pythoninterpreterisrunningthatmodule (source file) asthe mainprogram, itsets
the special __name__ variable tohave avalue “__main__”. If the file beingimportedfromanother
module, __name__ will be settothe module’sname.
If __name__ == “__main__”:
print(“Thisisascript”)
else
print(“Imported”)
Commandline arguments
sys module
The Python sys module providesaccesstoany command-lineargumentsviathe sys.argv.Thisserves
twopurposes−
sys.argvisthe listof command-linearguments.
len(sys.argv) isthe numberof command-linearguments.
Here sys.argv[0] isthe program ie.scriptname.
Consider the following script test.py −
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Now run above script as follows −
10. $ python test.py arg1 arg2 arg3
This produce following result −
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
getopt module
Pythonprovidesagetoptmodule thathelpsyouparse command-lineoptionsandarguments.
Pythonprovidedagetoptmodule thathelpsyouparse command-lineoptionsandarguments.This
module providestwofunctionsandan exceptiontoenablecommandline argumentparsing.
getopt.getoptmethod
Thismethodparsescommandline optionsandparameterlist.Followingissimple syntaxforthismethod
−
getopt.getopt(args,options,[long_options])
Here is the detail of the parameters−
args: Thisisthe argumentlistto be parsed.
options:This isthe stringof optionlettersthatthe scriptwantsto recognize,withoptionsthat
require anargumentshouldbe followedbyacolon(:).
long_options:Thisis optional parameterandif specified,mustbe alistof stringswiththe
namesof the longoptions,whichshouldbe supported.Longoptions,whichrequire an
argumentshouldbe followedbyanequal sign('=').To accept onlylongoptions,optionsshould
be an emptystring.
Thismethodreturnsvalue consistingof twoelements:the firstisalistof (option,value) pairs.
The secondis the listof program argumentsleftafterthe optionlistwasstripped.
Each option-and-valuepairreturnedhasthe optionasitsfirstelement,prefixed withahyphen
for shortoptions(e.g.,'-x') ortwohyphensforlongoptions(e.g.,'--long-option').
Exceptiongetopt.GetoptError
Thisis raisedwhenanunrecognizedoptionisfoundinthe argumentlistorwhenanoptionrequiringan
argumentisgivennone.
The argumentto the exceptionisastringindicatingthe cause of the error. The attributesmsgandopt
give the errormessage andrelatedoption.
11. Example
Consider we want to pass two file names through command line and we
also want to give an option to check the usage of the script. Usage of the
script is as follows −
usage: test.py -i <inputfile> -o <outputfile>
Here is the following script to test.py −
#!/usr/bin/python
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'Input file is "', inputfile
print 'Output file is "', outputfile
if __name__ == "__main__":
main(sys.argv[1:])
12. Now, run above script as follows −
$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i inputfile
Input file is " inputfile
Output file is "
Strings
A stringiscreatedby enteringtextbetweentwosingle ordouble quotationmarks.
-> 'HelloWorld'or "HelloWorld"
Some characters can't be includedinstringdirectly,example of these charactersare single quoteand
double quotes,tabs, arbitraryunicode characters.
Put a backslashbefore these charactersif youaddthese special charactersinyourstring.
"Ram's brothername is "Raj""-->Ram's brothername is Raj
n - representsnew line.
String formatting
Providesamore powerful waytoembednon-stringswithinstrings.
Stringformattingusesastring's format methodtosubstitute anumberof argumentsinthe string.
nums= [4, 5, 6]
msg = "Numbers:{0} {1} {2}".format(nums[0],nums[2],nums[3])
print(msg) -> Numbers:4 5 6
Stringformattingcan alsobe done withnamedargumets.
a = "{x},{y}".format(x=5,y=12)
print(a) -> 5, 12
13. String operations
Concatenation "spam"+"eggs"= spameggs
"spam"+","+"eggs"= spam,eggs
"2"+"2" = 22
1 + "2" = TypeError(ReferPythonerrorstable)
Multiplication "spam"*3 = spamspamspam
4 * "3" = 3333
"s" * "r" = TypeError
"s" * 7.0 = TypeError
Replace "hellome".replace("me","world") ->helloworld
Startswith "Thisis car".startswith("This") ->True
Endswith
Upper() "I am a boy".upper() ->I AM A BOY
Lower()
Split() "spam, eggs,ham".split(",")
Variables
In python,variablesdon'thave specifictypes,soyoucan assigna stringto a variable,andlaterassignan
integertothe same variable.
>>> a = 100
>>>print(a)
100
>>>a = "Raj"
>>>print(a)
'Raj'
Variable names:
The onlycharacters that are allowedare letter,numbersandunderscores.Also,theycan'tstart with
numbers.
NotfollowingtheserulesresultsinSyntaxErrorerror.
Pythonisa case sensitiveprogramminglanguage.Thus,Lastname andlastname are twodifferent
variable namesinPython.
Tryingto reference avariable thathasnot assignedinthe programcausesan error (NameError).
>>>a = "raj"
>>>a
raj
>>>b
NameError:name 'b' isnot defined.
>>>del a
14. del statement
del statementusedtoremove avariable fromprogram.
Special operators
Pythondoesn'tsupportspecial operators++and --.But,it supportsinplace operators(referoperation
table above)
Interpreterthrowssyntax errorif programuses++ or -- operators.
Example: File "./prog.py", line 12
a++
^
SyntaxError: invalid syntax
if statements
use if statementstorun code whencertainconditionholds.
if expression:
statements
Pythonusesindentation(white spacesatthe beginningof aline) todelimitblocksof code.Other
languages,suchas,C, use curlybraces to accomplishthis.But,inPythonindentationismandatory;
program won'tworkwithoutit.Asyou can see,the statementsinthe if shouldbe indented.
elif (short form of else if)
the elif (shortforelse if) statementisashortcutto use whenchainingif andelse statements.
if expression:
statement
else:
if expression:
statement
can be modifiedasbelow
if expression:
statement
elif expression:
statement
15. Boolean logic
Booleanlogicisusedtomake more complicatedconditionsfor itstatementsthatrelyon more than one
condition.
Python'sBooleanoperatorsare and,or, andnot.
While loops
while condition:
statement1
statement2
infinite loop
while 1==1:
print("inthe loop")
break
To enda while loopprematurely,the breakstatementcanbe used.
i = 0
while 1==1:
print(i)
i = i +1
if i >= 5:
printf("breaking")
break
continue
Unlike break, continue jumpsbackto the top of the loop,ratherthan stoppingit.
operator precedence
== has higherprecedencethan or.
Python'sorderof operationsisthe same as that of normal mathematics.
the followingtable listsall of Python'soperators,fromhighestprecedence tolowest.
Operator Description
** Exponentiation
~ + - Complement,unaryplus/minus
* / %// Multiplication,division.moduloandfloordivision
+ - Addition/subtraction
>> << Rightand leftbitwise shift
& Bitwise AND
16. ^ | Bitwise exclusive ORandregularOR
<= < > >= Comparisons
= %= /= //= -= += *= **= Assignmentoperators
isis not Identityoperators
innot in Membershipoperator
not or and Logical operators
More on else statements
Else with loops
Usingelse withforand while loops,the code withinit iscalledif the loopfinishednormally(whena
breakstatementdoesn’tcause anexitfromthe loop)
For I inrange(10):
if (i==999):
break
Else:
print(“Unbroken”)
Else with try/except
The else statementcanalsobe usedwithtry/exceptstatements.In thiscase,the code withinitisonly
executedif noerroroccurs inthe try statement.
Try:
print(1)
exceptZeroDivisionError:
print(2)
else:
print(3)
o/P:
1
3
Lists
Listsare one type of objectin Python.Theyare usedto store an indexedlistof items.
A listiscreatedusing square brackets withcommas separatingitems.Iteminthe listcanbe accessesby
usingitsindex insquare brackets. A comma can be placedafterlastitemalso,itsvalidonly.
words= ["Hello","world","!"]
print(words[0])
17. print(words[1])
print(words[2])
Empty list
An emptylistiscreatedwithanemptypairof square brackets.
empty_list=[]
print(empty_list) -->o/p:[]
Nested lists
Listscan alsoinclude differentitemtypesandalsobe nestedwithinotherlists.
num= 3
things= ["string",0, [1, 2, num],4.56]
print(things[1])
print(things[2])
print(things[2][2])
Errors
IndexError:whentryto accessout of boundvalues.print(things[4])
TypeError:whentry to accessintegerorfloat typesusingindex.
No errorwill be seenforstringtype.Example,str="Helloworld",print(str[0]),o/P:H
List operations
Assignment
The itemat certainindex ina listcan be reassigned.
AdditionandMultiplication
Listscan be addedandmultipliesinthe same wayas strings
nums= [1, 2, 3]
print(nums+[4, 5, 6]) -> [1,2,3,4,5,6]
print(nums*3) -> [1,2,3,1,2,3,1,2,3]
List andstringsare similarinmanyways - stringscan be thoughtof as listsof charactersthat can't be
changed.
in operator
To check if an itemisinlist,the in operatorcan be used.It returns True if the itemoccurs one or more
timesinthe list,and False if it doesn't.
18. words= ["spam","eggs","spam","sause"]
print("spam"inwords) ->True
print("tomo"inwords) ->False
The in operatoris alsousedto determinewhetherornota string issubstringof anotherstring.
not operator
To check if an itemisnot ina list.
print(not4 innums) -> True
print(4not innums) -> True
Loops
words= ["hello","world","spam"]
for wordinwords:
print(word)
o/p:
hello
world
spam
for i in range(3):
print("hi")
o/p:hi hi hi
List slices
Providesmore advancedwayof retrievingvaluesfromalist.
if the firstnumberina slice isomitted,itistakentobe the start of the list.If the 2nd numberisomitted,
it istakento be the end.
squares= [0, 1, 4, 9, 16, 25]
print(squares[1:4]) ->[1, 4, 9]
print(squares[0:1]) ->[0]
print(squares[:3]) ->[0, 1, 4]
print(squares[4:]) ->[16, 25]
List slicescanalsohave a 3rd number,representingthe step,toinclude onlyalternate valuesinthe slice.
print(squares[2:5:2]) ->[4, 16]
Negativeindexing
Negative valuescanbe usedinlistslicing(andnormal listindexing).
Whennegative valuesare usedforthe firstand2nd values ina slice (ora normal index),they count
fromthe endof the list.
19. print(squares[1:-1]) ->[1, 4, 9, 16]
If Negative value isusedforthe step,the slice isdone backwards.Using[ : : -1] as slice isa commonand
idiomaticwaytoreverse alist.
List comprehensions
List comprehensionsare auseful wayof quicklycreatinglistswhose contentsobeyasimple rule.
cubes= [i**3 fori in range(5)]
print(cubes) ->[0, 1, 8, 27, 64]
A listcomprehensioncanalsocontainan if statementtoenforce aconditiononvaluesinthe list.
evens= [i**2 for i in range(10) if i**2 %2 == 0]
print(evens) -->[0,4, 16, 36, 64]
Tryingto create a listina veryextensive range willresultina MemoryError.
even= [2*i fori in range(10**1000)] -> MemoryError.
Thisissue issolvedby generators.
List functions
Function Description
list.append(item):isamethodof listclass and
hence can be accessedusing dot before.
Addsan itemto the endof an existinglist.
Nums= [1, 2, 3]
Nums.append(4)
Print(nums) ->[1, 2, 3, 4]
len() Get the numberof itemsina list.
print(len(nums)) ->4
list.insert(index,item) Allowstoinsertanew itemat any positioninthe
list.
Nums.insert(1, 10)
print(nums) ->[1,10, 2, 3, 4]
list.index(item) Findsthe firstoccurrence of a listitemandreturns
thisindex.
If the itemisn'tinthe list,itraisesa ValueError.
print(nums.index(10)) ->1
print(nums.index(20)) ->ValueError:20is notin
the list
max(list) Returnsthe listitemwiththe maximumvalue
min(list) Returnsthe listitemwiththe minimumvalue
list.count(item) Returnsa count of how manytimesanitemoccurs
ina list.
list.remove(item) Removesanitemfroma list
list.reverse() Reversesitemsinlist
list(range(count)):Createsa sequential listof Nums= list(range(5))
20. numbers.range byitself createsarange object,
and thismustbe convertedtoa list.
print(nums) ->[0,1, 2, 3, 4]
list(range(first,end)):Producesalistfromthe first
to the end
Nums= list(range(2,7))
print(nums) ->[2,3, 4, 5, 6]
list(range(first,end,interval)) Nums= list(range(2,7,2))
print(nums) ->[2,4, 6]
all and any Take a listas argumentandreturnTrue if all or any
(respectively) of theirargumentsevaluatetoTrue.
Nums= [55, 44, 33]
If all([i>5fori innums]):
print("all are largerthan5")
If any([i%2== 0 for i in nums]):
Print("atleastone iseven")
Enumerate() Usedto iterate throughthe valuesandindicesof
listsimultaneously.
For v inenumerate(nums):
Print(v)
o/p:(0, 55)
(1, 44)
(2, 33)
Sets
Setsare data structures,similartolistsordictionaries.
Theyare createdusingcurlybraces,or the set function.
num_set= {1, 2, 3, 4}
word_set= set(["spam","eggs"])
print(3innum_set) -> True
print("spam"notinword_set) -> False
To create an emptyset,youmust use set(),as{} createsan emptydictionary.
Setsare unordered,whichmeansthattheycan'tbe indexed.
Theycannot containduplicate elements.Due tothe waytheyare stored,itsfasterto check whetheran
itemispart of a set,ratherthan part of a list.
Insteadof usingappend() toadd to a set,use add()
The methodremove() removesaspecificelementfromaset, pop() removesanarbitraryelement.
Mathematical operations - union/intersection
Setscan be combinedusingmathematical operations.
22. Return values
def max(x,y):
if x >= y:
returnx
else:
returny
z = max(8,5)
print(z)
Docstrings
Unlike conventional comments,docstringsare retainedthroughoutthe runtime of the program.This
allowsthe programmedtoinspectthese commentsatruntime.
Modules
Modulesare piecesof code that otherpeople have writtentofulfill commontasks,suchasgenerating
randomnumbersetc.
Tryingto importa module thatisn'tavailable causesanImportError.
Usage: addimport module_name at the top of yourcode.And,access functions/variable using
module_name.var
Example:
importrandom
for i in range(5):
val = random.randint(1, 6)
print(val)
Import certainfunctions
from module_name import var
for mathimportpi
print(pi)
for mathimportpi,sqrt
print(sqrt(25))
Importa module underadifferentname using askeyword
frommath importsqrt as square_root
print(square_root(100))
Standard Library
3 typesof modules
23. 1. those you write yourself
2. those you install fromexternal sources
3. those are pre-installedwithpython -->Standardlibrary
Tasks that can be done by usingstandardlibraryinclude
stringparsing
data serialization
testing|debugging
manipulatingdates,emails
commandline argumentsandsoon.
Python'sextensive standardlibraryisone of itsmainstrengthsasa language.
ExceptionHandling
Exceptionsoccurwhensomethinggoeswrong,due toincorrectcode orinput.
Whenan exceptionoccurs,the programimmediatelystops.
Handle exceptions:use tryand exceptstatements. Useful whendealingwithuserinput.
The try blockcontainscode that mightthrow an exception.If thatexceptionoccurs,the code inthe try
blockstopsbeingexecuted,andthe code inthe exceptblockis run.If noerror occurs, the code in the
exceptblockdoesn'trun.
try:
num1 = 7
num2 = 0
print(num1/num2)
exceptZeroDivisionError:
print("Anerroroccurreddue to zerodivision")
except(ValueError,TypeError):
print("Erroroccurred")
An exceptstatementwithoutanyexceptionspecifiedwill catchall errors.
try:
print(7/0)
except:
print("erroroccurred")
finally:
print("Thiscode will runnomatterswhat")
The finallystatementalwaysrunsaftertry/exceptblocksevenincase of exception.
24. Raising exception
raise statementcanbe usedto raise exceptionandspecifythe type of exceptionraised. Youcanpass
argumentfordetails.
print(1)
raise ValueError
print(2)
raise NameError("Invalidname found")
Assertions
An Assertionisasanity-checkthatyoucan turnon or turn off whenyouhave finishedtestingthe
program.
An expression istested,andif the resultcomesupfalse,andexceptionisraised.
Programmers oftenplace assertionsatthe start of a functiontocheckfor validinput,andaftera
functioncall tocheck forvalidoutput.
print(1)
assert2 + 2 == 4
print(2)
assert1 + 1 == 3
print(3)
o/p:
1
2
AssertionError
The assert can take a secondsargument thatis passedtothe AssertionErrorraisedif the assertionfails.
temp= -10
assert(temp>= 0),"Colderthanabsolute Zero!"
o/p:AssertionError:Colderthanabsolute zero!
Files handling
Opening files - open()
myfle =open("filename.txt")
The argumentof the open() functionisthe pathto the file. Youcan specifythe mode usedtoopena file
by 2nd argument.
25. r : Openfile inreadmode,whichisthe default.
w : Write mode,forre-writingthe contentsof the file
a : Appendmode,foraddingnewcontent tothe endof the file
b : Openfile ina binarymode,usedfornon-textfiles(image/soundfiles)
myfile =open("filename.txt","a");
myfile.close()
Reading Files - read()
cont = myfile.read()
print(cont) ->will printall the contentsof the file.
Provide numberof bytesthatreadfromfile bypassingvalue tothe read()
print(myfile.read(10)) ->10 bytesread
Afterall contentsina file have beenread,anyattempttoreadfurtherfromthat file will returnan
emptystring,because youare tryingto read from the endof the file.
To retrieve eachline inafile,use readlines function.Itreturnalistin whicheachelementisaline inthe
file.
file =open("filename.txt","r")
print(file.readline())
file.close()
o/p:
['line1n','line2n','line3']
Writing Files - write()
write() - writesastringto the file. "w"mode will create afile if notexist. If exist,the contentsof the file
will be deleted.
write() returnsthe numberof byteswrittentothe file,if successful.
file =open("new.txt","w")
file.write("Writtingtothe file")
file.close()
file =open("new.txt","r")
print(file.read())
file.close()
with statement
It ismandatoryto close the file afterread/writingthe fileevenincase of exceptionoccur.
26. An alternative wayof doingthisisusingwithstatement.The fileisautomaticallyclosedatthe endof
the with statement,evenif exceptionoccurwithinit.
withopen("new.txt") asf:
print(f.read())
None
representsabsence of the value.
The None objectisreturnedbyany functionthatdoesn'texplicitlyreturnanythingelse.
def myfunc():
printf("Hi")
var = myfunc()
print(var)
o/p:
Hi
None
Dictionaries
Dictionariesare datastructuresusedtomap arbitrary keystovalues. {"Key":Value}.
Emptydictionaryis{}
Each elementinadictionaryisrepresentedby key:value pair
Dictionarykeyscanbe assignedtodifferentvalueslikelists.
Tryingto index akeythat isn'tpart of the dictionaryreturnsa KeyError.
primary= {
"red":[255, 0, 0],
"green":[0,255, 0],
"blue":[0,0, 255],
}
print(primary["red"]) -->[255, 0, 0]
primary["white"] =[200, 140, 100]
primary["blue"] =[0,0, 245]
print(primary["yellow"])-->KeyError:"yellow"
Dictionarycan store any type of data as Value.
Onlyimmutable objectscanbe usedas keystodictionaries.
27. List anddictionariesare mutable objectsandhence can'tbe usedas keysinthe dictionary.
bad_dict= {[1,2, 3]: "one twothree",}
TypeError: unhashable type:list
Dictionary Functions
Search
Use in andnot in
nums= {1: "one",2: "two",3: "three",}
print(1in nums) -> True
print(1not in nums) -> False
print(4not in nums) -> True
get()
Usedto get the valuesbyitsindex,butif the keyisnot found,itreturnsanotherspecificvalue(2nd
argument) instead(Nonebydefault).
pairs= {1: "apple","orange":[2,3], True:False,None:"True",}
print(pairs.get("orange"))->[2,3]
print(pairs.get(7)) ->None
print(pairs.get(1234,"Notfound")) ->Notfound
Tuples
Similartolists,exceptthattheyare immutable (theycan'tbe changed).Also,these are createdusing
parenthesis,ratherthansquare brackets.
words= () -> emptytuple
words= ("spam","eggs")
or
words= "spam","eggs"
Tuple unpacking
It allowsyoutoassigneach iteminan iterable toa variable.
Numbers= (1, 2 ,3)
a, b, c = numbers
print(a) ->1
print(b) ->2
28. Variable*
A variable thatisprefacedwithanasterisk(*) takesall valuesfromthe iterable thatare leftoverfrom
the othervariables
A,b, *c, d = [1, 2, 3, 4 ,5 ,6, 7]
print(a) -> 1
print(b) -> 2
print(c) ->[3, 4, 5, 6]
print(d) -> 7
Ternary operator
It takesthree arguments
Status= 1
msg = “Logout” if status ==1 else “Login”
print(msg) ->Logout
Higher order functions
Lambdas
Whenfunctionsare createdusing lambdasyntax thenthe functionsare notassignedtoany variable
unlike functionscreatednormallyusing def assignsittoa variable automatically.
Stringsand integerscanbe createdonthe fly,withoutassigningthemtoavariable. Similarly,functions
can be createdwithoutassigningthemtoanyvariable usinglambdakeyword.
def my_func(f,arg):
returnf(arg)
my_func(lambdax:2*x*x, 5)
Lambda functionsgettheirname fromlambdacalculus.
Lambda functionsare notpowerful asnamedfunctions.Theycanonlydothingsthatrequire asingle
expression - usuallyequivalenttoa single line of code.
#namedfunction
def polynomial(x):
returnx**2 + 5*x + 4
print(polynomial(-4))
29. #lambda
print(lambdax:x**2+ 5*x + 4, -4)
Lambda functionscanbe assignedtovariables, andusedlike anormal functions
double =lambdax: x * 2
print(double(4))
map and filter
map and filteroperate onlists(orsimilarobjectscalled itterables)
Maps Lambda
def add_five(x):
returnx+5
nums= [1, 2, 3, 4, 5]
result= list(map(add_five,nums))
print(result) -> [6, 7, 8, 9, 10]
Nums= [1, 2, 3, 4, 5]
result= list(map(lambdax:x+5,nums))
print(result) -> [6,7, 8, 9, 10]
The function filterfiltersaniterable byremovingitemsthatdon'tmatch a predicate
res= list(filter(lambdax:x%2==0, nums))
print(res) -> [2, 4]
Generators
Generatorsare a type of iterable,likelistsortuples.
Unlike lists,theydon'tallowindexingwitharbitraryindices,buttheycanstill be iteratedthroughwith
for loops.
Generatorscan be createdusingfunctionsandthe yieldstatement.
def countdown():
i=5
while i>0:
yieldi
i- = 1
for i in countdown():
print(i)
o/p: 5 4 3 2 1
Yieldstatementisusedtodefine agenerator,replacingthe returnof afunctionto provide aresulttoits
calledwithoutdestroyinglocal variables.
30. Due to the fact thatthey yieldone itemat a time,generatorsdon'thave the memoryrestrictionsof lists.
In fact,theycan be infinite.
In short, generatorsallowsyouto declare afunction that behaveslikeaniteratori.e.itcanbe usedina
for loop.
def infinite_sevens():
while True:
yield7
for i in infinite_sevens():
print(i)
Finite generatorscanbe convertedintolistsbypassingthemasargumentstothe listfunction.Using
generatorsresultsinimprovedperformance,whichisthe resultsof the lazygenerationof values,which
translatestolowermemoryusage.Furthermore,we donotneedtowaituntil all the elementshave
beengeneratedbefore we starttouse them.
def numbers(x):
for i in range(x):
if i%2 == 0:
yieldi
print(list(numbers(11))) -> o/P:[0, 2, 4, 6, 8, 10]
Decorators
Providesawayto modifyfunctionsusingotherfunctions.
Thisis ideal whenyouneedtoextendthe functionalityof functionsthatyoudon't wantto modify.
def decor(func):
def wrap():
print("=====")
func()
print("=====")
returnwrap
def print_text():
print("Hello")
decorated= decor(print_text)
decorated()
def print_text():
print("hello")
print_text= decor(print_text)
@decor
def print_text():
print("Hello")
31. Object Oriented Programming
Classes
3 paradigmsof programming
1. Imperative - usingstatements,loops,andfunctionsassubroutines
2. Functional - usingpure functions,higherorderfunctions,andrecursion
3. ObjectOrientedprogramming(OOP)
Objectsare createdusingclasses,whichare actuallythe focal pointof OOP.
A Classcan be describedasan object'sblueprint,description,ordefinition.Same classcanbe usedfor
creatingmultiple differentobjects.
class Cat:
def __init__(self,color,legs):
self.color=color
self.legs=legs
def bark(self):
print("woof")
felix =Cat("ginger",4)
rover= Cat("dog-colored",4)
stumpy= Cat("brown",3)
__init__
Calledwhenaninstance (object)of the classiscreated,usingthe classname as function.
All methodsmusthave self astheirfirstparameter,althoughitisn'texplicitlypassed,pythonaddsthe
self argumenttothe listforyou; youdo not needtoinclude itwhenyoucall the methods.
The __init__ methodis calledthe classconstructor.
Methods
Definedtoaddfunctionalitytothem.
Inheritance
Inheritance providesawayto share functionalityb/w calsses.
classAnimal:
def __init__(self,name,color):
self.name =name
self.color=color
classCat(Animal):
def purr(self):
print("Purr..")
32. classDog(Animal):
def bark(self):
print("woof")
super().purr()
classRed_dog(Dog):
def sec_method(self):
print("secondmethod")
A classthat inheritsfromanotherclassiscalledasubclass.
A classthat is inheritedfromiscalledasuperclass.
If a classinheritsfromanotherwiththe same attributesormethods,itoverridesthem.
Super function
The function superis a useful inheritance relatedfunctionthatreferstothe parentclass.
Magic Methods
These are special methodswhicha double underscores at the beginningandendof theirnames.They
are alsoknown as dunders.
One commonuse of themis operator overloading.
Operator overloading
__add__ for + __truediv__for / __floordiv__for// __mod__ for%
__sub__ for- __and__ for & __pow__ for ** __xor__ for^ __or__ for |
classVector2D:
def __init__(self,x,y):
self.x =x
self.y=y
def __add__(self,other):
returnVector2D(self.x +other.x,self.y+other.y)
first= Vector2D(5,7)
sec = Vector2D(12, 9)
result= first+ sec
__lt__ for< __le__ for <= __eq__ for== __ne__ for!= __gt__ for > __ge__ for>=
Object Lifecycle
Made up of creation,manipulationanddestruction.
33. Garbage collection
The processof deletingobjectswhentheyare nolongerneedediscalled garbage collection.
Whenan object'sreference countreachesZero,pythonautomaticallydeletesit.
Data Hiding
A keypart of OOP is encapsulation, whichinvolvespackagingof relatedvariablesandfunctionsinto
single easy-to-useobject- an instance of a class.
A relatedconceptis data hiding,whichstatesthat implementationdetailsof aclassshouldbe hidden,
and a cleanstandardinterface be presentedforthose whowantto use the class.
Thiswill be done usingprivate methodsattributesinotherprogramminglanguage.
In python,there are noways of enforcingamethodor attribute be strictlyprivate.
Weeklyprivate methodsandattributeshave a single underscore atthe beginning.
Stronglyprivate methodsandattributeshave a double underscore atthe beginning.
Class methods
Classmethodsare calledbya class,whichis passedtothe cls parameterof the method.
classRectangle:
def __init__(self,width,height):
self.width=width
self.height=height
def calculate_area(self):
returnself.width*self.height
@classmethod
def new_square(cls,side_length):
returncls(side_length,side_length)
square = Rectangle.new_square(5)
print(sqaure.calculate_area())
Note:Technically,the parameters self andclsare just conventions;theycouldbe changedtoanything
else.
Static methods
These are similartoclass methods,excepttheydon'treceive anyadditional arguments;theyare
identical tonormal functionsthatbelongstoaclass.
Theyare markedwiththe staticmethod
classPizza:
def __init__(self,toppings):
34. self.toppings=toppings
@staticmethod
def validate_topping(topping):
if topping== "pineapple":
raise ValueError("NoPineaaple")
else:
returnTrue
ingredients=["cheese","onions","spam"]
if all(Pizza.validate_topping(i) fori iningredients):
pizza= Pizza(ingredients)
Staticmethodsbehave like plainfunctions,exceptforthe factthat youcan call themfrom an instance of
the class.
Properties
Propertiesprovide awayof customizingaccesstoinstance attributes.
Theyare createdbyputtingthe property decoratorabove a method,whichmeanswhenthe instance
attribute withthe same name as the methodisaccessed,the methodwillbe calledinstead.
One commonuse of a propertyisto make an attribute read-only.
classPizza:
def __init__(self,toppings):
self.toppings=toppings
@property
def pineapple_allowed(self):
returnFalse
@pineapple_allowed.setter
def pineapple_allowed(sefl,value):
if value:
pwd= input("Enterpassword")
if pwd== "admin"
self._pineapple_allowed=value
else
raise ValueError("Alert..Intruder")
pizza= Pizza(["cheese","tomoto"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed=True
o/p:
False
AttributeError:can'tset attribute -->If setterisnot defined
35. Enter password:admin
True
Propertiescanalsobe setby defining setter/getterfunctions.
The setterfunctionsetsthe correspondingpropery'svalue.
The gettergetsthe value.
Regular Expressions
RegularExpressionsare powerful tool forvariouskindsof stringmanipulation.
Matching pattern
Standardlibraryisre.
Needtoimportit andcall the belowfunction.
Importre
re.match(“spam”,“eggsspam”) ->Not found
re.search(“spam”, “eggsspam”) ->Found
re.findall(“spam”,“eggsspam”) ->[‘spam’]
Search() Findsa match of a patternanywhere inthe string
Match() Looksat the beginningof the stringonly
Findall() Returnsa listof all substringsthatmatch a pattern
Finditer() Doesthe same thingas findall() exceptitreturns
an iterator,ratherthan a list
re.search()
The search returnsan objectwithseveral methodsthatgive detailsaboutit.These methodsinclude
group() whichreturnsstringmatched, start() andend() whichreturnthe start and endingpositionsof
the match, and span() whichreturnsthe start and endpositionsasa tuple.
Importre
pattern= r”pam”
match = re.search(pattern,“eggspamsausage”)
if match:
print(match.group())
print(match.start())
print(match.end())
print(match.span())
36. o/p:
pam
4
7
(4, 7)
re.sub() - search & replace
sub() methodreplacesall occurrencesof the patterninstringwithreplace string,substitutingall
occurrences,unlessmax provided.
re.sub(pattern,repl,string,max=0)
importre
str = “My name is David.Hi David”
pattern= r”David”
newstr= re.sub(pattern,“Raj”,str)
print(newstr) -> My name isRaj. Hi Raj.
Metacharacters
Allowsustocreate regularexpressiontorepresentconceptslike “one ormore” repetitionsofa vowel.
. (dot)character
Thismatchesany character, otherthan a new line.
Importre
pattern= r”gr.y”
if re.match(pattern,“grey”):
print(“Match1”)
^ and $ - start and end
Thismatchesthe start and endof a string.
Patter= r”^gr.y$”
re.match(pattern,“grey”) ->True
re.match(pattern,“spamgrey”) ->False
Character classes
Provide away to matchonlyone of a specificsetof characters.
A character classis createdbyputtingthe characters itmatchesinside square brackets.
Pattern= r”[aeiou]
re.search(pattern, “grey”) - > True
re.search(pattern,“myths”) - > False
37. Supportsrange of charactersalso.
[a-z]-> matchesanylowercase alphabeticcharacter
[G-P]-> matchesanyuppercase characterfrom G to P
[0-9]
[A-Za-z]
^ character
Place a ^ at the start of a character class toinvert it.
Pattern= r”[^A-Z]”
re.search(“Hi Raj”) ->True
re.search(“HIRAJ”) ->False
More Metacharacters
* character
Zeroor more repetitions
+ character
One or more repetitions
? character
Zeroor one repetitions
Curlybraces
Usedto representthe numberof repetitionsb/w twonumbers.
Pattern= r”9{1, 3}$”
Re.match(pattern,“9”) ->True
re.match(pattern,“999”) -> True
re.match(pattern,“9999”) -> False
Groups
A groupcan be createdbysurroundingpartof a regularexpressionwith parenthesis.
Thismeansthat a group can be givenas an argument to metacharacterssuchas * and?
Pattern= r”egg(spam)*”
re.match(pattern,egg) ->True
re.match(pattern,spam) ->False
The contentsof groupsina matchcan be accessedusingthe group function.
A call of group(0) or group() returnsthe whole match.
A call of group(n),where nisthe greaterthan 0, returnsthe nthgroup fromthe left.
38. Pattern= r”a(bc)(de)(f(g)h)I”
match = re.match(pattern,“abcdefghijklmnop”)
if match:
Print(match.group())->abcdefghi
print(match.group(0)) ->abcdefghi
print(match.group(1)) ->bc
print(match.group(2)) ->de
print(match.groups()) ->(‘bc’,‘de’,‘fgh’,‘g’)
| character
Means or.
Pattern= r”gr(a|e)y”
re.match(pattern,“grey”) ->True
Named groups
Namedgroupshave format (?P<name>…),where name isthe name of the group, … isthe content.
Theybehave exactlysame asthe normal groupsexcepttheycanbe accessedby group(name) in
additiontoitsnumber.
Pattern= r”(?P<first>abc)(?:def)(ghi)”
match = re.match(pattern,“abcdefghi”)
if match:
Print(match.group(“first”)) ->abc
print(match.groups()) ->(‘abc’,‘ghi’)
Non-capturinggroups have the format (?:…).Theyare not accessible bythe groupmethods,sotheycan
be addedto an existingregularexpressionwithoutbreakingthe numbering.See above.
Special Sequences
number - Backslash
Thismatchesthe expressionof the groupof that number. 1to 99 allowed.
Pattern= r”(.+) 1”
re.match(pattern,“wordword”) ->True
re.match(pattern,“abccde”) ->False
Note:“(.+) 1” isnot the same as “(.+) (.+)”.Because, 1refersto the firstgroup’ssubexpression,which
isthe matchedexpressionitself,andnotthe regularexpressionpattern.
39. d and D sequence
d – matchesthe digits.
D – matchesanythingthatisn’t a digit
Pattern= r”(D+d)”
re.match(pattern,“Hi 999”) -> True
s and S sequence
s – matchesthe white spaces.
S – matchesanythingthatisn’t a white space
Pattern= r”(S+s)”
re.match(pattern,“Hi ”) -> True
w and W sequence
d – matchesthe wordcharacters.
D – matchesanythingthatisn’t a word character
A Sequence
The sequences A andZ match the beginningandendof astring,respectively.
b sequence
It matchesthe emptystringb/w wand W characters, or w characters and the beginningorendof the
string.
Informally,itrepresentsthe boundaryb/w words.
Pattern= r”b(cat)b”
re.search(pattern,“The catsat!” -> True
re.search(pattern,“we scattered”) ->False
“b(cat)b”basicallymatchesthe word“cat”surroundedbywordboundaries.
Email extraction
To extractemail like [email protected] fromtext,use below pattern
Pattern= r”([w.-]+)@([w.-])(.[w.]+)”
[w.-] ->matchesone or more wordcharacter, dot or dash
Str = “Please [email protected] forassistance”
match = re.search(pattern,str)
if match:
40. print(match.group())
o/p:[email protected]
Pythonicness & Packaging
Importthis module printsthe Zenof Pythonwhenimported.
There are 20 principlesinthe Zenof Python,butonly19 linesof test.The 20th
principle isamatterof
opinion,butourinterpretationisthatthe blankline means“Use white spaces”
PEP-PythonEnhancement Proposals
PEP are suggestionsforimprovementstothe language,made byexperiencedPythondevelopers.
PEP8 is a style guide onthe subjectof writingreadablecode.
- Modulesshouldhave short,all lowercase names
- Classnamesshould be inCapWordsstyle
- Most variablesandfunctionnamesshouldbe lowercase withunderscores
- Constantsshouldbe CAPSWITH UNDERSCORES
- Namesthatwouldclashwithpythinkeywordshouldhave atrailingunderscore.
- Linesshouldn’tbe longerthan80 characters
- “from module import*”shouldbe avoided
- There shouldbe onlybe one statementperline
Packaging
Referstoputtingmodulesyouhave writteninastandardformat,so that otherprogrammerscaninstall
and use themwithease.Thisinvolvesuse of the modules setuptoolsanddisutils.
Place all the filesyouwantto putin a libraryinthe same parentdirectory.Thisdirectoryshouldalso
containa file called __init__.py,whichcan be blankbut mustbe presentinthe directory.
Thisdirectorygoesintothe otherdirectorywhichwill have readme andlicense,aswell asan important
file called setup.py
Sololearn/
License.txt
Readme.txt
Setup.py
Sololearn/
__init__.py
sololearn.py
sololearn2.py
41. Setup.py
Thiscontainsinformationnecessarytoassemble the package soitcan be uploadedto PyPIand istalled
withpip
From disutils.core importsetup
Setup(
name=”Sololearn”,
version=’0.1dev’,
packages=[‘sololearn’,],
license=’MIT’,
long_description=open(‘README.txt’).read(),
)
To builda source distribution
python setup.pysdist
To builda binarydistribution
python setup.pybdist
To uploadpackage
python setup.pyregister
pythin setup.pysdistupload
Install apackage with pythonsetup.pyinstall
Packaging for Users
Py2exe tool can be usedtopackage a pythonscript,alongwithlibrariesitrequires,intoasingle
executable.
PyInstallerand cx_Freeze serve the same purpose.
Function arguments
Pythonallowstohave functionwithvaryingnumberof arguments.
*args
Using*args as a functionparameterenablesyoutopassan arbitrarynumberof argumentsto that
function.The argumentsare thenaccessible asthe tuple argsinthe bodyof the function.
Def function(named_arg,*arg):
print(named_arg)
print(args)
Function(1,2,3, 4, 5)
42. o/p:
1
(2, 3, 4, 5)
The parameter*args must come afterthe namesparameterstoa function.The name argsis justa
convention;youcanchoose to use another.
**kwargs – keyword arguments
Thisallowsyouto handle namedargumentsthatyouhave notdefinedinadvance.
The keywordargumentsreturnsadictionary,inwhichthe keysare the argumentnames, andthe values
are the argumentvalues.
Def my_func(x,y=7,*args, **kwargs):
print(kwargs)
My_func(2,3, 4, 5, 6, a=7, b=8)
o/P:
{‘a’:7, ‘b’:8}
The argumentsreturnedbythe **kwargs are notincludedin*args.
Major 3rd party libraries
Django
The most frequentlyusedwebframeworkwritteninPython,itpowerswebsitesthatincludeInstagram
and Dicqus.
CherryPy and Flask
Are alsopopularwebframeworks
BeautifulSoup
It isveryuseful,andleadstobetterresultsforscrappingdatafromwebsites.
Matplotlib
Allowsyoutocreate a graph basedon data inpython
NumPy
It allowsforthe use of multidimentional arraysthatare much fasterthan native pythonsolutionof
nestedlists.
43. SciPy
Containsnumerousextensionstothe functionalityof NumPy
Panda3D
For 3D games
Pygame for2D games
List Vs Dictionary Vs Tuples Vs Sets
Lists Sets Dictionaries Tuples
List = [10, 12, 15] Set= {1, 23, 34}
Print(set) ->{1,
23,24}
Set= {1, 1}
print(set) ->{1}
Dict = {"Ram": 26, "mary":
24}
Words = ("spam",
"egss")
Or
Words = "spam",
"eggs"
Access:print(list[0]) Print(set).
Setelementscan't
be indexed.
print(dict["ram"]) Print(words[0])
List[0] = 100 Setelementscan't
be indexed.So,use
add()
Set.add(7)
Dict["Ram"] = 27 Words[0] = "care" ->
TypeError
Mutable Mutable Mutable Immutable - Values
can't be changedonce
assigned
List = [] Set= set() Dict = {} Words = ()
Fasterthan listsbut
theycan't be changed.
Slicingcanbe done
print(list[1:2]) ->[12]
Notdone. Slicingcanalsobe
done on tuples
Can't contain
duplicate elements.
Use listsif youhave a
collectionof datathat
doesn'tneedrandom
access.
Use listswhenyouneed
a simple,iterable
collectionthatis
modifiedfrequently.
- Membership
testingandthe
eliminationof
duplicate entries.
- whenyouneed
uniquenessforthe
elements.
- Whenyouneeda logical
associationb/w key:value
pair.
- whenyouneedfast
lookupforyourdata, based
on a customkey.
- whenyourdata isbeing
constantlymodified.
Use tupleswhenyour
data cannot change.
A tuple isusedin
comibnationwitha
dictionary,for
example,atuple might
representakey,
because its
immutable.
44. itertools -standard library
The module itertoolsisastandardlibrary.Itproducesinfiniteiterators.
count():counts upinfinitelyfromavalue
cycle():infinitelyiteratesthroughaniterable (alistora string)
repeat():repeatsanobjects,eitherinfinitelyoraspecifiednumberof times.
fromitertoolsimportcount
for i in count(3):
print(i)
if i >= 11:
break
PythonVs C
C language Pythonlanguage
Special operators(++and --) works
I.e.a++; --a;
It doesn'tsupport++ and --.Throws Syntax error.
Each statementinC endswithsemicolon; No use of ; here.
Curlybracesare usedto delimitblocksof code
If (condition)
{
Statement1;
Statement2;
}
It useswhite spacesforthispurpose
If condition:
Statement1
Statement2
Example:
If 10 > 5:
print("10 isgreaterthan 5")
if 10 > 9:
print("10isgreaterthan 9")
else:
print("5is greaterthan10")
Compilingthe programbefore executionis
mandatory
Pythonprogramdirectlyexecuted byusing
interpreter. Nocompilerhere.
Booleanoperatorsare && and || and! Booleanoperatorsare and, or and not
Uses // for one line comment
Uses /* */ for multiple line comment
Uses # for one line comment
Uses """ """ for multi line comments (Docstrings).
Uses #include toimportstandardlibraryfunctions
#include<stdio.h>
Uses importkeywordtoinclude standardlibrary
functions
Importmath
Voidassert(intexpression)
Expression -Thiscanbe a variable orany C
expression.If expressionevaluatestoTRUE,
assert() doesnothing.If expressionevaluatesto
FALSE,assert() displaysanerrormessage
on stderr(standarderrorstreamto displayerror
assertexpression
Example
assert1 + 1 == 3
45. messagesanddiagnostics) andabortsprogram
execution.
NULL None - representsabsence of value
Don't have automaticmemorymanagement. AutomaticGarbage collection.
Web scraping: webbrowser library
https://automatetheboringstuff.com/chapter11/
Webscrapingis the term forusinga program to downloadandprocesscontentfromthe Web.For
example,Googlerunsmanywebscrapingprogramsto index webpagesforitssearchengine.
webbrowser. Comes with Python and opens a browser to a specific page.
Webbrowser.open()
webbrowser.open(url,new=0,autoraise=True)
Displayurl usingthe defaultbrowser.If new is0,the url is openedinthe same browserwindow if
possible.If newis1,a newbrowserwindow isopenedif possible.If new is2, a new browserpage
(“tab”) is openedif possible.If autoraise isTrue,the window israisedif possible (notethatundermany
windowmanagersthiswill occurregardlessof the settingof thisvariable).
Note that onsome platforms,tryingtoopena filename usingthisfunction,mayworkandstart the
operatingsystem’sassociatedprogram.However,thisisneithersupportednorportable.
webbrowser.open_new(url)
Openurl in a newwindowof the defaultbrowser,if possible,otherwise,openurl inthe onlybrowser
window.
webbrowser.open_new_tab(url)
Openurl in a newpage (“tab”) of the defaultbrowser,if possible,otherwise equivalenttoopen_new().
webbrowser.get([name])
Returna controllerobjectforthe browsertype name.If name isempty,returna controllerfora default
browserappropriate tothe caller’senvironment.
import webbrowser
url = 'http://idiotinside.com'
# Open URL in new browser window
webbrowser.open_new(url) # opens in default browser
# Opens in safari browser
webbrowser.get('safari').open_new(url)
# Open URL in a new tab
46. webbrowser.open_new_tab(url) # opens in default browser
# Opens in safari browser
webbrowser.get('safari').open_new_tab(url)
Type Name Class Name Notes
'mozilla' Mozilla('mozilla')
'firefox' Mozilla('mozilla')
'netscape' Mozilla('netscape')
'galeon' Galeon('galeon')
'epiphany' Galeon('epiphany')
'skipstone' BackgroundBrowser('skipstone')
'kfmclient' Konqueror() (1)
'konqueror' Konqueror() (1)
'kfm' Konqueror() (1)
'mosaic' BackgroundBrowser('mosaic')
'opera' Opera()
'grail' Grail()
'links' GenericBrowser('links')
'elinks' Elinks('elinks')
'lynx' GenericBrowser('lynx')
'w3m' GenericBrowser('w3m')
'windows-default' WindowsDefault (2)
'macosx' MacOSX('default') (3)
47. Type Name Class Name Notes
'safari' MacOSX('safari') (3)
'google-chrome' Chrome('google-chrome') (4)
'chrome' Chrome('chrome') (4)
'chromium' Chromium('chromium') (4)
'chromium-browser' Chromium('chromium-browser') (4)