Functions, Exception, Modules and Files
Functions: Difference between a Function and a Method, Defining a Function, Calling a Function, Returning Results from a Function, Returning Multiple Values from a Function, Functions are First Class Objects, Pass by Object Reference, Formal and Actual Arguments, Positional Arguments, Keyword Arguments, Default Arguments, Variable Length Arguments, Local and Global Variables, The Global Keyword, Passing a Group of Elements to a Function, Recursive Functions, Anonymous Functions or Lambdas (Using Lambdas with filter() Function, Using Lambdas with map() Function, Using Lambdas with reduce() Function), Function Decorators, Generators, Structured Programming, Creating our Own Modules in Python, The Special Variable __name__
Exceptions: Errors in a Python Program (Compile-Time Errors, Runtime Errors, Logical Errors),Exceptions, Exception Handling, Types of Exceptions, The Except Block, The assert Statement, UserDefined Exceptions, Logging the Exceptions
20%
Files: Files, Types of Files in Python, Opening a File, Closing a File, Working with Text Files Containing Strings, Knowing Whether a File Exists or Not, Working with Binary Files, The with Statement, Pickle in Python, The seek() and tell() Methods, Random Accessing of Binary Files, Random Accessing of Binary Files using mmap, Zipping and Unzipping Files, Working with Directories, Running Other Programs from Python Program
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the instance of the class.
Here is a Python class with the specifications provided in the question:
class PICTURE:
def __init__(self, pno, category, location):
self.pno = pno
self.category = category
self.location = location
def FixLocation(self, new_location):
self.location = new_location
This defines a PICTURE class with three instance attributes - pno, category and location as specified in the question. It also defines a FixLocation method to assign a new location as required.
Modules allow grouping of related functions and code into reusable files. Packages are groups of modules that provide related functionality. There are several ways to import modules and their contents using import and from statements. The document provides examples of creating modules and packages in Python and importing from them.
Basic Python Programming: Part 01 and Part 02Fariz Darari
This document discusses basic Python programming concepts including strings, functions, conditionals, loops, imports and recursion. It begins with examples of printing strings, taking user input, and calculating areas of shapes. It then covers variables and data types, operators, conditional statements, loops, functions, imports, strings, and recursion. Examples are provided throughout to demonstrate each concept.
YouTube Link: https://youtu.be/WvhQhj4n6b8
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'What is Python?' will help you understand and learn python programming language with its features. It is one of the most widely adopted programming language in the industry currently. Below are the topics covered in this Python Programming tutorial
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
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
Castbox: https://castbox.fm/networks/505?country=in
Files allow data to be permanently stored and accessed by programs. Basic file operations include opening, reading, writing, and closing files. To open a file, its name and access mode are passed to the fopen function, which returns a file pointer used for subsequent read/write operations. Characters can be read from and written to files using functions like getc and putc. Command line arguments passed when a program launches are accessible through the argc and argv parameters of the main function.
Python modules allow code reuse and organization. A module is a Python file with a .py extension that contains functions and other objects. Modules can be imported and their contents accessed using dot notation. Modules have a __name__ variable that is set to the module name when imported but is set to "__main__" when the file is executed as a script. Packages are collections of modules organized into directories, with each directory being a package. The Python path defines locations where modules can be found during imports.
This document provides an overview of object-oriented programming (OOP) including:
- The history and key concepts of OOP like classes, objects, inheritance, polymorphism, and encapsulation.
- Popular OOP languages like C++, Java, and Python.
- Differences between procedural and OOP like top-down design and modularity.
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the instance of the class.
Here is a Python class with the specifications provided in the question:
class PICTURE:
def __init__(self, pno, category, location):
self.pno = pno
self.category = category
self.location = location
def FixLocation(self, new_location):
self.location = new_location
This defines a PICTURE class with three instance attributes - pno, category and location as specified in the question. It also defines a FixLocation method to assign a new location as required.
Modules allow grouping of related functions and code into reusable files. Packages are groups of modules that provide related functionality. There are several ways to import modules and their contents using import and from statements. The document provides examples of creating modules and packages in Python and importing from them.
Basic Python Programming: Part 01 and Part 02Fariz Darari
This document discusses basic Python programming concepts including strings, functions, conditionals, loops, imports and recursion. It begins with examples of printing strings, taking user input, and calculating areas of shapes. It then covers variables and data types, operators, conditional statements, loops, functions, imports, strings, and recursion. Examples are provided throughout to demonstrate each concept.
YouTube Link: https://youtu.be/WvhQhj4n6b8
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'What is Python?' will help you understand and learn python programming language with its features. It is one of the most widely adopted programming language in the industry currently. Below are the topics covered in this Python Programming tutorial
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
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
Castbox: https://castbox.fm/networks/505?country=in
Files allow data to be permanently stored and accessed by programs. Basic file operations include opening, reading, writing, and closing files. To open a file, its name and access mode are passed to the fopen function, which returns a file pointer used for subsequent read/write operations. Characters can be read from and written to files using functions like getc and putc. Command line arguments passed when a program launches are accessible through the argc and argv parameters of the main function.
Python modules allow code reuse and organization. A module is a Python file with a .py extension that contains functions and other objects. Modules can be imported and their contents accessed using dot notation. Modules have a __name__ variable that is set to the module name when imported but is set to "__main__" when the file is executed as a script. Packages are collections of modules organized into directories, with each directory being a package. The Python path defines locations where modules can be found during imports.
This document provides an overview of object-oriented programming (OOP) including:
- The history and key concepts of OOP like classes, objects, inheritance, polymorphism, and encapsulation.
- Popular OOP languages like C++, Java, and Python.
- Differences between procedural and OOP like top-down design and modularity.
This document discusses Python namespaces and modules. It explains that namespaces prevent name conflicts and modules are the basic unit of code reuse. Functions, classes, and modules each have their own namespace. Importing modules adds their names to the global namespace. The document recommends importing modules using 'import' to avoid potential name conflicts or namespace pollution. It also describes how scopes resolve which definition to use when the same name is defined in multiple scopes.
The document discusses various concepts related to functions in Python including defining functions, passing arguments, default arguments, arbitrary argument lists, lambda expressions, function annotations, and documentation strings. Functions provide modularity and code reusability. Arguments can be passed by value or reference and default values are evaluated once. Keyword, arbitrary and unpacked arguments allow flexible calling. Lambda expressions define small anonymous functions. Annotations provide type metadata and docstrings document functions.
Youtube Link: https://youtu.be/woVJ4N5nl_s
** Python Certification Training: https://www.edureka.co/data-science-python-certification-course **
This Edureka PPT on 'Python Basics' will help you understand what exactly makes Python special and covers all the basics of Python programming along with examples.
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
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
Castbox: https://castbox.fm/networks/505?country=in
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on Python Functions tutorial covers all the important aspects of functions in Python right from the introduction to what functions are, all the way till checking out the major functions and using the code-first approach to understand them better.
Agenda
Why use Functions?
What are the Functions?
Types of Python Functions
Built-in Functions in Python
User-defined Functions in Python
Python Lambda Function
Conclusion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
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
Class, object and inheritance in pythonSantosh Verma
The document discusses object-oriented programming concepts in Python, including classes, objects, methods, inheritance, and the built-in __init__ method. Classes are created using the class keyword and contain attributes and methods. Methods must have a self parameter, which refers to the instance of the class. The __init__ method is similar to a constructor and is called when an object is instantiated. Inheritance allows one class to inherit attributes and methods from another class.
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
( Python Training : https://www.edureka.co/python )
This Edureka Python Class tutorial (Python Tutorial Blog: https://goo.gl/wd28Zr) will help you understand Python Classes and Objects with examples. It will also explain the concept of Abstract Classes and Inheritance in python.
Check out our Python Training Playlist: https://goo.gl/Na1p9G
This Python Programming tutorial video helps you to learn following topics:
1. Python Classes and Objects
2. Inheritance
3. Abstract Classes
Python functions allow for reusable code through defining functions, passing arguments, returning values, and setting scopes. Functions can take positional or keyword arguments, as well as variable length arguments. Default arguments allow functions to specify default values for optional parameters. Functions are objects that can be assigned to variables and referenced later.
This document provides an introduction to the Python programming language. It discusses Python's design philosophy emphasizing readability. It also covers printing messages, reading input, variables and data types, operators, and basic syntax like comments and identifiers. Arithmetic, relational, logical and bitwise operators are explained along with examples.
File handling in C programming uses file streams as the means of communication between programs and data files. The input stream extracts data from files and supplies it to the program, while the output stream stores data from the program into files. To handle file input/output, header file fstream.h is included, which contains ifstream and ofstream classes. Common file operations include opening, reading, writing, and closing files using functions like fopen(), fgetc(), fputs(), fclose(), and checking for end-of-file conditions. Files can be opened in different modes like read, write, append depending on the operation to be performed.
The document provides an introduction to Python programming including its features, uses, history, and installation process. Some key points covered include:
- Python is an interpreted, object-oriented programming language that is used for web development, scientific computing, and desktop applications.
- It was created by Guido van Rossum in 1991 and named after the Monty Python comedy group.
- To install Python on Windows, users download the latest version from python.org and run the installer, which also installs the IDLE development environment.
- The document then covers basic Python concepts like variables, data types, operators, and input/output functions.
This document provides an overview of object-oriented programming concepts including classes, objects, inheritance, abstraction, encapsulation, and polymorphism. It defines OOP as an engineering approach for building software systems based on modeling real-world entities as classes and objects that exchange messages. Key concepts are explained such as classes defining attributes and behaviors of objects, objects being instances of classes, and communication between objects occurring through messages. The four main principles of OOP - inheritance, abstraction, encapsulation, and polymorphism - are also summarized.
This document provides an introduction to the Python programming language. It covers Python's background, syntax, types, operators, control flow, functions, classes, tools, and IDEs. Key points include that Python is a multi-purpose, object-oriented language that is interpreted, strongly and dynamically typed. It focuses on readability and has a huge library of modules. Popular Python IDEs include Emacs, Vim, Komodo, PyCharm, and Eclipse.
This document discusses classes, objects, and inheritance in Python. It defines a class as a blueprint for creating objects, with objects being instances of a class. It describes how to define a class in Python using the class keyword and how to create object instances from a class. The document also explains inheritance in Python, where a derived or child class can inherit attributes and methods from a parent or base class, allowing for single, multiple, multilevel, hybrid and hierarchical inheritance.
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.
Header files in C contain function declarations and macros that can be included in C programs using the #include preprocessor directive. Common header files like stdio.h provide input/output functions, conio.h provides console input/output functions, and math.h provides mathematics functions. Other header files provide functions for strings, date/time, memory allocation, and other general utilities. Header files allow code to be reused across programs and abstraction of platform-specific details.
This document summarizes Week 3 of a Python programming course. It discusses introspection, which allows code to examine and manipulate other code as objects. It covers optional and named function arguments, built-in functions like type and str, and filtering lists with comprehensions. It also explains lambda functions and how and and or work in Python.
The document provides an introduction to the Python programming language. It discusses what Python is, its creator Guido van Rossum, and how to write a simple "Hello World" program. It also covers Python data types, operators, flow control using conditionals and loops, functions, input/output operations, and the Zen of Python philosophy guiding Python's design. The document serves as the first day of instruction in a Python course.
This document discusses Python namespaces and modules. It explains that namespaces prevent name conflicts and modules are the basic unit of code reuse. Functions, classes, and modules each have their own namespace. Importing modules adds their names to the global namespace. The document recommends importing modules using 'import' to avoid potential name conflicts or namespace pollution. It also describes how scopes resolve which definition to use when the same name is defined in multiple scopes.
The document discusses various concepts related to functions in Python including defining functions, passing arguments, default arguments, arbitrary argument lists, lambda expressions, function annotations, and documentation strings. Functions provide modularity and code reusability. Arguments can be passed by value or reference and default values are evaluated once. Keyword, arbitrary and unpacked arguments allow flexible calling. Lambda expressions define small anonymous functions. Annotations provide type metadata and docstrings document functions.
Youtube Link: https://youtu.be/woVJ4N5nl_s
** Python Certification Training: https://www.edureka.co/data-science-python-certification-course **
This Edureka PPT on 'Python Basics' will help you understand what exactly makes Python special and covers all the basics of Python programming along with examples.
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
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
Castbox: https://castbox.fm/networks/505?country=in
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on Python Functions tutorial covers all the important aspects of functions in Python right from the introduction to what functions are, all the way till checking out the major functions and using the code-first approach to understand them better.
Agenda
Why use Functions?
What are the Functions?
Types of Python Functions
Built-in Functions in Python
User-defined Functions in Python
Python Lambda Function
Conclusion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
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
Class, object and inheritance in pythonSantosh Verma
The document discusses object-oriented programming concepts in Python, including classes, objects, methods, inheritance, and the built-in __init__ method. Classes are created using the class keyword and contain attributes and methods. Methods must have a self parameter, which refers to the instance of the class. The __init__ method is similar to a constructor and is called when an object is instantiated. Inheritance allows one class to inherit attributes and methods from another class.
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
( Python Training : https://www.edureka.co/python )
This Edureka Python Class tutorial (Python Tutorial Blog: https://goo.gl/wd28Zr) will help you understand Python Classes and Objects with examples. It will also explain the concept of Abstract Classes and Inheritance in python.
Check out our Python Training Playlist: https://goo.gl/Na1p9G
This Python Programming tutorial video helps you to learn following topics:
1. Python Classes and Objects
2. Inheritance
3. Abstract Classes
Python functions allow for reusable code through defining functions, passing arguments, returning values, and setting scopes. Functions can take positional or keyword arguments, as well as variable length arguments. Default arguments allow functions to specify default values for optional parameters. Functions are objects that can be assigned to variables and referenced later.
This document provides an introduction to the Python programming language. It discusses Python's design philosophy emphasizing readability. It also covers printing messages, reading input, variables and data types, operators, and basic syntax like comments and identifiers. Arithmetic, relational, logical and bitwise operators are explained along with examples.
File handling in C programming uses file streams as the means of communication between programs and data files. The input stream extracts data from files and supplies it to the program, while the output stream stores data from the program into files. To handle file input/output, header file fstream.h is included, which contains ifstream and ofstream classes. Common file operations include opening, reading, writing, and closing files using functions like fopen(), fgetc(), fputs(), fclose(), and checking for end-of-file conditions. Files can be opened in different modes like read, write, append depending on the operation to be performed.
The document provides an introduction to Python programming including its features, uses, history, and installation process. Some key points covered include:
- Python is an interpreted, object-oriented programming language that is used for web development, scientific computing, and desktop applications.
- It was created by Guido van Rossum in 1991 and named after the Monty Python comedy group.
- To install Python on Windows, users download the latest version from python.org and run the installer, which also installs the IDLE development environment.
- The document then covers basic Python concepts like variables, data types, operators, and input/output functions.
This document provides an overview of object-oriented programming concepts including classes, objects, inheritance, abstraction, encapsulation, and polymorphism. It defines OOP as an engineering approach for building software systems based on modeling real-world entities as classes and objects that exchange messages. Key concepts are explained such as classes defining attributes and behaviors of objects, objects being instances of classes, and communication between objects occurring through messages. The four main principles of OOP - inheritance, abstraction, encapsulation, and polymorphism - are also summarized.
This document provides an introduction to the Python programming language. It covers Python's background, syntax, types, operators, control flow, functions, classes, tools, and IDEs. Key points include that Python is a multi-purpose, object-oriented language that is interpreted, strongly and dynamically typed. It focuses on readability and has a huge library of modules. Popular Python IDEs include Emacs, Vim, Komodo, PyCharm, and Eclipse.
This document discusses classes, objects, and inheritance in Python. It defines a class as a blueprint for creating objects, with objects being instances of a class. It describes how to define a class in Python using the class keyword and how to create object instances from a class. The document also explains inheritance in Python, where a derived or child class can inherit attributes and methods from a parent or base class, allowing for single, multiple, multilevel, hybrid and hierarchical inheritance.
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.
Header files in C contain function declarations and macros that can be included in C programs using the #include preprocessor directive. Common header files like stdio.h provide input/output functions, conio.h provides console input/output functions, and math.h provides mathematics functions. Other header files provide functions for strings, date/time, memory allocation, and other general utilities. Header files allow code to be reused across programs and abstraction of platform-specific details.
This document summarizes Week 3 of a Python programming course. It discusses introspection, which allows code to examine and manipulate other code as objects. It covers optional and named function arguments, built-in functions like type and str, and filtering lists with comprehensions. It also explains lambda functions and how and and or work in Python.
The document provides an introduction to the Python programming language. It discusses what Python is, its creator Guido van Rossum, and how to write a simple "Hello World" program. It also covers Python data types, operators, flow control using conditionals and loops, functions, input/output operations, and the Zen of Python philosophy guiding Python's design. The document serves as the first day of instruction in a Python course.
This presentation covers a detailed overview of python advanced concepts. it covers the below aspects.
Comprehensions
Lambda with (map, filter and reduce)
Context managers
Iterator, Generators, Decorators
Python GIL and multiprocessing and multithreading
Python WSGI
Python Unittests
This presentation about Python Interview Questions will help you crack your next Python interview with ease. The video includes interview questions on Numbers, lists, tuples, arrays, functions, regular expressions, strings, and files. We also look into concepts such as multithreading, deep copy, and shallow copy, pickling and unpickling. This video also covers Python libraries such as matplotlib, pandas, numpy,scikit and the programming paradigms followed by Python. It also covers Python library interview questions, libraries such as matplotlib, pandas, numpy and scikit. This video is ideal for both beginners as well as experienced professionals who are appearing for Python programming job interviews. Learn what are the most important Python interview questions and answers and know what will set you apart in the interview process.
Simplilearn’s Python Training Course is an all-inclusive program that will introduce you to the Python development language and expose you to the essentials of object-oriented programming, web development with Django and game development. Python has surpassed Java as the top language used to introduce U.S. students to programming and computer science. This course will give you hands-on development experience and prepare you for a career as a professional Python programmer.
What is this course about?
The All-in-One Python course enables you to become a professional Python programmer. Any aspiring programmer can learn Python from the basics and go on to master web development & game development in Python. Gain hands on experience creating a flappy bird game clone & website functionalities in Python.
What are the course objectives?
By the end of this online Python training course, you will be able to:
1. Internalize the concepts & constructs of Python
2. Learn to create your own Python programs
3. Master Python Django & advanced web development in Python
4. Master PyGame & game development in Python
5. Create a flappy bird game clone
The Python training course is recommended for:
1. Any aspiring programmer can take up this bundle to master Python
2. Any aspiring web developer or game developer can take up this bundle to meet their training needs
Learn more at https://www.simplilearn.com/mobile-and-software-development/python-development-training
The document discusses functions in Python. It defines what functions are, how to define functions, pass arguments to functions, return values from functions, and scope of objects in functions. It covers built-in functions, when to write your own functions, and different types of arguments like required arguments, keyword arguments, default arguments, and variable-length arguments. It also discusses how functions communicate with their environment through parameters and arguments, and pass-by-reference vs pass-by-value in Python functions.
Functions allow programmers to organize code into reusable blocks. A function is defined using the def keyword and can accept parameters. The body of a function contains a set of statements that run when the function is called. Functions can return values and allow code to be reused, reducing errors and improving readability. Parameters allow information to be passed into functions, while return values allow functions to provide results.
The document outlines an advanced Python course covering various Python concepts like object orientation, comprehensions, extended arguments, closures, decorators, generators, context managers, classmethods, inheritance, encapsulation, operator overloading, and Python packages. The course agenda includes how everything in Python is an object, comprehension syntax, *args and **kwargs, closures and decorators, generators and iterators, context managers, staticmethods and classmethods, inheritance and encapsulation, operator overloading, and Python package layout.
The document discusses functions, modules, and how to modularize Python programs. It provides examples of defining functions, using parameters, returning values, and function scope. It also discusses creating modules, importing modules, and the difference between running a Python file as a module versus running it as the main script using the __name__ == "__main__" check. The key points are that functions help break programs into reusable and readable components, modules further help organize code, and the __name__ check allows code to run differently depending on how it is imported or run directly.
This document discusses functions in Python. It begins by defining what a function is and provides examples of built-in functions and functions defined in modules. It then lists some advantages of using functions such as code reusability and readability. The document discusses the different types of functions - built-in functions, functions defined in modules, and user-defined functions. It provides examples of each type. The document also covers topics such as function parameters, return values, variable scope, lambda functions, and using functions from libraries.
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Python
Language
is uesd in engineeringStory adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
Story adapted from Stephen Covey (2004) “The Seven Habits of Highly Effective People” Simon & Schuster).
“Management is doing things right, leadership is doing the right things”
(Warren Bennis and Peter Drucker)
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they should believe the change is really going to happen.
The decision maker:
Leaders usually control resources such as people, budgets, and equipment, and thus have the authority to make decisions (as per their span of control) that affect the initiative.
During change, leaders must leverage their decision-making authority and choose the options that will support the initiative.
The Decision-Maker is decisive and sets priorities that support change.
The Sponsor:
Champion and advocates for the change at their level in the organization.
A Sponsor is the person who won’t let the change initiative die from lack of attention, and is willing to use their political capital to make the change happen
The Role model:
Behaviors and attitudes demonstrated by them are looked upon by everyone else. . Hence, they must be willing to go first.
Employees watch leaders for consistency between words and actions to see if they s
This document contains notes from a Python class covering functions, lists, strings, and their methods. It discusses built-in functions like len(), range(), and type conversions. It also covers control flow structures like if/else, for loops, exceptions, modules, and functions in more detail including defining functions, parameters, arguments, returning values, docstring, and variable scopes. Assignments include writing functions to process lists and check for palindromes in strings.
These questions will be a bit advanced level 2sadhana312471
These questions will be a bit advanced(Intermediate) in terms of Python interview.
This is the continuity of Nail the Python Interview Questions.
The fields that these questions will help you in are:
• Python Developer
• Data Analyst
• Research Analyst
• Data Scientist
This document discusses Python functions, including built-in functions, defining custom functions, parameters, arguments, return values, and more. Some key points:
- Functions allow storing and reusing code through definition and invocation.
- Built-in functions like print() come with Python, while custom functions are defined using def and def keywords.
- Parameters receive arguments passed to functions, and allow code within a function to access values from a particular call.
- Functions can return values using the return statement. Functions that produce results are called "fruitful," while those that don't are "void."
- Functions help organize code into logical, reusable blocks and avoid repetition. They can also break complex
The document provides an introduction to programming in Python. It discusses how Python can be used for web development, desktop applications, data science, machine learning, and more. It also covers executing Python programs, reading keyboard input, decision making and loops in Python, standard data types like numbers, strings, lists, tuples and dictionaries. Additionally, it describes functions, opening and reading/writing files, regular expressions, and provides examples of SQLite database connections in Python projects.
An Overview Of Python With Functional ProgrammingAdam Getchell
This document provides an overview of the Python programming language and its capabilities for functional programming. It describes Python's attributes such as being portable, object-oriented, and supporting procedural, object-oriented, and functional programming. It also lists several popular Python modules that provide additional functionality and examples of code written in both a procedural and object-oriented style in Python. Finally, it provides examples of functional programming concepts like map, filter and reduce implemented in Python along with references for further information.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and optionally returning values. Strings are sequences of characters that can be manipulated using indexes and methods. Common string methods include upper() and concatenation using +.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then gives the code to the processor to execute. Functions allow code to be reused by defining operations and returning values. Strings are sequences of characters that can be manipulated using indexes and methods. Common string methods include upper() and concatenation using +.
A program is a sequence of instructions that are run by the processor. To run a program, it must be compiled into binary code and given to the operating system. The OS then tells the processor to execute the program. Functions allow code to be reused by defining operations that take in arguments and return values. Strings are sequences of characters that can be accessed by index and manipulated with methods like upper() that return new strings.
Similar to PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BORSANIYA (20)
Dragon Fruit Nutrition Facts include sour and refreshing. They are fleshy enough to impart a luxurious and sophisticated taste. The dragon fruits cultivate better in a soil rich in vermicompost or the potting soil mixture.
REs and Python: Regular Expressions, Sequence Characters in Regular Expressions, Quantifiers in Regular Expressions, Special Characters in Regular Expressions, Using Regular Expressions on Files, Retrieving Information from a HTML File
Threading : Concurrent Programming and GIL, Uses of Threads, Creating Threads in Python, Thread Class Methods, Single Tasking using a Thread, Multitasking using Multiple Threads, Thread Synchronization Deadlock of Threads, Avoiding Deadlocks in a Program, Communication between Threads, Thread Communication using notify() and wait() Methods, Thread Communication using a Queue, Daemon Threads
Networking: Protocol, Sockets, Knowing IP Address, URL, Reading the Source Code of a Web Page, Downloading a Web Page from Internet, Downloading an Image from Internet, A TCP/IP Server, A TCP/IP Client, A UDP Server, A UDP Client, File Server, File Client, Two-Way Communication between Server and Client, Sending a Simple Mail,
This document provides an overview of GUI and Tkinter in Python. It discusses:
- Tkinter is the most commonly used method for developing GUI applications in Python as it is bundled with Python and offers a simple interface.
- The main components of a Tkinter application include importing Tkinter, creating a main window container, adding widgets to the window, and applying events to widgets.
- Common widgets like Button, Canvas, Checkbutton, Entry, Label, Menu, Radiobutton, Scale, Text, Spinbox are explained along with examples of how to create and use them.
- Geometry managers like pack, grid, place are discussed which control widget layout within their parent window.
- The mainloop method is used
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYAMaulik Borsaniya
This document discusses data visualization and Matplotlib. It begins with an introduction to data visualization and its importance. It then covers basic visualization rules like labeling axes and adding titles. It discusses what Matplotlib is and how to install it. It provides examples of common plot types in Matplotlib like sine waves, scatter plots, bar charts, and pie charts. It also discusses working with data science and Pandas, including how to create Pandas Series and DataFrames from various data sources.
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
Classes and Object-oriented Programming:
Classes: Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
Inheritance and Polymorphism: Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
Abstract Classes and Interfaces: Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces,
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAMaulik Borsaniya
Introduction to Python:
The basic elements of Python, Objects, expressions and numerical Types, Variables and assignments, IDLE, Branching programs, Strings and Input, Iteration
Structured Types, Mutability and Higher-order Functions:
Tuples, Lists and Mutability, Functions as Objects, Strings, Tuples and Lists, Dictionaries
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
“An Outlook of the Ongoing and Future Relationship between Blockchain Technologies and Process-aware Information Systems.” Invited talk at the joint workshop on Blockchain for Information Systems (BC4IS) and Blockchain for Trusted Data Sharing (B4TDS), co-located with with the 36th International Conference on Advanced Information Systems Engineering (CAiSE), 3 June 2024, Limassol, Cyprus.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
1. A function is a block of organized, reusable code that
is used to perform a single, related action.
Functions provide better modularity for your
application and a high degree of code reusing.
Function
Defining a Function
You can define functions to provide the required functionality. Here are
simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
The code block within every function starts with a colon (:) and is
indented.
The statement return [expression] exits a function,
Maulik Borsaniya - Gardividyapith
2. User Defining Function
• Simple function
def my_function():
print("Hello from a function")
my_function()
• Parameterized Function
Def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
• Return Value
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Maulik Borsaniya - Gardividyapith
8. ABS()
integer = -20
print('Absolute value of -20 is:',abs(integer))
Chr()
print(chr(97))
print(chr(65))
Max & Min
# using max(arg1, arg2, *args)
print('Maximum is:', max(1, 3, 2, 10, 4))
# using min(iterable)
num = [1, 3, 2, 8, 5, 10, 6]
print('Maximum is:', min(num))
Maulik Borsaniya - Gardividyapith
9. Method
• Python has some list methods that you can use
to perform frequency occurring task (related to
list) with ease. For example, if you want to add
element to a list, you can use append() method.
Simple Example
animal = ['cat', 'dog', 'rabbit']
animal.append('pig')
#Updated Animal List
print('Updated animal list: ',
animal)
• Eg-1 Eg-2
numbers = [2.5, 3, 4, -5]
numbersSum = sum(numbers)
print(numbersSum)
Maulik Borsaniya - Gardividyapith
12. Difference Between method and function
Python Method
• Method is called by its name, but it is associated to an object (dependent).
• A method is implicitly passed the object on which it is invoked.
• It may or may not return any data.
• A method can operate on the data (instance variables) that is contained by
the corresponding class
Functions
• Function is block of code that is also called by its name. (independent)
• The function can have different parameters or may not have any at all. If any
data (parameters) are passed, they are passed explicitly.
• It may or may not return any data.
• Function does not deal with Class and its instance concept.
Maulik Borsaniya - Gardividyapith
13. # Basic Python method
class class_name
def method_name () :
......
# method body
#Function Syntex
def function_name ( arg1, arg2, ...) :
......
# function body
......
Maulik Borsaniya - Gardividyapith
14. Lambda
• A lambda function is a small anonymous
function.
• A lambda function can take any number of
arguments, but can only have one expression.
Syntax
• lambda arguments : expression
• Eg.1 x = lambda a : a + 10
print(x(5))
• Eg.2 x = lambda a, b : a * b
print(x(5, 6))
Maulik Borsaniya - Gardividyapith
15. Why Use Lambda Functions?
The power of lambda is better shown when you use them as
an anonymous function inside another function.
Say you have a function definition that takes one argument,
and that argument will be multiplied with an unknown
number.
• Eg.
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
print(mydoubler(10))
Maulik Borsaniya - Gardividyapith
16. Filter With Lambda
• The filter() function in Python takes in a function and a list
as arguments.
• The function is called with all the items in the list and a new
list is returned which contains items for which the function
evaluates to True.
• Here is an example use of filter() function to filter out only
even numbers from a list.
• Eg.1
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Maulik Borsaniya - Gardividyapith
17. Map With Lambda
• The map() function in Python takes in a function and
a list.
• The function is called with all the items in the list and
a new list is returned which contains items returned
by that function for each item.
• Here is an example use of map() function to double
all the items in a list.
• Eg.1
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
Maulik Borsaniya - Gardividyapith
18. Creating our own module
1) Hello.py
# Define a function
def world():
print("Hello, World!")
2) Main.py
# Import hello module
import hello
# Call function
hello.world()
print(hello.variable)
variable = "Sammy"
Maulik Borsaniya - Gardividyapith
19. Exception Handling
• An exception is an event, which occurs during
the execution of a program that disrupts the
normal flow of the program's instructions. In
general, when a Python script encounters a
situation that it cannot cope with, it raises an
exception. An exception is a Python object
that represents an error.
• When a Python script raises an exception, it
must either handle the exception immediately
otherwise it terminates and quits.(there are
many built in exception is there)Maulik Borsaniya - Gardividyapith
20. Syntax
try:
You do your operations here;
......................
except Exception 1:
If there is Exception 1, then execute this block.
…………………….
except Exception 2:
If there is Exception 2, then execute this block.
......................
else:
If there is no exception then execute this block.
finally :
This would always be executed
Maulik Borsaniya - Gardividyapith
21. • Example
try:
fh = open("asd.txt", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can't find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Finally:
Print “wow Yaar !! You wrotted hainn !”
Maulik Borsaniya - Gardividyapith
22. Exception Handling With Assert Statement
• Syntex : assert
expression, argument,
messag
Eg . assert 2 + 2 == 4
assert 2 + 3 == 3, ’’error is
here’’
Eg.2
def avg(marks):
assert len(marks) != 0,"List is
empty.“
return sum(marks)/len(marks)
mark2 = [55,88,78,90,79]
print("Average of
mark2:",avg(mark2))
mark1 = []
print("Average of
mark1:",avg(mark1))
• Python has built-in assert
statement to use assertion
condition in the program.
• assert statement has a
condition or expression which
is supposed to be always true.
• If the condition is
false assert halts the program
and gives an AssertionError.
Maulik Borsaniya - Gardividyapith
23. User Define Exception
class Error(Exception):
"""Base class for other
exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is
too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is
too large"""
pass
# our main program
# user guesses a number until
he/she gets it right
# you need to guess this number
number = 10
while True:
try:
i_num = int(input("Enter a
number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try
again!")
print()
except ValueTooLargeError:
print("This value is too large, try
again!")
print()
print("Congratulations! You guessed
it correctly.")
Maulik Borsaniya - Gardividyapith
24. • File Handling
The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
• "r" - Read - Default value. Opens a file for reading, error if the file
does not exist
• "a" - Append - Opens a file for appending, creates the file if it does
not exist
• "w" - Write - Opens a file for writing, creates the file if it does not
exist
• "x" - Create - Creates the specified file, returns an error if the file
exists
Maulik Borsaniya - Gardividyapith
25. DemoFile.txt
• Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
Python file read
f = open("demofile.txt", "r")
print(f.read())
#print(f.readline())
append
f = open("demofile.txt", "a")
f.write("Now the file has one more line!")
Write
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
Maulik Borsaniya - Gardividyapith
26. Remove file
import os
if os.path.exists(“demofile"):
os.remove(“demofile")
else:
print("The file does not exist")
Maulik Borsaniya - Gardividyapith
27. File Positions
• The tell() method tells you the current position within
the file; in other words, the next read or write will
occur at that many bytes from the beginning of the file.
• The seek(offset[, from]) method changes the current
file position. The offset argument indicates the number
of bytes to be moved. The from argument specifies the
reference position from where the bytes are to be
moved.
• If from is set to 0, it means use the beginning of the file
as the reference position and 1 means use the current
position as the reference position and if it is set to 2
then the end of the file would be taken as the
reference position.
Maulik Borsaniya - Gardividyapith
28. • # Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
Maulik Borsaniya - Gardividyapith
29. Sr.No. Modes & Description
1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
2 rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is
the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the
file.
5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file
for writing.
Maulik Borsaniya - Gardividyapith
30. 6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new file for writing.
10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist, it creates a new file for reading and
writing.
12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
Maulik Borsaniya - Gardividyapith
31. Running Other Programs from Python
Program – Windows python
• import os
• command = "cmd"
• os.system(command)
Maulik Borsaniya - Gardividyapith
32. Python For Loops
• A for loop is used for iterating over a sequence (that is
either a list, a tuple or a string).
• This is less like the for keyword in other programming
language, and works more like an iterator method as found
in other object-orientated programming languages.
• With the for loop we can execute a set of statements, once
for each item in a list, tuple, set etc.
Example
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Maulik Borsaniya - Gardividyapith
33. • fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
• for x in range(2, 30, 3):
print(x)
• i = 1
while i < 6:
print(i)
i += 1
Maulik Borsaniya - Gardividyapith