Table of Contents
Python With Joe 🐍 - Your Journey to Python Mastery¶
📖 Overview¶
Welcome to Python With Joe, a comprehensive learning resource carefully curated and presented by Joseph, a DataCamp Python Data Associate Certified professional and a passionate student at Graphic Era Hill University, specializing in AI, Cyber Security, and Data Science.
This repository is designed to provide an accessible, structured, and engaging learning path for anyone seeking to master Python programming. Whether you're taking your first steps in programming or looking to deepen your Python expertise, this resource offers interactive notebooks, practical examples, and clear explanations that make learning both effective and enjoyable.
🌍 Multilingual Support¶
This documentation is available in three languages, making Python learning accessible to a broader audience:
| Language | Documentation | Description |
|---|---|---|
| 🇬🇧 English | View English Version | Complete English documentation |
| 🇲🇲 Myanmar | View Myanmar Version | Myanmar language documentation (မြန်မာဘာသာ) |
| 🦜 Hakha Chin | View Hakha Chin Version | Hakha Chin language documentation |
Chapter Availability¶
Currently available chapters in multiple languages: - Chapters 1-9: Available in English and Hakha Chin - Chapter 27: Available in all three languages (English, Myanmar, Hakha Chin)
[!NOTE] More chapters are being progressively translated into all three languages. Stay tuned for updates!
🚀 What You Will Learn¶
This comprehensive guide covers everything from fundamentals to advanced concepts:
- Core Fundamentals: Master variables, data types, loops, and functions
- Control Flow: Understand decision-making and repetition in code
- Data Structures: Build efficient solutions with Python's powerful lists, dictionaries, and sets
- Object-Oriented Programming: Dive deep into classes, inheritance, and design patterns
- File Handling & Exceptions: Learn robust error handling and file operations
- Advanced Python: Explore decorators, generators, context managers, and more
- Scientific Computing: High-performance numerical operations with NumPy
- Modern Best Practices: Write clean, efficient, and Pythonic code
📚 Repository Contents¶
This repository provides a rich learning experience through:
- Interactive Jupyter Notebooks: Hands-on chapters with executable code examples
- Chapter-wise Organization: Structured progression through Python concepts
- Practical Examples: Real-world code snippets and exercises
- Clear Explanations: Detailed commentary and concept breakdowns
Available Chapters¶
| Chapter | Topic | Description |
|---|---|---|
| Chapter 1 | Introduction to Python | Discover Python's history, popularity, and programming paradigms. Learn why Python is the language of choice for developers worldwide and explore functional, procedural, object-oriented, and event-driven programming models. |
| Chapter 2 | Python Basics | Master the fundamentals including variables, data types, operators, and expressions. Build a solid foundation for your Python journey. |
| Chapter 3 | Input and Output | Learn effective techniques for taking user input and displaying output. Understand formatting options and best practices for user interaction. |
| Chapter 4 | Strings | Deep dive into text processing with string creation, slicing, formatting, and powerful built-in methods. Master string manipulation techniques essential for real-world applications. |
| Chapter 5 | Decision Control | Make your programs intelligent with if, if-else, and elif statements. Learn to implement conditional logic and decision-making in your code. |
| Chapter 6 | Repetition Control | Automate repetitive tasks with for and while loops. Master iteration techniques and loop control statements for efficient programming. |
| Chapter 7 | Functions | Write modular, reusable code with functions. Understand parameters, return values, scope, and advanced function concepts. |
| Chapter 8 | Lists | Explore Python's most versatile data structure. Learn list operations, methods, slicing, and implement stack and queue data structures. |
| Chapter 9 | Advanced Topics | Dive into more sophisticated Python concepts and techniques to elevate your programming skills. |
| Chapter 27 | NumPy & Advanced Concepts | Master scientific computing with NumPy for high-performance numerical operations. Explore advanced Python features including decorators, generators, context managers, and techniques for building robust, production-ready applications. |
[!NOTE] More chapters are being progressively added and translated into multiple languages. Each chapter includes practical examples, exercises, and real-world applications to reinforce your learning!
🎯 Target Audience¶
This repository is perfect for:
- 🌱 Beginners starting their Python programming journey
- 🎓 Students seeking to strengthen their Python fundamentals
- 💼 Developers preparing for technical interviews
- 🔄 Career Switchers looking for structured learning materials
- 🚀 Enthusiasts who want to build real-world projects with Python
🛠️ Getting Started¶
Prerequisites¶
- Python 3.7 or higher
- Jupyter Notebook
- Basic understanding of programming concepts (helpful but not required)
Installation¶
-
Clone the repository
-
Install dependencies
-
Launch Jupyter Notebook
-
Navigate and Learn
- Open chapter notebooks to explore specific topics
- Execute code cells to see examples in action
- Study explanations and concepts at your own pace
View Online Documentation¶
Prefer reading online? Visit our beautifully formatted documentation site:
🌐 https://rose1996iv.github.io/PythonWithJoe/
Or run the docs locally:
Then open http://127.0.0.1:8000 in your browser.
📘 About the Resources¶
"Python With Joe" is a comprehensive guide that has helped thousands of learners master Python programming. The 5th Edition covers modern Python practices and includes:
- Clear, beginner-friendly explanations
- Progressive difficulty levels
- Extensive code examples
- Practice exercises and challenges
- Real-world application scenarios
Resources: Yashavant Kanetkar, Aditya Kanetkar, DataCamp, Python notes from GoalKicker
Curated by: Joseph
🤝 Contributing¶
Your contributions make this resource better for everyone! We welcome:
- 📝 Content Improvements: Clarifications, additional examples, or corrections
- 🐛 Bug Reports: Found an error? Let us know!
- 💡 Suggestions: Ideas for new chapters or topics
- 🌟 Enhancements: Better explanations or code optimizations
How to contribute:
- Fork the repository
- Create a new branch (
git checkout -b feature/amazing-improvement) - Make your changes
- Commit with clear messages (
git commit -m "Add detailed explanation for decorators") - Push to your branch (
git push origin feature/amazing-improvement) - Open a Pull Request
📞 Contact & Support¶
Have questions or feedback? We'd love to hear from you!
- 🐛 Issues: Open an issue
- 💬 Discussions: Share your learning journey
- 📧 Repository: PythonWithJoe
📄 License¶
This repository is licensed under the MIT License - see the LICENSE file for details.
⚠️ Disclaimer¶
This repository contains educational materials for learning purposes only. The content is curated from various resources including "Python With Joe" (5th Edition) by Yashavant Kanetkar and Aditya Kanetkar, DataCamp courses, and GoalKicker Python notes. For complete and original content, please refer to the respective official sources.
Happy Learning! 🐍✨
Embark on your Python journey today and transform from a beginner to a confident developer!
Last Updated: January 3, 2026
🇬🇧 English
Python Mastery 🐍 - Your Journey from Zero to Hero¶
📖 Overview¶
Welcome to Python Mastery, a comprehensive learning resource carefully curated and presented by Joseph, a DataCamp Python Data Associate Certified professional and a passionate student at Graphic Era Hill University, specializing in AI, Cyber Security, and Data Science.
This repository is designed to provide an accessible, structured, and engaging learning path for anyone seeking to master Python programming. Whether you're taking your first steps in programming or looking to deepen your Python expertise, this resource offers interactive notebooks, practical examples, and clear explanations that make learning both effective and enjoyable.
🚀 What You Will Learn¶
This comprehensive guide covers everything from fundamentals to advanced concepts:
- Core Fundamentals: Master variables, data types, loops, and functions.
- Control Flow: Understand how to make decisions and repeat actions in code.
- Data Structures: Build efficient solutions with Python's powerful lists, dictionaries, and sets.
- Modern Best Practices: Write clean, efficient, and Pythonic code.
- Scientific Computing: Introduction to powerful libraries like NumPy.
📚 Repository Contents¶
This repository provides a rich learning experience through:
- Interactive Jupyter Notebooks: Hands-on chapters with executable code examples.
- Chapter-wise Organization: Structured progression through Python concepts.
- Practical Examples: Real-world code snippets and exercises.
- Clear Explanations: Detailed commentary and concept breakdowns.
Available Chapters¶
| Chapter | Topic | Description |
|---|---|---|
| Chapter 1 | Introduction to Python | Discover Python's history, popularity, and programming paradigms. Learn why Python is the language of choice for developers worldwide and explore functional, procedural, object-oriented, and event-driven programming models. |
| Chapter 2 | Python Basics | Master the fundamentals including variables, data types, operators, and expressions. Build a solid foundation for your Python journey. |
| Chapter 3 | Input and Output | Learn effective techniques for taking user input and displaying output. Understand formatting options and best practices for user interaction. |
| Chapter 4 | Strings | Deep dive into text processing with string creation, slicing, formatting, and powerful built-in methods. Master string manipulation techniques essential for real-world applications. |
| Chapter 5 | Decision Control | Make your programs intelligent with if, if-else, and elif statements. Learn to implement conditional logic and decision-making in your code. |
| Chapter 6 | Repetition Control | Automate repetitive tasks with for and while loops. Master iteration techniques and loop control statements for efficient programming. |
| Chapter 7 | Functions | Write modular, reusable code with functions. Understand parameters, return values, scope, and advanced function concepts. |
| Chapter 8 | Lists | Explore Python's most versatile data structure. Learn list operations, methods, slicing, and implement stack and queue data structures. |
| Chapter 9 | Advanced Topics | Dive into more sophisticated Python concepts and techniques to elevate your programming skills. |
| Chapter 27 | NumPy & Advanced Concepts | Master scientific computing with NumPy for high-performance numerical operations. Explore advanced Python features including decorators, generators, context managers, and techniques for building robust, production-ready applications. |
[!NOTE] More chapters are being progressively added. Each chapter includes practical examples, exercises, and real-world applications to reinforce your learning!
🎯 Target Audience¶
This repository is perfect for:
- 🌱 Beginners starting their Python programming journey.
- 🎓 Students seeking to strengthen their Python fundamentals.
- 💼 Developers preparing for technical interviews.
- 🔄 Career Switchers looking for structured learning materials.
- 🚀 Enthusiasts who want to build real-world projects.
🛠️ Getting Started¶
Prerequisites¶
- Python 3.7 or higher
- Jupyter Notebook
- Basic understanding of programming concepts (helpful but not required)
Installation¶
-
Clone the repository
git clone https://github.com/rose1996iv/PythonWithJoe.git cd PythonWithJoe
-
Install dependencies
-
Launch Jupyter Notebook
-
Navigate and Learn
- Open chapter notebooks to explore specific topics.
- Execute code cells to see examples in action.
- Study explanations and concepts at your own pace.
View Online Documentation¶
Prefer reading online? Visit our beautifully formatted documentation site:
🌐 https://rose1996iv.github.io/PythonWithJoe/
Or run the docs locally:
Then open http://127.0.0.1:8000 in your browser.
📘 About the Book¶
"Python With Joe" is a comprehensive guide that has helped thousands of learners master Python programming. The 5th Edition covers modern Python practices and includes:
- Clear, beginner-friendly explanations
- Progressive difficulty levels
- Extensive code examples
- Practice exercises and challenges
- Real-world application scenarios
Resources: Yashavant Kanetkar, Aditya Kanetkar, DataCamp, Python notes from GoalKicker Curated by: Joseph
🤝 Contributing¶
Your contributions make this resource better for everyone! We welcome:
- 📝 Content Improvements: Clarifications, additional examples, or corrections
- 🐛 Bug Reports: Found an error? Let us know!
- 💡 Suggestions: Ideas for new chapters or topics
- 🌟 Enhancements: Better explanations or code optimizations
How to contribute:
- Fork the repository
- Create a new branch (
git checkout -b feature/amazing-improvement) - Make your changes
- Commit with clear messages (
git commit -m "Add detailed explanation for decorators") - Push to your branch (
git push origin feature/amazing-improvement) - Open a Pull Request
📞 Contact & Support¶
Have questions or feedback? We'd love to hear from you!
- 🐛 Issues: Open an issue
- 💬 Discussions: Share your learning journey
- 📧 Repository: PythonWithJoe
📄 License¶
This repository is licensed under the MIT License - see the LICENSE file for details.
Happy Learning! 🐍✨
Embark on your Python journey today and transform from a beginner to a confident developer!
Last Updated: December 11, 2025
Chapter 1 Introduction To Python¶
Keynote¶
1.1 What is Python?¶
- Python is a high-level programming language created by Guido Van Rossum - fondly known as Benevolent Dictator For Life.
- Python was first released in 1991. Today Python interpreters are available for many Operating Systems including Windows and Linux.
- Python programmers are often called Pythonists or Pythonistas.
1.2 Reasons for Popularity¶
There are several reasons for Python's popularity. Some of them are: (a) Free:
- Python is free to use and distribute and is supported by community.
- Python interpreter is available for every major platform.
(b) Software quality:
- Better than traditional and scripting languages.
- Readable code, hence reusable and maintainable.
- Support for advance reuse mechanisms.
© Developer productivity:
- Much better than statically typed languages.
- Much smaller code.
- Less to type, debug and maintain.
- No lengthy compile and link steps.
(d) Program portability:
- Python programs run unchanged on most platforms.
- Python runs on every major platform currently in use.
- Porting program to a new platform usually need only cut and paste. This is true even for GUI, DB access, Web programming, OS interfacing, Directory access, etc.
(e) Support libraries:
- Strong library support from Text pattern matching to networking.
- Vast collection of third party libraries.
- Libraries for Web site construction, Numeric programming, Game development, Machine Learning etc.
(f) Component integration:
- Can invoke C, C++ libraries and Java components.
- Can communicate with frameworks such as COM, .NET.
- Can interact over networks with interfaces like SOAP, XML-RPC, CORBA.
- With appropriate glue code, Python can subclass C++, Java, C# classes, thereby extending the reach of the program.
- Popularly used for product customization and extension.
(g) Enjoyment:
- Ease of use.
- Built-in toolset.
- Programming becomes pleasure than work.
1.3 What sets Python apart?¶
(a) Powerful:
- Dynamic typing.
- No variable declaration.
- Automatic allocation and Garbage Collection.
- Supports classes, modules and exceptions.
- Permits componentization and reuse.
- Powerful containers - Lists, Dictionaries, Tuples, etc.
(b) Ready-made stuff:
- Support for operations like joining, slicing, sorting, mapping, etc.
- Powerful library.
- Large collection of third-party utilities.
© Ease of use:
- Type and run.
- No compile and link steps.
- Interactive programming experience.
- Rapid turnaround.
- Programs are simpler, smaller and more flexible.
1.4 Where is Python used?¶
Python is used for multiple purposes. These include:
- a. System programming
- b. Building GUI applications
- c. Internet scripting
- d. Component integration
- e. Database programming
- f. Rapid prototyping
- g. Numeric and Scientific programming
- h. Game programming
- i. Robotics programming
1.5 Who uses Python today?¶
Many organizations use Python for varied purposes. These include:
- a. Google - In web search system
- b. YouTube - Video Sharing service
- c. Bit-torrent - Peer to Peer file sharing system
- d. Intel, HP, Seagate, IBM, Qualcomm - Hardware testing
- e. Pixar, Industrial Light and Magic - Movie animation
- f. JP Morgan, Chase, UBS - Financial market forecasting
- g. NASA, FermiLab - Scientific programming
- h. iRobot - Commercial robot vacuum cleaners
- i. NSA - Cryptographic and Intelligence analysis
- j. IronPort - Email Servers
1.6 Programming Paradigms¶
- Paradigm means organization principle. It is also known as model.
- Programming paradigm/model is a style of building the structure and elements of computer programs.
- There exist many programming models like Functional, Procedural, Object-oriented, Event-driven, etc.
- Many languages facilitate programming in one or more paradigms. For example, Python supports Functional, Procedural, Object-oriented and Event-driven programming models.
- There are situations when Functional programming is the obvious choice, and other situations were Procedural programming is the better choice.
- Paradigms are not meant to be mutually exclusive. A single program may use multiple paradigms.
1.6.1 Functional Programming Model¶
- Functional programming decomposes a problem into a set of functions. These functions provide the main source of logic in the program.
- Functions take input parameters and produce outputs. Python provides functional programming techniques like lambda, map, reduce and filter. These are discussed in Chapter 15.
- In this model computation is treated as evaluation of mathematical functions. For example, to get factorial value of a number, or nth Fibonacci number we can use the following functions:
factorial(n) = 1 if n == 0
= n * factorial(n - 1) if n > 0
fibo(n) = 0 if n = 0
= 1 if n = 1
= fibo(n - 2) + fibo(n - 1) if n > 1
- The output value of a function depends only on its arguments, so calling a function with the same value for an argument always produces the same result. As a result, it is a good fit for parallel execution.
- No function can have side effects on other variables (state remains unaltered).
- Functional programming model is often called a 'Declarative' programming paradigm as programming is done with expressions or declarations instead of statements.
1.6.2 Procedural Programming Model¶
Procedural programming decomposes a problem into a set of procedures. These procedures provide the main source of logic in the program. Procedures take input parameters and produce outputs. Python provides procedural programming techniques like functions, classes, modules, etc. These are discussed in Chapter 15. In this model computation is treated as evaluation of procedures. For example, to get factorial value of a number, or nth Fibonacci number we can use the following procedures:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def fibo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibo(n - 2) + fibo(n - 1)
The output value of a procedure depends only on its arguments, so calling a procedure with the same value for an argument always produces the same result. As a result, it is a good fit for parallel execution.
No procedure can have side effects on other variables (state remains unaltered).
Procedural programming model is often called a 'Imperative' programming paradigm as programming is done with statements or instructions instead of expressions or declarations.
Procedural programming solves the problem by implementing one statement (a procedure) at a time. Thus it contains explicit steps that are executed in a specific order.
It also uses functions, but these are not mathematical functions like the ones used in functional programming. Functional programming focuses on expressions, whereas Procedural programming focuses on statements.
The statements don't have values and instead modify the state of some conceptual machine. Same language expression can result in different values at different times depending on the global state of the executing program. Also, the functions may change a program's state.
Procedural programming model is often called 'Imperative' programming as it changes state with an explicit sequence of statements.
1.6.3 Object-oriented Programming Model¶
This model mimics the real world by creating inside the computer a mini-world of objects. In a University system objects can be VC, Professors, Non-teaching staff, students, courses, semesters, examinations, etc. Each object has a state (values) and behavior (interface/methods). Objects get state and behavior based on the class from which it created. Objects interact with one another by sending messages to each other by calling each other's interface methods.
1.6.4 Event-driven Programming Model¶
This model is popularly used for programming GUI applications containing elements like windows, check boxes, buttons, combo-boxes, scroll bars, menus, etc.
- When we interact with these elements (like clicking a button, or moving the scrollbar or selecting a menu item) events occur and these elements emit messages. There are listener methods which are registered with these GUI elements which react to these events.
- Since there is no guaranteed sequence in which events may occur (based on how we interact with GUI elements), the listeners should be able to handle them in asynchronous manner.
Exercises¶
[A] Answer the following:
- a. Mention 5 fields in which Python is popularly used.
- b. Where is event-driven programming popularly used?
- c. Why Python is called portable language?
- d. What is the single most important feature of different programming models discussed in this chapter?
- e. Which of the following is not a feature of Python?
- Static typing
- Dynamic typing
- Run-time error handling through error numbers
- Library support for containers like Lists, Dictionaries, Tuples
- f. Give an example application of each of the following programming models:
- Functional model
- Procedural model
- Object-oriented model
- Event-driven model
[B] State whether the following statements are True or False:
- a. Python is free to use and distribute.
- b. Same Python program can work on different OS - microprocessor combinations.
- c. It is possible to use C++ or Java libraries in a Python program.
- d. In Python type of the variable is decided based on its usage.
- e. Python cannot be used for building GUI applications.
- f. Python supports functional, procedural, object-oriented and event-driven programming models.
- g. GUI applications are based on event-driven programming model.
- h. Functional programming model consists of interaction of multiple objects.
[C] Match the following pairs:
- a. Functional programming 1. GUI element based interaction
- b. Event-driven programming 2. Interaction of objects
- c. Procedural programming 3. Statements
- d. OOP 4. Maths-like functions
[D] Fill in the blanks:
- a. Functional programming paradigm is also known as ________ programming model.
- b. Procedural programming paradigm is also known as ________ programming model.
- c. Python was created by _________.
- d. Python programmers are often called _________.
Chapter 2 Getting Started¶
Keynote¶
1.1 Python Specification¶
-
Python is a specification for a language that can be implemented in different ways. There are many implementations of this specification written in different languages.
-
Different popular Python implementations are:
- CPython - is the reference implementation, written in C.
- PyPy - Written in a subset of Python language called RPython.
- Jython - Written in Java.
-
IronPython - Written in C#.
-
All the implementations are compilers as well as interpreters. The compiler converts the Python program into intermediate bytecode. This bytecode is then interpreted by the interpreter.
1.2 Python Installation under Windows¶
-
Python has evolved over the years. At the time of writing of this edition the latest version for Windows and Linux environments was Python 3.14.1.
-
Python is not shipped as part of Windows OS. So we need to install it separately. For this we need to download the Python installer from www.python.org/downloads/.
-
While downloading ensure that you choose the appropriate installer from the following, based on whether you wish to install it on a 32-bit machine or a 64-bit machine:
- 64-bit machine: Download Windows x86-64 executable installer
-
32-bit machine: Download Windows x86 executable installer
-
Once you have chosen and downloaded an installer, execute it by double-clicking on the downloaded file. A dialog shown in Figure 2.1 will appear on the screen.

-
In this dialog check the check box 'Add Python 3.14 to PATH' or 'Add python.exe to PATH' to ensure that the interpreter will be placed in your execution path.
-
Click on 'Install Now' and the installation will happen in a few minutes. Python files will get installed in the directory:
C:\Users\Joseph\AppData\Local\Programs\Python\Python314 -
In this path ‘Joseph’ represents the user name and ‘Python314’ represents the version number of Python installation that you have downloaded and installed.
-
If you forget to check the check box, you can add the path mentioned above to PATH variable through Control Panel > System > Environment Variables > Edit. The PATH variable already contains many semicolon separated values. Append the above path to existing values.
-
Once the installation is complete, you can verify it by opening a command prompt and typing python --version.
-
If the installation was successful, you will see the version of Python installed on your system.
-
If you are using Windows 10, you can also verify the installation by opening Settings > Apps > Apps & features > Python.
-
If you are using Windows 11, you can also verify the installation by opening Settings > Apps > Apps & features > Python.
1.3 Python Installation under Linux¶
-
Most Linux distributions (like Ubuntu) already contain Python in them. However, the installed Python version may not be the latest one. You can check the version as shown below:
-
If you find that the version is not the latest one, then you can install the latest specific version (e.g., Python 3.13) using the command:
1.4 Python Resources¶
- Python source code, binaries and documentation is available at:
- Python official website: www.python.org
-
Documentation website: www.python.org/doc
-
Program development in Python can be done in 3 ways:
- Using built-in IDLE.
- Using third-party IDEs.
-
Using online Python shells.
-
Third-party development tools and the links from where they can be downloaded are given below:
- NetBeans IDE for Python: https://netbeans.apache.org/front/main/download/
- PyCharm IDE for Python: https://www.jetbrains.com/pycharm
-
Visual Studio Code IDE: https://code.visualstudio.com/download
-
If you do not wish to install any Python development tool on your machine, then you can use any of the following online Python shells:
- https://ideone.com/
- https://replit.com/languages/python3
1.5 Third-party Packages¶
-
Pythonistas in Python community create packages (libraries) and makes it available for use for other programmers. They use PyPI—Python Package Index (www.pypi.org) to distribute their packages.
-
PyPI maintains the list of such third-party Python packages available.
-
There are third-party packages available for literally doing everything under the sun. Some packages that are popularly used for creating Data Science applications include:
- NumPy: Advanced mathematical operations library with support for large multi-dimensional arrays and matrices.
- SciPy: Scientific computing library for optimization, integration, interpolation, signal processing, image processing, etc.
- Pandas: Library for manipulating numerical tables and time series.
- MatPlotLib: 2D and 3D Data visualization library.
- OpenCV: Open source Computer vision library.
1.6 Python Packages and Development Tools¶
-
You too can register at PyPI and upload your packages there. You should follow the guidelines given at www.pypi.org to create the package, build it and upload it to the Python Package Index.
-
pip is a commonly used tool for installing packages from PyPI. This tool gets installed when you install Python.
1.6.1 Data Science and AI Tools¶
- Many tools have come into existence to help Python programmers build and document their Data Science and Artificial Intelligence applications. These include:
- Jupyter Notebook - It is a very flexible browser-based tool that lets us to interactively work with Python (and many other languages). It lets us put our Python code, output of the code and any kind of visualization or plot etc. in the same document called Notebook. It is a great tool doing modular program development.
- Google Colab - This tool provides a free Jupyter notebook environment to execute code on Google's cloud servers. As a result, you can leverage the power of Google's hardware.
-
Spyder - This tool provides a Scientific Python Development Environment with sophisticated testing and debugging features.
-
Both Jupyter and Spyder are part of a very popular software distribution called Anaconda. So once you download and install Anaconda, you get Jupyter and Spyder ready-made.
1.6.2 IDLE (Integrated Development and Learning Environment)¶
-
Once Python is installed, program development can be done using the built-in Python Integrated Development and Learning Environment (IDLE).
-
IDLE is a good development tool. It offers handy features like syntax highlighting, context-sensitive help and debugging.
- Syntax highlighting feature display keywords, functions, methods and strings in different colors making it easy to identify them.
- Context-sensitive help can be obtained by pressing Ctrl Space wherever you need help as you type the program. This is immensely useful since it is almost impossible to remember names of all functions and methods and their parameters.
- Debugger lets you locate any logical errors that you may have committed in your program by allowing you trace the flow of execution of the program. This tracing can be done a step at a time by setting up break points and by single stepping through the program. As you do so IDLE lets you watch the values of different variables as they change during execution.
1.6.3 Python Modes¶
- Python can be used in two modes:
- Interactive mode - used for exploring Python syntax, seek help and debug short programs.
-
Script mode - used for writing full-fledged Python programs.
-
Both modes are supported by IDLE.
1.6.3.1 To use IDLE in Interactive mode:¶
- Locate it in Windows by typing IDLE in Windows search bar and hit enter, or double click the IDLE icon.
- It will open the Python shell window showing
>>>Python shell prompt. -
Execute the following Python code at this prompt.
-
It will display the message 'Keep calm and bubble on' followed by the
>>>prompt.
1.6.3.2 To use IDLE in Script mode:¶
-
Launch IDLE. In the IDLE shell window from the menu select File | New File. A new window will open. Type the following script in it:
-
Using File > Save and save the script under the name 'Test.py'.
- Execute the script from the Run menu or using F5. The two messages will get printed.
1.6.3.3 Using Other IDEs¶
- Instead of IDLE if you decide to use NetBeans or Visual Studio Code for program development then follow the steps given below:
- Create a new Python project ‘Test’.
- Type the script in Test.py.
- Execute the script using F6 in NetBeans or Ctrl F5 in Visual Studio Code.
- On execution it will print the two lines and then you are ready to create another project and another script in it.
1.7 Checking Python Version¶
-
Python has evolved over the years. You can determine the version installed on your machine through a simple Python script:
Exercises¶
[A] Answer the following quesitons:
- a. What do the prompt C:>,$ and >>> signify?
- b. In which two modes can IDLE be used?
- c. What is the purpose of the two programming modes offered by IDLE?
- d. How can third party libraries be used in a Python Program?
[B] Match the following pairs:
| Section A | Section B |
|---|---|
a. pip |
1. Advanced mathematical operations |
b. Jupyter |
2. Scientific Computing |
c. Sypder |
3. Manipulation numerical tables |
d. PyPI |
4. Visualization |
e. Numpy |
5. Computer Vision |
f. Scipy |
6. Package installation tool |
g. Pandas |
7. Build and document applications |
h. MatPlotlib |
8. Scientific Library |
i. OpenCV |
9. Python Package index |
[C] State whether the following statements are True or False:
- a. Python is a specification that can be implemented through languages like Python,C#,Java,etc.
- b. CPython is implementation of Python specification, written in C.
- c. Python program is first compiled intor byte code, which is then interpreted.
- d. Most Linux distributions already contain Python.
- e. Windows system doesn't contain Python and it needs to be separately installed.
- f. PYthon prgorams can be built using IDLE, Netbeans, PyCharm and Visual Studio Code.
- g. Thrid-party Python packages are distributed using PyPI.
Chapter 3 Python Basics¶
Keynote¶
3.1 Identifiers and Keywords¶
Python is a case sensitive language. Python identifier is a name used to identify a variable, function, class, module, or other object. Rules for creating identifiers: - Starts with alphabet or an underscore. - Followed by zero or more letters, _ , and digits. - keyword cannot be used as identifier. All keywords are in lowercase. Python has 33 keywords shown in Table 3.1
| Table 3.1 Keywords list | -/- | -/- | -/- |
|---|---|---|---|
| False | continue | from | not |
| None | def | global | or |
| True | del | if | pass |
| and | elif | import | raise |
| as | else | in | return |
| assert | except | is | try |
| break | finally | lambda | while |
| class | for | nonlocal | with |
| yield |
You can print a list of Python keywords through the statements:
import keyword # makes the module 'keyword' available
print(keyword.kwlist) # syntax modulename.object/function
3.2 Python Types¶
Python supports 3 categories of data types:
- Basic Types:
- int, float, complex, bool, string, bytes
- Container Types:
- list, tuple, set, dict
- User-defined types:
- class
Out of these, basic types will be covered in this chapter in detail. Container types will be covered briefly. A separate chapter is dedicated to each container type, where they are covered in greate detail. User-defined types will not be covered in this chapter. Chapter 17 discusses how to create and use them.
3.2.1 Basic Types¶
Examples of different basic types are given below:
- int can be expressed in binary, decimal, octal, hexadecimal
- binary starts with 0b/0B, octal with 0o/0O, hex with 0x/0X (eg. 0b10111, 156, 0o432, 0x4A3)
- float can be expressed in fractional or exponential form (eg. 314.1528, 3.141528e2, 3.141528E2)
- complex contains real and imaginary part (eg. 3 + 2j, 1 + 4J)
- bool can take any of the two Boolean values both starting in caps (eg.True, False)
- string is an immutable collection of Unicode characters enclosed within
' '," ", or""" """. 'Rosanna', "Rosanna", """Rosanna""". - bytes represent binary data
print(type(35)) # prints <class 'int'>
print(type(3.14)) # prints <class 'float'>
3.2.2 Integer and Float Ranges¶
int can be of any arbitrary size
Python has arbitrary precision integers. Hence you can create as big integers as you want. Moreover, arithmetic operations can be performed on integers without worrying about overflow/underflow.Floats are represented internally in binary as 64-bit double-precision values, as per the IEEE 754 standard. As per this standard, the maximum value a float can have is approximately 1.8 x 10^308. A number greater than this is represented as inf(short for infinity).
Many floats cannot be represented 'exactly' in binary form. So the internal representation is often an approximation of the actual value.
The difference between the actual value and the represented value is very small and should not usually cause significant problems.
3.3 Variable Type and Assignment¶
There is no need to define type of a variable. During execution the type of the variable is inferred from the context in which it is being used. Hence Python is called dynamically-typed language.
a = 25 # type of a is inferred as int
a = 31.4 # type of a is inferred as float
a = 'Hi' # type of a is inferred as str
Type of a variable can be checked using the built-in function type().
Simple variable assignment:
Multiple variable assignment:
a = 10 ; pi = 31.4 ; name = 'Rosanna' # use ; as statement separator
a, pi, name = 10, 3.14, 'Rosanna'
a = b = c = d = 5
3.3.1 Arithmetic Operators¶
Arithmetic Operators: +, - , * , /, %, //, **
a = 4 / 2 # performs true division and yields a float 2.0
a = 7 % 2 # % yields remainder 1
b = 3 ** 4 # ** yields 3 raised to 4 (exponentiation)
c = 4 // 3 # // yields quotient 1 after discarding fractional part
In-place assignment operators offer a good shortcut for arithmetic operations. These include +=, -=, *=, /=, %=, //=, **=.
3.3.2 Operation Nuances¶
On performing floor division a//b, result is the largest integer which is less than or equal to the quotient. // is called floor division operator.
print(10 // 3) # yields 3
print(-10 // 3) # yields -4
print(10 // -3) # yields -4
print(-10 // -3) # yields 3
print(3 // 10) # yields 0
print(3 // -10) # yields -1
print(-3 // 10) # yields -1
print(-3 // -10) # yields 0
In -10 // 3, multiple of 3 which will yield -10 is -3.333, whose floor value is -4. In 10 // -3, multiple of -3 which will yield 10 is -3.333, whose floor value is -4. In -10 // -3, multiple of -3 which will yield -10 is 3.333, whose floor value is 3.
print( ) is a function which is used for sending output to screen. It can be used in many forms. They are discussed in Chapter 7. Operation a % b is evaluated as a - (b * (a // b)). This can be best understood using the following examples:
print(10 % 3) # yields 1
print(-10 % 3) # yields 2
print(10 % -3) # yields -2
print(-10 % -3) # yields -1
print(3 % 10) # yields 3
print(3 % -10) # yields -7
print(-3 % 10) # yields 7
print(-3 % -10) # yields -3
Since a % b is evaluated as a - (b * (a // b)), -10 % 3 is evaluated as -10 - (3 * (-10 // 3)), which yields 2. 10 % -3 is evaluated as 10 - (-3 * (10 // -3)), which yields -2, -10 % -3 is evaluated as -10 - (-3 * (-10 // -3)), which yields -1.
Mathematical rule a / b x c is same as a x c / b holds, but not always.
# following expressions give same results
a = 300 / 100 * 250
a = 300 * 250 / 100
# However, these don't
b = 1e210 / 1e200 * 1e250
b = 1e210 * 1e250 / 1e200 # gives INF
Since True is 1 and False is 0, they can be added.
3.4 Precedence and Associativity¶
When multiple operators are used in an arithmetic expression, it is evaluated on the basis of precedence (priority) of the operators used.
Operators in decreasing order of their priority (PEMDAS):
( ) # Parentheses
** # Exponentiation
*, /, //, % # Multiplication, Division
+, - # Addition, Subtraction
Each operator has either left to right associativity or right to left associativity.
In expression c = a * b / c, * is done before / since arithmetic
operators have left to right associativity.
A complete list of Python operators, their priority and associativity is given in Appendix A.
3.4.1 Conversions¶
Mixed mode operations:
- Operation between int and float will yield float.
- Operation between int and complex will yield complex.
- Operation between float and complex will yield complex.
We can convert one numeric type to another using built-in functions int( ), float( ), complex( ) and bool( ).
Type conversions:
int(float/numeric string) # from float/numeric string to int
int(numeric string, base) # from numeric string to int in base
float(int/numeric string) # from int/numeric string to float
float(int) # from int to float
complex(int/float) # convert to complex with imaginary part 0
complex(int/float, int/float) # convert to complex
bool(int/float) # from int/float to True/False (1/0)
str(int/float/bool) # converts to string
chr(int) # yields character corresponding to int
int( ) removes the decimal portion from the quotient, so always rounds towards zero.
3.4.2 Built-in Functions¶
Python has many built-in functions that are always available in any part of the program. The print( ) function that we have been using to send output to screen is a built-in function.
Help about any built-in function is available using help(function).
Built-in functions that are commonly used with numbers are given below:
abs(x) # returns absolute value of x
pow(x, y) # returns value of x raised to y
min(x1, x2,...) # returns smallest argument
max(x1, x2,...) # returns largest argument
divmod(x, y) # returns a pair(x // y, x % y)
round(x [,n]) # returns x rounded to n digits after .
bin(x) # returns binary equivalent of x
oct(x) # returns octal equivalent of x
hex(x) # returns hexadecimal equivalent of x
Following Python program shows how to use some of these built-in functions:
a = abs(-3) # assigns 3 to a
print(min(10, 20, 30, 40)) # prints 10
print(hex(26)) # prints 1a
3.4.3 Built-in Modules¶
Apart from built-in functions, Python provides many built-in modules. Each module contains many functions. For performing sophisticated mathematical operations we can use the functions present in built-in modules math, cmath, random, decimal.
math - many useful mathematics functions.
cmath - functions for performing operations on complex numbers.
random - functions related to random number generation.
decimal - functions for performing precise arithmetic operations.
Mathematical functions in math module:
pi, e # values of constants pi and e
sqrt(x) # square root of x
factorial(x) # factorial of x
fabs(x) # absolute value of float x
log(x) # natural log of x (log to the base e)
log10(x) # base-10 logarithm of x
exp(x) # e raised to x
trunc(x) # truncate to integer
ceil(x) # smallest integer >= x
floor(x) # largest integer <= x
modf(x) # fractional and integer parts of x
round( ) built-in function can round to a specific number of decimal places, whereas math module's library functions trunc( ), ceil( ) and floor( ) always round to zero decimal places.
Trigonometric functions in math module:
degrees(x) # radians to degrees
radians(x) # degrees to radians
sin(x) # sine of x radians
cos(x) # cosine of x radians
tan(x) # tan of x radians
sinh(x) # hyperbolic sine of x
cosh(x) # hyperbolic cosine of x
tanh(x) # hyperbolic tan of x
acos(x) # cos inverse of x, in radians
asin(x) # sine inverse of x, in radians
atan(x) # tan inverse of x, in radians
hypot(x, y) # sqrt(x * x + y * y)
Random number generation functions from random module:
random( ) # random number between 0 and 1
randint(start, stop) # random number in the range
seed( ) # sets current time as seed for random number generation
seed(x) # sets x as seed for random number generation logic
Following Python program shows how to use some of the functions of math module and random module:
import math
import random
print(math.factorial(5)) # prints 120
print(math.degrees(math.pi)) # prints 180.0
print(random.random( )) # prints 0.8960522546341796
import math
print(dir(__builtins__)) # 2 underscores before and after builtins
print(dir(math))
3.5 Container Types¶
Container types typically refer to multiple values stored together Examples of different basic types are given below:
# list is a indexed collection of similar/dissimilar entities
[10, 20, 30, 20, 30, 40, 50, 10], ['She', 'sold', 10, 'shells'’]
# tuple is an immutable collection
('Rosanna', 34, 4500.55), ('Python With Joe', 350, 195.00)
# set is a collection of unique values
{10, 20, 30, 40}, {'Rosanna', 34, 45000}
# dict is a collection of key-value pairs, with unique key enclosed in
''
{'ME101' : 'Strength of materials', 'EE101' : 'Electronics'}
lst = [10, 20, 30, 20, 30, 40, 50, 10]
tpl = ('Python With Joe', 350, 195.00)
s = {10, 20, 30, 40}
dct = {'ME101' : 'SOM', 'EE101' : 'Electronics'}
print(lst[0], tpl[2]) # prints 10 195.0
print(dct['ME101']) # prints SOM
3.5.1 Python Type Jargon¶
Often following terms are used while describing Python types:
-
Collection - a generic term for container types.
-
Iterable - means a collection that can be iterated over using a loop.
-
Ordered collection - elements are stored in the same order in which they are inserted. Hence its elements can be accessed using an index, i.e. its position in the collection.
-
Unordered collection - elements are not stored in the same order in which they are inserted. So we cannot predict at which position a particular element is present. So we cannot access its elements using a position based index.
-
Sequence is the generic term for an ordered collection.
-
Immutable - means unchangeable collection.
-
Mutable - means changeable collection.
Let us now see which of these terms apply to types that we have seen so far:
-
String - ordered collection, immutable, iterable.
-
List - ordered collection, mutable, iterable.
-
Tuple - ordered collection, immutable, iterable.
-
Set - unordered collection, mutable, iterable.
-
Dictionary - unordered collection, mutable, iterable.
3.5.2 Comments and Indentation¶
Comments begin with #.
# calculate gross salary
gs = bs + da + hra + ca
si = p * n * r / 100 # calculate simple interest
Multi-line comments should be written in a pair of ''' or """.
''' Additional program: Calculate bonus to be paid
URL: https://github.com/rose1996iv/PythonWithJoe (https://github.com/rose1996iv/PythonWithJoe)
Author: Joseph, Date: 7 Dec 2025 '''
Indentation matters! Don’t use it casually. Following code will report an error 'Unexpected indent'.
a = 20
b = 45
Multi-lining
If statements are long they can be written as multi-lines with each line except the last ending with a .
total = physics + chemistry + maths + \
english + myanmar + history + \
geography + civics
[ ], { }, or ( ) don't need .
3.6 Classes and Objects¶
In Python every type is a class. So int, float, complex, bool, str, list, tuple, set, dict are all classes. These are ready-made classes. Python also permits us to create user-defined classes as we would see in Chapter 18
An object is created from a class. A class describes two things—the form an object created from it will take and the methods (functions) that can be used to access and manipulate the object.
From one class multiple objects can be created. When an object is created from a class, it is said that an instance of the class is being created.
A class has a name, whereas objects are nameless. Since objects do not have names, they are referred using their addresses in memory.
All the above statements can be verified through the following program. Refer to Observation to understand it better.
a = 30
b = 'Good'
print(a, b) # prints 3 Good
print(type(a), type(b)) # prints <class 'int'> <class 'str'>
print(id(a), id(b)) # prints 1356658640 33720000
print(isinstance(a, int), isinstance(b, str)) # prints True True
3.7 Python Object Reference Visualization¶
Understanding how variables refer to objects in memory is crucial in Python.
Key Concept
In Python, variables are essentially references (or pointers) to objects stored in memory. They do not contain the values directly but point to the memory location where the value is stored.
Memory Reference Breakdown¶
The following table details the references shown in the diagram:
| Variable Name | Reference ID (Address) | Points To (Object Type) | Object Value | Object Memory Address |
|---|---|---|---|---|
a |
1356658640 |
int object | 30 |
1356658640 |
b |
33720000 |
str object | Good |
33720000 |
Observation
- Variable
aholds the reference ID1356658640, which matches the address of the Integer Object30. - Variable
bholds the reference ID33720000, which matches the address of the String Object'Good'.
In this program we have created two objects—one from ready-made class int and another from ready-made class str.
The object of type int contains 30, whereas the object of type str contains 'Good'.
Both the objects are nameless. Their addresses in memory are
1356658640 and 33720000 which are stored in a and b.
These addresses can be obtained using the built-in function id( ). When you execute the program you may get different addresses.
Since a and b contain addresses they are said to refer to objects
present at these addresses. In simpler words they are pointers to
objects.
Type of objects to which a and b are referring to can be obtained
using the built-in function type( ).
Whether a refers to an instance of class int can be checked using
the built-in function isinstanceof( ).
Multiple Objects
Consider the following program:
a = 3
b = 3
print(id(a), id(b)) # prints 1356658640 1356658640
print(a is b) # prints True
a = 30 # now a refers to a different object
print(id(a)) # prints 1356659072
Are we creating 2 int objects? No. Since the value stored in int object is same, i.e. 3, only 1 int object is created. Both a and b are referring to the same int object. That is why id(a) and id(b) return same addresses.
This can also be verified using the is operator. It returns True since a and b both are referring to the same object.
When we attempt to store a new value in a, a new int object is created as a different value, 30, is to be stored in it. a now starts referring to this new int object, whereas b continues to refer to int object with value 3.
Instead of saying that a is referring to an int object containing a value 3, it is often said that a is an int object, or 3 is assigned to a.
Many programmers continue to believe that a and b are int variables, which we now know is not the case.
Problem 3.1¶
Demonstrate use of integer types and operators that can be used on them.
Program
Tips
- ¾ doesn't yield 0.
- Multiple statements in a line should be separated using;
- print(w, x, y) prints values separated by a space.
Problem 3.2¶
Demonstrate use of float, complex and bool types and operators that can be used on them.
Program

Tips
- % works on floats.
- It is possible to obtain real and imag part from a complex number.
- On evaluation of a condition it replaced by True or False.
Problem 3.3¶
Demonstrate how to convert from one number type to another.
Program
# convert to int
print(int(3.14)) # from float to int
a = int('485') # from numeric string to int
b = int('768') # from numeric string to int
c = a + b
print(c)
print(int('1011', 2)) # convert from binary to decimal int
print(int('341', 8)) # convert from octal to decimal int
print(int('21', 16)) # convert from hex to decimal int
# convert to float
print(float(35)) # from int to float
i = float('4.85') # from numeric string to float
j = float('7.68') # from numeric string to float
k = i + j
print(k)
# convert to complex
print(complex(35)) # from int to float
x = complex(4.85, 1.1) # from numeric string to float
y = complex(7.68, 2.1) # from numeric string to float
z = x + y
print(z)
# convert to bool
print(bool(35))
print(bool(1.2))
print(int(True))
print(int(False))
Tips
- It is possible to convert a binary numeric string, octal numeric string or hexadecimal numeric string to equivalent decimal integer. Same cannot be done for a float.
- While converting to complex if only one argument is used, imaginary part is considered to be
0. - Any non-zero number (int or float) is treated as True.
0is treated as False.
Problem 3.4¶
Write a program that makes use of built-in mathematical functions.
Program
Tips
- divmod(a, b) yields a pair (a // b, a % b).
- bin( ), oct( ), hex( ) return binary, octal and hexadecimal equivalents.
- round(x) assumes that rounding-off has to be done with 0 places beyond decimal point.
Problem 3.5¶
Write a program that makes use of functions in the math module.
Program
# mathematical functions from math module
import math
x = 1.5357
print ( math.pi, math.e)
print(math.sqrt( x))
print(math.factorial(6))
print(math.fabs(x))
print(math.log(x))
print(math.log10(x))
print(math.exp(x))
print(math.trunc(x))
print(math.floor(x))
print(math.ceil(x))
print(math.trunc(-x))
print(math.floor(-x))
print(math.ceil(-x))
print(math.modf(x))
Output
Tips
- floor( ) rounds down towards negative infinity, ceil( ) rounds up towards positive infinity, trunc( ) rounds up or down towards 0.
- trunc( ) is like floor( ) for positive numbers.
- trunc( ) is like ceil( ) for negative numbers.
- modf( ) returns a pair of numbers
(f, i)such thatx = f + iand0 <= f < 1.
Problem 3.6¶
Write a program that generates float and integer random numbers.
Program
Tips
- It is necessary to import random module.
- If we seed the random number generation logic with current time, we get different random numbers on each execution of the program.
- random.seed( ) with no parameter also seeds the logic with current time.
Problem 3.7¶
How will you identify which of the following is a string, list, tuple set or dictionary?
{10, 20, 30.5}
[1, 2, 3.14, 'Nagpur']
{12 : 'Simple', 43 : 'Complicated', 13 : 'Complex'}
"Check it out!"
3 + 2j
Program
Tips
- type( ) is a built-in function which can determine type of any data—built-in, container or user-defined.
Exercises¶
[A] Answer the following questions:¶
a. Write a program that swaps the values of variables a and b. You are not allowed to use a third variable. You are not allowed to perform arithmetic on a and b.
b. Write a program that makes use of trigonometric functions available in math module.
c. Write a program that generates 5 random numbers in the range 10 to 50. Use a seed value of 6. Make a provision to change this seed value every time you execute the program by associating it with time of execution?
d. Use trunc( ), floor( ) and ceil( ) for numbers -2.8, -0.5, 0.2, 1.5 and 2.9 to understand the difference between these functions clearly.
e. Assume a suitable value for temperature of a city in Fahrenheit degrees. Write a program to convert this temperature into Centigrade degrees and print both temperatures.
f. Given three sides a, b, c of a triangle, write a program to obtain and print the values of three angles rounded to the next integer. Use the formulae:
[B] How will you perform the following operations:¶
a. Print imaginary part out of 2 + 3j.
b. Obtain conjugate of 4 + 2j.
c. Print decimal equivalent of binary 1100001110.
d. Convert a float value 4.33 into a numeric string.
e. Obtain integer quotient and remainder while dividing 29 with 5.
f. Obtain hexadecimal equivalent of decimal 34567.
g. Round-off 45.6782 to second decimal place.
h. Obtain 4 from 3.556.
i. Obtain 17 from 16.7844.
j. Obtain remainder on dividing 3.45 with 1.22.
[C] Which of the following is invalid variable name and why?¶
| BASICSALARY | _basic | basic-hra | #MEAN |
|---|---|---|---|
| group. | 422 | pop in 2020 | over |
| timemindovermatter | SINGLE | hELLO | queue. |
| team'svictory | Plot#3 | 2015_DDay |
[D] Evaluate the following expressions:¶
a. 2 ** 6 // 8 % 2
b. 9 ** 2 // 5 - 3
c. 10 + 6 - 2 % 3 + 7 - 2
d. 5 % 10 + 10 -23 * 4 // 3
e. 5 + 5 // 5 - 5 * 5 ** 5 % 5
f. 7 % 7 + 7 // 7 - 7 * 7
[E] Evaluate the following expressions:¶
a. min(2, 6, 8, 5)
b. bin(46)
c. round(10.544336, 2)
d. math.hypot(6, 8)
e. math.modf(3.1415)
[F] Match the following pairs:¶
| a. complex | 1. \ |
|---|---|
| b. Escape special character | 2. Container type |
| c. Tuple | 3. Basic type |
| d. Natural logarithm | 4. log( ) |
| e. Common logarithmlog10( ) | 5. log10( ) |
Chapter 4 Strings¶
Keynote¶
4.1 What are Strings?¶
-
Python string is a collection of Unicode characters.
-
Python strings can be enclosed in single, double or triple quotes.
Handling Special Characters in Strings
If there are characters like ', " or \ within a string, they can be retained in two ways:
- Escape Sequence: Escape them by preceding them with a
\(backslash). - Raw String: Prepend the string with a
rindicating that it is a raw string.
# (a) Using Backslash to escape quotes
msg_escape = 'He said, \'Python With Joe.\''
print(msg_escape)
# Output: He said, 'Python With Joe.'
# (b) Using Raw String (r prefix)
# Useful when you have many backslashes (e.g., file paths or regex)
path = r"C:\Users\Name\Documents"
print(path)
# Output: C:\Users\Name\Documents
Creating Multiline Strings
Multiline strings can be created in 3 ways:
- Using Backslash (
\): All but the last line ends with a backslash. - Triple Quotes: Enclosed within
"""..."""or'''...'''. - Parentheses: Using implicit string concatenation within brackets
().
# Method 1: Using Backslash (\)
# Note: Ensure there is no space after the backslash
msg1 = 'one msg ' \
'another msg'
# Method 2: Triple Quotes
# This preserves the newline characters inside the string
msg2 = """one msg
another msg"""
# Method 3: Using Parentheses
# Often preferred for long strings to keep code clean
msg3 = ('one msg '
'another msg')
4.2 Accessing String Elements¶
- String elements can be accessed using an index value, starting with 0.
- Negative index value is allowed. The last character is considered to be at index -1.
4.2.1 Visualizing Indices¶
The relationship between positive and negative indices is shown below using the string "PYTHON" as an example:
| Character | P | Y | T | H | O | N |
|---|---|---|---|---|---|---|
| Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
s = "PYTHON"
# Accessing first character
print(s[0]) # Output: P
print(s[-6]) # Output: P
# Accessing last character
print(s[5]) # Output: N
print(s[-1]) # Output: N
4.2.2 String Slicing¶
A sub-string can be sliced out of a string using the syntax [start : end].
Common Slicing Patterns
| Syntax | Description |
|---|---|
s[start : end] |
Extract from start to end - 1. |
s[start :] |
Extract from start to the end of string. |
s[: end] |
Extract from beginning to end - 1. |
s[-start :] |
Extract from -start (included) to end. |
s[: -end] |
Extract from beginning to -end - 1. |
Handling Out-of-Bounds Indices
One important feature of slicing is how it handles indices that are larger than the string length.
Slicing vs. Direct Indexing
- Direct Indexing (
msg[100]): Raises an Error if the index is too large. - Slicing (
msg[3:100]): Handled elegantly. It simply returns characters up to the end of the string without crashing.
msg = 'Rafting'
# Slicing with a large index (Safe)
print(msg[3:100])
# Output: 'ting' (extracts from 't' up to end)
# Direct indexing with a large index (Unsafe)
# print(msg[100])
# Error: IndexError: string index out of range
4.3 String Properties¶
Python strings are immutable—they cannot be changed once created.
- Immutability: Python strings are immutable—they cannot be changed in place.
- Concatenation: Strings can be joined using
+. - Replication: Strings can be repeated using
*. - Membership: Check if a substring exists using
in.
Basic String Operations
Python provides intuitive operators to manipulate strings easily.
Concatenation (+)
Strings can be joined together (concatenated) using the + operator.
msg1 = "Hello "
msg2 = "World"
msg3 = msg1 + msg2
print(msg3)
# Output: Hello World
Replication (*)
Strings can be repeated (replicated) using the * operator. This is very useful for formatting output, such as creating separator lines.
Syntax Note
To replicate a string, you must use the asterisk *, not a comma.
print('-', 50)will simply print the character and the number (e.g.,- 50).print('-' * 50)will print the character 50 times.
Membership Testing (in)
Membership testing checks if a substring exists within a string. It returns True if the substring is found, otherwise False.
s = "Hello World"
print('World' in s) # Output: True
print('Python' in s) # Output: False
String Length (len())
The len() function returns the number of characters in a string.
String Indexing
String indexing allows you to access individual characters in a string using their position (index).
String Slicing
String slicing allows you to extract a portion of a string using a range of indices.
s = "Hello World"
print(s[0:5]) # Output: Hello
print(s[-6:-1]) # Output: World
Modern String Formatting (f-strings)
Up-to-Date Feature (Python 3.6+)
- The traditional way to combine strings and variables is using
+(Concatenation) or.format(). However,f-strings(Formatted String Literals) are the modern, preferred way because they are more readable and faster.
4.5 Built-in Functions & Methods¶
Built-in Functions:
len(s): Returns the length of the string.min(s): Returns the character with the minimum Unicode value.max(s): Returns the character with the maximum Unicode value.
Content Test Methods
isalpha(): Checks if all characters are alphabets.isdigit(): Checks if all characters are digits.isalnum(): Checks if all characters are alphanumeric.islower()/isupper(): Checks case.startswith()/endswith(): Checks prefix/suffix.
Search and Replace
find(sub): Returns index of substring (returns -1 if not found).replace(old, new): Replaces occurrences of a substring.
Trimming & Splitting
1. lstrip(), rstrip(), strip(): Removes whitespace from ends.
2. split(sep): Splits string into a list.
3. join(iterable): Joins elements into a string.
Modern Python: removing prefix/suffix (Python 3.9+)
- Using
strip()to remove specific words can be risky (it removes character sets). Modern Python provides safer methods:
filename = "report.pdf"
print(filename.removesuffix(".pdf")) # Output: report
print(filename.removeprefix("report")) # Output: .pdf
4.6 String Conversions & Comparison¶
- Case Conversion: upper(), lower(), capitalize(), title(), swapcase().
- Type Conversion: str(), int(), float(), complex().
- ASCII/Unicode:
ord('A'): Returns integer 65.chr(65): Returns character 'A'.
- Comparison: Done lexicographically (dictionary order).
s1 > s2(Evaluates based on Unicode values).
Solved Problems¶
Problem 4.1¶
Question: Demonstrate how to create simple and multi-line strings and whether a
string can change after creation. Also show the usage of built-in
functions len(), min(), max() on a string.
Program
# simple strings
msg1 = 'Hoopla'
print(msg1)
# strings with special characters
msg2 = 'He said, \'Python With Joe\'.'
file1 = 'C:\\temp\\newfile'
file2 = r'C:\temp\newfile' # raw string - prepend r
print(msg2)
print(file1)
print(file2)
# multiline strings
# whitespace at beginning of second line becomes part of string
msg3 = 'What is this life if full of care...\
We have no time to stand and stare'
# enter at the end of first line becomes part of string
msg4 = """What is this life if full of care...
We have no time to stand and stare"""
# strings are concatenated properly.( ) necessary
msg5 = ('What is this life if full of care...'
'We have no time to stand and stare')
print(msg3)
print(msg4)
print(msg5)
# string replication during printing
msg6 = 'MacLearn!!'
print(msg1 * 3)
# immutability of strings
# Utopia cannot change, msg7 can
msg7 = 'Utopia'
msg8 = 'Today!!!'
msg7 = msg7 + msg8 # concatenation using +
print(msg7)
# use of built-in functions on strings
print(len('Hoopla'))
print(min('Hoopla'))
print(max('Hoopla'))
Output
Hoopla
He said, 'Python With Joe'.
C:\temp\newfile
C:\temp\newfile
What is this life if full of care... We have no time to stand and stare
What is this life if full of care...
We have no time to stand and stare
What is this life if full of care...We have no time to stand and stare
HooplaHooplaHoopla
UtopiaToday!!!
6
H
p
Tips
- Special characters can be retained in a string by either escaping them or by marking the string as a raw string.
- Strings cannot change, but the variables that store them can.
len( )returns the number of characters present in string.min( )andmax( )return the character with minimum and maximum Unicode value from the string.
Problem 4.2¶
Question: For a given string 'Bamboozled', write a program to obtain the following output:
B a
e d
e d
mboozled
mboozled
mboozled
Bamboo
Bamboo
Bamboo
Bamboo
delzoobmaB
Bamboozled
Bmoze
Bbzd
Boe
BamboozledHype!
BambooMonger!
Program
s = 'Bamboozled'
# extract B a
print(s[0], s[1])
print(s[-10], s[-9])
# extract e d
print(s[8], s[9])
print(s[-2], s[-1])
# extract mboozled
print(s[2:10])
print(s[2:])
print(s[-8:])
# extract Bamboo
print(s[0:6])
print(s[:6])
print(s[-10:-4])
print(s[:-4])
# reverse Bamboozled
print(s[::-1])
print(s[0:10:1])
print(s[0:10:2])
print(s[0:10:3])
print(s[0:10:4])
s = s + 'Hype!'
print(s)
s = s[:6] + 'Monger' + s[-1]
print(s)
Tips
- Special characters can be retained in a string by either escaping them or by marking the string as a raw string.
s[4:8]is same ass[4:8:1], where 1 is the default.s[4:8:2]returns a character, then move forward 2 positions, etc.
Problem 4.3¶
Question: For the following strings find out which are having only alphabets, which are numeric, which are alphanumeric, which are lowercase, which are uppercase. Also find out whether 'And Quiet Flows The Don' begins with 'And' or ends with 'And' : 'NitiAayog' 'And Quiet Flows The Don' '1234567890' 'Make $1000 a day'
Program
s1 = 'NitiAayog'
s2 = 'And Quiet Flows The Don'
s3 = '1234567890'
s4 = 'Make $1000 a day'
print('s1 = ', s1)
print('s2 = ', s2)
print('s3 = ', s3)
print('s4 = ', s4)
# Content test functions
print('check isalpha on s1, s2')
print(s1.isalpha( ))
print(s2.isalpha( ))
print('check isdigit on s3, s4')
print(s3.isdigit( ))
print(s4.isdigit( ))
print('check isalnum on s1, s2, s3, s4')
print(s1.isalnum( ))
print(s2.isalnum( ))
print(s3.isalnum( ))
print(s4.isalnum( ))
print('check islower on s1, s2')
print(s1.islower( ))
print(s2.islower( ))
print('check isupper on s1, s2')
print(s1.isupper( ))
print(s2.isupper( ))
print('check startswith and endswith on s2')
print(s2.startswith('And'))
print(s2.endswith('And'))
Output
s1 = NitiAayog
s2 = And Quiet Flows The Don
s3 = 1234567890
s4 = Make $1000 a day
check isalpha on s1, s2
True
False
check isdigit on s3, s4
True
False
check isalnum on s1, s2, s3, s4
True
False
True
False
check islower on s1, s2
False
False
check isupper on s1, s2
False
False
check startswith and endswith on s2
True
False
Problem 4.4¶
Question: Given the following string: 'Bring It On' ' Flanked by spaces on either side ' 'C:\Users\Joseph\Documents' write a program to produce the following output using appropriate string functions. BRING IT ON bring it on Bring it on Bring It On bRING iT oN 6 9 Bring Him On Flanked by spaces on either side Flanked by spaces on either side ['C:', 'Users', 'Joseph', 'Documents'] ('C:', '\', 'Users\Joseph\Documents')
Program
s1 = 'Bring It On'
# Conversions
print(s1.upper( ))
print(s1.lower( ))
print(s1.capitalize( ))
print(s1.title( ))
print(s1.swapcase( ))
# search and replace
print(s1.find('I'))
print(s1.find('On'))
print(s1.replace('It', 'Him'))
# trimming
s2 = ' Flanked by spaces on either side '
print(s2.lstrip( ))
print(s2.rstrip( ))
# splitting
s3 = 'C:\\Users\\Joseph\\Documents'
print(s3.split('\\'))
print(s3.partition('\\'))
Problem 4.5¶
Question: Find all occurrences of 'T' in the string 'The Terrible Tiger Tore The Towel'. Replace all occurrences of 'T' with 't'.
Program
s = 'The Terrible Tiger Tore The Towel'
pos = s.find('T', 0)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos)
c = s.count('T')
s = s.replace('T', 't', c)
print(s)
Tips
- First call to search( ) returns the position where first 'T' is found. To search subsequent 'T' search is started from pos + 1.
- When 'T' is not found search( ) returns -1.
- count( ) returns the number of occurrences of 'T' in the string.
- Third parameter in the call to replace( ) indicates number of replacements to be done.
Exercise¶
[A] Answer the following questions:
a. Write a program that generates the following output from the string 'Shenanigan'.
b. Write a program to convert the following string 'Visit ykanetkar.com for online courses in programming' into 'Visit Ykanetkar.com For Online Courses In Programming'
c. Write a program to convert the following string 'Light travels faster than sound. This is why some people appear bright until you hear them speak.' into 'LIGHT travels faster than SOUND. This is why some people appear bright until you hear them speak.'
d. What will be the output of the following program? s = 'HumptyDumpty' print('s = ', s) print(s.isalpha( )) print(s.isdigit( )) print(s.isalnum( )) print(s.islower( )) print(s.isupper( )) print(s.startswith('Hump')) print(s.endswith('Dump'))
e. What is the purpose of a raw string?
f. If we wish to work with an individual word in the following string, how will you separate them out: 'The difference between stupidity and genius is that genius has its limits'
g. Mention two ways to store a string: He said, "Python With Joe".
h. What will be the output of following code snippet?
i. What will be the output of the following code snippet?j. Strings in Python are iterable, sliceable and immutable. (True/False)
k. How will you extract ' TraPoete' from the string 'ThreadProperties'?
l. How will you eliminate spaces on either side of the string ' Flanked by spaces on either side '?
m. What will be the output of the following code snippet?
n. What will get stored in ch in the following code snippet:
[B] Match the following pairs Assumingmsg = 'Keep yourself warm':
| Option A | Description | Option B | Match |
|---|---|---|---|
a. msg.partition(' ') |
Splits at the first space into a 3-tuple. | ('Keep', ' ', 'yourself warm') |
8 |
b. msg.split(' ') |
Splits by space into a list of substrings. | ['Keep', 'yourself', 'warm'] |
7 |
c. msg.startswith('Keep') |
Checks if string starts with ""Keep"". | True | 5 |
d. msg.endswith('Keep') |
Checks if string ends with ""Keep"". | False | 6 |
e. msg.swapcase() |
Swaps uppercase to lowercase and vice versa. | kEEP YOURSELF WARM | 2 |
f. msg.capitalize() |
Capitalizes first letter, lowercases the rest. | Keep yourself warm | 3 |
g. msg.count('e') |
Counts occurrences of 'e'. | 3 | 4 |
h. len(msg) |
Returns the total length of the string. | 18 | 1 |
i. msg[0] |
Accesses the first character. | K | 11 |
j. msg[-1] |
Accesses the last character. | m | 13 |
k. msg[1:1:1] |
Slicing with same start/end yields empty. | empty string | 12 |
l. msg[-1:3] |
Slicing with positive step from right to left invalid. | empty string | 15 |
m. msg[:-3] |
Slices from start up to the last 3 characters. | Keep yourself w | 9 |
n. msg[-3:] |
Slices the last 3 characters. | arm | 14 |
o. msg[0:-2] |
Slices from start up to the last 2 characters. | Keep yourself wa | 10 |
Chapter 5 Decision Control Instructions¶
Keynote¶
5.1 What are Decision Control Instructions?¶
So far statements in all our programs got executed sequentially or one after the other. Sequence of execution of instructions in a program can be altered using: - Decision control instruction - Repetition control instruction
Decision Control Instruction
Three ways for taking decisions in a program:
if condition : else
if condition1 : elif condition2 : elif condition3 : else :
- The
colon (:)afterif,else,elifis compulsory. - Statements in
ifblock,else, block,elifblock have to be indented. Indented statements are treated as a block of statements. - Indentation is used to group statements. Use either 4 spaces or a tab for indentation. Don't mix tabs and spaces. They may appear ok on screen, but would be reported as error.
- In the first form shown above
elseandelifare optional. - In the second form shown above, if condition is True all statements
in
ifblock get executed. If condition is False then statements inelseblock get executed. - In the third form shown above, if a condition fails, then condition in
the following
elifblock is checked. Theelseblock goes to work if all conditions fail. if-elsestatements can be nested. Nesting can be as deep as the program logic demands.
5.2 Nuances of Conditions¶
Condition is built using relation operators <, >, <=, >=, ==, !=.
10 < 20 # yields True
'Santosh' < 'Adi' # yields False, alphabetical order is checked
'gang' < 'God' # yields False, lowercase is > uppercase
a = b is assignment, a == b is comparison.
Ranges or multiple equalities can be checked more naturally.
if a < b < c # checks whether b falls between a and c
if a == b == c # checks whether all three are equal
if 10 != 20 != 10 # evaluates to True, even though 10 != 10 is False
print(bool(3.14)) # prints True
print(bool(25)) # prints True
print(bool(0)) # prints False
5.3 Logical Operators¶
More complex decision making can be done using logical operators and, or and not.
Conditions can be combined using and and or as shown below:
cond1 and cond2 - returns True if both are True, otherwise False
cond1 or cond2 - returns True if one of them is True, otherwise False
Strictly speaking, we need not always combine only conditions with and/or. We can use any valid expression in place of conditions.
Hence when used with expressions we may not get True/False.
and operator evaluates ALL expressions. It returns last expression if all expressions evaluate to True. Otherwise it returns first value that
evaluates to False.
a = 40
b = 30
x = 75 and a >= 20 and b < 60 and 35 # assigns 35 to x
y = -30 and a >= 20 and b < 15 and 35 # assigns False to y
z = -30 and a >= 20 and 0 and 35 # assigns 0 to z
or operator evaluates ALL expressions and returns the first value that evaluates to True. Otherwise it returns last value that evaluates
to False.
a = 40
b = 30
x = 75 or a >= 20 or 60 # assigns 75 to x
y = a >= 20 or 75 or 60 # assigns True to y
z = a < 20 or 0 or 35 # assigns 35 to z
not Condition’s result can be negated using not.
a = not b does not change value of b.
If an operator needs only 1 operand it is known as Unary operator. If it needs two, then it is a binary operator.
not- needs only 1 operand, so unary operator+, -, <, >, and, or, etc.- need 2 operands, so binary operators
5.4 Conditional Expressions¶
Python supports one additional decision-making entity called a conditional expression.
<expr1> if <conditional expression> else <expr2>
<conditional expression> is evaluated first. If it is true, the expression evaluates to <expr1>. If it is false, the expression evaluates to <expr2>.
Examples of condition expressions:
age = 15
status = 'minor' if age < 18 else 'adult' # sets minor
sunny = False
print('Let's go to the', 'beach' if sunny else 'room')
humidity = 76.8
setting = 25 if humidity > 75 else 28 # sets 25
5.5 all( ) and any( )¶
Instead of using the and and or logical operators, we can use the built-in functions all( ) and any( ) to get the same effect. Their usage is shown in the following program:
a, b, c = 10, 20, 30
res = all((a > 5, b > 20, c > 15))
print(res) # prints False, as second condition is False
res = any((a > 5, b > 20, c > 15))
print(res) # prints True since one of the condition is True
all( ) and any( ) both receive a single parameter of the type string, list, tuple, set or dictionary. We have passed a tuple of 3 conditions to them. If argument is a dictionary it is checked whether the keys are true or not.
any( ) function returns True if at least one element of its parameter is True. all( ) function returns True if all elements of its parameter are True.
5.6 Receiving Input¶
The way print( ) function is used to output values on screen, input( ) built-in function can be used to receive input values from keyboard.
input( ) function returns a string, i.e. if 23 is entered it returns '23'. So if we wish to perform arithmetic on the number entered, we need to convert the string into int or float as shown below.
n = input('Enter your name: ')
age = int(input('Enter your age: '))
salary = float(input('Enter your salary: '))
print(name, age, salary)
5.7 Pass Statement¶
passstatement is intended to do nothing on execution. Hence it is often called a no-op instruction.- If we wish that on execution of a statement nothing should happen, we can achieve this using a
passstatement. Its utility is shown inProblem 5.6. It is often used as a placeholder for unimplemented code in anif,loop,functionorclass. This is not a good use of pass. Instead you should use...in its place. - If you use
passit might make one believe that you actually do not intend to do anything in theif/loop/function/class.
5.7.1 Ellipsis¶
Ellipsis is a built-in constant in Python. It is denoted by ....
Ellipsis is used to represent an unknown value. It is often used as a placeholder for unimplemented code in an if, loop, function or class.
Ellipsis is not the same as pass. pass is a statement, while ... is a constant.
Ellipsis is often used as a placeholder for unimplemented code in an if, loop, function or class.
Problems¶
Problem 5.1¶
While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If quantity and price per item are input through the keyboard, write a program to calculate the total expenses.
Program
Tips
input( )returns a string, so it is necessary to convert it intointorfloatsuitably. If we do not do the conversion,qty > 1000will throw an error as a string cannot be compared with anint.str( )should be used to convert totexp to string before doing concatenation using+.
Problem 5.2¶
In a company an employee is paid as under: If his basic salary is less than Rs. 1500, then HRA = 10%of basic salary and DA = 90% of basic salary. If his salary is either equal to or above Rs. 1500, then HRA = Rs. 500 and DA = 98% of basic salary. If the employee's salary is input through the keyboard write a program to find his gross salary.
Program
Tips
ifblock andelseblock can contain multiple statements in them, suitably indented.
Problem 5.3¶
Percentage marks obtained by a student are input through the keyboard. The student gets a division as per the following rules:
Percentage above or equal to 60 - First division
Percentage between 50 and 59 - Second division
Percentage between 40 and 49 - Third division
Percentage less than 40 - Fail
Program
Problem 5.4¶
A company insures its drivers in the following cases: - If the driver is married. - If the driver is unmarried, male & above 30 years of age. - If the driver is unmarried, female & above 25 years of age. In all other cases, the driver is not insured. If the marital status, sex and age of the driver are the inputs, write a program to determine whether the driver should be insured or not.
Program
Problem 5.5¶
Suppose there are four flag variables w, x, y, z. Write a program to check in multiple ways whether one of them is true.
Program
Tips
- any( ) is a built-in function that returns True if at least one of the element of its parameter is True.
- We have to pass a string, list, tuple, set or dictionary to any( ).
- There is another similar function called all( ), which returns True if all elements of its parameter are True. This function too should be passed a string, list, tuple, set or dictionary.
Problem 5.6¶
Given a number n we wish to do the following:
If n is positive - print n * n, set a flag to true
If n is negative - print n * n * n, set a flag to true
if n is 0 - do nothing
n = int(input('Enter a number: '))
if n > 0 :
flag = True
print(n * n)
elif n < 0 :
flag = True
print(n * n * n)
Answer
This is misleading code. At a later date, anybody looking at this code may feel that flag = True should be written outside if and else. Better code will be as follows:Exercise¶
[A] Answer the following questions:¶
a. Write conditional expressions for
- If a < 10 b = 20, else b = 30
- Print 'Morning' if time < 12, otherwise print 'Afternoon'
- If marks >= 70, set remarks to True, otherwise False
[B] What will be the output of the following programs:¶
a.
i, j, k = 4, -1, 0
w = i or j or k
x = i and j and k
y = i or j and k
z = i and j or k
print(w, x, y, z)
c.
x, y, z = 20, 40, 45
if x > y and x > z :
print('biggest = ' + str(x))
elif y > x and y > z :
print('biggest = ' + str(y))
elif z > x and z > y :
print('biggest = ' + str(z))
d.
e. f. g. h. i.[C] Point out the errors, if any, in the following programs:¶
a.
b. c. d. e.x, y = 30, 40
if x == y :
print('x is equal to y')
elseif x > y :
print('x is greater than y')
elseif x < y :
print('x is less than y')
[D] If a = 10, b = 12, c = 0, find the values of the following expressions:¶
[E] Attempt the following questions:¶
- a. Any integer is input through the keyboard. Write a program to find out whether it is an odd number or even number.
- b. Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not.
- c. If ages of Ram, Shyam and Ajay are input through the keyboard, write a program to determine the youngest of the three.
- d. Write a program to check whether a triangle is valid or not, when the three angles of the triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to 180 degrees.
- e. Write a program to find the absolute value of a number entered through the keyboard.
- f. Given the length and breadth of a rectangle, write a program to find whether the area of the rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and breadth = 4 is greater than its perimeter.
- g. Given three points (x1, y1), (x2, y2) and (x3, y3), write a program to check if all the three points fall on one straight line.
- h. Given the coordinates (x, y) of center of a circle and its radius, write a program that will determine whether a point lies inside the circle, on the circle or outside the circle. (Hint: Use
sqrt( )andpow( )functions) - i. Given a point (x, y), write a program to find out if it lies on the X-axis, Y-axis or on the origin.
- j. A year is entered through the keyboard, write a program to determine whether the year is leap or not. Use the logical operators and and or.
- k. If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is valid or not. The triangle is valid if the sum of two sides is greater than the largest of the three sides.
- l. If the three sides of a triangle are entered through the keyboard, write a program to check whether the triangle is isosceles, equilateral, scalene or right angled triangle.
Chapter 6 Repetition Control Instructions¶
Keynote¶
6.1 What are Repetition Control Instructions?¶
It helps us a repeat a set of statements in a program. There are two types of repetition control instructions:
- while
- for
Unlike many other languages there is no do-while loop in Python.
while is used to repeatedly execute instructions as long as condition is true. It has two forms:
- else block is optional. If present, it is executed when condition fails.
- If the while loop is terminated abruptly using a break statement then the else block is not executed.
for is used to iterate over elements of a sequence such as string, tuple or list. It has two forms:
- During each iteration var is assigned the next value from the list.
- In place of a
listastring,tuple,setordictionarycan also be used. - else block is optional. If present, it is executed if loop is not terminated abruptly using break.
6.2 Usage of while loop¶
A while loop can be used in following three situations:
- Repeat a set of statements till a condition remains True.
- Repeat a set of statements a finite number of times.
- Iterate through a string, list and tuple.
When we use while loop to repeat a set of statements till a condition remains True, it means that when we do not know before-hand how many times the statements are to be executed.
num = int(input('Enter a number: '))
while num != 5 :
print(num, num * num)
num = int(input('Enter a number: '))
We can use a while loop to repeat a set of statements a finite number of times.
A while loop can also be used to iterate through a string, a list or a tuple using an index value as shown in the following program:
s = 'Mumbai'
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
tpl = (10, 20, 30, -20, -10)
i = 0
while i < len(lst) :
print(i, s[i], lst[i], tpl[i])
i += 1
- Since items in a set or a dictionary cannot be accessed using an index value, it is better to use a for loop to access their elements.
Of the three usages of while loop shown above, the most popular is the first usage—repeat statements an unknown number of times. The other two situations are usually handled using a for loop.
6.3 Usage of for loop¶
A for loop can be used in following two situations:
- Repeat a set of statements a finite number of times.
- Iterate through a
string,list,tuple,setordictionary.
To repeat a set of statements a finite number of times a built-in function range( ) is used.
range( ) function generates a sequence of integers.
range(10) - generates numbers from 0 to 9.
range(10, 20) - generates numbers from 10 to 19.
range(10, 20, 2) - generates numbers from 10 to 19 in steps of 2.
range(20, 10, -3) - generates numbers from 20 to 9 in steps of -3.
- Note that
range( )cannot generate a sequence offloats. In general,range(start, stop, step)
produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
The list of numbers generated using range( ) can be iterated through using a for loop.
for char in 'Leopard' :
print(char)
for animal in ['Cat', 'Dog', 'Tiger', 'Lion', 'Leopard'] :
print(animal)
for flower in ('Rose', 'Lily', 'Jasmine') :
print(flower)
for num in {10, 20, 30, -10, -25} :
print(num)
for key in {'A101' : 'Rajesh', 'A111' : 'Sunil', 'A112' : 'Rakesh'} :
print(key)
loop in each iteration of the loop char is assigned the next value from the string.
Similarly, in the second, third and fourth for loop, in each iteration of the loop animal/flower/num is assigned the next value form the
list/tuple/set.
- Note that in the last for loop we are printing only the keys in the dictionary. Printing values, or printing both keys and values are covered in Chapter 11.
If while iterating through a collection using a for loop if we wish to also get an index of the item we should use the built-in enumerate( )
function as shown below:
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
for i, ele in enumerate(lst) :
print(i, ele)
6.4 break and continue¶
breakandcontinuestatements can be used withwhileandfor.breakstatement terminates the loop without executing theelseblock.continuestatement skips the rest of the statements in the block and continues with the next iteration of the loop.
6.5 Else Block of a Loop¶
- else block of a while loop should be used in situations where you wish to execute some statements if the loop is terminated normally and not if it is terminated abruptly.
- Such a situation arises if we are to determine whether a number is prime or not.
-
Note the indentation of else. else is working for the while and not for if.
-
In the following example else block will not go to work as the list contains 3, a non-multiple of 10, on encountering which we terminate the loop.
6.6 Nested Loops¶
- A loop can be used inside another loop.
- The inner loop is executed completely for each iteration of the outer loop.
Problems¶
Problem 6.1¶
Write a program that receives 3 sets of values of p, n and r and calculates simple interest for each.
Program
Output
Problem 6.2¶
Write a program that prints numbers from 1 to 10 using an infinite loop. All numbers should get printed in the same line.
Tips
while 1creates an infinite loop, as 1 is non-zero, hence true.- Replacing 1 with any non-zero number will create an infinite loop.
- Another way of creating an infinite loop is
while True. end = ' ' in print( )prints a space after printing i in each iteration. Default value of end is newline ('\n').
Problem 6.3¶
Write a program that prints all unique combinations of 1, 2 and 3.
Program
Problem 6.4¶
Write a program that obtains decimal value of a binary numeric string. For example, decimal value of '1111' is 15.
Program
Tips
- ord(1) is 49, whereas ord('0') is 0.
- b = b[1:] strips the first character in b.
Problem 6.5¶
Write a program that generates the following output using a for loop: A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z, z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,
Program
Output
Tips
- Unicode values of alphabets A-Z are 65-90. Unicode values of alphabets a-z are 97-122.
- Each output of print statement ends with a comma.
- Empty print( ) statement positions the cursor at the beginning of the next line.
Exercise¶
[A] Answer the following questions:
a. When does the else block of a while loop go to work?
b. Can range( ) function be used to generate numbers from 0.1 to 1.0 in steps of 0.1?
c. Can a while loop be nested within a for loop and vice versa?
d. Can a while/for loop be used in an if/else and vice versa?
e. Can a do-while loop be used to repeat a set of statements?
f. How will you write an equivalent for loop for the following:
(g) What will be the output of the following code snippet? for index in range(20, 10, -3) : print(index, end = ' ') (h) Why should break and continue be always used with an if embedded in a while or for loop?
[B] Point out the errors, if any, in the following programs:¶
a.
b.
c. d. e. f. g.[C] Match the following for the values each range( ) function will generate¶
a. range(5) 1. 1, 2, 3, 4
b. range(1, 10, 3) 2. 0, 1, 2, 3, 4
c. range(10, 1, -2) 3. Nothing
d. range(1, 5) 4. 10, 8, 6, 4, 2
e. range(-2) 5. 1, 4, 7
[D] Attempt the following questions:¶
a. Write a program to print first 25 odd numbers using range( ). b. Rewrite the following program using for loop.
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
s = 'Mumbai'
i = 0
while i < len(lst) :
if i > 3 :
break
else :
print(i, lst[i], s[i])
i += 1
d. A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.
e. Write a program to find the factorial value of any number entered through the keyboard.
f. Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 ).
g. Write a program to print all prime numbers from 1 to 300.
h. Write a program to print the multiplication table of the number entered by the user. The table should get displayed in the following form:
i. When interest compounds q times per year at an annual rate of r % for n years, the principal p compounds to an amount a as per the following formula: a = p ( 1 + r / q )nq Write a program to read 10 sets of p, r, n & q and calculate the corresponding as.
j. Write a program to generate all Pythagorean Triplets with side length less than or equal to 30.
k. Population of a town today is 100000. The population has increased steadily at the rate of 10 % per year for last 10 years. Write a program to determine the population at the end of each year in the last decade.
l. Ramanujan number is the smallest number that can be expressed as sum of two cubes in two different ways. Write a program to print all such numbers up to a reasonable limit.
m. Write a program to print 24 hours of day with suitable suffixes like AM, PM, Noon and Midnight.
Chapter 7 Console Input/Output¶
Keynote¶
7.1 Console Input/Output¶
Console Input/Output means input from keyboard and output to screen.
7.2 Console Input¶
Console input can be received using the built-in input( ) function.
General form of input( ) function is s = input('prompt')
- prompt is a string that is displayed on the screen, soliciting a value. input( ) returns a string. If 123 is entered as input, '123' is returned.
# receive full name
name = input('Enter full name')
# separate first name, middle name and surname
fname, mname, lname = input('Enter full name: ').split( )
split( ) function will split the entered fullname with space as a delimiter. The split values will then be assigned to fname, mname, lname.
If we are to receive multiple int values, we can receive them as strings and then convert them to ints.
n1, n2, n3 = input('Enter three values: ').split( )
n1, n2, n3 = int(n1), int(n2), int(n3)
print(n1 + 10, n2 + 20, n3 + 30)
The same thing can be done using in a more compact manner using a feature called list comprehension. It applies int( ) function to every element of the list returned by the split( ) function.
n1, n2, n3 = [int(n) for n in input('Enter three values: ').split( )]
print(n1 + 10, n2 + 20, n3 + 30)
input( ) can be used to receive arbitrary number of values.
numbers = [int(x) for x in input('Enter values: ').split( )]
for n in numbers :
print(n + 10)
input( ) can be used to receive different types of values at a time.
data = input('Enter name, age, salary: ').split( )
name = data[0]
age = int(data[1])
salary = float(data[2])
print(name, age, salary)
7.3 Console Output¶
- Built-in function
print( )is used to send output to screen.
print( ) function has this form:
- This means that by default objects will be printed on screen (sys.stdout), separated by space
(sep = ' ')and last printed object will be followed by a newline (end = '\n').flush = Falseindicates that output stream will not be flushed.
Python has a facility to call functions and pass keyword-based values as arguments. So while calling print( ) we can pass specific values for sep and end. In this case, default values will not be used; instead the values that we pass will be used.
print(a, b, c, sep = ',', end = '!') # prints ',' after each value, ! at end
print(x, y, sep = '...', end = '#') # prints '...' after each value, # at end
7.4 Formatted Printing¶
There are 4 ways to control the formatting of output:
- a. Using formatted string literals - easiest
- b. Using the format( ) method - older
- c. C printf( ) style - legacy
- d. Using slicing and concatenation operation - difficult
Today (a) is most dominantly used method followed by (b).
r, l, b = 1.5678, 10.5, 12.66
print(f'radius = {r}')
print(f'length = {l} breadth = {b} radius = {r}')
name = 'Sushant Ajay Raje'
for n in name.split( ) :
print(f'{n:10}') # print in 10 columns
r, l, b = 1.5678, 10.5, 12.66
name, age, salary = 'Rakshita', 30, 53000.55
# print in order by position of variables using empty {}
print('radius = {} length = {} breadth ={}'.format(r, l, b))
print('name = {} age = {} salary = {}'.format(name, age, salary))
# print in any desired order
print('radius = {2} length = {1} breadth ={0}'.format(r, l, b))
print('age={1} salary={2} name={0}'.format(name, age, salary))
# print name in 15 columns, salary in 10 columns
print('name = {0:15} salary = {1:10}'.format(name, salary))
# print radius in 10 columns, with 2 digits after decimal point
print('radius = {0:10.2f}'.format(r))
- On execution, the above code snippet will produce the following output:
Problems¶
Problem 7.1¶
Write a program to receive radius of a circle, and length and breadth of a rectangle in one call to input( ). Calculate and print the circumference of circle and perimeter of rectangle.
Program
Tips
input( )returns a string, so it is necessary to convert it into int or float suitably, before performing arithmetic operations.
Problem 7.2¶
Write a program to receive 3 integers using one call to input( ). The three integers signify starting value, ending value and step value for a range. The program should use these values to print the number, its square and its cube, all properly right-aligned. Also output the same values left-aligned.
Program
start, end, step = input('Enter start, end, step values: ').split( )
# right aligned printing
for n in range(int(start), int(end), int(step)) :
print(f'{n:>5}{n**2:>7}{n**3:>8}')
print( )
# left aligned printing
for n in range(int(start), int(end), int(step)) :
print('{0:<5}{1:<7}{2:<8}'.format(n, n ** 2, n ** 3))
Output
Tips
{n:>5}will print n right-justified within 5 columns. Use<to left-justify.{0:<5}will left-justify 0th parameter in the list within 5 columns. Use>to right-justify.
Problem 7.3¶
Write a program to maintain names and cell numbers of 4 persons and then print them systematically in a tabular form.
Program
Problem 7.4¶
Suppose there are 5 variables in a program—max, min, mean, sd and var, having some suitable values. Write a program to print these variables properly aligned using multiple fstrings, but one call to print( ).
Program
Problem 7.5¶
Write a program that prints square root and cube root of numbers from 1 to 10, up to 3 decimal places. Ensure that the output is displayed in separate lines, with number center-justified and square and cube roots, right-justified.
Program
Output
Exercises¶
[A] Attempt the following questions:¶
a. How will you make the following code more compact?
b. How will you print "Rendezvous" in a line and retain the cursor in the same line in which the output has been printed?
c. What will be the output of the following code snippet?
d. In the following statement what do > 5, > 7 and > 8 signify?
e. What will be the output of the following code segment?
f. How will you print the output of the following code segment using fstring?
g. How will you receive arbitrary number of floats from keyboard?
h. What changes should be made in
print(f'{'\nx = ':4}{x:>10}{'\ny = ':4}{y:>10}')
to produce the output given below:
x = 14.99
y = 114.39
i. How will you receive a boolean value as input?
j. How will you receive a complex number as input?
k. How will you display price in 10 columns with 4 places beyond decimal points? Assume value of price to be 1.5567894.
l. Write a program to receive an arbitrary number of floats using one input( ) statement. Calculate the average of floats received.
m. Write a program to receive the following using one input( ) statement.
Name of the person
Years of service
Diwali bonus received
Calculate and print the agreement deduction as per the following
formula:
deduction = 2 * years of service + bonus * 5.5 / 100
n. Which import statement should be added to use the built-in functions input( ) and print( )?
o. Is the following statement correct?
p. Write a program to print the following values as shown below:[B] Match the following pairs:¶
| Option A | Option B |
|---|---|
| a. Default value of sep in print( ) | 1. ' ' |
| b. Default value of end in print( ) | 2. Using fstring |
| c. Easiest way to print output | 3. Right justify num in 5 columns |
| d. Return type of split( ) | 4. Left justify num in 5 columns |
| e. print('{num:>5}') | 5. list |
| f. print('{num:<5}') | 6. \n |
Chapter 8 Lists¶
Keynote¶
8.1 Lists¶
Container is an entity which contains multiple data items. It is also known as a collection or a compound data type.
Python has following container data types:
- Lists Tuples
- Sets Dictionaries
A list can grow or shrink during execution of the program. Hence it is also known as a dynamic array. Because of this nature of lists they are commonly used for handling variable length data.
A list is defined by writing comma-separated elements within [ ].
List can contain dissimilar types, though usually they are a collection of similar types. For example:
Items in a list can be repeated, i.e. a list may contain duplicate items.
Like printing, * can be used to repeat an element multiple times. An empty list is also feasible.
ages = [25, 26, 25, 27, 26] # duplicates allowed
num = [10] * 5 # stores [10, 10, 10, 10, 10]
lst = [ ] # empty list, valid
8.2 Accessing List Elements¶
Entire list can be printed by just using the name of the list.
Like strings, individual elements in a list can be accessed using indices. Hence they are also known as sequence types. The index value starts from 0. Like strings, lists can be sliced.8.3 Looping in Lists¶
If we wish to process each item in the list, we should be able to iterate through the list. This can done using a while or for loop.
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
# using while loop
i = 0
while i < len(animals) :
print(animals[ i ])
i += 1
# using more convenient for loop
for a in animals :
print(a)
enumerate( ) function.
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
for index, a in enumerate(animals) :
print(index, a)
8.4 Basic List Operations¶
Mutability - Unlike strings, lists are mutable (changeable). So lists can be updated as shown below:
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
ages = [25, 26, 25, 27, 26, 28, 25]
animals[2] ='Rhinoceros'
ages[5] = 31
ages[2:5] = [24, 25, 32] # sets items 2 to 5 with values 24, 25, 32
ages[2:5] = [ ] # delete items 2 to 4
Concatenation - One list can be concatenated (appended) at the end of another as shown below:
lst = [12, 15, 13, 23, 22, 16, 17]
lst = lst + [33, 44, 55]
print(lst) # prints [12, 15, 13, 23, 22, 16, 17, 33, 44, 55]
s = [10, 20, 30]
t = [100, 200, 300]
z = s + t
print(z) # prints [10, 20, 30, 100, 200, 300]
Conversion - A string/tuple/set can be converted into a list using the list( ) conversion function.
lst = list('Africa') # converts the string to a list ['A', 'f', 'r', 'i', 'c', 'a']
Aliasing - On assigning one list to another, both refer to the same list. Changing one changes the other. This assignment is often known as shallow copy or aliasing.
lst1 = [10, 20, 30, 40, 50]
lst2 = lst1 # doesn't copy list. lst2 refers to same list as lst1
print(lst1) # prints [10, 20, 30, 40, 50]
print(lst2) # prints [10, 20, 30, 40, 50]
lst1[0] = 100
print(lst1[0], lst2[0]) # prints 100 100
Cloning - This involves copying contents of one list into another. After copying both refer to different lists, though both contain same values. Changing one list, doesn't change another. This operation is often known as deep copy.
lst1 = [10, 20, 30, 40, 50]
lst2 = [ ] # empty list
lst2 = lst2 + lst1 # lst1, lst2 refer to different lists
print(lst1) # prints [10, 20, 30, 40, 50]
print(lst2) # prints [10, 20, 30, 40, 50]
lst1[0] = 100
print(lst1[0], lst2[0]) # prints 100, 10
lst = ['a', 'e', 'i', 'o', 'u']
res = 'a' in lst # return True since 'a' is present in list
res = 'z' not in lst # return True since 'z' is absent in list
Identity - Whether the two variables are referring to the same list can be checked using the is identity operator as shown below:
lst1 = [10, 20, 30, 40, 50]
lst2 = [10, 20, 30, 40, 50]
lst3 = lst1
print(lst1 is lst2) # prints False
print(lst1 is lst3) # prints True
print(lst1 is not lst2) # prints True
num1 = 10
num2 = 10
s1 = 'Hi'
s2 = 'Hi'
print( num1 is num2) # prints True
print( s1 is s2) # prints True
Comparison - It is possible to compare contents of two lists. Comparison is done item by item till there is a mismatch. In following code it would be decided that a is less than b when 3 and 5 are compared.
Emptiness - We can check if a list is empty using not operator.
- Alternately, we can convert a list to a bool and check the result.
Also note that the following values are considered to be False:
None
Number equivalent to zero: 0, 0.0, 0j
Empty string, list and tuple: ' ', "", [ ], ( )
Empty set and dictionary: { }
8.5 Using Built-in Functions on Lists¶
Many built-in functions can be used with lists.
len(lst) # return number of items in the list
max(lst) # return maximum element in the list
min(lst) # return minimum element in the list
sum(lst) # return sum of all elements in the list
any(lst) # return True if any element of lst is True
all(lst) # return True if all elements of lst are True
del( ) # deletes element or slice or entire list
sorted(lst) # return sorted list, lst remains unchanged
reversed(lst) # used for reversing lst
sorted( ) and reversed( ) are discussed in section after next. del( ) function's usage is shown below:
lst1 = [10, 20, 30, 40, 50]
lst = del(lst[3]) # delete 3rd item in the list
del(lst[2:5]) # delete items 2 to 4 from the list
del(a[:]) # delete entire list
lst = [ ] # another way to delete an entire list
If multiple variables are referring to same list, then deleting one doesn't delete the others.
lst1 = [10, 20, 30, 40, 50]
lst3 = lst2 = lst1 # all refer to same list
lst1 = [ ] # lst1 refers to empty list; lst2, lst3 to original list
print(lst2) # prints [10, 20, 30, 40, 50]
print(lst3) # prints [10, 20, 30, 40, 50]
If multiple variables are referring to same list and we wish to delete all, we can do so as shown below:
lst2[:] = [ ] # list is emptied by deleting all items
print(lst2) # prints [ ]
print(lst3) # prints [ ]
8.6 List Methods¶
Any list is an object of type list. Its methods can be accessed using the syntax lst.method( ). Usage of some of the commonly used methods is shown below:
lst = [12, 15, 13, 23, 22, 16, 17] # create list
lst.append(22) # add new item at end
lst.remove(13) # delete item 13 from list
lst.remove(30) # reports valueError as 30 is absent in lst
lst.pop( ) # removes last item in list
lst.pop(3) # removes 3rd item in the list
lst.insert(3,21) # insert 21 at 3rd position
lst.count(23) # return no. of times 23 appears in lst
idx = lst.index(22) # return index of item 22
idx = lst.index(50) # reports valueError as 50 is absent in lst
8.7 Sorting and Reversing¶
Usage of list methods for reversing a list and for sorting is shown below:
lst = [10, 2, 0, 50, 4]
lst.reverse( )
print(lst) # prints [4, 50, 0, 2, 10]
lst.sort( )
print(lst) # prints [0, 2, 4, 10, 50]
lst.sort(reverse = True) # sort items in reverse order
print(lst) # prints [50, 10, 4, 2, 0]
- Note that
reverse( )andsort( )do not return a list. Both manipulate the list in place.
Usage of built-in functions for reversing a list and for sorting is shown below:
lst = [10, 2, 0, 50, 4]
print(sorted(lst)) # prints [0, 2, 4, 10, 50]
print(sorted(lst, reverse = True)) # prints [50, 10, 4, 2, 0]
print(list(reversed(lst))) # prints [4, 50, 0, 2, 10]
sorted( ) function returns a new sorted list and keeps the original list unchanged. Also, reversed( ) function returns a list_reverseiterator object which has to converted into a list to get a reversed list.
Reversal is also possible using a slicing operation as shown below:
8.8 List Varieties¶
It is possible to create a list of lists (nested lists).
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]
c = [a, b]
print(c[0][0], c[1][2]) # 0th element of 0th list, 2nd ele. of 1st list
A list may be embedded in another list.
It is possible to unpack a string or list within a list using the*operator.
s = 'Hello'
l = [*s]
print(l) # outputs ['H', 'e', 'l', 'l', 'o']
x = [1, 2, 3, 4]
y = [10, 20, *x, 30]
print(y) # outputs [10, 20, 1, 2, 3, 4, 30]
8.9 Stack Data Structure¶
A data structure refers to an arrangement of data in memory. Popular data structures are stack, queue, tree, graph and map.
Stack is a last in first out (LIFO) list, i.e. last element that is added to the list is the first element that is removed from it.
Adding an element to a stack is called push operation and removing an element from it is called pop operation. Both these operations are carried out at the rear end of the list.
Push and pop operations can be carried out using the append( ) and pop( ) methods of list object. This is demonstrated in Program 8.3.
8.10 Queue Data Structure¶
Queue is a first in first out (FIFO) list, i.e. first element that is added to the list is the first element that is removed from it.
Lists are not efficient for implementation of queue data structure.
With lists removal of items from beginning is not efficient, since it involves shifting of rest of the elements by 1 position after deletion.
Hence for fast additions and deletions, dequeue class of collections module is preferred.
Deque stands for double ended queue. Addition and deletion in a deque can take place at both ends.
Usage of deque class to implement a queue data structure is demonstrated in Program 8.4.
Problems¶
Problem 8.1¶
Perform the following operations on a list of names.
- Create a list of 5 names - 'Anil', 'Amol', 'Aditya', 'Avi', 'Alka'
- Insert a name 'Anuj' before 'Aditya'
- Append a name 'Zulu'
- Delete 'Avi' from the list
- Replace 'Anil' with 'AnilKumar'
- Sort all the names in the list
- Print reversed sorted list
Program
# Create a list of 5 names
names = ['Anil', 'Amol', 'Aditya', 'Avi', 'Alka']
print(names)
# insert a name 'Anuj' before 'Aditya'
names.insert(2,'Anuj')
print(names)
# append a name 'Zulu'
names.append('Zulu')
print(names)
# delete 'Avi' from the list
names.remove('Avi')
print(names)
# replace 'Anil' with 'AnilKumar'
i=names.index('Anil')
names[i] = 'AnilKumar'
print(names)
# sort all the names in the list
names.sort( )
print(names)
# print reversed sorted list
names.reverse( )
print(names)
Output
['Anil', 'Amol', 'Aditya', 'Avi', 'Alka']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Avi', 'Alka']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Avi', 'Alka', 'Zulu']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Alka', 'Zulu']
['AnilKumar', 'Amol', 'Anuj', 'Aditya', 'Alka', 'Zulu']
['Aditya', 'Alka', 'Amol', 'AnilKumar', 'Anuj', 'Zulu']
['Zulu', 'Anuj', 'AnilKumar', 'Amol', 'Alka', 'Aditya']
Problem 8.2¶
Perform the following operations on a list of numbers.
- Create a list of 5 odd numbers
- Create a list of 5 even numbers
- Combine the two lists
- Add prime numbers 11, 17, 29 at the beginning of the combined list
- Report how many elements are present in the list
- Replace last 3 numbers in the list with 100, 200, 300
- Delete all the numbers in the list
- Delete the list
Program
# create a list of 5 odd numbers
a = [1, 3, 5, 7, 9]
print(a)
# create a list of 5 even numbers
b = [2, 4, 6, 8, 10]
print(b)
# combine the two lists
a = a + b
print(a)
# add prime numbers 11, 17, 29 at the beginning of the combined list
a = [11, 17, 29] + a
print(a)
# report how many elements are present in the list
num = len(a)
print(num)
# replace last 3 numbers in the list with 100, 200, 300
a[num-3:num] = [100, 200, 300]
print(a)
# delete all the numbers in the list
a[:] = [ ]
print(a)
# delete the list
del a
Output
Problem 8.3¶
Write a program to implement a Stack data structure. Stack is a Last In First Out (LIFO) list in which addition and deletion takes place at the same end.
Program
Problem 8.4¶
Write a program to implement a Queue data structure. Queue is a First In First Out (FIFO) list, in which addition takes place at the rear end of the queue and deletion takes place at the front end of the queue.
Program
Output
Problem 8.5¶
Write a program to generate and store in a list 20 random numbers in the range 10 to 100. From this list delete all those entries which have value between 20 and 50. Print the remaining list.
Program
Output
Problem 8.6¶
Write a program to add two 3 x 4 matrices.
Program
mat1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
mat2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
mat3 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# iterate through rows
for i in range(len(mat1)) :
# iterate through columns
for j in range(len(mat1[0])) :
mat3[i][j] = mat1[i][j] + mat2[i][j]
print(mat3)
Exercises¶
[A] What will be the output of the following programs:¶
a.
b.
c.d.
e.
f.
num1 = [10, 20, 30, 40, 50]
num2 = num1
print(id(num1))
print(type(num2))
print(isinstance(num1, list))
print(num1 is num2)
g.
h. i. j.[B] Attempt the following questions:¶
a. Which of the following is a valid List?
b. What will happen on execution of the following code snippet?c. The following code snippet deletes elements 30 and 40 from the list:
In which other way can the same effect be obtained?d. Which of the following is an INCORRECT list?
e. From the list given below
How will you create the list num2 containing:f. Given a list
How will you sort it in descending order?g. Given a list
How will you check whether 30 is present in the list or not?h. Given a list
How will you insert 30 between 25 and 4?i. Given a string
How will you obtain a list['H', 'e', 'l', 'l', 'o'] from it?
[C] Answer the following questions:¶
a. Write a program to create a list of 5 odd integers. Replace the third element with a list of 4 even integers. Flatten, sort and print the list.
b. Suppose a list contains 20 integers generated randomly. Receive a number from the keyboard and report position of all occurrences of this number in the list.
c. Suppose a list has 20 numbers. Write a program that removes all duplicates from this list.
d. Suppose a list contains positive and negative numbers. Write a program to create two lists—one containing positive numbers and another containing negative numbers.
e. Suppose a list contains 5 strings. Write a program to convert all these strings to uppercase.
f. Write a program that converts list of temperatures in Fahrenheit degrees to equivalent Celsius degrees.
g. Write a program to obtain a median value of a list of numbers, without disturbing the order of the numbers in the list.
h. A list contains only positive and negative integers. Write a program to obtain the number of negative numbers present in the list.
i. Suppose a list contains several words. Write a program to create another list that contains first character of each word present in the first list.
j. A list contains 10 numbers. Write a program to eliminate all duplicates from the list.
k. Write a program to find the mean, median and mode of a list of 10 numbers.
Chapter 9 Tuples¶
Keynote¶
9.1 Tuples¶
What are Tuples?
- Though a list can store dissimilar data, it is commonly used for storing similar data.
- Though a tuple can store similar data it is commonly used for storing dissimilar data. The tuple data is enclosed within ( ) as shown below
a = ( ) # empty tuple
b = (10,) # tuple with one item. , after 10 is necessary
c = ('Sunny', 25, 34555.50) # tuple with dissimilar items
d = (10, 20, 30, 40) # tuple with similar items
- While creating the tuple
b, if we do not use the comma after 10,bis treated to be of typeint.
While initializing a tuple, we may drop ( ).
c = 'Sunny', 25, 34555.50 # tuple with multiple items
print(type(c)) # c is of the type tuple
Items in a tuple can be repeated, i.e. tuple may contain duplicate items. However, unlike list, tuple elements cannot be repeated using a *.
9.2 Accessing Tuple Elements¶
Entire tuple can be printed by just using the name of the tuple.
Tuple is an ordered collection. So order of insertion of elements in a tuple is same as the order of access. So like a string and list, tuple items too can be accessed using indices, starting with 0.
Like strings and lists, tuples too can be sliced to yield smaller tuples.
emp = ('Sunny', 23, 23000, 1760, 2040)
print(emp[1:3]) # prints (23, 23000)
print(emp[3:]) # prints (1760, 2040)
print(emp[:3]) # prints ('Sunny', 23, 23000)
9.3 Looping in Tuples¶
If we wish to process each item in a tuple, we should be able to iterate through it. This can be done using a while loop or for loop.
tpl = (10, 20, 30, 40, 50)
i = 0
while i < len(tpl) :
print(tpl[i])
i += 1
for n in tpl :
print(n)
While iterating through a tuple using a for loop, if we wish to keep track of index of the element that is being currently processed, we can do so using the built-in enumerate( ) function.
9.4 Basic Tuple Operations¶
Mutability - Unlike a list, a tuple is immutable, i.e. it cannot be modified.
msg = ('Fall', 'In', 'Line')
msg[0] ='FALL' # error
msg[1:3] = ('Above', 'Mark') # error
msg = ('Fall', 'In', 'Line')
msg.append('Like') # error
msg.remove('Line') # error
msg.insert(1, 'Above') # error
Though a tuple itself is immutable, it can contain mutable objects like lists.
If a tuple contains a list, the list can be modified since list is a mutable object.s = ([1, 2, 3, 4], [10, 20], 'Oynx')
s[1][1] = 45 # changes first item of first list, i.e. 20
print(s) # prints ([1, 2, 3, 4], [4, 45], 'Oynx')
# one more way to change first item of first list
p = s[1]
p[1] = 100
print(s) # prints ([1, 2, 3, 4], [4, 100], 'Oynx')
The other basic operations that are done on a tuple are very similar to the ones done on a list. These operations are discussed in Chapter 8. You may try the following operations on tuples as an exercise:
- Concatenation
- Merging
- Conversion
- Aliasing
- Cloning
- Searching
- Identity
- Comparison
- Emptiness
9.5 Using Built-in Functions on Tuples¶
Many built-in functions can be used with tuples.
t = (12, 15, 13, 23, 22, 16, 17) # create tuple
len(t) # return number of items in tuple t
max(t) # return maximum element in tuple t
min(t) # return minimum element in tuple t
sum(t) # return sum of all elements in tuple t
any(t) # return True if any element of tpl is True
all(t) # return True if all elements of tpl are True
sorted(t) # return sorted list (not sorted tuple)
reversed(t) # used for reversing t
9.6 Tuple Methods¶
Any tuple is an object of type tuple. Its methods can be accessed using the syntax tpl.method( ). Usage of two methods is shown below:
tpl = (12, 15, 13, 23, 22) # create tuple
print(tpl.count(23)) # return no. of times 23 appears in lst
print(tpl.index(22)) # return index of item 22
print(tpl.index(50)) # reports valueError as 50 is absent in lst
9.7 Tuple Varieties¶
It is possible to create a tuple of tuples.
a = (1, 3, 5, 7, 9)
b = (2, 4, 6, 8, 10)
c = (a, b)
print(c[0][0], c[1][2]) # 0th element of 0th tuple, 2nd ele of 1st tuple
records = (
('Priya', 24, 3455.50), ('Sunny', 25, 4555.50),
('Sunday', 25, 4505.50), ('Sonia', 27, 4455.55)
)
print(records[0][0], records[0][1], records[0][2])
print(records[1][0], records[1][1], records[1][2])
for n, a, s in records :
print(n,a,s)
*operator.
It is possible to create a list of tuples, or a tuple of lists.
lst = [('Priya', 24, 3455.50), ('Sunny', 25, 4555.50)]
tpl = (['Priya', 24, 3455.50], ['Sunny', 25, 4555.50])
import operator
# each embedded tuple/list contains name, age, salary
lst = [('Shailesh', 24, 3455.50), ('Priyanka', 25, 4555.50)]
tpl = (['Shailesh', 24, 3455.50], ['Priyanka', 25, 4555.50])
print(sorted(lst))
print(sorted(tpl))
print(sorted(lst, key = operator.itemgetter(2)))
print(sorted(tpl, key = operator.itemgetter(2)))
sorted( ) sorts by first item in list/tuple, i.e. name.
If we wish to sort by salary, we need to use the itemgetter( ) function of operator module.
The key parameter of sorted( ) requires a key function (to be applied to objects to be sorted) rather than a single key value.
operator.itemgetter(2) will give us a function that fetches salary from a list/tuple.
In general, operator.itemgetter(n) constructs a function that takes a list/tuple as input, and fetches the n-th element out of it.
Problems¶
Problem 8.1¶
Pass a tuple to the divmod( ) function and obtain the quotient and the remainder.
Tips
- If we pass t to divmod( ) an error is reported. We have to unpack the tuple into two distinct values and then pass them to
divmod( ).divmod( )returns a tuple consisting of quotient and remainder.
Problem 8.2¶
Write a Python program to perform the following operations:
- Pack first 10 multiples of 10 into a tuple
- Unpack the tuple into 10 variables, each holding 1 value
- Unpack the tuple such that first value gets stored in variable x, last value in y and all values in between into disposable variables _
- Unpack the tuple such that first value gets stored in variable i, last value in j and all values in between into a single disposable variable _
Program
Output
Tips
- Disposable variable _ is usally used when you do not wish to use the variable further, and is being used only as a place-holder.
Problem 8.3¶
A list contains names of boys and girls as its elements. Boys' names are stored as tuples. Write a Python program to find out number of boys and girls in the list.
Program
Tips
isinstance( )functions checks whether ele is an instance of tuple type.- Note that since the tuples contain a single element, it is followed by a comma.
Problem 8.4¶
A list contains tuples containing roll number, names and age of student. Write a Python program to gather all the names from this list into another list.
Program
Tips
nlstis an empty to begin with. During each iteration name is extracted from the tuple usingele[1]and added to the current list of names innlst.
Problem 8.5¶
Given the following tuple ('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd'), write a Python program to carry out the following operations:
- Add an ! at the end of the tuple
- Convert a tuple to a string
- Extract ('b', 'b') from the tuple
- Find out number of occurrences of 'e' in the tuple
- Check whether 'r' exists in the tuple
- Convert the tuple to a list
- Delete characters 'b, 'b', 'e', 'r' from the tuple
Program
tpl = ('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd')
# addition of ! is not possible as tuple is an immutable
# so to add ! we need to create a new tuple and then make tpl refer to it
tpl = tpl + ('!',)
print(tpl)
# convert tuple to string
s = ''.join(tpl)
print(s)
# extract ('b', 'b') from the tuple
t = tpl[3:5]
print(t)
# count number of 'e' in the tuple
count = tpl.count('e')
print('count = ', count)
# check whether 'r' exists in the tuple
print('r' in tpl)
# Convert the tuple to a list
lst = list(tpl)
print(lst)
# tuples are immutable, so we cannot remove elements from it
# we need to split the tuple, eliminate the unwanted element and then
merge the tuples
tpl = tpl[:3] + tpl[7:]
print(tpl)
Output
Exercises¶
[A] Which of the following properties apply to string, list and tuple?¶
- Iterable
- Sliceable
- Indexable
- Immutable
- Sequence
- Can be empty
- Sorted collection
- Ordered collection
- Unordered collection
- Elements can be accessed using their position in the collection
[B] Which of the following operations can be performed on string, list and tuple?¶
- a = b + c
- a += b
- Appending a new element at the end
- Deletion of an element at the 0th position
- Modification of last element
- In place reversal
[C] Answer the following questions:¶
a. Is this a valid tuple? tpl = ('Square')
b. What will be the output of the following code snippet?
num1 = num2 = (10, 20, 30, 40, 50)
print(id(num1), type(num2))
print(isinstance(num1, tuple))
print(num1 is num2)
print(num1 is not num2)
print(20 in num1)
print(30 not in num2)
c. Suppose a date is represented as a tuple (d, m, y). Write a program to create two date tuples and find the number of days between the two dates.
d. Create a list of tuples. Each tuple should contain an item and its price in float. Write a program to sort the tuples in descending order by price. Hint: Use operator.itemgetter( ).
e. Store the data about shares held by a user as tuples containing the following information about shares:
Write a program to determine:- Total cost of the portfolio.
- Total amount gained or lost.
- Percentage profit made or loss incurred.
f. Write a program to remove empty tuple from a list of tuples.
g. Write a program to create following 3 lists:
- a list of names
- a list of roll numbers
- a list of marks
Generate and print a list of tuples containing name, roll number and marks from the 3 lists. From this list generate 3 tuples—one containing all names, another containing all roll numbers and third containing all marks.
[D] Match the following pairs:¶
| Options A | Options B |
|---|---|
a. tpl1 = ('A',) |
1. tuple of length 6 |
b. tpl1 = ('A') |
2. tuple of lists |
c. t = tpl[::-1] |
3. Tuple |
d. ('A', 'B', 'C', 'D') |
4. list of tuples |
e. [(1, 2), (2, 3), (4, 5)] |
5. String |
f. tpl = tuple(range(2, 5)) |
6. Sorts tuple |
g. ([1, 2], [3, 4], [5, 6]) |
7. (2, 3, 4) |
h. t = tuple('Ajooba') |
8. tuple of strings |
i. [*a, *b, *c] |
9. Unpacking of tuples in a list |
j. (*a, *b, *c) |
10. Unpacking of lists in a tuple |
Chapter 27 Numpy Library¶
Keynote¶
- Numpy stands for Numerical Python. It is a popular library used for solving problems in science and engineering. It provides a high-performance multidimensional array object, and methods for fast operations on arrays, these operations include mathematical, logical, shape manipulation, sorting, selecting, I/O, statistical operations, etc.
27.1 Creation of Array¶
- To use Numpy Library, it must be downloaded and installed as shown below:
- Though Numpy Array looks like Python list, it is optimized to run faster than lists.
- Unlike lists, all elements of a Numpy array are of the same type.
- To create a Numpy array we have to use the np.array() function and pass a list of numbers to it as shown below:
- If we mix ints and floats, Numpy defaults to array of flatts.
- While creating an array if we do not specify the type of elements in it, then from the values Numpy guesses the type. If we wish we can also specify the type.
- 2D array (matrix) is a collection of several 1D arrays and 3D array is a collection of several 2D arrrays. They can be created as shown below:
- Array of complex numbers can also be created:
27.2 Creation of Filler Arrays¶
- We can create Numpy Arrays which contain initial placeholder values, which can be replaced later.
- For example, we can create arrays which are filled with all 0s, all 1s or a fixed value. We can even create empty arrays which are filled with garbage values.
import numpy as np
a1 = np.empty((3,4)) # creates 2D array with garbage values
a2 = np.zeros((3,4)) # creates 2D array of zeros.
a3 = np.ones((3,4)) # creates 2D array of ones
a4 = np.full((2,2),7) # creates 2D array with all values set to 7
import numpy as np
a1 = np.random.random((4)) # creates array with 4 random val
a2 = np.range(5) # creates [0,1,2,3,4]
a3 = np.linspace(0,2,5) # creates [0.0 0.5 1.0 1.5 2.0]
27.3 Array Attributes¶
- A Numpy array has several attributes that indicate the element type, element size, shape of array, size of array, etc.
- We can obtain the type of elements present in a Numpy array their size, their location in memory, etc.
import numpy as np a1 = np.array([1,2,3,4]) a2 = np.array([1.1,2.2,3.3,4.4]) print(a1.dtype) # prints int32 print(a2.dtype) # prints float64 print(a1.itemsize) # prints 4 print(a2.itemsize) # prints 8 print(a1.nbytes) # prints 16 print(a2.nbytes) # prints 16 print(a1.data) # prints <memory at 0x024BEE08> print(a1.strides) # prints (4,) print(a2.data) # prints <memory at 0x0291EE08> print(a2.strides) # prints (8,) - Here dtype specifies the type of elements contained in the array. Number of bytes occupied by individual array element and by entrie array are available through attributes itemsize and nbytes, respectively.
- data gives the address in memory where the array begins (often called base address) and strides indicates the number of bytes that should be added to base address to reach the next array element.
- Attributes ndim, shape and size yield the number of dimensions in the array the shape of the array and the number of elements in it.
27.4 Array Operations¶
- Many operations can be performed on Numpy arrays. These operations are compact and fast. The speed is achieved through the already precompiled routines present in the library.
- The different array operations include the following:
- (a) Arithmetic Operations
- (b) Statistical Operations
- © Linear Algebra Operations
- (d) Bitwise Operations
- (e) Copying, Sorting
- (f) Comparsion Operations
27.4.1 Arithmetic Operations¶
- You can perform many operations like +,-,,/,% on two arrays.When we use these operators, ther operations are performed on corresponding elements of the two arrays. Instead of using these operators, you may also use methods like **add()*, subtract(), multiply(), divide(), and remainder(). These operations are often known as vector operations.
- We can perform scalar arithmetic operations on array elements.
- In place operators +=,-=, /= modify an existing array, instead of creating a new one.
- Other operations that can be done on array elements include exp(), sqrt(), cos(), sin(), log().
27.4.2 Statistical Operations¶
- Numpy can perform following operations either on all elements of the array or on the elements of the specified axis. Note that axis means dimension, so a 1D array has 1 axis, a 2D array has 2 axes and so on.
import numpy as np a = np.array([[1,2,3,],[4,5,6]]) print(a.sum()) print(a.min()) # finds minimum in array print(a.max(axis = 0)) # finds maximum in each column print(a.max(axis = 1)) # finds maximum in each row print(a.sum(axis = 1)) # sum along axis 1 print(a.cumsum(axis = 1)) # cumulative sum print(np.mean(a)) print(np.median(a)) print(np.corrcoef(a)) print(np.std(a)) - It is imprtant to understand the use of axis in calls to max(). Our array is a 2D array of dimensions 2 x 3. When we use axis = 0, don't think about this as 'max along columns' or 'max along rows'. Instead, think that when we use axis = 0, Numpy finds maximum by condensing (or collapsing) size 2. So, result is an array containing 3 elements [4,5,6]. Similarly, when we use axis = 1, Numpy condenses size 3, resulting in an array containing elements [3,6].
27.4.3 Linear Algebra Operations¶
- Note the difference between the two multiplication operations:
- Transpose of a matrix can also be obtained:
- Trace of a matrix is the sum of its diagonal elements. It can be obtained as shown below.
- Inverse of a matrix ia a matrix which when multiplied with the original matrix results in an identity matrix.
- We can also obtain a solution to linear simultaneous equations. For example, the solution to a system of equations $$ 3x + y = 9 $$ $\(and\)$ $$ x = 2y = 8 $$ can be obtained as shown below.
27.4.4 Bitwise Operations¶
- Bitwise operations can also be performed on array elements as shown below:
import numpy as np a1 = np.array([[10,2,3,4],[5,6,7,8]]) a2 = np.array([[1,1,1,1],[2,2,2,2]]) a3 = np.bitwise_and(a1,a2) a4 = np.bitwise_or(a1,a2) a5 = np.bitwise_xor(a1,a2) a6 = invert(a1) a7 = np.left_shift(a1,3) # shifts each element 3 bits to left a8 = np.right_shift(a1,2) # shifts each element 2 bits to right
27.4.5 Copying and Sorting¶
- There 3 possible copy operations - no copy, shallow copy operation and deep-copy.
- In no copy, neither the object nor its data gets copied. Only address of array is assigned to a variable. In shallow copy a new array object is created but it points to the same data as the old array object. In deep copy a new array object and copies old object's attributes and data in it.
import numpy as np a = np.array([[3,3,7],[1,5,2]]) b = a # no copy print(b is a) # prints True, a and b are referring to same array b[0][0] = 100 # changes a[0][0] c = a.view() print(c is a) # prints false, a and c are referring to diff objectts c[0][0] = 50 # prints [[3 3 7][1 5 2]] print(d is a) # prints False d, a are referring to diff objects d[0][0] = 150 # doesn't change a[0][0] a = np.array([[3,7,6],[1,5,2]]) b = np.array([[3,7,6],[1,5,2]]) a.sort() b.sort(axis = 0) # sort elements in each column
27.4.6 Comparison¶
- Three types of comparsions are common with arrays:
- (a) Compare all elements of an array witth one value and return a Boolean array of the result.
- (b) Compare corresponding elements of two arrays and return an array of Booleans.
- © Compare shape and elements of two array, return TRUE if equl, FALS other wise.
- Comparsion of all array elements with one value:
- Comparison of corresponding array elements:
- Comparison of two arrays:
27.4.7 Indexing and Slicing¶
- As with lists, single element indexing is 0-based and accepts negative indices for indexing from end of the array.
- Individual elements of a mutli-dimensional array are accessed using multiple indices.
- Note that in a[1][2], a new temporary array is created after first index (i.e. [1,5,9]) and then its second element is fetched.
- Slicing works same as lists except that it can be applied to multiple dimensions.
- Note that in b[1:3][2:4] firstly arrays[[1,5,9,2,4][0,0,3,1,5]] is created and then elements 2 to 3 are fetched from it. Since this new array has only two elements, it returns [].
27.5 Array Manipulation¶
- Once an array is created we can change its shape using the method reshape(). This method returns an array ccontaining same data, but a new shape.
- We can faltten a multi-dimensional array.
- We can append values at the end of an existing array.
- Note that the values are appended to a copy of existing array. The values being appended must be of same shape as existing array. If axis is not specified, values can be any shape and will be flattened before use.
- There exist functions that let you insert elements, delete elements, split array etc. You are advised to expore them on your own.
Problems¶
Problem 27.1¶
- Write a program that constructs a 3D array of dimensions 4 x 2 x 3. Initialize the array to some values. Find the maximum along each axis.
Program
Output
Problem 27.2¶
- Write a program to create an array of shape 5 x 4 containing elements 1 to 20. Find the sum of entire array as well as sums along each row and column.
Program
Output
Problem 27.3¶
- Write a program to achieve the following tasks:
- Create an array a of size 10 with each element of it set to a value 3.
- Find the memory size of this array and its individual element.
- Create an array b of size 10 with values ranging from 0 to 90 evenly spaced.
- Reverse elements of array b.
- Add arrays a and b and store the result in array c.
Program
Output
Problem 27.4¶
- Write a program to achieve the following tasks:
- Create a 2D array of size 5 x 5 with elements on border set to 1, and all inner elements set to a value 3.
- Multiply a 4 x 3 matrix containing all 2s.
- Given a 1D array, negate all elements which are between 2 and 8, in place.
Program
Output
Exercises¶
[A] State whether the following statements are True or False: - [ ] Numpy library gets installed when we install Python. - [ ] Numpy arrays work faster than lists. - [ ] Numpy array elements can be of different types. - [ ] Once created, a Numpy arrays size and shape can be changed dynmically. - [ ] np.array_equal(a,b) would return True if shape and elements of a and b match.
[B] Answer the following questions: - (a) How will you create Numpy Array of first 10 natural numbers? - (b) Can we create an array of complex numbers using Numpy? - © How would you create 5 arrays each of size 3 x 4 x 5 and fill them with values, 0, 1,5, random and garbage values respectively? - (d) How would you create a 50-element array and fill it with odd numbers starting from 1? - (e) How will you obtain the type of elements, number of elements, base address and number of bytes occupied by the following Numpy array? - (f) How will you obtain dimension and shape of a Numpy array created by a1 = np.array([[1,2,3,4],[5,6,7,8]])? - (g) Given two 3 x 4 matrices how would you add, subtract, multiply and divide corresponding elements of these matrices? - (h) Which of the following are the scalar arithmetic operations on Numpy array?
```python
a1 = np.array([[10,2,3,4],[5,6,7,8]])
a2 = np.array([[1,1,1,1],[2,2,2,2]])
a3 = a1 + a2
a4 = a1 - a2
a5 = a1 * a2
a6 = a1 / a2
a7 = a1 % a2
a8 = a1 ** 2
a9 += a1
a10 += 5
a11 = a1 + 2
a12 = a1 ** 2
```
[C] Match The Following pairs:
| Code / Function | Operation / Description |
|---|---|
(a) s = np.trace(a) |
1. Statistical Operation |
(b) s = a.cumsum(axis = 1) |
2. Linear Algebra Operation |
© a2 = np.copy(a1) |
3. Deep copy operation |
(d) print(a1 < 2) |
4. Corresponding ele.comparison |
(e) print(a1 > a2) |
5. Comparison with one value |
(f) print(a[1:3][3:6]) |
6. Bitwise Operation |
(g) a2 = invert(a1) |
7. Slicing Operation |
🇲🇲 Myanmar
Python Mastery 🐍 - သင့်ရဲ့ Python လေ့လာရေးခရီးစဉ် (Zero to Hero)¶
📖 အကျဉ်းချုပ်¶
Python Mastery မှ ကြိုဆိုပါတယ်။ ဒီသင်ခန်းစာတွေကို Graphic Era Hill University မှ AI, Cyber Security နဲ့ Data Science ကျောင်းသား၊ DataCamp Python Data Associate Certified ရရှိထားသူ Joseph က သေချာ စုစည်းတင်ဆက်ထားတာ ဖြစ်ပါတယ်။
ဒီ Repository ဟာ Python programming ကို ကျွမ်းကျင်ချင်သူ ဘယ်သူမဆို လွယ်ကူထိရောက်စွာ လေ့လာနိုင်ဖို့ ရည်ရွယ်ပါတယ်။ သင်ဟာ Programming ကို အခုမှ စတင်လေ့လာသူပဲဖြစ်ဖြစ်၊ ရှိပြီးသား Python knowledge ကို ပိုမိုနက်ရှိုင်းအောင် လေ့လာချင်သူပဲဖြစ်ဖြစ်၊ ဒီသင်ခန်းစာတွေမှာ လက်တွေ့စမ်းသပ်နိုင်တဲ့ interactive notebooks တွေ၊ ရှင်းလင်းတဲ့ ဥပမာတွေ ပါဝင်တာကြောင့် ပျော်ရွှင်စွာ လေ့လာနိုင်မှာပါ။
🚀 ဘာတွေ လေ့လာရမလဲ?¶
ဒီလမ်းညွှန်မှာ အခြေခံကစပြီး အဆင့်မြင့် Concepts တွေအထိ စုံလင်စွာ ပါဝင်ပါတယ် -
- Core Fundamentals: Variables, data types, loops နဲ့ functions တွေကို ကျွမ်းကျင်စွာ သုံးတတ်ခြင်း။
- Control Flow: Code တွေရေးတဲ့အခါ ဆုံးဖြတ်ချက်ချတာ (Decision making) နဲ့ လုပ်ဆောင်ချက်တွေကို ထပ်ခါထပ်ခါ လုပ်ခိုင်းတာ (Looping) တွေကို နားလည်ခြင်း။
- Data Structures: Python ရဲ့ အားကောင်းတဲ့ lists, dictionaries နဲ့ sets တွေကို အသုံးပြုပြီး ထိရောက်တဲ့ Solutions တွေ တည်ဆောက်ခြင်း။
- Modern Best Practices: သန့်ရှင်းသပ်ရပ်ပြီး စွမ်းဆောင်ရည်ကောင်းတဲ့ Python code တွေ ရေးသားနည်း (Clean Code)။
- Scientific Computing: NumPy လိုမျိုး အစွမ်းထက်တဲ့ Libraries တွေကို မိတ်ဆက်ပေးခြင်း။
📚 Repository မှာ ပါဝင်တဲ့ အရာများ¶
ဒီ Repository မှာ လေ့လာရလွယ်ကူအောင် အောက်ပါအတိုင်း စီစဉ်ထားပါတယ် -
- Interactive Jupyter Notebooks: ကိုယ်တိုင် Run ကြည့်လို့ရတဲ့ လက်တွေ့ကုတ်တွေ ပါဝင်ပါတယ်။
- Chapter-wise Organization: ခေါင်းစဉ်အလိုက် အဆင့်ဆင့် လေ့လာနိုင်အောင် စီစဉ်ထားပါတယ်။
- Practical Examples: လက်တွေ့လုပ်ငန်းခွင်သုံး Code အပိုင်းအစတွေနဲ့ လေ့ကျင့်ခန်းတွေ ပါဝင်ပါတယ်။
- Clear Explanations: သဘောတရားတွေကို အသေးစိတ် ရှင်းလင်းချက်များ ပါဝင်ပါတယ်။
ရရှိနိုင်သော အခန်းများ (Chapters)¶
| အခန်း | ခေါင်းစဉ် | အကြောင်းအရာ |
|---|---|---|
| Chapter 1 | Introduction to Python | Python ရဲ့ သမိုင်းကြောင်း၊ လူကြိုက်များမှုနဲ့ Programming ပုံစံများ။ Python ကို ဘာကြောင့် ကမ္ဘာတစ်ဝန်းက Developers တွေ ရွေးချယ်ကြတာလဲ ဆိုတာနဲ့ functional, procedural, object-oriented, event-driven စတဲ့ programming models တွေကို လေ့လာရပါမယ်။ |
| Chapter 2 | Python Basics | Variables, data types, operators နဲ့ expressions စတဲ့ အခြေခံအုတ်မြစ်တွေကို ခိုင်မာအောင် တည်ဆောက်ခြင်း။ |
| Chapter 3 | Input and Output | User ဆီက Input ယူနည်းနဲ့ Output ပြန်ပြနည်းများ။ Formatting options တွေနဲ့ အကောင်းဆုံး အလေ့အကျင့်များကို လေ့လာခြင်း။ |
| Chapter 4 | Strings | စာသား (Text) တွေကို ကိုင်တွယ်ဖြေရှင်းခြင်း။ String ဖန်တီးပုံ၊ ဖြတ်တောက်ပုံ (Slicing)၊ ပြုပြင်ပုံ (Formatting) နဲ့ Built-in methods တွေကို လေ့လာခြင်း။ |
| Chapter 5 | Decision Control | if, if-else, elif တွေကို သုံးပြီး သင့် Program ကို ဉာဏ်ရည်ရှိအောင် လုပ်ဆောင်ခြင်း။ Conditional logic တွေကို လက်တွေ့အသုံးချခြင်း။ |
| Chapter 6 | Repetition Control | for နဲ့ while loops တွေကို သုံးပြီး ထပ်ခါတလဲလဲ လုပ်ရမယ့် အလုပ်တွေကို Automate လုပ်ခြင်း။ |
| Chapter 7 | Functions | Code တွေကို အပိုင်းလိုက်ခွဲပြီး (Modular) ပြန်လည်အသုံးပြုလို့ရအောင် (Reusable) ရေးသားခြင်း။ Parameters, return values နဲ့ Scope အကြောင်းများ။ |
| Chapter 8 | Lists | Python ရဲ့ အသုံးအဝင်ဆုံး Data structure ဖြစ်တဲ့ List အကြောင်း။ List operations တွေနဲ့ Stack/Queue data structures တွေကို တည်ဆောက်ခြင်း။ |
| Chapter 9 | Advanced Topics | သင့်ရဲ့ Programming skill ကို မြှင့်တင်ပေးမယ့် ပိုမိုနက်ရှိုင်းတဲ့ Python concept များ။ |
| Chapter 27 | NumPy & Advanced Concepts | Scientific computing အတွက် NumPy ကို အသုံးပြုခြင်း။ Decorators, generators, context managers စတဲ့ Advanced features များနဲ့ Production-ready application တွေ တည်ဆောက်နည်းများ။ |
[!NOTE] နောက်ထပ် အခန်းတွေကိုလည်း တဖြည်းဖြည်းချင်း ထပ်ထည့်ပေးသွားမှာ ဖြစ်ပါတယ်။ အခန်းတိုင်းမှာ လက်တွေ့လေ့ကျင့်ခန်းတွေနဲ့ Real-world applications တွေ ပါဝင်ပါတယ်။
🎯 ဘယ်သူတွေ လေ့လာသင့်လဲ?¶
- 🌱 Beginners: Python ကို အခုမှ စတင်လေ့လာမယ့်သူများ။
- 🎓 Students: Python အခြေခံကို ပိုမိုခိုင်မာအောင် လုပ်ချင်တဲ့ ကျောင်းသား/သူများ။
- 💼 Developers: အလုပ်အင်တာဗျူးတွေအတွက် ပြင်ဆင်နေသူများ။
- 🔄 Career Switchers: စနစ်တကျ လေ့လာသင်ယူဖို့ ရှာဖွေနေသူများ။
- 🚀 Enthusiasts: လက်တွေ့ Project တွေ ရေးဆွဲချင်တဲ့ ဝါသနာရှင်များ။
🛠️ စတင်လေ့လာခြင်း (Getting Started)¶
လိုအပ်ချက်များ (Prerequisites)¶
- Python 3.7 (သို့မဟုတ်) အထက်
- Jupyter Notebook
- Programming အခြေခံအနည်းငယ် (မရှိလည်း အဆင်ပြေပါတယ်)
Installation (ထည့်သွင်းပုံ)¶
-
Repository ကို Clone လုပ်ပါ
-
လိုအပ်တာတွေ Install လုပ်ပါ
-
Jupyter Notebook ကို ဖွင့်ပါ
-
စတင်လေ့လာပါ
- Chapter အလိုက် Notebook တွေကို ဖွင့်ကြည့်ပါ။
- Code cells တွေကို ကိုယ်တိုင် Run ကြည့်ပါ။
- ရှင်းလင်းချက်တွေကို ဖတ်ပြီး ကိုယ်ပိုင်အရှိန်နဲ့ လေ့လာပါ။
Online Documentation ဖတ်ရှုရန်¶
Browser ကနေပဲ သက်တောင့်သက်သာ ဖတ်ချင်တယ်ဆိုရင်တော့ အောက်ပါ Link မှာ ဝင်ဖတ်နိုင်ပါတယ် -
🌐 https://rose1996iv.github.io/PythonWithJoe/
(သို့မဟုတ်) စက်ထဲမှာ run ပြီးဖတ်ချင်ရင် -
ပြီးရင် Browser မှာ http://127.0.0.1:8000 ကို ဖွင့်လိုက်ပါ။
📘 စာအုပ်အကြောင်း¶
"Python With Joe" ဟာ လူပေါင်းများစွာကို Python ကျွမ်းကျင်အောင် ကူညီပေးခဲ့တဲ့ လမ်းညွှန်စာအုပ်ဖြစ်ပါတယ်။ 5th Edition မှာတော့ ခေတ်မီ Python နည်းလမ်းတွေအပြင် အောက်ပါတို့ ပါဝင်ပါတယ် -
- Beginners တွေအတွက် နားလည်လွယ်တဲ့ ရှင်းလင်းချက်များ
- လွယ်ရာမှ ခက်ရာသို့ တဖြည်းဖြည်းချင်း လေ့လာနိုင်မယ့် ပုံစံ
- များပြားလှတဲ့ Code examples များ
- လက်တွေ့လေ့ကျင့်ခန်းများနှင့် စိန်ခေါ်မှုများ
မှီငြမ်းထားသည်များ: Yashavant Kanetkar, Aditya Kanetkar, DataCamp, GoalKicker Python notes
ပြုစုသူ: Joseph
🤝 ပါဝင်ကူညီခြင်း (Contributing)¶
ဒီ Resource ကို ပိုကောင်းအောင် ဝိုင်းဝန်းကူညီပေးဖို့ ဖိတ်ခေါ်ပါတယ်ခင်ဗျာ။ အောက်ပါအချက်တွေနဲ့ ကူညီနိုင်ပါတယ် -
- 📝 Content Improvements: ရှင်းလင်းချက်တွေ ပြင်ဆင်တာ၊ ဥပမာတွေ ထပ်ထည့်တာ။
- 🐛 Bug Reports: အမှားတွေ့ရင် ပြောပြပေးတာ။
- 💡 Suggestions: အခန်းသစ်တွေ၊ ခေါင်းစဉ်သစ်တွေ အကြံပြုတာ။
📞 ဆက်သွယ်ရန် (Contact & Support)¶
မေးချင်တာတွေ၊ အကြံပြုချင်တာတွေရှိရင် ဆက်သွယ်နိုင်ပါတယ် -
- 🐛 Issues: Open an issue
- 📧 Repository: PythonWithJoe
📄 License¶
This repository is licensed under the MIT License - see the LICENSE file for details.
Happy Learning! 🐍✨
ဒီနေ့ပဲ သင့်ရဲ့ Python ခရီးစဉ်ကို စတင်လိုက်ပြီး Beginner ဘဝကနေ ယုံကြည်မှုရှိတဲ့ Developer တစ်ယောက်အဖြစ် ပြောင်းလဲလိုက်ပါ။
🗓️ Last Updated: January 3, 2026
Chapter 1 Introduction To Python¶
Keynote¶
1.1 What is Python? (Python ဆိုတာ ဘာလဲ)¶
- Python ဆိုတာက Guido Van Rossum ဖန်တီးခဲ့တဲ့ High-level programming language တစ်ခု ဖြစ်ပါတယ်။ ဖန်တီးရှင် Guido ကိုတော့ ချစ်စနိုးနဲ့ Benevolent Dictator For Life လို့ တင်စားခေါ်ဝေါ်ကြပါတယ်။
- Python ကို ၁၉၉၁ ခုနှစ်မှာ စတင်မိတ်ဆက်ခဲ့တာပါ။ အခုဆိုရင် Windows နဲ့ Linux အပါအဝင် Operating Systems တော်တော်များများမှာ Python interpreters တွေကို အသုံးပြုနိုင်နေပါပြီ။
- Python ရေးတဲ့ Programmers တွေကိုတော့ Pythonists (သို့မဟုတ်) Pythonistas လို့ ခေါ်လေ့ရှိကြပါတယ်။
1.2 Reasons for Popularity (ဘာလို့ ဒီလောက် ခေတ်စားလာတာလဲ)¶
Python ဒီလောက်ထိ လူကြိုက်များပြီး ခေတ်စားလာရတဲ့ အကြောင်းရင်းတွေ အများကြီးရှိပါတယ်။ တချို့အချက်တွေကတော့ -
(a) Free (အခမဲ့ရတယ်):
- Python က သုံးရတာ Free ဖြစ်သလို ဖြန့်ဝေရတာလည်း လွတ်လပ်တယ်။ ပြီးတော့ Community support လည်း အရမ်းကောင်းတယ်။
- Python interpreter ကို အဓိက Platform တိုင်းအတွက် ရနိုင်ပါတယ်။
(b) Software quality (Software အရည်အသွေး):
- ရိုးရိုး Scripting languages တွေနဲ့ တခြားရိုးရာ Languages တွေထက် ပိုကောင်းတယ်။
- Code က ဖတ်ရလွယ်တဲ့အတွက် ပြန်သုံးရတာ (Reusable)၊ ပြင်ဆင်ထိန်းသိမ်းရတာ (Maintainable) အရမ်းအဆင်ပြေတယ်။
- အဆင့်မြင့်တဲ့ Reuse mechanisms တွေကိုလည်း Support လုပ်ပေးတယ်။
© Developer productivity (ရေးသားသူအတွက် တွင်ကျယ်မှု):
- Statically typed languages တွေထက်စာရင် အများကြီး ပိုပြီး အလုပ်တွင်တယ်။
- Code ရေးရတာ အများကြီး ပိုတိုတယ်။
- စာရိုက်ရတာ သက်သာမယ်၊ Debug လုပ်ရတာနဲ့ Maintain လုပ်ရတာ ပိုလွယ်တယ်။
- Compile လုပ်တာတို့၊ Link ချိတ်တာတို့လို ကြာတဲ့အဆင့်တွေ လုပ်နေစရာ မလိုတော့ဘူး။
(d) Program portability (နေရာစုံမှာ အလုပ်လုပ်နိုင်မှု):
- Python Programs တွေက Platform တော်တော်များများမှာ ဘာမှ ပြင်စရာမလိုဘဲ ဒီတိုင်း Run လို့ရတယ်။
- လက်ရှိ လူသုံးများတဲ့ Platform တိုင်းမှာ Python က အလုပ်လုပ်ပါတယ်။
- ကိုယ်ရေးထားတဲ့ Program ကို Platform အသစ်တစ်ခုဆီ ပြောင်းတင်ချင်ရင် (Porting) ဟိုဘက်ဒီဘက် Cut and paste လုပ်လိုက်ရုံပါပဲ။ ဒါက GUI၊ DB access၊ Web programming၊ OS interfacing နဲ့ Directory access စတာတွေအထိ အကျုံးဝင်ပါတယ်။
(e) Support libraries (Library အထောက်အပံ့များ):
- Text pattern matching ကနေ Networking အပိုင်းထိ Library support အရမ်းတောင့်တင်းတယ်။
- Third party libraries တွေလည်း တော်တော်များများ စုဆောင်းထားပြီးသား ရှိတယ်။
- Web site တည်ဆောက်တာ၊ Numeric programming၊ Game development နဲ့ Machine Learning တွေအတွက်ပါ Libraries တွေ အစုံရှိတယ်။
(f) Component integration (တခြားအရာများနှင့် ချိတ်ဆက်နိုင်မှု):
- C၊ C++ libraries တွေနဲ့ Java components တွေကို လှမ်းခေါ်သုံးလို့ရတယ်။
- COM၊ .NET လို Frameworks တွေနဲ့လည်း ချိတ်ဆက်လုပ်ဆောင်နိုင်တယ်။
- SOAP၊ XML-RPC၊ CORBA လို Interfaces တွေကနေတစ်ဆင့် Network ပေါ်မှာ ချိတ်ဆက်ဆောင်ရွက်နိုင်တယ်။
- လိုအပ်တဲ့ Glue code လေးတွေ သုံးလိုက်မယ်ဆိုရင် Python ကနေ C++၊ Java၊ C# classes တွေကို Subclass လုပ်ပြီး ကိုယ့် Program ရဲ့ လုပ်ဆောင်နိုင်စွမ်းကို ချဲ့ထွင်လို့ရတယ်။
- Product တစ်ခုကို Customization လုပ်တာတို့၊ Extension လုပ်တာတို့မှာ လူသုံးများကြတယ်။
(g) Enjoyment (သုံးရတာ အရသာရှိခြင်း):
- သုံးရတာ လွယ်ကူရိုးရှင်းတယ်။
- Built-in toolset တွေ ပါတယ်။
- အလုပ်လုပ်ရတာမျိုး မဟုတ်ဘဲ Programming ရေးရတာကိုက ပျော်စရာကောင်းနေစေတယ်။
1.3 What sets Python apart? (Python ကို ဘာက ထူးခြားစေတာလဲ)¶
(a) Powerful (စွမ်းရည်မြင့်မားခြင်း):
- Dynamic typing ဖြစ်တယ်။
- Variable declaration ကြေညာပေးစရာ မလိုဘူး။
- Automatic allocation နဲ့ Garbage Collection ပါပြီးသား။
- Classes၊ Modules နဲ့ Exceptions တွေကို Support လုပ်တယ်။
- Componentization နဲ့ Reuse လုပ်တာတွေကို ခွင့်ပြုပေးတယ်။
- Lists၊ Dictionaries၊ Tuples စတဲ့ Containers တွေက အရမ်း Powerful ဖြစ်တယ်။
(b) Ready-made stuff (အဆင်သင့်သုံးနိုင်သော အရာများ):
- Joining၊ Slicing၊ Sorting၊ Mapping စတဲ့ Operations တွေအတွက် Support ပါတယ်။
- Library ပိုင်း တောင့်တင်းတယ်။
- Third-party utilities တွေလည်း အများကြီးရှိတယ်။
© Ease of use (အသုံးပြုရ လွယ်ကူခြင်း):
- ရိုက်ပြီး တန်း Run လိုက်ရုံပဲ (Type and run)။
- Compile နဲ့ Link အဆင့်တွေ မလိုဘူး။
- Interactive programming experience ကို ရစေတယ်။
- အလုပ်ပြီးမြောက်မှု မြန်ဆန်တယ် (Rapid turnaround)။
- Programs တွေက ရိုးရှင်းတယ်၊ ပိုပြီး Compact ဖြစ်သလို ပိုပြီး Flexible ဖြစ်တယ်။
1.4 Where is Python used? (Python ကို ဘယ်နေရာတွေမှာ သုံးကြလဲ)¶
Python ကို နေရာစုံ၊ ကဏ္ဍစုံမှာ အသုံးပြုကြပါတယ်။ အဓိက အသုံးပြုကြတာတွေကတော့
- System programming
- GUI applications တွေ တည်ဆောက်တဲ့နေရာ
- Internet scripting
- Component integration (တခြား Component တွေနဲ့ ချိတ်ဆက်ခြင်း)
- Database programming
- Rapid prototyping (နမူနာပုံစံ အမြန်ချရေးခြင်း)
- Numeric နဲ့ Scientific programming
- Game programming
- Robotics programming
1.5 Who uses Python today? (လက်ရှိ Python ကို ဘယ်သူတွေ သုံးနေကြလဲ)¶
နာမည်ကြီး Organizations တော်တော်များများက Python ကို ရည်ရွယ်ချက်အမျိုးမျိုးနဲ့ သုံးနေကြပါတယ်။ ဥပမာအားဖြင့်
- Google - သူတို့ရဲ့ Web search system မှာ သုံးပါတယ်။
- YouTube - Video Sharing service အပိုင်းမှာ သုံးပါတယ်။
- Bit-torrent - Peer to Peer file sharing system မှာ သုံးပါတယ်။
- Intel, HP, Seagate, IBM, Qualcomm - Hardware testing ပြုလုပ်တဲ့အပိုင်းမှာ သုံးပါတယ်။
- Pixar, Industrial Light and Magic - Movie animation ဖန်တီးတဲ့နေရာမှာ သုံးပါတယ်။
- JP Morgan, Chase, UBS - Financial market forecasting (ငွေကြေးဈေးကွက် ခန့်မှန်းတွက်ချက်ခြင်း) အတွက် သုံးပါတယ်။
- NASA, FermiLab - Scientific programming အတွက် သုံးပါတယ်။
- iRobot - စီးပွားဖြစ်ရောင်းချတဲ့ Robot vacuum cleaners တွေမှာ သုံးပါတယ်။
- NSA - Cryptographic နဲ့ Intelligence analysis ပြုလုပ်ရာမှာ သုံးပါတယ်။
- IronPort - Email Servers တွေမှာ သုံးပါတယ်။
1.6 Programming Paradigms¶
- Paradigm ဆိုတာက Organization principle တစ်ခုပါ၊ Model လို့လည်း ခေါ်ကြပါတယ်။
- Programming paradigm/model ဆိုတာ Computer programs တွေရဲ့ Structure နဲ့ Elements တွေကို ဘယ်လိုတည်ဆောက်မလဲဆိုတဲ့ ပုံစံ (Style) တစ်ခုပါပဲ။
- Functional၊ Procedural၊ Object-oriented၊ Event-driven စသဖြင့် Programming models တွေ အများကြီး ရှိပါတယ်။
- Languages တော်တော်များများက Paradigms တစ်ခုမက Support ပေးထားကြပါတယ်။ ဥပမာ - Python ဆိုရင် Functional၊ Procedural၊ Object-oriented နဲ့ Event-driven programming models အားလုံးကို Support လုပ်ပါတယ်။
- တချို့အခြေအနေတွေမှာ Functional programming က ရွေးချယ်စရာ ဖြစ်နေပေမယ့်၊ တခြားအခြေအနေတွေမှာတော့ Procedural programming က ပိုပြီး အဆင်ပြေတာမျိုး ရှိပါတယ်။
- Paradigms တွေဆိုတာ တစ်ခုနဲ့တစ်ခု သီးသန့်ခွဲခြားထားရမယ့်အရာတွေ မဟုတ်ပါဘူး။ Program တစ်ပုဒ်တည်းမှာတင် Paradigms အများကြီးကို ရောသုံးလို့ ရပါတယ်။
1.6.1 Functional Programming Model¶
- Functional programming က ပြဿနာတစ်ခုကို Functions အသေးလေးတွေအဖြစ် ခွဲခြမ်းစိတ်ဖြာလိုက်တာပါ။ အဲဒီ Functions တွေက Program ရဲ့ အဓိက Logic တွေ ဖြစ်လာပါတယ်။
- Functions တွေက Input parameters တွေကို လက်ခံပြီး Outputs တွေကို ထုတ်ပေးပါတယ်။ Python မှာ lambda၊ map၊ reduce နဲ့ filter လိုမျိုး Functional programming techniques တွေ ပါဝင်ပါတယ်။ ဒါတွေကို Chapter 15 ရောက်ရင် အသေးစိတ် ဆွေးနွေးပါမယ်။
- ဒီ Model မှာ Computation (တွက်ချက်ခြင်း) ကို Mathematical functions တွေ ဖြေရှင်းတွက်ချက်သလိုမျိုး သဘောထားပါတယ်။ ဥပမာ - ကိန်းဂဏန်းတစ်ခုရဲ့ Factorial value ရှာတာ၊ သို့မဟုတ် ဘယ်နှခုမြောက် Fibonacci number လဲဆိုတာ ရှာချင်ရင် အောက်က Functions တွေကို သုံးနိုင်ပါတယ် -
factorial(n) = 1 if n == 0
= n * factorial(n - 1) if n > 0
fibo(n) = 0 if n = 0
= 1 if n = 1
= fibo(n - 2) + fibo(n - 1) if n > 1
- Function တစ်ခုရဲ့ Output value က သူ့ရဲ့ Arguments တွေအပေါ်မှာပဲ မူတည်ပါတယ်။ ဒါကြောင့် Function တစ်ခုကို တူညီတဲ့ Value နဲ့ ခေါ်လိုက်တိုင်း အမြဲတမ်း တူညီတဲ့ Result ကိုပဲ ရရှိစေပါတယ်။ ဒီအချက်ကြောင့် Parallel execution လုပ်ဖို့အတွက် အထူးသင့်တော်ပါတယ်။
- ဘယ် Function ကမှ တခြား Variables တွေအပေါ် Side effects မဖြစ်စေပါဘူး (State က မပြောင်းလဲဘဲ ကျန်ရှိနေပါတယ်)။
- Functional programming model ကို Declarative programming paradigm လို့လည်း ခေါ်လေ့ရှိကြပါတယ်။ ဘာကြောင့်လဲဆိုတော့ Statements တွေအစား Expressions (သို့မဟုတ်) Declarations တွေနဲ့ Programming ရေးသားလို့ ဖြစ်ပါတယ်။
1.6.2 Procedural Programming Model¶
- Procedural programming က ပြဿနာတစ်ခုကို Procedures အစုအဝေးတွေအဖြစ် ခွဲခြားလိုက်တာပါ။ ဒီ Procedures တွေက Program ရဲ့ အဓိက Logic တွေ ဖြစ်လာပါတယ်။
- Procedures တွေက Input parameters တွေကို လက်ခံပြီး Outputs တွေကို ထုတ်ပေးပါတယ်။ Python မှာ Functions၊ Classes၊ Modules စတဲ့ Procedural programming techniques တွေ ပါဝင်ပါတယ်။ ဒါတွေကို Chapter 15 မှာ ဆွေးနွေးသွားပါမယ်။
- ဒီ Model မှာ Computation (တွက်ချက်ခြင်း) ကို Procedures တွေရဲ့ Evaluation လုပ်ဆောင်ချက်အဖြစ် သတ်မှတ်ပါတယ်။ ဥပမာ - ကိန်းဂဏန်းတစ်ခုရဲ့ Factorial value ရှာတာ၊ သို့မဟုတ် ဘယ်နှခုမြောက် Fibonacci number လဲဆိုတာ ရှာချင်ရင် အောက်က Procedures တွေကို သုံးနိုင်ပါတယ် -
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def fibo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibo(n - 2) + fibo(n - 1)
- Procedure တစ်ခုရဲ့ Output value က သူ့ရဲ့ Arguments တွေအပေါ်မှာပဲ မူတည်ပါတယ်။ ဒါကြောင့် Procedure တစ်ခုကို တူညီတဲ့ Value နဲ့ ခေါ်လိုက်တိုင်း အမြဲတမ်း တူညီတဲ့ Result ကိုပဲ ရရှိစေပါတယ်။ ဒီအချက်ကြောင့် Parallel execution လုပ်ဖို့အတွက် အထူးသင့်တော်ပါတယ်။
- ဘယ် Procedure ကမှ တခြား Variables တွေအပေါ် Side effects မဖြစ်စေပါဘူး (State က မပြောင်းလဲဘဲ ကျန်ရှိနေပါတယ်)။
- Procedural programming model ကို Imperative programming paradigm လို့လည်း ခေါ်ကြပါတယ်။ ဘာကြောင့်လဲဆိုတော့ Expressions (သို့မဟုတ်) Declarations တွေအစား Statements (သို့မဟုတ်) Instructions တွေနဲ့ Programming လုပ်လို့ ဖြစ်ပါတယ်။
-
Procedural programming က Statement တစ်ကြောင်းချင်းစီ (Procedure တစ်ခုချင်းစီ) အလုပ်လုပ်ပြီး ပြဿနာကို ဖြေရှင်းပါတယ်။ ဒါကြောင့် သူ့မှာ သတ်မှတ်ထားတဲ့ Order အတိုင်း Execute လုပ်မယ့် အဆင့်ဆင့် ပါဝင်ပါတယ်။
-
သူကလည်း Functions တွေကို သုံးပေမယ့် Functional programming မှာ သုံးတဲ့ Mathematical functions တွေနဲ့တော့ မတူပါဘူး။ Functional programming က Expressions တွေကို အဓိကထားပြီး၊ Procedural programming ကတော့ Statements တွေကို အဓိကထားပါတယ်။
- Statements တွေမှာ Values မရှိပါဘူး၊ အဲဒီအစား သူတို့က Conceptual machine ရဲ့ State တစ်ခုခုကို ပြောင်းလဲပေးလိုက်ပါတယ်။
- တူညီတဲ့ Language expression ဖြစ်ပေမယ့် Run နေတဲ့ Program ရဲ့ Global state အပေါ်မူတည်ပြီး အချိန်မတူရင် Values ကွဲပြားသွားနိုင်ပါတယ်။ နောက်ပြီး Functions တွေက Program ရဲ့ State ကို ပြောင်းလဲနိုင်ပါတယ်။
- Explicit sequence of statements တွေနဲ့ State ကို ပြောင်းလဲတဲ့အတွက် Procedural programming model ကို Imperative programming လို့ ခေါ်လေ့ရှိကြတာပါ။
1.6.3 Object-oriented Programming Model¶
- ဒီ Model ကတော့ ကွန်ပျူတာထဲမှာ Objects လေးတွေနဲ့ တည်ဆောက်ထားတဲ့ ကမ္ဘာငယ်လေးတစ်ခု ဖန်တီးပြီး Real world (အပြင်လောကကြီး) ကို တုပထားတာ ဖြစ်ပါတယ်။
- တက္ကသိုလ်တစ်ခုရဲ့ System မှာဆိုရင် VC (ပါမောက္ခချုပ်)၊ Professors၊ Non-teaching staff၊ Students၊ Courses၊ Semesters၊ Examinations စတာတွေ အားလုံးက Objects တွေ ဖြစ်နိုင်ပါတယ်။
- Object တိုင်းမှာ State (values) နဲ့ Behavior (interface/methods) ရှိကြပါတယ်။ Objects တွေက သူတို့ကို ဖန်တီးလိုက်တဲ့ Class အပေါ်မူတည်ပြီး State နဲ့ Behavior တွေကို ရရှိပါတယ်။
- Objects တွေက တစ်ခုနဲ့တစ်ခု Interface methods တွေကို လှမ်းခေါ်ပြီး Messages တွေ ပေးပို့ကာ အပြန်အလှန် ဆက်သွယ်လုပ်ဆောင်ကြပါတယ်။
1.6.4 Event-driven Programming Model¶
- ဒီ Model ကိုတော့ Windows၊ Check boxes၊ Buttons၊ Combo-boxes၊ Scroll bars၊ Menus စတာတွေပါတဲ့ GUI applications တွေ ရေးသားရာမှာ အများဆုံး သုံးကြပါတယ်။
- ကျွန်တော်တို့က ဒီ Elements တွေနဲ့ ထိတွေ့ဆက်ဆံလိုက်တဲ့အခါ (ဥပမာ - Button နှိပ်တာ၊ Scrollbar ဆွဲတာ၊ Menu item ရွေးတာမျိုး)၊ Events တွေ ဖြစ်ပေါ်လာပြီး ဒီ Elements တွေက Messages တွေကို ထုတ်လွှတ်ပေးပါတယ်။ ဒီ GUI elements တွေမှာ Register လုပ်ထားတဲ့ Listener methods တွေက အဲဒီ Events တွေကို တုံ့ပြန်ဆောင်ရွက်ပါတယ်။
- ကျွန်တော်တို့ GUI elements တွေကို သုံးတဲ့ပုံစံအပေါ် မူတည်ပြီး Events တွေက ဘယ်အစဉ်လိုက် ဖြစ်မယ်ဆိုတာ အသေအချာ ပြောလို့မရတဲ့အတွက် Listeners တွေက Events တွေကို Asynchronous manner (အစဉ်လိုက်မဟုတ်သော ပုံစံ) နဲ့ Handle လုပ်နိုင်စွမ်း ရှိရပါမယ်။
Exercises¶
[A] Answer the following (အောက်ပါတို့ကို ဖြေဆိုပါ):
- (a) Python ကို လူသုံးများတဲ့ နယ်ပယ် (၅) ခုကို ဖော်ပြပါ။
- (b) Event-driven programming ကို ဘယ်နေရာမှာ အဓိက အသုံးပြုသလဲ။
- © ဘာကြောင့် Python ကို Portable language လို့ ခေါ်တာလဲ။
- (d) ဒီ Chapter မှာ ဆွေးနွေးခဲ့တဲ့ Programming models အမျိုးမျိုးရဲ့ အရေးအကြီးဆုံး Feature တစ်ခုစီက ဘာလဲ။
- (e) အောက်ပါအချက်များထဲမှ ဘယ်အရာက Python ရဲ့ Feature မဟုတ်သလဲ။
- Static typing
- Dynamic typing
- Error numbers ဖြင့် Run-time error handling လုပ်ခြင်း
- Lists၊ Dictionaries၊ Tuples ကဲ့သို့သော Containers များအတွက် Library support ပါဝင်ခြင်း
- (f) အောက်ပါ Programming models တစ်ခုစီအတွက် ဥပမာ Application တစ်ခုစီ ပေးပါ။
- Functional model
- Procedural model
- Object-oriented model
- Event-driven model
[B] State whether the following statements are True or False (အောက်ပါအဆိုများသည် မှန်/မှား ဖော်ပြပါ):
- (a) Python သည် အခမဲ့အသုံးပြုနိုင်ပြီး ဖြန့်ဝေနိုင်သည်။
- (b) Python Program တစ်ပုဒ်တည်းကို မတူညီတဲ့ OS - Microprocessor တွဲဖက်တွေမှာ အသုံးပြုနိုင်သည်။
- © Python Program ထဲတွင် C++ သို့မဟုတ် Java libraries များကို အသုံးပြုနိုင်သည်။
- (d) Python တွင် Variable ၏ Type ကို ၎င်း၏ အသုံးပြုပုံအပေါ် မူတည်ပြီး ဆုံးဖြတ်သည်။
- (e) Python ကို GUI applications များ တည်ဆောက်ရန် အသုံးမပြုနိုင်ပါ။
- (f) Python သည် Functional၊ Procedural၊ Object-oriented နှင့် Event-driven programming models များကို Support လုပ်သည်။
- (g) GUI applications များသည် Event-driven programming model ကို အခြေခံသည်။
- (h) Functional programming model သည် Objects အများအပြား ချိတ်ဆက်လုပ်ဆောင်ခြင်း ဖြစ်သည်။
[C] Match the following pairs (အောက်ပါတို့ကို တွဲဖက်ပါ):
- (a) Functional programming -> 1. GUI element based interaction
- (b) Event-driven programming -> 2. Interaction of objects
- © Procedural programming -> 3. Statements
- (d) OOP -> 4. Maths-like functions
[D] Fill in the blanks (ကွက်လပ်ဖြည့်ပါ):
- (a) Functional programming paradigm ကို ________ programming model ဟုလည်း ခေါ်သည်။
- (b) Procedural programming paradigm ကို ________ programming model ဟုလည်း ခေါ်သည်။
- © Python ကို _________ က ဖန်တီးခဲ့သည်။
- (d) Python Programmers များကို _________ ဟု ခေါ်လေ့ရှိသည်။
Chapter 2 Getting Started¶
Keynote¶
1.1 Python Specification¶
-
Python ဆိုတာက Language တစ်ခုအတွက် Specification တစ်ခုဖြစ်ပြီး နည်းလမ်းအမျိုးမျိုးနဲ့ Implement လုပ်လို့ရပါတယ်။ ဒီ Specification ကို မတူညီတဲ့ Languages တွေနဲ့ ရေးသားထားတဲ့ Implementations တွေ အများကြီး ရှိပါတယ်။
-
လူသုံးများတဲ့ Python implementations တွေကတော့ -
- CPython - C နဲ့ ရေးထားတဲ့ Reference implementation ဖြစ်ပါတယ်။
- PyPy - RPython လို့ခေါ်တဲ့ Python language ရဲ့ subset တစ်ခုနဲ့ ရေးထားတာပါ။
- Jython - Java နဲ့ ရေးထားတာပါ။
-
IronPython - C# နဲ့ ရေးထားတာပါ။
-
ဒီ Implementations တွေအားလုံးက Compilers တွေဖြစ်သလို Interpreters တွေလည်း ဖြစ်ပါတယ်။ Compiler က Python program ကို ကြားခံ Bytecode အဖြစ် ပြောင်းပေးပြီး၊ အဲဒီ Bytecode ကိုမှ Interpreter က တဆင့်ပြန်ပြီး အလုပ်လုပ်ပေးတာပါ။
1.2 Python Installation under Windows¶
-
Python က နှစ်တွေကြာလာတာနဲ့အမျှ တိုးတက်ပြောင်းလဲလာပါတယ်။ ဒီစာရေးနေတဲ့အချိန်မှာ Windows နဲ့ Linux Environments တွေအတွက် နောက်ဆုံး Version က Python 3.14.1 ဖြစ်ပါတယ်။
-
Python က Windows OS မှာ တပါတည်း ပါမလာပါဘူး။ ဒါကြောင့် သီးသန့် Install လုပ်ပေးဖို့ လိုပါတယ်။ www.python.org/downloads/ ကနေ Python installer ကို ဒေါင်းလို့ရပါတယ်။
-
ဒေါင်းတဲ့အခါ ကိုယ့်စက်က 32-bit machine လား 64-bit machine လားဆိုတာပေါ် မူတည်ပြီး မှန်ကန်တဲ့ Installer ကို ရွေးဖို့လိုပါတယ် -
- 64-bit machine: Windows x86-64 executable installer ကို ဒေါင်းပါ။
-
32-bit machine: Windows x86 executable installer ကို ဒေါင်းပါ။
-
Installer ကို ရွေးပြီး ဒေါင်းလို့ပြီးသွားရင် Double-click နှိပ်ပြီး Execute လုပ်လိုက်ပါ။ Figure 2.1 မှာ ပြထားသလို Dialog box ပေါ်လာပါလိမ့်မယ်။

-
ဒီ Dialog မှာ 'Add Python 3.14 to PATH' (သို့မဟုတ်) 'Add python.exe to PATH' ဆိုတဲ့ check box လေးကို အမှန်ခြစ်ခဲ့ဖို့ မမေ့ပါနဲ့။ ဒါမှ Interpreter က ကိုယ့်ရဲ့ Execution path ထဲရောက်သွားမှာပါ။
-
'Install Now' ကို နှိပ်လိုက်ရင် မိနစ်ပိုင်းလောက်နဲ့ Installation ပြီးသွားပါလိမ့်မယ်။ Python files တွေက
C:\Users\Joseph\AppData\Local\Programs\Python\Python314Directory ထဲမှာ ရောက်သွားပါမယ်။ -
ဒီ Path ထဲက ‘Joseph’ နေရာမှာ ကိုယ့်ရဲ့ User name ဖြစ်ပြီး၊ ‘Python314’ ကတော့ ကိုယ် ဒေါင်းပြီး Install လုပ်လိုက်တဲ့ Python installation ရဲ့ Version number ကို ကိုယ်စားပြုပါတယ်။
-
တကယ်လို့ Check box ကို အမှန်ခြစ်ဖို့ မေ့သွားခဲ့ရင် Control Panel > System > Environment Variables > Edit ကနေတဆင့် PATH variable ထဲမှာ အပေါ်က Path ကို သွားထည့်ပေးလို့ ရပါတယ်။ PATH variable ထဲမှာ Semicolon separated values တွေ အများကြီး ရှိပြီးသားပါ။ ရှိပြီးသားတန်ဖိုးတွေရဲ့ နောက်ဆုံးမှာ အခု Path ကို ထပ်ဖြည့်လိုက်ရုံပါပဲ။
-
Installation ပြီးသွားရင် Command prompt ကိုဖွင့်ပြီး python --version လို့ ရိုက်ပြီး စစ်ကြည့်နိုင်ပါတယ်။
-
Installation အောင်မြင်တယ်ဆိုရင် စက်ထဲမှာ တင်ထားတဲ့ Python Version ကို တွေ့ရပါလိမ့်မယ်။
-
Windows 10 သုံးနေရင် Settings > Apps > Apps & features > Python ကနေလည်း ဝင်စစ်လို့ရသလို၊ Windows 11 ဆိုရင်လည်း Settings >Apps > Apps & features > Python ကနေပဲ ဝင်စစ်လို့ရပါတယ်။
1.3 Python Installation under Linux¶
-
Linux distributions အများစု (ဥပမာ Ubuntu) မှာ Python က ပါပြီးသားပါ။ ဒါပေမယ့် Install လုပ်ထားပြီးသား Python version က နောက်ဆုံးထွက် Latest version ဖြစ်ချင်မှ ဖြစ်မှာပါ။ ကိုယ့်စက်ထဲက Version ကို အောက်ပါအတိုင်း စစ်ကြည့်လို့ရပါတယ် -
-
တကယ်လို့ Latest version မဟုတ်နေဘူးဆိုရင်၊ လိုချင်တဲ့ Specific version (ဥပမာ - Python 3.13) ကို အောက်က Command တွေသုံးပြီး Install လုပ်နိုင်ပါတယ် -
1.4 Python Resources (Python လေ့လာစရာ အရင်းအမြစ်များ)¶
- Python source code၊ Binaries နဲ့ Documentation တွေကို အောက်ပါလင့်ခ်တွေမှာ ရနိုင်ပါတယ် -
- Python official website: www.python.org
-
Documentation website: www.python.org/doc
-
Python နဲ့ Program development လုပ်မယ်ဆိုရင် နည်းလမ်း (၃) မျိုး ရှိပါတယ် -
- ပါပြီးသား IDLE ကို သုံးခြင်း။
- Third-party IDEs တွေကို သုံးခြင်း။
-
Online Python shells တွေကို သုံးခြင်း။
-
Third-party development tools တွေနဲ့ သူတို့ကို ဒေါင်းလုပ်ဆွဲနိုင်တဲ့ လင့်ခ်တွေကတော့ အောက်ပါအတိုင်း ဖြစ်ပါတယ် -
- NetBeans IDE for Python: https://netbeans.apache.org/front/main/download/
- PyCharm IDE for Python: https://www.jetbrains.com/pycharm
-
Visual Studio Code IDE: https://code.visualstudio.com/download
-
တကယ်လို့ ကိုယ့်စက်ထဲမှာ ဘာ Python development tool မှ Install မလုပ်ချင်ဘူးဆိုရင်တော့ အောက်ပါ Online Python shells တစ်ခုခုကို သုံးနိုင်ပါတယ် -
- https://www.python.org/shell/
- https://ideone.com/
- https://replit.com/languages/python3
1.5 Third-party Packages (ပြင်ပ Packages များ)¶
-
Python community ထဲက Pythonistas တွေက တခြား Programmers တွေ အသုံးပြုနိုင်ဖို့အတွက် Packages (Libraries) တွေကို ဖန်တီးပေးကြပါတယ်။ သူတို့ရဲ့ Packages တွေကို ဖြန့်ဝေဖို့အတွက် PyPI—Python Package Index (www.pypi.org) ကို သုံးကြပါတယ်။
-
PyPI က ရရှိနိုင်တဲ့ Third-party Python packages စာရင်းကို ထိန်းသိမ်းပေးထားပါတယ်။
-
ဘာလုပ်ချင်ချင်၊ အရာအားလုံးနီးပါးအတွက် Third-party packages တွေ ရှိပြီးသားပါ။ Data Science applications တွေ ဖန်တီးဖို့အတွက် လူသုံးများတဲ့ Packages တချို့ကတော့ -
- NumPy: Multi-dimensional arrays နဲ့ Matrices ကြီးတွေကို Support လုပ်ပေးတဲ့ အဆင့်မြင့် Mathematical operations library ဖြစ်ပါတယ်။
- SciPy: Optimization၊ Integration၊ Interpolation၊ Signal processing နဲ့ Image processing စတာတွေအတွက် Scientific computing library ဖြစ်ပါတယ်။
- Pandas: Numerical tables နဲ့ Time series တွေကို ကိုင်တွယ်ဖို့အတွက် Library ဖြစ်ပါတယ်။
- MatPlotLib: 2D နဲ့ 3D Data visualization library ဖြစ်ပါတယ်။
- OpenCV: Open source Computer vision library ဖြစ်ပါတယ်။
1.6 Python Packages and Development Tools¶
-
ကိုယ်တိုင်လည်း PyPI မှာ Register လုပ်ပြီး ကိုယ့်ရဲ့ Packages တွေကို တင်လို့ရပါတယ်။ Package တစ်ခု ဖန်တီးတာ၊ Build လုပ်တာနဲ့ Python Package Index ပေါ် တင်တာတွေအတွက် www.pypi.org မှာ ပေးထားတဲ့ လမ်းညွှန်ချက်တွေကို လိုက်နာရပါမယ်။
-
pip ဆိုတာက PyPI ကနေ Packages တွေကို Install လုပ်ဖို့ သုံးလေ့ရှိတဲ့ Tool တစ်ခုပါ။ Python ကို Install လုပ်ကတည်းက ဒီ Tool က ပါပြီးသားပါ။
1.6.1 Data Science and AI Tools¶
- Python programmers တွေအနေနဲ့ Data Science နဲ့ Artificial Intelligence applications တွေကို တည်ဆောက်တာ၊ Document လုပ်တာတွေမှာ ကူညီပေးဖို့ Tools တွေ အများကြီး ပေါ်လာပါပြီ။ အဲဒီအထဲမှာ -
- Jupyter Notebook - ဒါက Browser-based tool ဖြစ်ပြီး Python (နဲ့ တခြား Languages) တွေကို Interactive ဖြစ်ဖြစ် အသုံးပြုလို့ရစေပါတယ်။ ကိုယ့်ရဲ့ Python code၊ Output၊ Visualization (သို့မဟုတ်) Plot တွေကို Notebook လို့ခေါ်တဲ့ Document တစ်ခုတည်းမှာ စုစည်းထားလို့ ရပါတယ်။ Modular program development လုပ်ဖို့ အရမ်းကောင်းတဲ့ Tool ပါ။
- Google Colab - ဒီ Tool ကတော့ Google's cloud servers ပေါ်မှာ Code run လို့ရအောင် အခမဲ့ Jupyter notebook environment ကို ပေးထားတာပါ။ ဒါကြောင့် Google ရဲ့ Hardware စွမ်းရည် (GPU/TPU) တွေကို လှမ်းသုံးလို့ရပါတယ်။
-
Spyder - ဒီ Tool ကတော့ Scientific Python Development Environment တစ်ခုဖြစ်ပြီး အဆင့်မြင့်တဲ့ Testing နဲ့ Debugging features တွေ ပါဝင်ပါတယ်။
-
Jupyter ရော Spyder ပါ Anaconda လို့ခေါ်တဲ့ နာမည်ကြီး Software distribution ထဲမှာ ပါဝင်ပါတယ်။ ဒါကြောင့် Anaconda ကို ဒေါင်းပြီး Install လုပ်လိုက်တာနဲ့ Jupyter နဲ့ Spyder ကို အဆင်သင့် ရရှိမှာပါ။
1.6.2 IDLE (Integrated Development and Learning Environment)¶
-
Python ကို Install ပြီးသွားရင် ပါပြီးသားဖြစ်တဲ့ Python Integrated Development and Learning Environment (IDLE) ကိုသုံးပြီး Program development စလုပ်လို့ ရပါပြီ။
-
IDLE က မဆိုးဘူးလို့ ပြောလို့ရတဲ့ Development tool တစ်ခုပါ။ Syntax highlighting၊ Context-sensitive help နဲ့ Debugging လိုမျိုး အသုံးဝင်တဲ့ Features တွေ ပါပါတယ်။
- Syntax highlighting ဆိုတာက Keywords၊ Functions၊ Methods နဲ့ Strings တွေကို အရောင်မတူတာလေးတွေနဲ့ ခွဲပြပေးတဲ့အတွက် မြင်ရလွယ်ကူစေပါတယ်။
- Context-sensitive help ဆိုတာက Program ရိုက်နေရင်း အကူအညီလိုတဲ့နေရာမှာ Ctrl Space နှိပ်လိုက်ရင် ပေါ်လာတာမျိုးပါ။ Functions နဲ့ Methods နာမည်တွေ၊ Parameters တွေ အကုန်လုံးကို မှတ်မိနေဖို့ဆိုတာ မဖြစ်နိုင်တဲ့အတွက် ဒါက အရမ်းအသုံးဝင်ပါတယ်။
- Debugger ကတော့ ကိုယ့် Program ရဲ့ Flow of execution ကို ခြေရာခံကြည့်ပြီး Logical errors တွေကို ရှာဖွေနိုင်စေပါတယ်။ Break points တွေ သတ်မှတ်ပြီး Single stepping နဲ့ တစ်ဆင့်ချင်းစီ Run ကြည့်လို့ရပါတယ်။ အဲဒီလို Run ရင်းနဲ့ IDLE မှာ Variables တွေရဲ့ Values ပြောင်းလဲသွားပုံကို စောင့်ကြည့်လို့ရပါတယ်။
1.6.3 Python Modes¶
- Python ကို Mode နှစ်မျိုးနဲ့ အသုံးပြုနိုင်ပါတယ် -
- Interactive mode - Python syntax တွေကို စမ်းသပ်ဖို့၊ Help ရှာဖို့နဲ့ Programs အတိုလေးတွေကို Debug လုပ်ဖို့ သုံးပါတယ်။
-
Script mode - ပြည့်စုံတဲ့ Python programs တွေ ရေးသားဖို့ သုံးပါတယ်။
-
ဒီ Mode နှစ်မျိုးစလုံးကို IDLE မှာ သုံးလို့ရပါတယ်။
1.6.3.1 To use IDLE in Interactive mode (Interactive mode သုံးနည်း):¶
- Windows မှာဆိုရင် Windows search bar မှာ IDLE လို့ရိုက်ပြီး Enter ခေါက်ပါ (သို့မဟုတ်) IDLE icon ကို Double click နှိပ်ပါ။
>>>ဆိုတဲ့ Python shell prompt နဲ့အတူ Python shell window ပွင့်လာပါလိမ့်မယ်။-
အဲဒီ Prompt မှာ အောက်ပါ Python code ကို ရိုက်ပြီး Run ကြည့်ပါ -
-
'Keep calm and bubble on' ဆိုတဲ့ စာသားပေါ်လာပြီး အောက်မှာ
>>>Prompt ပြန်ပေါ်လာပါလိမ့်မယ်။
1.6.3.2 To use IDLE in Script mode (Script mode သုံးနည်း):¶
-
IDLE ကို ဖွင့်ပါ။ IDLE shell window ရဲ့ Menu ကနေ File | New File ကို ရွေးပါ။ Window အသစ်တစ်ခု ပွင့်လာပါမယ်။ အဲဒီထဲမှာ အောက်ပါ Script ကို ရိုက်ထည့်ပါ -
-
File | Save ကို နှိပ်ပြီး Script ကို 'Test.py' နာမည်နဲ့ သိမ်းလိုက်ပါ။
- Run menu (သို့မဟုတ်) F5 ကို နှိပ်ပြီး Script ကို Run ပါ။ စာကြောင်း နှစ်ကြောင်း ထွက်လာပါလိမ့်မယ်။
1.6.3.3 Using Other IDEs (တခြား IDEs များ သုံးနည်း)¶
- Program development အတွက် IDLE အစား NetBeans (သို့မဟုတ်) Visual Studio Code ကို သုံးချင်တယ်ဆိုရင် အောက်ပါအတိုင်း လုပ်ဆောင်နိုင်ပါတယ် -
- Python project အသစ်တစ်ခုကို ‘Test’ ဆိုပြီး ဖန်တီးပါ။
- Test.py ဖိုင်ထဲမှာ Script ကို ရိုက်ထည့်ပါ။
- NetBeans ဆိုရင် F6၊ Visual Studio Code ဆိုရင် Ctrl F5 နှိပ်ပြီး Script ကို Run နိုင်ပါတယ်။
- Run လိုက်ရင် စာကြောင်းနှစ်ကြောင်း ထွက်လာမှာဖြစ်ပြီး နောက်ထပ် Project အသစ်၊ Script အသစ်တွေ ထပ်ဖန်တီးဖို့ အဆင်သင့် ဖြစ်ပါပြီ။
1.7 Checking Python Version (Version စစ်ဆေးခြင်း)¶
- Python က အမြဲတမ်း ပြောင်းလဲတိုးတက်နေပါတယ်။ ကိုယ့်စက်ထဲမှာ ဘယ် Version ရှိနေလဲဆိုတာကို ရိုးရှင်းတဲ့ Python script လေးနဲ့ စစ်ဆေးနိုင်ပါတယ် -
Exercises¶
[A] Answer the following questions: (အောက်ပါမေးခွန်းများကို ဖြေဆိုပါ)
a. Prompt တွေဖြစ်တဲ့ C:\>, $ နဲ့ >>> တွေက ဘာကို ဆိုလိုတာလဲ?
- Answer:
C:\>က Windows Command Prompt ၊$က Linux Shell/Terminal ၊>>>ကတော့ Python Interactive Shell ကို ကိုယ်စားပြုပါတယ်။
b. IDLE ကို ဘယ် Mode နှစ်မျိုးနဲ့ သုံးလို့ရလဲ?
- Answer: Interactive mode နဲ့ Script mode ဆိုပြီး နှစ်မျိုးသုံးလို့ရပါတယ်။
b. IDLE ကို ဘယ် Mode နှစ်မျိုးနဲ့ သုံးလို့ရလဲ?
- Answer: Interactive mode နဲ့ Script mode ဆိုပြီး နှစ်မျိုးသုံးလို့ရပါတယ်။
c. IDLE မှာပါတဲ့ Programming modes နှစ်မျိုးရဲ့ ရည်ရွယ်ချက်က ဘာလဲ?
- Answer: Interactive mode က Code အတိုလေးတွေကို စမ်းသပ်ဖို့၊ Debug လုပ်ဖို့ သုံးပြီး၊ Script mode ကတော့ Program အပြည့်အစုံ ရေးသားပြီး Save လုပ်ဖို့အတွက် သုံးပါတယ်။
d. Python Program တစ်ပုဒ်မှာ Third party libraries တွေကို ဘယ်လိုသုံးမလဲ?
- Answer: PyPI ကနေ pip သုံးပြီး Install လုပ်ရပါတယ်၊ ပြီးရင်တော့ ကိုယ့် Code ထဲမှာ import လုပ်ပြီး လှမ်းသုံးလို့ရပါတယ်။
[B] Match the following pairs: (အောက်ပါတို့ကို တွဲဖက်ပါ)
| Section A | Section B |
|---|---|
a. pip |
1. Advanced mathematical operations |
b. Jupyter |
2. Scientific Computing |
c. Sypder |
3. Manipulation numerical tables |
d. PyPI |
4. Visualization |
e. Numpy |
5. Computer Vision |
f. Scipy |
6. Package installation tool |
g. Pandas |
7. Build and document applications |
h. MatPlotlib |
8. Scientific Library |
i. OpenCV |
9. Python Package index |
Answer:
| Section A | Section B |
|---|---|
a. pip |
6. Package installation tool |
b. Jupyter |
7. Build and document applications |
c. Spyder |
8. Scientific Library (Note: မူရင်းစာအုပ်တွင် Spyder ကို Environment အစား Library ဟု မှားယွင်းစွာ တွဲပေးထားတတ်သဖြင့် ဤနေရာတွင် 8 နှင့် တွဲပေးထားပါသည်။ SciPy နှင့် လဲနိုင်ပါသည်။) |
d. PyPI |
9. Python Package index |
e. NumPy |
1. Advanced mathematical operations |
f. SciPy |
2. Scientific Computing |
g. Pandas |
3. Manipulation numerical tables |
h. MatPlotlib |
4. Visualization |
i. OpenCV |
5. Computer Vision |
[C] State whether the following statements are True or False: (အောက်ပါအဆိုများသည် မှန်/မှား ဖော်ပြပါ)
a. Python သည် Python (RPython)၊ C#၊ Java စသည့် Languages များဖြင့် Implement လုပ်နိုင်သော Specification တစ်ခုဖြစ်သည်။
- Ans -> True
b. CPython သည် C ဖြင့်ရေးသားထားသော Python specification ၏ Implementation ဖြစ်သည်။
- Ans -> True
c. Python program ကို အရင်ဆုံး Byte code အဖြစ် Compile လုပ်ပြီးမှ Interpret လုပ်သည်။
- Ans -> True
d. Linux distributions အများစုတွင် Python ပါဝင်ပြီးသားဖြစ်သည်။
- Ans -> True
e. Windows system တွင် Python ပါဝင်လာခြင်းမရှိဘဲ သီးသန့် Install လုပ်ရန်လိုအပ်သည်။
- Ans -> True
f. Python programs များကို IDLE၊ NetBeans၊ PyCharm နှင့် Visual Studio Code တို့ကို သုံး၍ တည်ဆောက်နိုင်သည်။
- Ans -> True
g. Third-party Python packages များကို PyPI အသုံးပြု၍ ဖြန့်ဝေသည်။
- Ans -> True
Chapter 3 Python Basics¶
Keynote¶
3.1 Identifiers and Keywords¶
Python က Case sensitive language တစ်ခုပါ။ Python identifier ဆိုတာက Variable၊ Function၊ Class၊ Module သို့မဟုတ် တခြား Object တွေကို ခွဲခြားသိနိုင်ဖို့ ပေးထားတဲ့ နာမည်တစ်ခု ဖြစ်ပါတယ်။ Identifiers တွေ ဖန်တီးတဲ့အခါ လိုက်နာရမယ့် စည်းကမ်းတွေကတော့ -
-
Alphabet (အက္ခရာ) သို့မဟုတ် Underscore (_) နဲ့ စရပါမယ်။
-
အဲဒီနောက်မှာ စာလုံးတွေ၊ _ ၊ နဲ့ Digits (ဂဏန်း) တွေ လိုက်လို့ရပါတယ်။
-
Keyword တွေကို Identifier အနေနဲ့ သုံးလို့ မရပါဘူး။
Keywords အားလုံးက Lowercase (အက္ခရာအသေး) တွေ ဖြစ်ပါတယ်။ Python မှာ Keywords စုစုပေါင်း (၃၃) လုံးရှိပြီး Table 3.1 မှာ ဖော်ပြထားပါတယ်။
| Table 3.1 Keywords list | -/- | -/- | -/- |
|---|---|---|---|
| False | continue | from | not |
| None | def | global | or |
| True | del | if | pass |
| and | elif | import | raise |
| as | else | in | return |
| assert | except | is | try |
| break | finally | lambda | while |
| class | for | nonlocal | with |
| yield |
Python keywords စာရင်းကို အောက်ပါ Statements တွေသုံးပြီး ထုတ်ကြည့်လို့ ရပါတယ် -
import keyword # 'keyword' module ကို သုံးလို့ရအောင် ခေါ်လိုက်တာ
print(keyword.kwlist) # syntax ကတော့ modulename.object/function ပုံစံပါ
3.2 Python Types¶
Python မှာ Data types (၃) မျိုး (၃) စား ရှိပါတယ် -
- Basic Types:
- int, float, complex, bool, string, bytes
- Container Types:
- list, tuple, set, dict
- User-defined types:
- class
ဒီအထဲမှာ Basic types အကြောင်းကို ဒီ Chapter မှာ အသေးစိတ် ရှင်းပြသွားပါမယ်။ Container types အကြောင်းကိုတော့ အကြမ်းဖျင်းပဲ ပြောသွားပါမယ်။ Container type တစ်ခုစီအတွက် သီးသန့် Chapter တွေနဲ့ အသေးစိတ် ထပ်ရှင်းပြပေးထားပါတယ်။ User-defined types အကြောင်းကိုတော့ ဒီ Chapter မှာ မပြောတော့ပါဘူး။ Chapter 17 ကျမှ ဘယ်လိုဖန်တီးမလဲ၊ ဘယ်လိုသုံးမလဲဆိုတာ ဆွေးနွေးသွားပါမယ်။
3.2.1 Basic Types¶
Basic types အမျိုးမျိုးရဲ့ ဥပမာတွေကို အောက်မှာ ဖော်ပြပေးထားပါတယ် -
- int ကို binary, decimal, octal, hexadecimal ပုံစံတွေနဲ့ ဖော်ပြလို့ရပါတယ်။
- binary ဆိုရင် 0b/0B ၊ octal ဆိုရင် 0o/0O ၊ hex ဆိုရင် 0x/0X နဲ့ စပါတယ်။ (ဥပမာ - 0b10111, 156, 0o432, 0x4A3)
- float ကို fractional (ဒသမကိန်း) သို့မဟုတ် exponential form (ထပ်ကိန်းပုံစံ) နဲ့ ဖော်ပြလို့ရပါတယ်။ (ဥပမာ - 314.1528, 3.141528e2, 3.141528E2)
- complex မှာ real နဲ့ imaginary part ဆိုပြီး ပါပါတယ်။ (ဥပမာ - 3 + 2j, 1 + 4J)
- bool က Boolean values နှစ်ခုထဲက ကြိုက်တာတစ်ခု ဖြစ်နိုင်ပြီး နှစ်ခုလုံးက အက္ခရာအကြီးနဲ့ စပါတယ်။ (ဥပမာ - True, False)
- string ဆိုတာ
' '," ", သို့မဟုတ်""" """တွေကြားထဲမှာ ရေးထားတဲ့ Immutable collection of Unicode characters ဖြစ်ပါတယ်။ ဥပမာ - 'Rosanna', "Rosanna", """Rosanna"""။ - bytes က Binary data ကို ကိုယ်စားပြုပါတယ်။
print(type(35)) # <class 'int'> ဆိုပြီး print ထုတ်ပေးပါလိမ့်မယ်
print(type(3.14)) # <class 'float'> ဆိုပြီး print ထုတ်ပေးပါလိမ့်မယ်
3.2.2 Integer and Float Ranges¶
- int တွေက Arbitrary size ဖြစ်တဲ့အတွက် ကြိုက်သလောက် အရွယ်အစား ထားလို့ရပါတယ်။ (Memory ဆန့်သရွေ့ ဂဏန်းအလုံးရေ အကန့်အသတ်မရှိပါဘူး)။
Floats တွေကိုတော့ Internal မှာ IEEE 754 standard အရ Binary ပုံစံနဲ့ 64-bit double-precision values အနေနဲ့ သိမ်းဆည်းပါတယ်။ ဒီ Standard အရ Float တစ်ခုရဲ့ အကြီးဆုံးတန်ဖိုး (Maximum value) က ခန့်မှန်းခြေ 1.8 x 10^308 ဖြစ်ပါတယ်။ ဒီထက်ကြီးတဲ့ ကိန်းဂဏန်းဆိုရင် inf (infinity အတိုကောက်) အနေနဲ့ ဖော်ပြပါလိမ့်မယ်။
Floats တော်တော်များများကို Binary form နဲ့ 'တိတိကျကျ' (Exactly) ဖော်ပြလို့ မရနိုင်ပါဘူး။ ဒါကြောင့် Internal representation က တကယ့်တန်ဖိုးရဲ့ Approximation (နီးစပ်ဆုံးတန်ဖိုး) သာ ဖြစ်လေ့ရှိပါတယ်။
တကယ့်တန်ဖိုးနဲ့ Represented value ကြားက ကွာဟချက်က အရမ်းသေးငယ်တဲ့အတွက် ပုံမှန်အားဖြင့်တော့ ပြဿနာကြီးကြီးမားမား မဖြစ်စေပါဘူး။
3.3 Variable Type and Assignment¶
Variable တစ်ခုရဲ့ Type ကို ကြိုပြီး သတ်မှတ်ပေးစရာ (Define) မလိုပါဘူး။ Execution လုပ်နေတဲ့အချိန်ကျမှ သူအသုံးပြုနေတဲ့ Context ပေါ်မူတည်ပြီး Variable type ကို အလိုအလျောက် ဆုံးဖြတ် (Infer) သွားတာပါ။ ဒါကြောင့် Python ကို Dynamically-typed language လို့ ခေါ်တာဖြစ်ပါတယ်။
a = 25 # a ရဲ့ type ကို int လို့ ယူဆလိုက်ပါတယ်
a = 31.4 # a ရဲ့ type ကို float လို့ ယူဆလိုက်ပါတယ်
a = 'Hi' # a ရဲ့ type ကို str လို့ ယူဆလိုက်ပါတယ်
Variable တစ်ခုရဲ့ Type ကို Built-in function ဖြစ်တဲ့ type() ကို သုံးပြီး စစ်ဆေးနိုင်ပါတယ်။
Simple variable assignment:
Variables အများကြီးကို တစ်ပြိုင်နက် Assignment လုပ်ခြင်း -
a = 10 ; pi = 31.4 ; name = 'Rosanna' # ; ကို statement separator အနေနဲ့ သုံးထားတာပါ
a, pi, name = 10, 3.14, 'Rosanna'
a = b = c = d = 5
3.3.1 Arithmetic Operators¶
Arithmetic Operators: +, - , * , /, %, //, **
a = 4 / 2 # True division လုပ်ဆောင်ပြီး Float 2.0 ကို ရရှိပါတယ်
a = 7 % 2 # % က အကြွင်း (Remainder) 1 ကို ပေးပါတယ်
b = 3 ** 4 # ** က ထပ်ကိန်းတင်ပေးပါတယ် (3 raised to 4)
c = 4 // 3 # // က ဒသမပိုင်းတွေကို ဖယ်ထုတ်ပြီး စားလဒ် (Quotient) 1 ကိုပဲ ယူပါတယ်
In-place assignment operators တွေက Arithmetic operations တွေလုပ်ဖို့အတွက် Shortcut ကောင်းကောင်းတစ်ခု ဖြစ်ပါတယ်။ သူတို့ထဲမှာ +=, -=, *=, /=, %=, //=, **= တို့ ပါဝင်ပါတယ်။
3.3.2 Operation Nuances¶
Floor division (a//b) လုပ်ဆောင်တဲ့အခါ ရလာမယ့် Result က Quotient (စားလဒ်) ထက် ငယ်တဲ့ (သို့မဟုတ်) ညီတဲ့အထဲက အကြီးဆုံး Integer ဖြစ်ပါတယ်။ // ကို Floor division operator လို့ ခေါ်ပါတယ်။
ရိုးရိုးလေး မှတ်မယ်ဆိုရင်တော့ Number line ပေါ်မှာ ဘယ်ဘက် (တန်ဖိုးပိုငယ်တဲ့ဘက်) ကို အမြဲတမ်း 'Floor' (အောက်ချ) လိုက်တယ်လို့ မှတ်ယူနိုင်ပါတယ်။ ဒါကြောင့် -3.33 ဆိုရင် -3 မဖြစ်ဘဲ -4 ဖြစ်သွားတာပါ။
print(10 // 3) # 3 ကို ရပါတယ် (3.33... ထက် ငယ်တဲ့/ညီတဲ့ integer)
print(-10 // 3) # -4 ကို ရပါတယ် (-3.33... ထက် ငယ်တဲ့ integer က -4 ပါ)
print(10 // -3) # -4 ကို ရပါတယ်
print(-10 // -3) # 3 ကို ရပါတယ်
print(3 // 10) # 0 ကို ရပါတယ် (0.3 ထက် ငယ်တဲ့/ညီတဲ့ integer)
print(3 // -10) # -1 ကို ရပါတယ် (-0.3 ထက် ငယ်တဲ့ integer က -1 ပါ)
print(-3 // 10) # -1 ကို ရပါတယ်
print(-3 // -10) # 0 ကို ရပါတယ်
-10 // 3 မှာ -10 ရဖို့ 3 နဲ့စားလိုက်ရင် -3.333 ရပါတယ်၊ သူ့ရဲ့ Floor value (အောက်ချလိုက်တဲ့ တန်ဖိုး) က -4 ဖြစ်ပါတယ်။
10 // -3 မှာ 10 ရဖို့ -3 နဲ့စားလိုက်ရင် -3.333 ရပါတယ်၊ သူ့ရဲ့ Floor value က -4 ဖြစ်ပါတယ်။
-10 // -3 မှာ -10 ရဖို့ -3 နဲ့စားလိုက်ရင် 3.333 ရပါတယ်၊ သူ့ရဲ့ Floor value က 3 ဖြစ်ပါတယ်။
print( ) ဆိုတာ Screen ပေါ်မှာ Output ထုတ်ပေးဖို့ သုံးတဲ့ Function တစ်ခုပါ။ သူ့ကို ပုံစံမျိုးစုံနဲ့ သုံးလို့ရပါတယ်။ Chapter 7 ရောက်ရင် အသေးစိတ် ဆွေးနွေးပါမယ်။
a % b Operation ကို a - (b * (a // b)) ဆိုတဲ့ ပုံသေနည်းအတိုင်း Evaluate လုပ် (တွက်ချက်) ပါတယ်။
ဒါကို အောက်က ဥပမာတွေကြည့်ရင် အရှင်းဆုံး နားလည်ပါလိမ့်မယ် -
print(10 % 3) # 1 ရပါတယ် (ပုံမှန် အကြွင်းပါ)
print(-10 % 3) # 2 ရပါတယ် (Formula: -10 - (3 * -4) = -10 + 12 = 2)
print(10 % -3) # -2 ရပါတယ် (Formula: 10 - (-3 * -4) = 10 - 12 = -2)
print(-10 % -3) # -1 ရပါတယ် (Formula: -10 - (-3 * 3) = -10 + 9 = -1)
print(3 % 10) # 3 ရပါတယ်
print(3 % -10) # -7 ရပါတယ် (Formula: 3 - (-10 * -1) = 3 - 10 = -7)
print(-3 % 10) # 7 ရပါတယ် (Formula: -3 - (10 * -1) = -3 + 10 = 7)
print(-3 % -10) # -3 ရပါတယ်
a % b ကို a - (b * (a // b)) ဆိုပြီး Evaluate လုပ်တဲ့အတွက်ကြောင့်၊
-10 % 3 ဆိုရင် -10 - (3 * (-10 // 3)) လို့ တွက်ပါတယ်၊ ဒါကြောင့် ရလဒ် 2 ကို ရပါတယ်။
10 % -3 ဆိုရင် 10 - (-3 * (10 // -3)) လို့ တွက်ပါတယ်၊ ဒါကြောင့် รလဒ် -2 ကို ရပါတယ်။
-10 % -3 ဆိုရင် -10 - (-3 * (-10 // -3)) လို့ တွက်ပါတယ်၊ ဒါကြောင့် ရလဒ် -1 ကို ရပါတယ်။
Mathematical rule အရ a / b x c နဲ့ a x c / b က တူတယ်ဆိုပေမယ့်၊ Programming မှာ အမြဲတမ်းတော့ မမှန်ပါဘူး။ (အထူးသဖြင့် ဂဏန်းအကြီးကြီးတွေ တွက်တဲ့အခါမျိုးမှာပေါ့)။
# အောက်ပါ expressions တွေက results အတူတူပဲ ထွက်ပါတယ်
a = 300 / 100 * 250
a = 300 * 250 / 100
# ဒါပေမယ့် ဒီဟာတွေကတော့ မတူတော့ပါဘူး
b = 1e210 / 1e200 * 1e250
b = 1e210 * 1e250 / 1e200 # INF (Infinity) ထွက်သွားပါတယ်
True ဆိုတာ 1၊ False ဆိုတာ 0 ဖြစ်တဲ့အတွက် သူတို့ကို ဂဏန်းတွေလိုပဲ ပေါင်းလို့ရပါတယ်။
3.4 Precedence and Associativity¶
Arithmetic expression တစ်ခုမှာ Operators တွေ အများကြီး ပါလာတဲ့အခါ၊ အဲဒီ Operators တွေရဲ့ Precedence (ဦးစားပေးအဆင့်/Priority) ပေါ်မူတည်ပြီး Evaluate လုပ် (တွက်ချက်) ပါတယ်။
Priority အမြင့်ဆုံးကနေ အနိမ့်ဆုံးအလိုက် စီထားတဲ့ Operators တွေကတော့ (PEMDAS) အတိုင်း ဖြစ်ပါတယ် -
( ) # Parentheses (ကွင်းများ)
** # Exponentiation (ထပ်ကိန်းတင်ခြင်း)
*, /, //, % # Multiplication, Division (အမြှောက်၊ အစား အုပ်စု)
+, - # Addition, Subtraction (အပေါင်း၊ အနုတ် အုပ်စု)
Operator တိုင်းမှာ Left to right associativity (ဘယ်မှ ညာသို့) သို့မဟုတ် Right to left associativity (ညာမှ ဘယ်သို့) ဆိုတာ ရှိကြပါတယ်။
ဥပမာ - c = a * b / c ဆိုတဲ့ Expression မှာ * နဲ့ / က Priority တူပါတယ်။ ဒါပေမယ့် Arithmetic operators တွေက Left to right associativity ရှိတဲ့အတွက် * ကို / ထက် အရင်လုပ်ပါတယ်။ (ဘယ်ဘက်အခြမ်းက ကောင်ကို အရင်လုပ်တာပါ)။
Python operators အားလုံးရဲ့ Priority နဲ့ Associativity စာရင်းအပြည့်အစုံကို Appendix A မှာ ကြည့်ရှုနိုင်ပါတယ်။
3.4.1 Conversions¶
Mixed mode operations (Type မတူတာတွေ ရောပြီး တွက်ခြင်း):
- int နဲ့ float တွဲလုပ်ရင် float ရပါမယ်။
- int နဲ့ complex တွဲလုပ်ရင် complex ရပါမယ်။
- float နဲ့ complex တွဲလုပ်ရင် complex ရပါမယ်။
Built-in functions တွေဖြစ်တဲ့ int( ), float( ), complex( ) နဲ့ bool( ) တို့ကို သုံးပြီး Numeric type တစ်ခုကနေ နောက်တစ်ခုကို ပြောင်းလဲ (Convert) နိုင်ပါတယ်။
Type conversions:
int(float/numeric string) # float သို့မဟုတ် numeric string ကို int ပြောင်းခြင်း
int(numeric string, base) # numeric string ကို base တစ်ခုခုအလိုက် int ပြောင်းခြင်း
float(int/numeric string) # int သို့မဟုတ် numeric string ကို float ပြောင်းခြင်း
float(int) # int ကို float ပြောင်းခြင်း
complex(int/float) # complex ပြောင်းခြင်း (imaginary part က 0 ဖြစ်နေမယ်)
complex(int/float, int/float) # complex ပြောင်းခြင်း (real, imag နှစ်ခုလုံးပါမယ်)
bool(int/float) # int/float ကို True/False (1/0) ပြောင်းခြင်း
str(int/float/bool) # string အဖြစ် ပြောင်းခြင်း
chr(int) # int တန်ဖိုးနဲ့ သက်ဆိုင်တဲ့ character (ASCII/Unicode) ကို ထုတ်ပေးခြင်း
int( ) က Decimal portion (ဒသမပိုင်း) ကို ဖြတ်ထုတ်လိုက်တာဖြစ်တဲ့အတွက် အမြဲတမ်း Zero ဘက်ကိုပဲ Round လုပ်သွားပါတယ် (Rounds towards zero ဖြစ်ပါတယ်)။
3.4.2 Built-in Functions¶
Python မှာ Program ရဲ့ ဘယ်နေရာမှာမဆို အချိန်မရွေး ခေါ်သုံးလို့ရတဲ့ Built-in functions တွေ အများကြီး ပါပါတယ်။ ကျွန်တော်တို့ Output ကို Screen ပေါ်ထုတ်ဖို့ သုံးနေကျ print( ) function ကလည်း Built-in function တစ်ခုပါပဲ။
Built-in function တစ်ခုခုအကြောင်း Help လိုချင်ရင် help(function) ကို သုံးပြီး ကြည့်လို့ရပါတယ်။
Numbers တွေနဲ့ တွဲသုံးလေ့ရှိတဲ့ Built-in functions တွေကို အောက်မှာ ဖော်ပြထားပါတယ် -
abs(x) # x ရဲ့ Absolute value (ပကတိတန်ဖိုး) ကို ပြန်ပေးပါတယ်
pow(x, y) # x ရဲ့ y ထပ်ကိန်းတန်ဖိုး (x raised to y) ကို ပြန်ပေးပါတယ်
min(x1, x2,...) # ပေးထားတဲ့ထဲက အငယ်ဆုံးတန်ဖိုး (Smallest argument) ကို ပြန်ပေးပါတယ်
max(x1, x2,...) # ပေးထားတဲ့ထဲက အကြီးဆုံးတန်ဖိုး (Largest argument) ကို ပြန်ပေးပါတယ်
divmod(x, y) # (x // y, x % y) ဆိုပြီး စားလဒ်နဲ့ အကြွင်းအတွဲ (Pair) ကို ပြန်ပေးပါတယ်
round(x [,n]) # x ကို ဒသမနေရာ n ခုအထိ ဖြတ်ပြီး (Round လုပ်ပြီး) ပြန်ပေးပါတယ်
bin(x) # x ရဲ့ Binary equivalent (Binary တန်ဖိုး) ကို ပြန်ပေးပါတယ်
oct(x) # x ရဲ့ Octal equivalent (Octal တန်ဖိုး) ကို ပြန်ပေးပါတယ်
hex(x) # x ရဲ့ Hexadecimal equivalent (Hexadecimal တန်ဖိုး) ကို ပြန်ပေးပါတယ်
အောက်ပါ Python program မှာ ဒီ Built-in functions တွေထဲက တချို့ကို ဘယ်လိုသုံးရမလဲဆိုတာ ပြထားပါတယ် -
a = abs(-3) # a ထဲကို 3 ထည့်လိုက်ပါတယ်
print(min(10, 20, 30, 40)) # 10 ကို print ထုတ်ပေးပါတယ်
print(hex(26)) # 1a (hex value) ကို print ထုတ်ပေးပါတယ်
3.4.3 Built-in Modules¶
Built-in functions တွေအပြင်၊ Python မှာ Built-in modules တွေလည်း အများကြီး ပါဝင်ပါတယ်။ Module တစ်ခုစီမှာ Functions တွေ အများကြီး ပါဝင်ပါတယ်။ အဆင့်မြင့် Mathematical operations တွေ လုပ်ဆောင်ဖို့အတွက် Built-in modules တွေဖြစ်တဲ့ math, cmath, random, decimal တို့ထဲက Functions တွေကို အသုံးပြုနိုင်ပါတယ်။
math - အသုံးဝင်တဲ့ mathematics functions တွေ အများကြီး ပါပါတယ်။
cmath - complex numbers တွေပေါ်မှာ operations လုပ်ဖို့ functions တွေ ပါပါတယ်။
random - random number generation (ဂဏန်းတွေ ကျပန်းထုတ်ပေးတာ) နဲ့ ပတ်သက်တဲ့ functions တွေ ပါပါတယ်။
decimal - တိကျသေချာတဲ့ arithmetic operations တွေ လုပ်ဖို့ functions တွေ ပါပါတယ်။
math module ထဲက Mathematical functions များ:
pi, e # pi နဲ့ e constants တွေရဲ့ တန်ဖိုးများ
sqrt(x) # x ရဲ့ Square root
factorial(x) # x ရဲ့ Factorial
fabs(x) # Float x ရဲ့ Absolute value
log(x) # x ရဲ့ Natural log (log to the base e)
log10(x) # x ရဲ့ Base-10 logarithm
exp(x) # e ရဲ့ x ထပ်ကိန်း (e raised to x)
trunc(x) # Integer ဖြစ်အောင် ဖြတ်ထုတ်လိုက်ခြင်း (Truncate)
ceil(x) # x နဲ့ ညီတဲ့ (သို့) x ထက်ကြီးတဲ့အထဲက အငယ်ဆုံး Integer (Ceiling)
floor(x) # x နဲ့ ညီတဲ့ (သို့) x ထက်ငယ်တဲ့အထဲက အကြီးဆုံး Integer (Floor)
modf(x) # x ရဲ့ Fractional နဲ့ Integer parts တွေကို ခွဲထုတ်ပေးခြင်း
round( ) built-in function က Decimal places (ဒသမနေရာ) အရေအတွက် သတ်မှတ်ပြီး Round လုပ်လို့ရပေမယ့်၊ math module ရဲ့ Library functions တွေဖြစ်တဲ့ trunc( )၊ ceil( ) နဲ့ floor( ) တွေကတော့ အမြဲတမ်း Decimal places မပါအောင် (Zero decimal places အထိ) Round လုပ်ပေးပါတယ်။
math module ထဲက Trigonometric functions များ:
degrees(x) # Radians ကနေ Degrees သို့ ပြောင်းခြင်း
radians(x) # Degrees ကနေ Radians သို့ ပြောင်းခြင်း
sin(x) # x Radians ရဲ့ Sine တန်ဖိုး
cos(x) # x Radians ရဲ့ Cosine တန်ဖိုး
tan(x) # x Radians ရဲ့ Tan တန်ဖိုး
sinh(x) # x ရဲ့ Hyperbolic sine
cosh(x) # x ရဲ့ Hyperbolic cosine
tanh(x) # x ရဲ့ Hyperbolic tan
acos(x) # x ရဲ့ Cos inverse (Radians နဲ့ ရပါမယ်)
asin(x) # x ရဲ့ Sine inverse (Radians နဲ့ ရပါမယ်)
atan(x) # x ရဲ့ Tan inverse (Radians နဲ့ ရပါမယ်)
hypot(x, y) # sqrt(x * x + y * y) (ထောင့်မှန်ခံအနား ရှာခြင်း)
random module ကနေ Random number generation လုပ်ပေးတဲ့ Functions များ:
random( ) # 0 နဲ့ 1 ကြားက random number တစ်ခု ထုတ်ပေးပါတယ်
randint(start, stop) # သတ်မှတ်ထားတဲ့ range ထဲက random number တစ်ခု ထုတ်ပေးပါတယ်
seed( ) # random number generation logic အတွက် current time ကို seed အနေနဲ့ သတ်မှတ်ပါတယ်
seed(x) # random number generation logic အတွက် x ကို seed အနေနဲ့ သတ်မှတ်ပါတယ်
အောက်ပါ Python program မှာ math module နဲ့ random module ထဲက Functions တချို့ကို ဘယ်လိုအသုံးပြုလဲဆိုတာ ပြသထားပါတယ် -
import math
import random
print(math.factorial(5)) # 120 ကို print ထုတ်ပေးပါတယ်
print(math.degrees(math.pi)) # 180.0 ကို print ထုတ်ပေးပါတယ်
print(random.random( )) # 0.8960522546341796 (ကျပန်းဂဏန်းတစ်ခု) ကို print ထုတ်ပေးပါတယ်
import math
print(dir(__builtins__)) # builtins ရဲ့ ရှေ့နဲ့နောက်မှာ underscores 2 ခုစီ ပါပါတယ်
print(dir(math))
3.5 Container Types¶
Container types ဆိုတာက ပုံမှန်အားဖြင့် Values အများကြီးကို တစုတစည်းတည်း သိမ်းဆည်းထားတာကို ဆိုလိုပါတယ်။ Container types အမျိုးမျိုးရဲ့ ဥပမာတွေကို အောက်မှာ ဖော်ပြထားပါတယ် -
# list ဆိုတာက တူတာတွေရော၊ မတူတာတွေရော ရောနှောသိမ်းဆည်းလို့ရတဲ့ indexed collection တစ်ခုပါ
[10, 20, 30, 20, 30, 40, 50, 10], ['She', 'sold', 10, 'shells']
# tuple ဆိုတာက ပြင်ဆင်လို့မရတဲ့ immutable collection တစ်ခုပါ
('Rosanna', 34, 4500.55), ('Python With Joe', 350, 195.00)
# set ဆိုတာက unique values (ထပ်နေတာ မပါတဲ့ တန်ဖိုး) တွေကို စုစည်းထားတာပါ
{10, 20, 30, 40}, {'Rosanna', 34, 45000}
# dict ဆိုတာက key-value pairs တွေကို စုစည်းထားတာဖြစ်ပြီး၊ unique key တွေကို '' ကြားထဲမှာ ထားရပါတယ်
{'ME101' : 'Strength of materials', 'EE101' : 'Electronics'}
အောက်ပါ Program မှာ ဒါတွေကို ဘယ်လိုလုပ်လဲဆိုတာ ပြထားပါတယ် -
lst = [10, 20, 30, 20, 30, 40, 50, 10]
tpl = ('Python With Joe', 350, 195.00)
s = {10, 20, 30, 40}
dct = {'ME101' : 'SOM', 'EE101' : 'Electronics'}
# List နဲ့ Tuple ကို Index (Position) သုံးပြီး Access လုပ်ခြင်း
print(lst[0], tpl[2]) # 10 နဲ့ 195.0 ကို print ထုတ်ပေးပါတယ်
# Dictionary ကို Key သုံးပြီး Access လုပ်ခြင်း
print(dct['ME101']) # SOM ကို print ထုတ်ပေးပါတယ်
3.5.1 Python Type Jargon¶
Python Types တွေအကြောင်း ပြောတဲ့အခါ အောက်ပါ Terms (ဝေါဟာရ) တွေကို မကြာခဏ သုံးလေ့ရှိပါတယ် -
-
Collection - Container types တွေကို ယေဘုယျခေါ်တဲ့ အခေါ်အဝေါ်ပါ။
-
Iterable - Loop ပတ်ပြီး အထဲက တန်ဖိုးတွေကို တစ်ခုချင်းစီ ဆွဲထုတ်အသုံးပြုလို့ရတဲ့ Collection မျိုးကို ဆိုလိုတာပါ။
-
Ordered collection - Elements တွေကို ထည့်လိုက်တဲ့ အစဉ်လိုက်အတိုင်းပဲ သိမ်းဆည်းပေးထားတာပါ။ ဒါကြောင့် သူ့ရဲ့ Elements တွေကို Index (Position) သုံးပြီး လှမ်းခေါ်လို့ ရပါတယ်။
-
Unordered collection - Elements တွေကို ထည့်လိုက်တဲ့ အစဉ်လိုက်အတိုင်း သိမ်းမပေးပါဘူး။ ဒါကြောင့် Element တစ်ခုက ဘယ်နေရာ (Position) မှာ ရောက်နေမလဲဆိုတာ ကြိုခန့်မှန်းလို့ မရပါဘူး။ ဒီတော့ Position ကို အခြေခံတဲ့ Index ကိုသုံးပြီး လှမ်းခေါ်လို့ မရပါဘူး။
-
Sequence - Ordered collection တွေကို ယေဘုယျခေါ်တဲ့ အခေါ်အဝေါ်ပါ။
-
Immutable - ပြောင်းလဲလို့မရတဲ့ (Unchangeable) Collection ကို ဆိုလိုပါတယ်။
-
Mutable - ပြောင်းလဲလို့ရတဲ့ (Changeable) Collection ကို ဆိုလိုပါတယ်။
အခုလေ့လာခဲ့ပြီးတဲ့ Types တွေက ဒီအချက်တွေထဲက ဘယ်ဟာတွေနဲ့ ကိုက်ညီလဲဆိုတာ ကြည့်လိုက်ရအောင် -
-
String - Ordered collection ဖြစ်တယ်၊ Immutable ဖြစ်တယ်၊ Iterable ဖြစ်တယ်။
-
List - Ordered collection ဖြစ်တယ်၊ Mutable ဖြစ်တယ်၊ Iterable ဖြစ်တယ်။
-
Tuple - Ordered collection ဖြစ်တယ်၊ Immutable ဖြစ်တယ်၊ Iterable ဖြစ်တယ်။
-
Set - Unordered collection ဖြစ်တယ်၊ Mutable ဖြစ်တယ်၊ Iterable ဖြစ်တယ်။
-
Dictionary - Unordered collection ဖြစ်တယ်၊ Mutable ဖြစ်တယ်၊ Iterable ဖြစ်တယ်။
3.5.2 Comments and Indentation¶
Comments တွေကို # နဲ့ စတင်ရေးသားရပါတယ်။
# calculate gross salary
gs = bs + da + hra + ca
si = p * n * r / 100 # calculate simple interest
Multi-line comments တွေကို ''' (သို့မဟုတ်) """ အစုံလိုက် (Pair) ကြားထဲမှာ ရေးသားသင့်ပါတယ်။
''' Additional program: Calculate bonus to be paid
URL: [https://github.com/rose1996iv/PythonWithJoe](https://github.com/rose1996iv/PythonWithJoe)
Author: Joseph, Date: 7 Dec 2025 '''
Indentation က အရမ်းအရေးကြီးပါတယ်! ပေါ့ပေါ့ဆဆ သုံးလို့မရပါဘူး။ အောက်က Code မှာဆိုရင် 'Unexpected indent' ဆိုတဲ့ Error တက်ပါလိမ့်မယ်။
Multi-lining
တကယ်လို့ Statements တွေက ရှည်နေခဲ့ရင် စာကြောင်းအများကြီးခွဲပြီး (Multi-lines) ရေးလို့ရပါတယ်။ အဲဒီလိုရေးတဲ့အခါ နောက်ဆုံးစာကြောင်းကလွဲရင် ကျန်တဲ့စာကြောင်းတွေရဲ့ အဆုံးမှာ \ ထည့်ပေးရပါမယ်။
total = physics + chemistry + maths + \
english + myanmar + history + \
geography + civics
[ ]၊ { } (သို့မဟုတ်) ( ) တွေကြားထဲမှာရေးတဲ့ Multi-line statements တွေအတွက်တော့ \ ထည့်ပေးစရာ မလိုပါဘူး။
3.6 Classes and Objects¶
Python မှာ Type တိုင်းက Class တစ်ခု ဖြစ်ပါတယ်။ ဒါကြောင့် int၊ float၊ complex၊ bool၊ str၊ list၊ tuple၊ set၊ dict စတာတွေ အကုန်လုံးက Classes တွေချည်းပါပဲ။ ဒါတွေက Ready-made classes တွေပါ။ Python က User-defined classes တွေကို ကိုယ်တိုင်ဖန်တီးခွင့် ပေးထားပါတယ် (Chapter 18 ကျရင် တွေ့ရပါမယ်)။
Object တစ်ခုကို Class ကနေ ဖန်တီးယူပါတယ်။ Class တစ်ခုက အချက်နှစ်ချက်ကို သတ်မှတ်ပေးပါတယ် - 1. သူ့ဆီကနေ ထွက်လာမယ့် Object ယူမယ့် ပုံစံ (Form) 2. အဲဒီ Object ကို Access လုပ်ဖို့နဲ့ Manipulate လုပ်ဖို့ သုံးရမယ့် Methods (Functions) များ
Class တစ်ခုတည်းကနေ Objects အများကြီး ဖန်တီးလို့ ရပါတယ်။ Class တစ်ခုကနေ Object တစ်ခု ဖန်တီးလိုက်တာကို အဲဒီ Class ရဲ့ Instance တစ်ခု ဖန်တီးလိုက်တယ်လို့ ပြောလေ့ရှိကြပါတယ်။
Class မှာ နာမည်ရှိပေမယ့် Objects တွေမှာ နာမည်မရှိပါဘူး။ Objects တွေမှာ နာမည်မရှိတဲ့အတွက် Memory ထဲက သူတို့ရဲ့ Addresses တွေကို သုံးပြီး ရည်ညွှန်း (Refer) ကြပါတယ်။
ဒီအချက်တွေကို အောက်ပါ Program နဲ့ စမ်းသပ်အတည်ပြုနိုင်ပါတယ်။ ပိုပြီးနားလည်သွားအောင် Observation (လေ့လာတွေ့ရှိချက်) တွေကို ကြည့်ပါ။
a = 30
b = 'Good'
print(a, b) # 3 Good ဆိုပြီး print ထွက်ပါမယ်
print(type(a), type(b)) # <class 'int'> <class 'str'> ဆိုပြီး Class တွေကို ပြပါမယ်
print(id(a), id(b)) # 1356658640 33720000 ဆိုပြီး Memory address တွေ ပြပါမယ်
print(isinstance(a, int), isinstance(b, str)) # True True ဆိုပြီး ပြပါမယ်
3.7 Python Object Reference Visualization¶
Python မှာ Variables တွေက Memory ပေါ်မှာရှိတဲ့ Objects တွေကို ဘယ်လို Refer လုပ်သလဲ (ဘယ်လို ညွှန်ပြထားသလဲ) ဆိုတာ နားလည်ဖို့ အရမ်းအရေးကြီးပါတယ်။
Key Concept
- Python မှာ Variables တွေဆိုတာ တကယ်တမ်းကျတော့ Memory ထဲမှာ သိမ်းဆည်းထားတဲ့ Objects တွေကို ညွှန်ပြနေတဲ့ References (သို့မဟုတ် Pointers) တွေပဲ ဖြစ်ပါတယ်။ သူတို့က Values တွေကို တိုက်ရိုက် သိမ်းဆည်းထားတာ မဟုတ်ပါဘူး။ Value သိမ်းထားတဲ့ Memory location ကို ညွှန်ပြပေးနေတာသာ ဖြစ်ပါတယ်။
Memory Reference Breakdown¶
အောက်ပါဇယားက ပုံထဲမှာပြထားတဲ့ References တွေကို အသေးစိတ် ရှင်းပြထားတာပါ -
| Variable Name | Reference ID (Address) | Points To (Object Type) | Object Value | Object Memory Address |
|---|---|---|---|---|
a |
1356658640 |
int object | 30 |
1356658640 |
b |
33720000 |
str object | Good |
33720000 |
Observation (လေ့လာတွေ့ရှိချက်)
- Variable
aမှာ Reference ID1356658640ရှိနေပါတယ်။ အဲဒါက Integer Object30ရှိနေတဲ့ Address နဲ့ အတူတူပါပဲ။ - Variable
bမှာ Reference ID33720000ရှိနေပါတယ်။ အဲဒါက String Object'Good'ရှိနေတဲ့ Address နဲ့ အတူတူပါပဲ။
ဒီ Program မှာ ကျွန်တော်တို့ Objects နှစ်ခုကို ဖန်တီးခဲ့ပါတယ်။ တစ်ခုက Ready-made class ဖြစ်တဲ့ int ကနေဖြစ်ပြီး၊ နောက်တစ်ခုက Ready-made class ဖြစ်တဲ့ str ကနေ ဖြစ်ပါတယ်။
int type Object ထဲမှာ 30 ပါဝင်ပြီး၊ str type Object ထဲမှာတော့ 'Good' ပါဝင်ပါတယ်။
Objects နှစ်ခုလုံးက နာမည်မရှိပါဘူး (Nameless ဖြစ်ပါတယ်)။ Memory ထဲက သူတို့ရဲ့ Addresses တွေဖြစ်တဲ့ 1356658640 နဲ့ 33720000 ကို a နဲ့ b ထဲမှာ သိမ်းဆည်းထားတာပါ။
ဒီ Addresses တွေကို Built-in function ဖြစ်တဲ့ id( ) ကိုသုံးပြီး ရယူနိုင်ပါတယ်။ (မှတ်ချက် - ခင်ဗျားတို့စက်မှာ ကိုယ်တိုင် Run ရင်တော့ Addresses တွေ မတူတာ ထွက်လာနိုင်ပါတယ်)။
a နဲ့ b က Addresses တွေကို သိမ်းထားတဲ့အတွက် သူတို့ကို အဲဒီ Addresses မှာရှိတဲ့ Objects တွေကို Refer လုပ်နေတယ် (ရည်ညွှန်းနေတယ်) လို့ ပြောကြပါတယ်။ လွယ်လွယ်ပြောရရင် သူတို့က Objects တွေကို ညွှန်ပြနေတဲ့ Pointers တွေပါပဲ။
a နဲ့ b က Refer လုပ်နေတဲ့ Objects တွေရဲ့ Type ကို သိချင်ရင် Built-in function ဖြစ်တဲ့ type( ) ကို သုံးနိုင်ပါတယ်။
a က class int ရဲ့ Instance ဟုတ်မဟုတ် စစ်ဆေးချင်ရင်တော့ Built-in function ဖြစ်တဲ့ isinstance( ) ကို သုံးနိုင်ပါတယ်။
Multiple Objects
အောက်ပါ Program လေးကို ဆက်ကြည့်ရအောင် -
a = 3
b = 3
print(id(a), id(b)) # 1356658640 1356658640 ဆိုပြီး တူနေတာကို တွေ့ရပါမယ်
print(a is b) # True ပြပါမယ်
a = 30 # အခု a က Object အသစ်တစ်ခုကို Refer လုပ်သွားပါပြီ
print(id(a)) # 1356659072 ဆိုပြီး Address ပြောင်းသွားပါမယ်
ကျွန်တော်တို့ int objects နှစ်ခု ဖန်တီးလိုက်တာလား? မဟုတ်ပါဘူး။ int object ထဲမှာ သိမ်းထားတဲ့ Value က တူနေတဲ့အတွက် (နှစ်ခုလုံးက 3 ဖြစ်နေလို့)၊ int object တစ်ခုတည်းကိုပဲ ဖန်တီးပါတယ်။ a ရော b ရောက အဲဒီ int object တစ်ခုတည်းကိုပဲ လှမ်းပြီး Refer လုပ်နေကြတာပါ။ ဒါကြောင့် id(a) နဲ့ id(b) က တူညီတဲ့ Addresses တွေကို ပြန်ပေးတာဖြစ်ပါတယ်။
ဒါကို is operator သုံးပြီးလည်း စစ်ဆေးနိုင်ပါတယ်။ a နဲ့ b က Object တစ်ခုတည်းကိုပဲ Refer လုပ်နေတဲ့အတွက် True လို့ ပြန်ပေးပါလိမ့်မယ်။
ကျွန်တော်တို့က a ထဲကို Value အသစ်တစ်ခု ထည့်ဖို့ ကြိုးစားလိုက်တဲ့အခါ (ဥပမာ - 30 ထည့်လိုက်ရင်)၊ သိမ်းရမယ့် တန်ဖိုးက ကွဲပြားသွားပြီဖြစ်တဲ့အတွက် int object အသစ်တစ်ခုကို ဖန်တီးလိုက်ပါတယ်။ အခုအခါမှာ a က ဒီ int object အသစ်ကို ပြောင်းပြီး Refer လုပ်သွားပါပြီ။ b ကတော့ မူလ int object (Value 3 ရှိတဲ့ကောင်) ကိုပဲ ဆက်ပြီး Refer လုပ်နေတုန်းပါပဲ။
a က 3 ပါဝင်တဲ့ int object ကို Refer လုပ်နေတယ်လို့ ပြောမယ့်အစား၊ a သည် int object ဖြစ်တယ်၊ သို့မဟုတ် 3 ကို a ထဲ Assign လုပ်လိုက်တယ်လို့ပဲ အလွယ်ပြောလေ့ရှိကြပါတယ်။
Programmers တော်တော်များများက a နဲ့ b ကို int variables တွေ (တန်ဖိုးတွေကို တိုက်ရိုက်သိမ်းတဲ့ အကွက်တွေ) လို့ ထင်နေကြတုန်းပါပဲ။ တကယ်တမ်းက အဲဒီလိုမဟုတ်ဘူးဆိုတာ အခုလောက်ဆို သိလောက်ပါပြီ။
Problem 3.1¶
Integer types တွေနဲ့ သူတို့အပေါ်မှာ သုံးလို့ရတဲ့ Operators တွေကို ဘယ်လိုအသုံးပြုမလဲဆိုတာ သရုပ်ပြပါ။
Program (နှိပ်ပြီး ကြည့်နိုင်ပါတယ်)
# use of integer types
print(3 / 4) # Division (အမြှောက်)
print(3 % 4) # Modulus (အကြွင်း)
print(3 // 4) # Floor Division (စားလဒ် အရေအတွက်)
print(3 ** 4) # Exponentiation (ထပ်ကိန်း)
a = 10 ; b = 25 ; c = 15 ; d = 30 ; e = 2 ; f = 3 ; g = 5
w = a + b - c
x = d ** e
y = f % g
print(w, x, y)
# Python handles large integers automatically
h = 99999999999999999
i = 54321
print(h * i)
Tips
- ¾ က 0 မထွက်ပါဘူး (Python 3 မှာ Float division ဖြစ်သွားလို့ 0.75 ထွက်ပါတယ်)။
- တစ်ကြောင်းတည်းမှာ Statements အများကြီးရေးမယ်ဆိုရင်
;ခံပြီး ခြားရေးရပါမယ်။ - print(w, x, y) က Values တွေကို Space ခြားပြီး Print ထုတ်ပေးပါတယ်။
Problem 3.2¶
float၊ complex နဲ့ bool types တွေနဲ့ သူတို့အပေါ်မှာ သုံးလို့ရတဲ့ Operators တွေကို ဘယ်လိုအသုံးပြုမလဲဆိုတာ သရုပ်ပြပါ။
Program (နှိပ်ပြီး ကြည့်နိုင်ပါတယ်)
# use of float (float ကို အသုံးပြုခြင်း)
i = 3.5
j = 1.2
print(i % j) # Modulus ရှာခြင်း
# use of complex (complex number ကို အသုံးပြုခြင်း)
a = 1 + 2j
b = 3 * (1 + 2j)
c = a * b
print(a)
print(b)
print(c)
print(a.real) # Real part ကို ထုတ်ကြည့်ခြင်း
print(a.imag) # Imaginary part ကို ထုတ်ကြည့်ခြင်း
print(a.conjugate( )) # Conjugate လုပ်ခြင်း
print(a)
# use of bool (Boolean ကို အသုံးပြုခြင်း)
x = True
y = 3 > 4
print(x)
print(y)

Tips
%(Modulus operator) က floats တွေပေါ်မှာလည်း အလုပ်လုပ်ပါတယ်။- Complex number တစ်ခုကနေ real နဲ့ imag part တွေကို ခွဲထုတ်ယူလို့ရပါတယ်။
- Condition တစ်ခုကို Evaluation လုပ်လိုက်ရင် True သို့မဟုတ် False အဖြစ် အစားထိုးသွားပါတယ်။
Problem 3.3¶
Number type တစ်ခုကနေ နောက်တစ်ခုကို ဘယ်လို Convert လုပ်မလဲဆိုတာ သရုပ်ပြပါ။
Program (နှိပ်ပြီး ကြည့်နိုင်ပါတယ်)
# convert to int (Integer ပြောင်းခြင်း)
print(int(3.14)) # float ကနေ int သို့ ပြောင်းတာပါ (ဒသမဖြတ်ပါတယ်)
a = int('485') # numeric string ကနေ int သို့
b = int('768') # numeric string ကနေ int သို့
c = a + b
print(c)
# Base တွေပြောင်းပြီး int လုပ်ခြင်း
print(int('1011', 2)) # binary string ကနေ decimal int သို့
print(int('341', 8)) # octal string ကနေ decimal int သို့
print(int('21', 16)) # hex string ကနေ decimal int သို့
# convert to float (Float ပြောင်းခြင်း)
print(float(35)) # int ကနေ float သို့ (35.0 ဖြစ်သွားမယ်)
i = float('4.85') # numeric string ကနေ float သို့
j = float('7.68') # numeric string ကနေ float သို့
k = i + j
print(k)
# convert to complex (Complex number ပြောင်းခြင်း)
print(complex(35)) # int ကနေ complex သို့ (35+0j)
x = complex(4.85, 1.1) # arguments နှစ်ခုပေးပြီး ဆောက်ခြင်း
y = complex(7.68, 2.1)
z = x + y
print(z)
# convert to bool (Boolean ပြောင်းခြင်း)
print(bool(35)) # Non-zero မို့ True ရပါမယ်
print(bool(1.2)) # Non-zero မို့ True ရပါမယ်
print(int(True)) # 1 ရပါမယ်
print(int(False)) # 0 ရပါမယ်
Tips
- Binary, Octal, Hexadecimal numeric string တွေကို သူတို့နဲ့ညီမျှတဲ့ Decimal integer အဖြစ် ပြောင်းလို့ရပါတယ်။ ဒါပေမယ့် Float အတွက်တော့ အဲဒီလိုလုပ်လို့ မရပါဘူး။
- Complex ကို Convert လုပ်တဲ့အခါ Argument တစ်ခုတည်းပေးမယ်ဆိုရင် Imaginary part ကို
0လို့ ယူဆသွားပါတယ်။ - သုညမဟုတ်တဲ့ ဂဏန်း (Non-zero number - int ဖြစ်ဖြစ် float ဖြစ်ဖြစ်) မှန်သမျှကို True လို့ သတ်မှတ်ပြီး၊
0ကိုတော့ False လို့ သတ်မှတ်ပါတယ်။
Problem 3.4¶
Built-in mathematical functions တွေကို အသုံးပြုထားတဲ့ Program တစ်ပုဒ် ရေးပါ။
Program (နှိပ်ပြီး ကြည့်နိုင်ပါတယ်)
# built-in math functions (ပါပြီးသား သင်္ချာ function များ)
print(abs(-25)) # Absolute value ရှာခြင်း (25)
print(pow(2, 4)) # ထပ်ကိန်းတင်ခြင်း (16)
print(min(10, 20, 30, 40, 50)) # အငယ်ဆုံးရှာခြင်း (10)
print(max(10, 20, 30, 40, 50)) # အကြီးဆုံးရှာခြင်း (50)
print(divmod(17, 3)) # စားလဒ်နဲ့ အကြွင်း တွဲထုတ်ခြင်း ((5, 2))
print(bin(64), oct(64), hex(64)) # Binary, Octal, Hex ပြောင်းခြင်း
print(round(2.567), round(2.5678, 2)) # ကိန်းပြည့်ဖြတ်ခြင်းနှင့် ဒသမ ၂ နေရာဖြတ်ခြင်း
Tips
- divmod(a, b) က (a // b, a % b) ဆိုတဲ့ အတွဲ (Pair) ကို ထုတ်ပေးပါတယ်။
- bin( )၊ oct( )၊ hex( ) တွေက Binary၊ Octal နဲ့ Hexadecimal တန်ဖိုးတွေကို ပြန်ပေးပါတယ်။
- round(x) ကို သုံးတဲ့အခါ ဒသမနေရာ မပါအောင် (0 decimal places) ဖြတ်မယ်လို့ ယူဆပြီး အလုပ်လုပ်ပါတယ်။
Problem 3.5¶
math module ထဲက Functions တွေကို အသုံးပြုထားတဲ့ Program တစ်ပုဒ် ရေးပါ။
Program (နှိပ်ပြီး ကြည့်နိုင်ပါတယ်)
# mathematical functions from math module
import math
x = 1.5357
print(math.pi, math.e) # pi နဲ့ e တန်ဖိုးများ
print(math.sqrt(x)) # Square root ရှာခြင်း
print(math.factorial(6)) # Factorial ရှာခြင်း
print(math.fabs(x)) # Absolute float value
print(math.log(x)) # Natural log (base e)
print(math.log10(x)) # Log base 10
print(math.exp(x)) # e raised to x
print(math.trunc(x)) # ဒသမဖြတ်ထုတ်ခြင်း (Truncate)
print(math.floor(x)) # အောက်ချခြင်း (Floor)
print(math.ceil(x)) # အပေါ်တင်ခြင်း (Ceiling)
# Negative values တွေနဲ့ စမ်းသပ်ခြင်း
print(math.trunc(-x))
print(math.floor(-x))
print(math.ceil(-x))
print(math.modf(x)) # Fractional part နဲ့ Integer part ကို ခွဲထုတ်ခြင်း
Output
Tips
- floor( ) က Negative infinity ဘက်ကို ဆွဲချပြီး Round လုပ်ပါတယ် (တန်ဖိုးအနည်းဘက်ကို ယူပါတယ်)။ ceil( ) က Positive infinity ဘက်ကို ဆွဲတင်ပြီး Round လုပ်ပါတယ် (တန်ဖိုးအများဘက်ကို ယူပါတယ်)။ trunc( ) ကတော့ 0 ဘက်ကို ဦးတည်ပြီး Round လုပ်ပါတယ် (ဒသမတွေကို ရိုးရိုးလေး ဖြတ်ထုတ်လိုက်တာပါ)။
- Positive numbers တွေအတွက်ဆိုရင် trunc( ) က floor( ) နဲ့ အတူတူပါပဲ။
- Negative numbers တွေအတွက်ဆိုရင် trunc( ) က ceil( ) နဲ့ အတူတူပါပဲ။
- modf( ) က
(f, i)ဆိုတဲ့ ကိန်းဂဏန်းအတွဲ (Pair) ကို ပြန်ပေးပါတယ် (ဒီမှာx = f + iဖြစ်ပြီး0 <= f < 1ဖြစ်ပါတယ်)။
Problem 3.6¶
Float နဲ့ Integer random numbers တွေကို ထုတ်ပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
Program (နှိပ်ပြီး ကြည့်နိုင်ပါတယ်)
# random number operations using random module
import random
import datetime
# Seed သတ်မှတ်ခြင်း (လက်ရှိအချိန်ကို မူတည်ပြီး Random ပုံစံပြောင်းအောင်လုပ်တာပါ)
# Note: ပုံမှန်အားဖြင့် Python က ဒါကို အလိုအလျောက် လုပ်ပေးပါတယ်
random.seed(datetime.time( ))
print(random.random( )) # 0.0 နဲ့ 1.0 ကြား Random float
print(random.random( ))
print(random.randint(10, 100)) # 10 နဲ့ 100 ကြား Random integer
Tips
- random module ကို မဖြစ်မနေ import လုပ်ဖို့ လိုအပ်ပါတယ်။
- Random number generation logic ကို လက်ရှိအချိန် (Current time) နဲ့ Seed လုပ်ပေးလိုက်ရင်၊ Program ကို Execute လုပ်လိုက်တိုင်း မတူညီတဲ့ Random numbers တွေကို ရရှိစေပါတယ်။
- Parameter မပါတဲ့ random.seed( ) ကလည်း Logic ကို လက်ရှိအချိန်နဲ့ပဲ Seed လုပ်ပေးပါတယ်။
Problem 3.7¶
အောက်ဖော်ပြပါ Data တွေထဲက ဘယ်ဟာက string၊ list၊ tuple၊ set (သို့မဟုတ်) dictionary ဖြစ်မလဲဆိုတာ ဘယ်လို ခွဲခြားသိနိုင်မလဲ?
{10, 20, 30.5}
[1, 2, 3.14, 'Nagpur']
{12 : 'Simple', 43 : 'Complicated', 13 : 'Complex'}
"Check it out!"
3 + 2j
Program
# determine type of data (Data Type တွေကို စစ်ဆေးခြင်း)
print(type({10, 20, 30.5})) # Curly braces {} နဲ့မို့ Set ပါ
print(type([1, 2, 3.14, 'Nagpur'])) # Square brackets [] နဲ့မို့ List ပါ
print(type({12 : 'Simple', 43 : 'Complicated', 13 : 'Complex'})) # Key-Value pairs ပါလို့ Dict ပါ
print(type("Check it out!")) # Quotes "" ပါလို့ String ပါ
print(type(3 + 2j)) # j ပါလို့ Complex ပါ
Tips
- type( ) ဆိုတာက built-in ဖြစ်စေ၊ container ဖြစ်စေ၊ user-defined ဖြစ်စေ မည်သည့် Data အမျိုးအစားကိုမဆို ခွဲခြားစစ်ဆေးပေးနိုင်တဲ့ Built-in function တစ်ခုဖြစ်ပါတယ်။
Exercises¶
[A] Answer the following questions:¶
a. Variable a နဲ့ b ရဲ့ တန်ဖိုးတွေကို အချင်းချင်းလှဲလှယ် (Swap) ပေးမယ့် Program တစ်ပုဒ်ရေးပါ။ တတိယ Variable တစ်လုံးကို အကူအညီယူပြီး သုံးခွင့်မရှိပါဘူး။ a နဲ့ b အပေါ်မှာ Arithmetic operations (အပေါင်း၊ အနုတ် စသည်) လုပ်ဆောင်ခွင့်မရှိပါဘူး။
b. math module မှာပါဝင်တဲ့ Trigonometric functions တွေကို အသုံးပြုထားတဲ့ Program တစ်ပုဒ်ရေးပါ။
c. 10 ကနေ 50 ကြားထဲမှာရှိတဲ့ Random numbers 5 လုံးကို ထုတ်ပေးမယ့် Program တစ်ပုဒ်ရေးပါ။ Seed value ကို 6 ထားပြီး သုံးပါ။ Program ကို Execute လုပ်လိုက်တိုင်း ဒီ Seed value ကို Execution time နဲ့ တွဲပြီး ပြောင်းလဲသွားအောင် (Change ဖြစ်သွားအောင်) စီစဉ်ပေးပါ။
d. -2.8, -0.5, 0.2, 1.5 နဲ့ 2.9 စတဲ့ ကိန်းဂဏန်းတွေအတွက် trunc( )၊ floor( ) နဲ့ ceil( ) တို့ရဲ့ ကွာခြားချက်ကို ရှင်းရှင်းလင်းလင်း သိရအောင် လက်တွေ့စမ်းသပ်ပါ။
e. မြို့တစ်မြို့ရဲ့ အပူချိန်ကို Fahrenheit degrees နဲ့ သင့်တော်သလို သတ်မှတ်ပါ။ ပြီးရင် ဒီအပူချိန်ကို Centigrade degrees ပြောင်းလဲပြီး အပူချိန်နှစ်မျိုးလုံးကို Print ထုတ်ပေးမယ့် Program ရေးပါ။
f. တြိဂံတစ်ခုရဲ့ အနားများဖြစ်တဲ့ a, b, c တို့ကို ပေးထားရင်၊ ယင်းတြိဂံရဲ့ ထောင့် (Angles) ၃ ခုကို ရှာဖွေပြီး Next integer အဖြစ် Round လုပ်ကာ ထုတ်ပေးမယ့် Program ကို ရေးပါ။ အောက်ပါ Formulae များကို အသုံးပြုပါ -
[B] How will you perform the following operations:¶
အောက်ပါ Operations တွေကို ဘယ်လို လုပ်ဆောင်မလဲ -
a. 2 + 3j ရဲ့ Imaginary part ကို Print ထုတ်ပါ။
b. 4 + 2j ရဲ့ Conjugate ကို ရယူပါ။
c. Binary 1100001110 နဲ့ ညီမျှတဲ့ Decimal တန်ဖိုးကို Print ထုတ်ပါ။
d. Float value 4.33 ကို Numeric string အဖြစ် ပြောင်းလဲပါ။
e. 29 ကို 5 နဲ့ စားတဲ့အခါ ရလာမယ့် Integer quotient (ကိန်းပြည့်စားလဒ်) နဲ့ Remainder (အကြွင်း) ကို ရယူပါ။
f. Decimal 34567 နဲ့ ညီမျှတဲ့ Hexadecimal တန်ဖိုးကို ရယူပါ။
g. 45.6782 ကို ဒသမ ၂ နေရာအထိ (Second decimal place) Round-off လုပ်ပါ။
h. 3.556 ကနေ 4 ရအောင် လုပ်ပါ။ (Hint: ceil သို့မဟုတ် round)
i. 16.7844 ကနေ 17 ရအောင် လုပ်ပါ။
j. 3.45 ကို 1.22 နဲ့ စားတဲ့အခါ ရလာမယ့် Remainder (အကြွင်း) ကို ရယူပါ။
[C] Which of the following is invalid variable name and why?¶
အောက်ဖော်ပြပါအမည်တွေထဲက ဘယ်ဟာက Invalid variable name (မှားယွင်းနေတဲ့ နာမည်) ဖြစ်သလဲ၊ ဘာကြောင့်လဲ?
| BASICSALARY | _basic | basic-hra | #MEAN |
|---|---|---|---|
| group. | 422 | pop in 2020 | over |
| timemindovermatter | SINGLE | hELLO | queue. |
| team'svictory | Plot#3 | 2015_DDay |
[D] Evaluate the following expressions:¶
အောက်ပါ Expressions တွေကို Evaluate လုပ်ပါ (တွက်ချက်အဖြေထုတ်ပါ) - (မှတ်ချက် - Operator Precedence ခေါ် ဦးစားပေးအဆင့်ကို သတိပြုတွက်ချက်ပါ)
a. 2 ** 6 // 8 % 2
b. 9 ** 2 // 5 - 3
c. 10 + 6 - 2 % 3 + 7 - 2
d. 5 % 10 + 10 -23 * 4 // 3
e. 5 + 5 // 5 - 5 * 5 ** 5 % 5
f. 7 % 7 + 7 // 7 - 7 * 7
[E] Evaluate the following expressions:¶
အောက်ပါ Expressions တွေကို Evaluate လုပ်ပါ -
a. min(2, 6, 8, 5)
b. bin(46)
c. round(10.544336, 2)
d. math.hypot(6, 8)
e. math.modf(3.1415)
[F] Match the following pairs:¶
အောက်ပါ အတွဲများကို မှန်ကန်အောင် ယှဉ်တွဲပေးပါ -
| Column A | Column B |
|---|---|
| a. complex | 1. \ |
| b. Escape special character | 2. Container type |
| c. Tuple | 3. Basic type |
| d. Natural logarithm | 4. log( ) |
| e. Common logarithm | 5. log10( ) |
Chapter 4 Strings¶
Keynote¶
4.1 What are Strings? (Strings ဆိုတာ ဘာလဲ?)¶
-
Python string ဆိုတာ Unicode characters တွေကို စုစည်းထားခြင်း (Collection) ဖြစ်ပါတယ်။
-
Python strings တွေကို single (' '), double (" ") သို့မဟုတ် triple (''' ''' or """ """) quotes တွေကြားထဲမှာ ထည့်ရေးလို့ ရပါတယ်။
Handling Special Characters in Strings
String တစ်ခုထဲမှာ ' ၊ " (သို့မဟုတ်) \ လိုမျိုး Characters တွေ ပါလာခဲ့ရင် အောက်ပါနည်းလမ်း (၂) မျိုးနဲ့ သိမ်းဆည်းနိုင်ပါတယ် -
- Escape Sequence: အဲဒီ Characters တွေရဲ့ ရှေ့မှာ
\(backslash) ခံပြီး Escape လုပ်ပေးနည်းပါ။ - Raw String: String ရဲ့ အရှေ့ဆုံးမှာ
rထည့်ပေးပြီး ဒါက raw string ဖြစ်တယ်လို့ သတ်မှတ်ပေးတဲ့နည်းပါ။
# (a) Quotes တွေကို escape လုပ်ဖို့ Backslash သုံးခြင်း
msg_escape = 'He said, \'Python With Joe.\''
print(msg_escape)
# Output: He said, 'Python With Joe.'
# (b) Raw String (r prefix) ကို သုံးခြင်း
# Backslashes တွေ အများကြီးပါတဲ့အခါ (ဥပမာ - file paths သို့မဟုတ် regex) အသုံးဝင်ပါတယ်
path = r"C:\Users\Name\Documents"
print(path)
# Output: C:\Users\Name\Documents
Creating Multiline Strings
Multiline strings (စာကြောင်းများစွာပါသော စာသားများ) ကို အောက်ပါနည်းလမ်း (၃) မျိုးနဲ့ ဖန်တီးနိုင်ပါတယ် -
- Using Backslash (
\): နောက်ဆုံးစာကြောင်းကလွဲရင် ကျန်တဲ့စာကြောင်းတွေရဲ့ အဆုံးမှာ\(backslash) ထည့်ပေးရပါမယ်။ - Triple Quotes:
"""..."""(သို့မဟုတ်)'''...'''ကြားထဲမှာ ရေးသားခြင်းဖြစ်ပါတယ်။ - Parentheses:
()ကြားထဲမှာ String တွေကို ခွဲရေးပြီး ဆက်ပေးနည်းဖြစ်ပါတယ် (Implicit string concatenation)။
# Method 1: Backslash (\) ကို အသုံးပြုခြင်း
# Note: Backslash နောက်မှာ space မပါအောင် သတိထားပါ
msg1 = 'one msg ' \
'another msg'
# Method 2: Triple Quotes
# ဒီနည်းက Newline characters တွေကိုပါ string ထဲမှာ မပျက်မကွက် သိမ်းပေးပါတယ်
msg2 = """one msg
another msg"""
# Method 3: Parentheses () ကို အသုံးပြုခြင်း
# Code ကို သန့်ရှင်းသပ်ရပ်ချင်တဲ့အခါ ဒီနည်းကို အသုံးများကြပါတယ်
msg3 = ('one msg '
'another msg')
4.2 Accessing String Elements¶
- String elements (String ထဲမှာပါတဲ့ စာလုံးတစ်လုံးချင်းစီ) ကို Index value အသုံးပြုပြီး လှမ်းယူလို့ရပါတယ်။ Index က 0 ကနေ စတင်ပါတယ်။
- Negative index value (အနှုတ်လက္ခဏာပြ index) ကိုလည်း သုံးခွင့်ပြုပါတယ်။ နောက်ဆုံး Character ကို Index -1 လို့ သတ်မှတ်ပါတယ်။
4.2.1 Visualizing Indices¶
Positive နဲ့ Negative indices ဆက်စပ်ပုံကို "PYTHON" ဆိုတဲ့ String လေးနဲ့ ဥပမာပေးပြီး အောက်ပါဇယားမှာ ပြထားပါတယ် -
| Character | P | Y | T | H | O | N |
|---|---|---|---|---|---|---|
| Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
s = "PYTHON"
# Accessing first character (ပထမဆုံး character ကို ယူခြင်း)
print(s[0]) # Output: P
print(s[-6]) # Output: P
# Accessing last character (နောက်ဆုံး character ကို ယူခြင်း)
print(s[5]) # Output: N
print(s[-1]) # Output: N
4.2.2 String Slicing¶
String တစ်ခုထဲကနေ sub-string (အပိုင်းအစ) တစ်ခုကို လိုချင်ရင် [start : end] ဆိုတဲ့ syntax ကိုသုံးပြီး ဖြတ်ထုတ် (Slice) လို့ရပါတယ်။
Common Slicing Patterns (အသုံးများသော ပုံစံများ)
| Syntax | Description |
|---|---|
s[start : end] |
start ကနေ end - 1 အထိ ယူပါတယ်။ |
s[start :] |
start ကနေ String ရဲ့ အဆုံးထိ ယူပါတယ်။ |
s[: end] |
အစ ကနေ end - 1 အထိ ယူပါတယ်။ |
s[-start :] |
-start (ပါဝင်သည်) ကနေ အဆုံးထိ ယူပါတယ်။ |
s[: -end] |
အစ ကနေ -end - 1 အထိ ယူပါတယ်။ |
Handling Out-of-Bounds Indices
Slicing ရဲ့ အရေးကြီးတဲ့ အားသာချက်တစ်ခုကတော့ String အရှည်ထက်ကျော်လွန်နေတဲ့ Indices တွေကို ကိုင်တွယ်ပုံပါပဲ။
Slicing vs. Direct Indexing
- Direct Indexing (
msg[100]): တကယ်လို့ Index က အရမ်းကြီးနေရင် (မရှိတဲ့နေရာဖြစ်နေရင်) Error တက်ပါတယ်။ - Slicing (
msg[3:100]): သူ့ကိုတော့ Error မတက်အောင် ပြေပြေလည်လည် ဖြေရှင်းပေးပါတယ်။ String ဆုံးတဲ့အထိပဲ ယူပြီး အဆင်ပြေပြေ Return ပြန်ပေးပါတယ်။
msg = 'Rafting'
# Slicing with a large index (Safe - စိတ်ချရပါတယ်)
print(msg[3:100])
# Output: 'ting' ('t' ကနေ အဆုံးထိပဲ ယူသွားပါတယ်)
# Direct indexing with a large index (Unsafe - အန္တရာယ်ရှိပါတယ်)
# print(msg[100])
# Error: IndexError: string index out of range (Index ကျော်နေလို့ Error တက်ပါမယ်)
4.3 String Properties¶
Python strings တွေက immutable ဖြစ်ပါတယ် — ဆိုလိုတာက သူတို့ကို တကြိမ် ဖန်တီးပြီးသွားရင် ပြင်ဆင်ပြောင်းလဲလို့ မရတော့ပါဘူး။
- Immutability: Python strings တွေကို မူလနေရာမှာ ပြင်လို့မရပါဘူး (Cannot be changed in place)။
- Concatenation: Strings တွေကို
+သုံးပြီး ဆက်လို့ရပါတယ်။ - Replication: Strings တွေကို
*သုံးပြီး ပွားလို့ (Repeat လုပ်လို့) ရပါတယ်။ - Membership: String တစ်ခုထဲမှာ ကိုယ်လိုချင်တဲ့ စာသားပါမပါ
inသုံးပြီး စစ်လို့ရပါတယ်။
Basic String Operations
Python က String တွေကို လွယ်လွယ်ကူကူ ကိုင်တွယ်နိုင်ဖို့ Operators တွေကို ထည့်သွင်းပေးထားပါတယ်။
Concatenation (+)
Strings တွေကို + operator အသုံးပြုပြီး ပေါင်းစပ် (Concatenate) လို့ရပါတယ်။
msg1 = "Hello "
msg2 = "World"
msg3 = msg1 + msg2 # msg1 နဲ့ msg2 ကို ပေါင်းလိုက်ပါတယ်
print(msg3)
# Output: Hello World
Replication (*)
Strings တွေကို * operator အသုံးပြုပြီး ထပ်ခါထပ်ခါ ပွားယူလို့ (Replicate လုပ်လို့) ရပါတယ်။ ဒါက Output ကို လှပအောင် Format ချတဲ့နေရာတွေ (ဥပမာ - စည်းကြောင်းတွေ ဆွဲတာမျိုး) မှာ အရမ်းအသုံးဝင်ပါတယ်။
Syntax Note
String တစ်ခုကို ပွားယူဖို့အတွက် Asterisk * ကို မဖြစ်မနေ သုံးရပါမယ်။ Comma , သုံးလို့ မရပါဘူး။
print('-', 50)လို့ရေးရင် Character နဲ့ ဂဏန်းကို ဒီတိုင်းပဲ ရိုက်ထုတ်ပေးပါလိမ့်မယ် (ဥပမာ -- 50)။print('-' * 50)လို့ရေးမှသာ Character ကို အခါ ၅၀ တိတိ ပွားပြီး ထုတ်ပေးမှာ ဖြစ်ပါတယ်။
# Prints 50 dashes in a single line (Dash အခု ၅၀ ကို တစ်ကြောင်းတည်း ပွားထုတ်ခြင်း)
print('-' * 50)
Membership Testing (in)
Membership testing ဆိုတာက String တစ်ခုထဲမှာ ကိုယ်ရှာချင်တဲ့ Substring (စာသားအပိုင်းအစ) ပါဝင်ခြင်း ရှိ/မရှိ စစ်ဆေးတာ ဖြစ်ပါတယ်။ တကယ်လို့ ပါဝင်ရင် True လို့ ပြန်ပေးပြီး၊ မပါဝင်ဘူးဆိုရင်တော့ False လို့ ပြန်ပေးပါတယ်။
s = "Hello World"
print('World' in s) # Output: True (World ပါလို့ True ပြပါတယ်)
print('Python' in s) # Output: False (Python မပါလို့ False ပြပါတယ်)
String Length (len())
len() function က String တစ်ခုထဲမှာပါဝင်တဲ့ Characters အရေအတွက် (String အရှည်) ကို ပြန်ပေးပါတယ်။
s = "Hello World"
print(len(s)) # Output: 11 (Space အပါအဝင် Character ၁၁ လုံး ရှိပါတယ်)
String Indexing
String indexing ဆိုတာ String တစ်ခုထဲမှာပါတဲ့ Characters တစ်လုံးချင်းစီကို သူတို့ရဲ့ တည်နေရာပြ Index သုံးပြီး လှမ်းယူတာ ဖြစ်ပါတယ်။
s = "Hello World"
print(s[0]) # Output: H (Index 0 ဖြစ်တဲ့ ပထမဆုံး စာလုံးကို ယူပါတယ်)
print(s[-1]) # Output: d (Index -1 ဖြစ်တဲ့ နောက်ဆုံး စာလုံးကို ယူပါတယ်)
String Slicing
String slicing ဆိုတာ Indices တွေကို Range လိုက်သတ်မှတ်ပြီး String တစ်ခုထဲက ကိုယ်လိုချင်တဲ့ အပိုင်းအစကို ဖြတ်ထုတ်ယူတာ ဖြစ်ပါတယ်။
s = "Hello World"
print(s[0:5]) # Output: Hello (Index 0 ကနေ 5 မရောက်ခင်ထိ ယူပါတယ်)
print(s[-6:-1]) # Output: World (Negative Index သုံးပြီး ဖြတ်ယူတာပါ)
Modern String Formatting (f-strings)
Up-to-Date Feature (Python 3.6+)
- Strings နဲ့ Variables တွေကို ပေါင်းစပ်ဖို့အတွက် ရှေးရိုးစွဲနည်းလမ်းတွေဖြစ်တဲ့
+(Concatenation) သို့မဟုတ်.format()တို့ရှိပါတယ်။ - ဒါပေမယ့်
f-strings(Formatted String Literals) ကတော့ Code ကို ဖတ်ရလွယ်ကူစေပြီး (Readable)၊ လုပ်ဆောင်ချက် ပိုမြန်ဆန်တဲ့အတွက် (Faster) လက်ရှိမှာ Modern Way အနေနဲ့ အသုံးပြုဖို့ အထူးအကြံပြုထားပါတယ်။
name = "Joseph"
age = 25
# Old Way (Concatenation - နည်းဟောင်း)
# Integer ကို String ပြောင်းဖို့ str(age) ခံပေးရပါတယ်
msg = "My name is " + name + " and I am " + str(age) + " years old."
# Modern Way (f-string - နည်းသစ်)
# Variable တွေကို {} ထဲမှာ တိုက်ရိုက်ထည့်ရေးလို့ ရပါတယ် (Type conversion အလိုလိုလုပ်ပေးပါတယ်)
msg = f"My name is {name} and I am {age} years old."
4.5 Built-in Functions & Methods¶
Built-in Functions:
len(s): String ရဲ့ အရှည် (Character အရေအတွက်) ကို ပြန်ပေးပါတယ်။min(s): Unicode တန်ဖိုး အနည်းဆုံး Character ကို ပြန်ပေးပါတယ်။max(s): Unicode တန်ဖိုး အများဆုံး Character ကို ပြန်ပေးပါတယ်။
Content Test Methods (ပါဝင်သည့်အရာကို စစ်ဆေးခြင်း)
isalpha(): အားလုံးက Alphabets (စာလုံး) တွေချည်းပဲလား စစ်ပေးပါတယ်။isdigit(): အားလုံးက Digits (ဂဏန်း) တွေချည်းပဲလား စစ်ပေးပါတယ်။isalnum(): အားလုံးက Alphanumeric (စာလုံး သို့မဟုတ် ဂဏန်း) ဖြစ်မဖြစ် စစ်ပေးပါတယ်။islower()/isupper(): စာလုံးအသေးလား / အကြီးလား စစ်ပေးပါတယ်။startswith()/endswith(): သတ်မှတ်ထားတဲ့စာသားနဲ့ စ/မစ (Prefix) သို့မဟုတ် ဆုံး/မဆုံး (Suffix) စစ်ပေးပါတယ်။
Search and Replace
find(sub): Substring ရှိတဲ့ Index ကို ပြန်ပေးပါတယ်။ (မတွေ့ရင်-1ပြန်ပေးပါတယ်)replace(old, new): Substring အဟောင်းနေရာမှာ အသစ်နဲ့ အစားထိုး (Replace) လုပ်ပေးပါတယ်။
Trimming & Splitting
lstrip(),rstrip(),strip(): ဘယ်ဘက်၊ ညာဘက် သို့မဟုတ် ဘေးနှစ်ဖက်လုံးက Whitespace တွေကို ဖယ်ရှားပေးပါတယ်။split(sep): String ကို ပိုင်းဖြတ်ပြီး List အဖြစ် ပြောင်းပေးပါတယ်။join(iterable): List (သို့မဟုတ် Iterable) ထဲက Element တွေကို String အဖြစ် ပြန်ဆက်ပေးပါတယ်။
Modern Python: removing prefix/suffix (Python 3.9+)
strip()ကိုသုံးပြီး စာလုံးဖြတ်တာက တခါတလေ အန္တရာယ်ရှိနိုင်ပါတယ် (သူက စာလုံးအစုအဝေးလိုက် Character Set အနေနဲ့ ဖြတ်လို့ပါ)။- ဒါကြောင့် Python 3.9+ မှာ ပိုစိတ်ချရတဲ့ Method တွေကို ထည့်ပေးထားပါတယ်။
filename = "report.pdf"
print(filename.removesuffix(".pdf")) # Output: report
print(filename.removeprefix("report")) # Output: .pdf
4.6 String Conversions & Comparison¶
1. Case Conversion:
စာလုံးအကြီး၊ အသေး ပုံစံပြောင်းလဲခြင်းများ ဖြစ်ပါတယ်။
* upper(), lower(): စာလုံးအားလုံးကို အကြီး/အသေး ပြောင်းပါတယ်။
* capitalize(): စာကြောင်းရဲ့ ပထမဆုံးစာလုံးကိုပဲ အကြီးပြောင်းပါတယ်။
* title(): စကားလုံးတိုင်းရဲ့ အစစာလုံးကို အကြီးပြောင်းပေးပါတယ် (Title Case)။
* swapcase(): အကြီးဆို အသေး၊ အသေးဆို အကြီး ပြောင်းပြန်လုပ်ပေးပါတယ်။
2. Type Conversion:
Data Type တစ်ခုကနေ တစ်ခုသို့ ပြောင်းလဲခြင်း (Casting) ဖြစ်ပါတယ်။
* str(), int(), float(), complex() စတာတွေကို သုံးပြီး String နဲ့ Number ကြား အပြန်အလှန် ပြောင်းလဲနိုင်ပါတယ်။
3. ASCII/Unicode:
Character တွေနဲ့ သူတို့ရဲ့ ကိုယ်စားပြုကိန်းဂဏန်း (Code point) တွေကို လဲလှယ်ကြည့်ရှုခြင်း ဖြစ်ပါတယ်။
* ord('A'): Character 'A' ရဲ့ Integer တန်ဖိုး 65 ကို ပြန်ပေးပါတယ်။ (Char to Int)
* chr(65): Integer 65 နဲ့ သက်ဆိုင်တဲ့ Character 'A' ကို ပြန်ပေးပါတယ်။ (Int to Char)
4. Comparison:
Strings တွေကို ယှဉ်ပြိုင်တဲ့အခါ Lexicographical order (Dictionary ထဲက စီစဉ်ပုံ) အတိုင်း ယှဉ်ပြိုင်ပါတယ်။
* s1 > s2 လိုမျိုး Comparison operator တွေသုံးတဲ့အခါ Character တစ်လုံးချင်းစီရဲ့ Unicode values ပေါ်မူတည်ပြီး ဆုံးဖြတ်ပါတယ်။ (ဥပမာ - 'a' (97) က 'A' (65) ထက် ကြီးပါတယ်)
Solved Problems¶
Problem 4.1¶
Question: Simple string နဲ့ Multi-line string ဖန်တီးပုံ၊ String တစ်ခုကို ဖန်တီးပြီးနောက် ပြင်ဆင်လို့ ရ/မရ (Immutability) နဲ့ len(), min(), max() functions တွေ အသုံးပြုပုံကို လက်တွေ့ပြသပါ။
Program
# ရိုးရှင်းသော String များ
msg1 = 'Hoopla'
print(msg1)
# Special characters ပါသော String များ
msg2 = 'He said, \'Python With Joe\'.' # Quote ပါနေလို့ \ ခံပြီး Escape လုပ်ထားပါတယ်
file1 = 'C:\\temp\\newfile' # Backslash အတွက် \\ သုံးထားပါတယ်
file2 = r'C:\temp\newfile' # Raw string - ရှေ့မှ r ခံလိုက်ရင် \ ကို Escape လုပ်စရာမလိုပါ
print(msg2)
print(file1)
print(file2)
# Multiline strings (စာကြောင်းများစွာပါသော String များ)
# 1. Backslash (\) သုံးခြင်း
# ဒုတိယလိုင်းအစမှ Space (Whitespace) များသည် String ထဲတွင် ပါသွားပါမည်
msg3 = 'What is this life if full of care...\
We have no time to stand and stare'
# 2. Triple Quotes (""") သုံးခြင်း
# ပထမလိုင်းအဆုံးမှ Enter (New line) သည် String ထဲတွင် ပါသွားပါမည်
msg4 = """What is this life if full of care...
We have no time to stand and stare"""
# 3. Parentheses ( ) သုံးခြင်း
# String များကို ( ) သုံး၍ အလိုအလျောက် ဆက်ပေးသည် (Implicit concatenation)
msg5 = ('What is this life if full of care...'
'We have no time to stand and stare')
print(msg3)
print(msg4)
print(msg5)
# String replication (စာသားပွားယူခြင်း)
msg6 = 'MacLearn!!'
print(msg1 * 3) # msg1 ကို ၃ ခါ ပွားထုတ်ပါမည်
# Immutability of strings (String များ ပြောင်းလဲမရနိုင်ခြင်း)
# 'Utopia' ဆိုတဲ့ Object ကို ပြင်လို့မရပါ၊ msg7 variable ကိုသာ အသစ်ပြန်ညွှန်းလို့ရပါတယ်
msg7 = 'Utopia'
msg8 = 'Today!!!'
msg7 = msg7 + msg8 # + ကိုသုံး၍ စာသားဆက်ပြီး msg7 ကို Update လုပ်လိုက်ပါတယ်
print(msg7)
# String များအပေါ် Built-in function များ အသုံးပြုခြင်း
print(len('Hoopla')) # စာလုံးအရေအတွက်
print(min('Hoopla')) # ASCII တန်ဖိုး အငယ်ဆုံးစာလုံး
print(max('Hoopla')) # ASCII တန်ဖိုး အကြီးဆုံးစာလုံး
Output
Hoopla
He said, 'Python With Joe'.
C:\temp\newfile
C:\temp\newfile
What is this life if full of care... We have no time to stand and stare
What is this life if full of care...
We have no time to stand and stare
What is this life if full of care...We have no time to stand and stare
HooplaHooplaHoopla
UtopiaToday!!!
6
H
p
Tips
- Special characters တွေကို String ထဲမှာ ထည့်သွင်းသိမ်းဆည်းချင်ရင်၊ သူတို့ကို Escape လုပ်ပြီးဖြစ်စေ၊ Raw string အဖြစ် သတ်မှတ်ပြီးဖြစ်စေ လုပ်ဆောင်နိုင်ပါတယ်။
- Strings တွေက ပြင်ဆင်ပြောင်းလဲလို့ မရပါဘူး (Immutable ဖြစ်ပါတယ်)။ ဒါပေမယ့် သူတို့ကို သိမ်းဆည်းထားတဲ့ Variables တွေကိုတော့ အသစ်ပြန်ညွှန်းလို့ (Change လုပ်လို့) ရပါတယ်။
len( )က String ထဲမှာရှိတဲ့ စာလုံးအရေအတွက်ကို ပြန်ပေးပါတယ်။min( )နဲ့max( )ကတော့ String ထဲမှာရှိတဲ့ Unicode value အနည်းဆုံးနဲ့ အများဆုံး Character တွေကို အသီးသီး ပြန်ပေးပါတယ်။
Problem 4.2¶
ဒီပုစ္ဆာမှာ 'Bamboozled' ဆိုတဲ့ String ကိုအသုံးပြုပြီး Indexing, Slicing, Stepping နဲ့ Concatenation နည်းလမ်းစုံကို သုံးပြီး Output ထုတ်ပြပေးပါ။
B a
e d
e d
mboozled
mboozled
mboozled
Bamboo
Bamboo
Bamboo
Bamboo
delzoobmaB
Bamboozled
Bmoze
Bbzd
Boe
BamboozledHype!
BambooMonger!
Program
s = 'Bamboozled'
# extract B a
print(s[0], s[1])
print(s[-10], s[-9])
# extract e d
print(s[8], s[9])
print(s[-2], s[-1])
# extract mboozled
print(s[2:10])
print(s[2:])
print(s[-8:])
# extract Bamboo
print(s[0:6])
print(s[:6])
print(s[-10:-4])
print(s[:-4])
# reverse Bamboozled
print(s[::-1])
print(s[0:10:1])
print(s[0:10:2])
print(s[0:10:3])
print(s[0:10:4])
s = s + 'Hype!'
print(s)
s = s[:6] + 'Monger' + s[-1]
print(s)
Tips
- Special characters တွေကို String ထဲမှာ မပျောက်ပျက်အောင် သိမ်းဆည်းချင်ရင် (Retain)၊ သူတို့ကို Escape လုပ်ပြီးဖြစ်စေ၊ Raw string အဖြစ် သတ်မှတ်ပြီးဖြစ်စေ လုပ်ဆောင်နိုင်ပါတယ်။
s[4:8]နဲ့s[4:8:1]က အတူတူပဲ ဖြစ်ပါတယ်။ ဘာကြောင့်လဲဆိုတော့ Step ရဲ့ Default တန်ဖိုးက 1 ဖြစ်လို့ပါ။s[4:8:2]ကတော့ Character တစ်လုံးယူလိုက်၊ ၂ နေရာ ခုန်ကျော်လိုက် (Move forward 2 positions) နဲ့ ဆက်သွားမှာ ဖြစ်ပါတယ်။
Problem 4.3¶
ဒီပုစ္ဆာမှာ ပေးထားတဲ့ String တစ်ခုချင်းစီအတွက် အောက်ပါအချက်တွေကို စစ်ဆေးပေးရပါမယ် -
1. Alphabets တွေချည်းပဲလား (isalpha)
2. Numeric (ဂဏန်း) တွေချည်းပဲလား (isdigit)
3. Alphanumeric (စာလုံး သို့မဟုတ် ဂဏန်း) တွေချည်းပဲလား (isalnum)
4. Lowercase / Uppercase ဖြစ်လား (islower, isupper)
5. 'And Quiet Flows The Don' စာကြောင်းက 'And' နဲ့ စလား/ဆုံးလား (startswith, endswith)
Program
s1 = 'NitiAayog'
s2 = 'And Quiet Flows The Don'
s3 = '1234567890'
s4 = 'Make $1000 a day'
print('s1 = ', s1)
print('s2 = ', s2)
print('s3 = ', s3)
print('s4 = ', s4)
# Content test functions
print('check isalpha on s1, s2')
print(s1.isalpha( ))
print(s2.isalpha( ))
print('check isdigit on s3, s4')
print(s3.isdigit( ))
print(s4.isdigit( ))
print('check isalnum on s1, s2, s3, s4')
print(s1.isalnum( ))
print(s2.isalnum( ))
print(s3.isalnum( ))
print(s4.isalnum( ))
print('check islower on s1, s2')
print(s1.islower( ))
print(s2.islower( ))
print('check isupper on s1, s2')
print(s1.isupper( ))
print(s2.isupper( ))
print('check startswith and endswith on s2')
print(s2.startswith('And'))
print(s2.endswith('And'))
Output
s1 = NitiAayog
s2 = And Quiet Flows The Don
s3 = 1234567890
s4 = Make $1000 a day
check isalpha on s1, s2
True
False
check isdigit on s3, s4
True
False
check isalnum on s1, s2, s3, s4
True
False
True
False
check islower on s1, s2
False
False
check isupper on s1, s2
False
False
check startswith and endswith on s2
True
False
Problem 4.4¶
Question: - အောက်ဖော်ပြပါ String များကို အသုံးပြုပြီး -
'Bring It On'' Flanked by spaces on either side ''C:\Users\Joseph\Documents'
သင့်လျော်သော String functions များကို အသုံးပြုကာ အောက်ပါ Output ရလဒ်များကို ရရှိစေမည့် Program တစ်ပုဒ်ကို ရေးသားပါ။
ရရှိလိုသော Output များ:
BRING IT ON
bring it on
Bring it on
Bring It On
bRING iT oN
6
9
Bring Him On
Flanked by spaces on either side
Flanked by spaces on either side
['C:', 'Users', 'Joseph', 'Documents']
('C:', '\\', 'Users\\Joseph\\Documents')
Program
s1 = 'Bring It On'
# Conversions
print(s1.upper( ))
print(s1.lower( ))
print(s1.capitalize( ))
print(s1.title( ))
print(s1.swapcase( ))
# search and replace
print(s1.find('I'))
print(s1.find('On'))
print(s1.replace('It', 'Him'))
# trimming
s2 = ' Flanked by spaces on either side '
print(s2.lstrip( ))
print(s2.rstrip( ))
# splitting
s3 = 'C:\\Users\\Joseph\\Documents'
print(s3.split('\\'))
print(s3.partition('\\'))
Problem 4.5¶
Question - 'The Terrible Tiger Tore The Towel' ဆိုတဲ့ String ထဲမှာပါဝင်နေတဲ့ 'T' အားလုံးကို ရှာဖွေပါ။
ထို့နောက် 'T' ပါဝင်သော နေရာတိုင်းကို 't' ဖြင့် အစားထိုး (Replace) လုပ်ပါ။
Program
s = 'The Terrible Tiger Tore The Towel'
pos = s.find('T', 0)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos)
c = s.count('T')
s = s.replace('T', 't', c)
print(s)
Tips
search( )(သို့မဟုတ်find()) ကို ပထမဆုံးအကြိမ် ခေါ်ယူတဲ့အခါ ပထမဆုံးတွေ့ရှိတဲ့ 'T' ရဲ့ တည်နေရာ (Position) ကို ပြန်ပေးပါတယ်။ နောက်ထပ်တွေ့နိုင်မယ့် 'T' တွေကို ဆက်ရှာဖို့အတွက် လက်ရှိတွေ့ထားတဲ့နေရာ (pos) ရဲ့ နောက်တစ်နေရာ (pos + 1) ကနေ စတင်ရှာဖွေရပါမယ်။- တကယ်လို့ 'T' ကို ရှာမတွေ့တော့ဘူးဆိုရင်
search( )က-1တန်ဖိုးကို ပြန်ပေးပါတယ်။ count( )က String ထဲမှာ 'T' ဘယ်နှကြိမ်ပါဝင်နေသလဲဆိုတဲ့ အရေအတွက်ကို ပြန်ပေးပါတယ်။replace( )function ကို အသုံးပြုတဲ့အခါ ထည့်သွင်းရတဲ့ တတိယမြောက် Parameter က အကြိမ်အရေအတွက်ဘယ်လောက် အစားထိုးမလဲ (Number of replacements) ဆိုတာကို ညွှန်ပြပါတယ်။
Exercise¶
[A] မေးခွန်းအားလုံးကို ဖြေဆိုပါ¶
a. 'Shenanigan' ဆိုတဲ့ String ကို အသုံးပြုပြီး အောက်ဖော်ပြပါ Output ရလဒ်များကို ရရှိစေမည့် Program တစ်ပုဒ်ကို ရေးသားပါ။
ရရှိလိုသော Output များ:
b. အောက်ပါ String ဖြစ်သော
'Visit ykanetkar.com for online courses in programming' ကို
'Visit Ykanetkar.com For Online Courses In Programming'
အဖြစ်သို့ ပြောင်းလဲပေးမည့် Program တစ်ပုဒ်ကို ရေးသားပါ။
c. အောက်ပါ String ဖြစ်သော 'Light travels faster than sound. This is why some people appear bright until you hear them speak.' ကို
'LIGHT travels faster than SOUND. This is why some people appear bright until you hear them speak.' အဖြစ်သို့ ပြောင်းလဲပေးမည့် Program တစ်ပုဒ်ကို ရေးသားပါ။
d. အောက်ပါ Program ကို Run လိုက်လျှင် မည်သည့် Output ထွက်လာမလဲ စမ်းကြည့်ပေးပါ။
s = 'HumptyDumpty'
print('s = ', s)
print(s.isalpha( )) # Alphabets တွေချည်းပဲလား စစ်ဆေးခြင်း
print(s.isdigit( )) # ဂဏန်းတွေချည်းပဲလား စစ်ဆေးခြင်း
print(s.isalnum( )) # စာလုံး သို့မဟုတ် ဂဏန်း ဖြစ်လား စစ်ဆေးခြင်း
print(s.islower( )) # စာလုံးအသေးတွေချည်းပဲလား စစ်ဆေးခြင်း
print(s.isupper( )) # စာလုံးအကြီးတွေချည်းပဲလား စစ်ဆေးခြင်း
print(s.startswith('Hump')) # 'Hump' နှင့် စ၊ မစ စစ်ဆေးခြင်း
print(s.endswith('Dump')) # 'Dump' နှင့် ဆုံး၊ မဆုံး စစ်ဆေးခြင်း
e. Python တွင် Raw string (r'...') ကို အသုံးပြုရခြင်း၏ ရည်ရွယ်ချက်မှာ အဘယ်နည်း။
f. အောက်ဖော်ပြပါ String အတွင်းရှိ စကားလုံး (Word) များကို တစ်လုံးချင်းစီ သီးခြားခွဲထုတ်လိုပါက မည်သို့ ပြုလုပ်မည်နည်း။
'The difference between stupidity and genius is that genius has its limits'
g. He said, "Python With Joe". ဆိုသော စာသားကို String တစ်ခုအဖြစ် သိမ်းဆည်းရန် နည်းလမ်း (၂) ခုကို ဖော်ပြပါ။
h. အောက်ပါ Code snippet ၏ Output သည် မည်သို့ဖြစ်မည်နည်း။
s = 'Imaginary'
print(id(s)) # Memory address (Unique ID) ကို ပြပါမည်
print(type(s)) # Data Type ကို ပြပါမည်
j. Python ရှိ String များသည် Iterable (Loop ပတ်၍ရခြင်း)၊ Sliceable (ပိုင်းဖြတ်၍ရခြင်း) နှင့် Immutable (ပြင်ဆင်၍မရခြင်း) တို့ ဖြစ်ကြသည်။ (True သို့မဟုတ် False)
k. 'ThreadProperties' ဟူသော String ထဲမှ ' TraPoete' ဆိုသော စာသားကို ရရှိရန် မည်သို့ ထုတ်ယူမည်နည်း (How to extract)။
l. ' Flanked by spaces on either side ' ဟူသော String ၏ ဘေးတစ်ဖက်တစ်ချက်စီ (Either side) တွင် ရှိနေသော Spaces များကို မည်သို့ ဖယ်ရှားမည်နည်း။
m. အောက်ပါ Code snippet ၏ Output သည် မည်သို့ဖြစ်မည်နည်း။
n. အောက်ပါ Code snippet အလုပ်လုပ်ပြီးသွားတဲ့အခါ ch variable ထဲမှာ မည်သည့်အရာ ဝင်ရောက်သိမ်းဆည်းသွားမည်နည်း။
[B] Match the following pairs¶
Assuming msg = 'Keep yourself warm':
(msg = 'Keep yourself warm' ဖြစ်သည်ဟု ယူဆပြီး အောက်ပါတို့ကို ယှဉ်တွဲပါ)
| Option A (Code) | Description (ရှင်းလင်းချက်) | Option B (Result) | Match |
|---|---|---|---|
a. msg.partition(' ') |
ပထမဆုံးတွေ့တဲ့ Space နေရာမှာ ဖြတ်ပြီး 3-tuple အဖြစ် ခွဲထုတ်ပေးပါတယ်။ | ('Keep', ' ', 'yourself warm') |
8 |
b. msg.split(' ') |
Space တွေ့တဲ့နေရာတိုင်းမှာ ဖြတ်ပြီး Substrings တွေကို List အဖြစ် ထုတ်ပေးပါတယ်။ | ['Keep', 'yourself', 'warm'] |
7 |
c. msg.startswith('Keep') |
String က "Keep" နဲ့ စ၊ မစ စစ်ဆေးပေးပါတယ်။ | True | 5 |
d. msg.endswith('Keep') |
String က "Keep" နဲ့ ဆုံး၊ မဆုံး စစ်ဆေးပေးပါတယ်။ | False | 6 |
e. msg.swapcase() |
စာလုံးအကြီးကို အသေး၊ အသေးကို အကြီး ပြောင်းပြန် လုပ်ပေးပါတယ်။ | kEEP YOURSELF WARM | 2 |
f. msg.capitalize() |
ပထမဆုံးစာလုံးကို အကြီး**တင်ပြီး ကျန်တာကို **အသေး ပြောင်းပေးပါတယ်။ | Keep yourself warm | 3 |
g. msg.count('e') |
String ထဲမှာ 'e' ဘယ်နှလုံးပါလဲ ရေတွက်ပေးပါတယ်။ | 3 | 4 |
h. len(msg) |
String ရဲ့ အရှည် (Character စုစုပေါင်း) ကို ပြန်ပေးပါတယ်။ | 18 | 1 |
i. msg[0] |
ပထမဆုံး Character ကို ယူပါတယ်။ | K | 11 |
j. msg[-1] |
နောက်ဆုံး Character ကို ယူပါတယ်။ | m | 13 |
k. msg[1:1:1] |
Slicing လုပ်တဲ့အခါ Start နဲ့ End တူနေရင် ဗလာ (Empty) ဖြစ်သွားပါတယ်။ | empty string | 12 |
l. msg[-1:3] |
ညာဘက်မှ ဘယ်ဘက်သို့ Positive step သုံးပြီး ဖြတ်မရနိုင်ပါ (Empty ရပါမည်)။ | empty string | 15 |
m. msg[:-3] |
အစကနေ နောက်ဆုံး ၃ လုံးအထိ (နောက်ဆုံး ၃ လုံးမပါ) ဖြတ်ယူပါတယ်။ | Keep yourself w | 9 |
n. msg[-3:] |
နောက်ဆုံး ၃ လုံး ကိုပဲ သီးသန့်ဖြတ်ယူပါတယ်။ | arm | 14 |
o. msg[0:-2] |
အစကနေ နောက်ဆုံး ၂ လုံးအထိ (နောက်ဆုံး ၂ လုံးမပါ) ဖြတ်ယူပါတယ်။ | Keep yourself wa | 10 |
Chapter 5 Decision Control Instructions¶
Keynote¶
5.1 What are Decision Control Instructions?¶
အခုချိန်ထိ ကျွန်တော်တို့ ရေးခဲ့သမျှ Program တွေမှာ Code တွေက တစ်ကြောင်းပြီးတစ်ကြောင်း အစဉ်လိုက် (Sequentially) အလုပ်လုပ်သွားတာ ဖြစ်ပါတယ်။
ဒါပေမယ့် Program ရဲ့ အလုပ်လုပ်ပုံ အစီအစဉ် (Sequence of execution) ကို လိုအပ်သလို ပြောင်းလဲချင်တယ်ဆိုရင်တော့ အောက်ပါ (၂) မျိုးကို အသုံးပြုနိုင်ပါတယ် -
- Decision control instruction: အခြေအနေပေါ်မူတည်ပြီး ဆုံးဖြတ်ချက်ချကာ လမ်းကြောင်းပြောင်းခြင်း (Selection)။
- Repetition control instruction: အလုပ်တစ်ခုကို ထပ်ခါထပ်ခါ လုပ်ဆောင်ခြင်း (Loops/Iteration)။
Decision Control Instruction
Program တစ်ခုမှာ ဆုံးဖြတ်ချက် (Decisions) ချမှတ်ဖို့အတွက် အဓိက နည်းလမ်း (၃) ခုရှိပါတယ်။
- ပထမဦးဆုံး
ifcondition အကြောင်းကို ကြည့်ကြပါစို့။
if condition
- Condition (အခြေအနေ) တစ်ခု မှန်ကန်ခဲ့ရင် (True) သတ်မှတ်ထားတဲ့ အလုပ်ကို လုပ်မယ်၊ မမှန်ရင် (False) ကျော်သွားမယ်ဆိုတဲ့ ပုံစံဖြစ်ပါတယ်။
if elsecondition ကို ကြည့်ကြပါစို့

if condition : else
if condition1 : elif condition2 : elif condition3 : else :ကို ကြည့်ကြပါစို့
if condition1 : elif condition2 : elif condition3 : else :
if,else,elifတို့ရဲ့ နောက်ဆုံးမှာ Colon (:) ကို မဖြစ်မနေ ထည့်ပေးရပါမယ်။ifblock,elseblock နဲ့elifblock အောက်က Statements တွေကို Indent လုပ်ပြီး (Space ခွာပြီး) ရေးရပါမယ်။ အဲဒီလို Indent လုပ်ထားတဲ့ Statements တွေကို Block of statements တစ်ခုအနေနဲ့ သတ်မှတ်ပါတယ်။- Indentation ကို Statements တွေ အုပ်စုဖွဲ့ဖို့ (Group လုပ်ဖို့) အသုံးပြုပါတယ်။ Indentation အတွက် 4 spaces (သို့မဟုတ်) Tab တစ်ချက်ကို အသုံးပြုပါ။ Tabs နဲ့ Spaces တွေကို ရောမသုံးပါနဲ့။ Screen ပေါ်မှာ ကြည့်ရင် အဆင်ပြေနေသလို ထင်ရပေမယ့် တကယ် Run တဲ့အခါ Error တက်ပါလိမ့်မယ်။
- ပထမပုံစံ (
ifonly) မှာelseနဲ့elifက မပါလည်း ရပါတယ် (Optional ဖြစ်ပါတယ်)။ - ဒုတိယပုံစံ (
if-else) မှာ Condition က True ဖြစ်ရင်ifblock ထဲက Statements တွေ အကုန်အလုပ်လုပ်မယ်။ Condition က False ဖြစ်ရင်elseblock ထဲက Statements တွေ အလုပ်လုပ်ပါမယ်။ - တတိယပုံစံ (
if-elif-else) မှာ Condition တစ်ခု မမှန်ခဲ့ရင် (Fail ဖြစ်ရင်)၊ နောက်ထပ်elifblock ထဲက Condition ကို ဆက်စစ်သွားပါမယ်။ Condition တွေ အားလုံး မမှန်တော့မှသာelseblock က အလုပ်လုပ်ပါမယ်။ if-elsestatements တွေကို Nest လုပ်လို့ရပါတယ် (တဆင့်ပြီးတဆင့် ထပ်ခါထပ်ခါ အထဲမှာ ထပ်ထည့်ရေးလို့ရပါတယ်)။ Program logic လိုအပ်ချက်ရှိသလောက် အနက်ရှိုင်းဆုံးအထိ Nest လုပ်သွားနိုင်ပါတယ်။
5.2 Nuances of Conditions (Conditions တွေရဲ့ သိမ်မွေ့တဲ့ အချက်များ)¶
Condition တစ်ခုကို Relational operators တွေဖြစ်တဲ့ <, >, <=, >=, ==, != တွေကို အသုံးပြုပြီး တည်ဆောက်ပါတယ်။
10 < 20 # True ရပါတယ် (၁၀ က ၂၀ ထက် ငယ်လို့ပါ)
'Santosh' < 'Adi' # False ရပါတယ် (Alphabetical order အတိုင်း စစ်ပါတယ် - S က A ထက် နောက်ကျမှလာလို့ တန်ဖိုးကြီးပါတယ်)
'gang' < 'God' # False ရပါတယ် (Lowercase တွေက Uppercase တွေထက် ASCII value ပိုကြီးလို့ပါ)
a = b က Assignment ဖြစ်ပါတယ်၊ a == b က Comparison ဖြစ်ပါတယ်။
Ranges သို့မဟုတ် Multiple equalities (ညီမျှခြင်း ရှိ/မရှိ အများကြီးစစ်တာ) တွေကို သဘာဝကျကျ ဆက်တိုက်ရေးလို့ ရပါတယ်။
if a < b < c : # b က a နဲ့ c ကြားမှာ ရှိ၊ မရှိ စစ်ဆေးပါတယ်
if a == b == c : # သုံးခုလုံး တူညီခြင်း ရှိ၊ မရှိ စစ်ဆေးပါတယ်
# 10 != 10 က False ဖြစ်ပေမယ့်၊ ဒီနေရာမှာ True ထွက်ပါတယ်
# ဘာလို့လဲဆိုတော့ Python က (10 != 20) and (20 != 10) ဆိုပြီး ခွဲစစ်သွားလို့ပါ
if 10 != 20 != 10 : # True ရပါတယ်
True လို့ သတ်မှတ်ပြီး၊ 0 ကိုတော့ False လို့ သတ်မှတ်ပါတယ်။
print(bool(3.14)) # True ထွက်ပါတယ် (Non-zero မို့လို့ပါ)
print(bool(25)) # True ထွက်ပါတယ်
print(bool(0)) # False ထွက်ပါတယ်
5.3 Logical Operators¶
ပိုမိုရှုပ်ထွေးတဲ့ ဆုံးဖြတ်ချက်တွေ (Complex decision making) ချမှတ်ဖို့အတွက် Logical operators တွေဖြစ်တဲ့ and, or နဲ့ not တို့ကို အသုံးပြုနိုင်ပါတယ်။
Conditions တွေကို and နဲ့ or အသုံးပြုပြီး အောက်ပါအတိုင်း ပေါင်းစပ်နိုင်ပါတယ် -
cond1 and cond2 # နှစ်ခုလုံး True ဖြစ်မှသာ True ကို ပြန်ပေးပါတယ် (မဟုတ်ရင် False ပါ)
cond1 or cond2 # တစ်ခုခု True ဖြစ်တာနဲ့ True ကို ပြန်ပေးပါတယ် (အားလုံး False မှသာ False ပါ)
တိတိကျကျပြောရရင် and/or ကိုသုံးတဲ့အခါ Conditions တွေချည်းပဲ ဖြစ်နေစရာ မလိုပါဘူး။ Conditions နေရာမှာ Valid expression မှန်သမျှကို အစားထိုးသုံးလို့ ရပါတယ်။ ဒါကြောင့် ဒီလိုသုံးတဲ့အခါ ရလဒ်က True/False အမြဲဖြစ်နေမှာ မဟုတ်ဘဲ Expression ရဲ့ တကယ့်တန်ဖိုး (Actual Value) ဖြစ်နေနိုင်ပါတယ်။
and Operator အလုပ်လုပ်ပုံ:
* Expression တွေကို ဘယ်ကနေ ညာ လိုက်စစ်ပါတယ် (Evaluate လုပ်ပါတယ်)။
* တကယ်လို့ အားလုံးက True (Truthy values) ဖြစ်နေရင်၊ နောက်ဆုံး Expression ရဲ့ တန်ဖိုးကို Return ပြန်ပေးပါတယ်။
* တကယ်လို့ False (Falsy value) တစ်ခုခုတွေ့တာနဲ့ ဆက်မစစ်တော့ဘဲ အဲဒီ False ဖြစ်စေတဲ့ တန်ဖိုး ကို ချက်ချင်း Return ပြန်ပေးပါတယ် (Short-circuit ဖြစ်သွားပါတယ်)။
a = 40
b = 30
# အားလုံး True ဖြစ်နေလို့ နောက်ဆုံးတန်ဖိုး 35 ကို x ထဲထည့်ပါတယ်
# 75 (True), a>=20 (True), b<60 (True), 35 (True) -> Result: 35
x = 75 and a >= 20 and b < 60 and 35
# b < 15 က False ဖြစ်သွားလို့ အဲဒီ False တန်ဖိုးကိုပဲ y ထဲထည့်ပါတယ်
# -30 (True), a>=20 (True), b<15 (False) -> Result: False
y = -30 and a >= 20 and b < 15 and 35
# 0 က False (Falsy) ဖြစ်လို့ 0 ကိုပဲ z ထဲထည့်ပါတယ် (နောက်ဆုံးက 35 ကို ဆက်မကြည့်တော့ပါ)
# -30 (True), a>=20 (True), 0 (False) -> Result: 0
z = -30 and a >= 20 and 0 and 35
or Operator အလုပ်လုပ်ပုံ:
* Expression တွေကို ဘယ်ကနေ ညာ လိုက်စစ်ပါတယ် (Evaluate လုပ်ပါတယ်)။
* True (Truthy value) ဖြစ်တဲ့ ပထမဆုံး တန်ဖိုးကို တွေ့တာနဲ့ ကျန်တာတွေ ဆက်မစစ်တော့ဘဲ အဲဒီတန်ဖိုးကို ချက်ချင်း Return ပြန်ပေးပါတယ် (Short-circuit ဖြစ်သွားပါတယ်)။
* တကယ်လို့ အားလုံးက False (Falsy values) ဖြစ်နေရင်တော့၊ နောက်ဆုံး Expression ရဲ့ တန်ဖိုးကို Return ပြန်ပေးပါတယ်။
a = 40
b = 30
# 75 က True (Truthy) ဖြစ်တာနဲ့ ချက်ချင်း 75 ကို x ထဲထည့်ပါတယ် (နောက်ကဟာတွေ ဆက်မကြည့်ပါ)
# Result: 75
x = 75 or a >= 20 or 60
# a >= 20 က True ဖြစ်တဲ့အတွက် True ကို y ထဲထည့်ပါတယ်
# Result: True
y = a >= 20 or 75 or 60
# a < 20 (False), 0 (False), 35 (True) -> ပထမဆုံးတွေ့တဲ့ True ဖြစ်တဲ့ 35 ကို z ထဲထည့်ပါတယ်
# Result: 35
z = a < 20 or 0 or 35
not Operator
Condition တစ်ခုရဲ့ ရလဒ်ကို not သုံးပြီး ပြောင်းပြန်လှန်နိုင်ပါတယ် (Negate လုပ်နိုင်ပါတယ်)။ True ဖြစ်နေရင် False၊ False ဖြစ်နေရင် True ဖြစ်သွားပါမယ်။
a = 10
b = 20
# a <= b (10 <= 20) က True ပါ၊ ဒါကို not ခံလိုက်တော့ False ရပါတယ်
# ဒါက a > b နဲ့ အဓိပ္ပာယ်တူပါတယ်
not (a <= b) # yields False
# a >= b (10 >= 20) က False ပါ၊ ဒါကို not ခံလိုက်တော့ True ရပါတယ်
# ဒါက a < b နဲ့ အဓိပ္ပာယ်တူပါတယ်
not (a >= b) # yields True
1 နဲ့ 0 ကြား တန်ဖိုးတွေကို အပြန်အလှန်ပြောင်းလဲဖို့ (Toggle လုပ်ဖို့) Shortcut နည်းလမ်းဖြစ်ပါတယ်။
# input ယူပါမယ် (မှတ်ချက် - Python 3 မှာ input() က string ပြန်ပေးလို့ int() ခံသင့်ပါတယ်)
a = input('Enter 0 or 1')
# a က 1 (True) ဖြစ်နေရင် 0 (False) ပြောင်းလိုက်ပါမယ်
# a က 0 (False) ဖြစ်နေရင် 1 (True) ပြောင်းလိုက်ပါမယ်
a = not a
a = not b လို့ ရေးလိုက်တဲ့အတွက် b ရဲ့ တန်ဖိုးက ပြောင်းလဲသွားမှာ မဟုတ်ပါဘူး (Original value မပျက်ပါဘူး)။
Operator တစ်ခုက အလုပ်လုပ်ဖို့အတွက် Operand (လုပ်ဆောင်ခံရမယ့် တန်ဖိုး) တစ်ခုတည်းသာ လိုအပ်တယ်ဆိုရင် အဲဒါကို Unary operator လို့ ခေါ်ပါတယ်။ တကယ်လို့ Operand နှစ်ခု လိုအပ်ရင်တော့ Binary operator လို့ ခေါ်ပါတယ်။
not- Operand 1 ခုပဲ လိုတဲ့အတွက် Unary operator ဖြစ်ပါတယ်။+, -, <, >, and, orစတာတွေက - Operands 2 ခု လိုတဲ့အတွက် Binary operators တွေ ဖြစ်ကြပါတယ်။
5.4 Conditional Expressions¶
Python မှာ Conditional expression (တနည်းအားဖြင့် Ternary Operator) လို့ခေါ်တဲ့ Decision-making လုပ်နိုင်တဲ့ နောက်ထပ်နည်းလမ်းတစ်ခု ရှိပါသေးတယ်။ သူက if-else ကို တစ်ကြောင်းတည်းနဲ့ ပြီးအောင်ရေးချင်တဲ့အခါ (One-liner) အရမ်းအသုံးဝင်ပါတယ်။
Syntax:
<expr1> if <conditional expression> else <expr2>
အလုပ်လုပ်ပုံ:
1. <conditional expression> ကို အရင်ဆုံး Evaluate လုပ် (စစ်ဆေး) ပါတယ်။
2. တကယ်လို့ True ဖြစ်ခဲ့ရင်၊ <expr1> ရဲ့ တန်ဖိုးကို ရလဒ်အဖြစ် ယူပါတယ်။
3. တကယ်လို့ False ဖြစ်ခဲ့ရင်၊ <expr2> ရဲ့ တန်ဖိုးကို ရလဒ်အဖြစ် ယူပါတယ်။
Examples:
age = 15
# age < 18 ဖြစ်တဲ့အတွက် True ပါ၊ ဒါကြောင့် if ရှေ့က 'minor' ကို status ထဲထည့်ပါတယ်
status = 'minor' if age < 18 else 'adult'
sunny = False
# sunny က False ဖြစ်တဲ့အတွက် else နောက်က 'room' ကို ယူပါတယ်
# Output: Let's go to the room
print("Let's go to the", 'beach' if sunny else 'room')
humidity = 76.8
# humidity > 75 ဖြစ်တဲ့အတွက် True ပါ၊ ဒါကြောင့် 25 ကို setting ထဲထည့်ပါတယ်
setting = 25 if humidity > 75 else 28
if-elif-else ladder ကို တစ်ကြောင်းတည်းနဲ့ ရေးသလိုပါပဲ။
# wt = 55 ဖြစ်တဲ့အတွက် 'Prim' ကို msg ထဲ Assign လုပ်သွားပါမယ်
wt = 55
msg = 'Obese' if wt > 85 else 'Hefty' if wt > 60 else 'Prim'
5.5 all( ) and any( )¶
and နဲ့ or logical operators တွေကို အများကြီးဆက်သုံးနေမယ့်အစား၊ Built-in functions တွေဖြစ်တဲ့ all( ) နဲ့ any( ) ကို အသုံးပြုပြီး ပိုသပ်ရပ်အောင် ရေးလို့ရပါတယ်။
all(iterable): ပေးထားတဲ့ Conditions အားလုံး မှန်မှ (True) ရလဒ် True ကို ပြန်ပေးပါတယ် (andတွေချည်းပဲ ဆက်ထားတာနဲ့ တူပါတယ်)။any(iterable): ပေးထားတဲ့ Conditions တွေထဲက တစ်ခုခု မှန်တာနဲ့ (At least one True) ရလဒ် True ကို ပြန်ပေးပါတယ် (orတွေချည်းပဲ ဆက်ထားတာနဲ့ တူပါတယ်)။
အသုံးပြုပုံကို အောက်ပါ Program မှာ လေ့လာနိုင်ပါတယ် -
a, b, c = 10, 20, 30
# all() ဥပမာ
# a > 5 (True), b > 20 (False), c > 15 (True)
# b > 20 က False ဖြစ်နေတဲ့အတွက် (အားလုံး True မဖြစ်တော့လို့) False ပြန်ပေးပါတယ်
res = all((a > 5, b > 20, c > 15))
print(res) # prints False
# any() ဥပမာ
# Conditions တွေထဲက တစ်ခုခု True ဖြစ်တာနဲ့ True ပါ
# a > 5 က True ဖြစ်နေတဲ့အတွက် True ပြန်ပေးပါတယ်
res = any((a > 5, b > 20, c > 15))
print(res) # prints True
all( ) နဲ့ any( ) နှစ်ခုလုံးက Iterable type (ဥပမာ string, list, tuple, set, dictionary) ဖြစ်တဲ့ Single parameter (Parameter တစ်ခုတည်း) ကိုပဲ လက်ခံပါတယ်။
အပေါ်က ဥပမာမှာတော့ Condition ၃ ခုပါဝင်တဲ့ Tuple တစ်ခုကို Argument အနေနဲ့ ပေးပို့ထားတာ ဖြစ်ပါတယ်။ တကယ်လို့ Dictionary ကို ပေးလိုက်မယ်ဆိုရင်တော့ သူ့ရဲ့ Keys တွေက True ဖြစ်/မဖြစ်ကို စစ်ဆေးသွားမှာ ဖြစ်ပါတယ်။
any( ): Parameter ထဲက Element အနည်းဆုံး တစ်ခု True ဖြစ်တာနဲ့ True ပြန်ပေးပါတယ်။all( ): Parameter ထဲက Elements အားလုံး True ဖြစ်မှသာ True ပြန်ပေးပါတယ်။
5.6 Receiving Input (Input လက်ခံရယူခြင်း)¶
print( ) function ကို Screen ပေါ်မှာ Output ထုတ်ဖို့ သုံးသလိုမျိုး၊ input( ) built-in function ကိုတော့ Keyboard ကနေ Input values တွေကို လက်ခံရယူဖို့ အသုံးပြုပါတယ်။
input( ) function က အမြဲတမ်း String ကိုပဲ Return ပြန်ပေးပါတယ်။ ဆိုလိုတာက 23 လို့ ရိုက်ထည့်လိုက်ရင် Number 23 မဟုတ်ဘဲ String '23' ကို ရရှိမှာပါ။
ဒါကြောင့် ဒီ Input တွေကို ဂဏန်းတွေအနေနဲ့ တွက်ချက်မှု (Arithmetic) လုပ်ချင်တယ်ဆိုရင် အောက်ပါအတိုင်း int သို့မဟုတ် float ကို Convert (ပြောင်းလဲ) ပေးဖို့ လိုအပ်ပါတယ်။
# String input ယူခြင်း
n = input('Enter your name: ')
# Integer input ယူခြင်း (input ယူပြီးတာနဲ့ int() နဲ့ convert လုပ်ပါတယ်)
age = int(input('Enter your age: '))
# Float input ယူခြင်း (input ယူပြီးတာနဲ့ float() နဲ့ convert လုပ်ပါတယ်)
salary = float(input('Enter your salary: '))
print(n, age, salary)
5.7 Pass Statement¶
passstatement က Execution လုပ်တဲ့အခါ ဘာမှမလုပ်ဖို့ (Do nothing) ရည်ရွယ်ပါတယ်။ ဒါကြောင့် သူ့ကို no-op (no operation) instruction လို့ ခေါ်လေ့ရှိပါတယ်။- Statement တစ်ခု Run လိုက်တဲ့အခါ ဘာမှမဖြစ်စေချင်ဘူးဆိုရင်
passstatement ကို သုံးနိုင်ပါတယ်။ သူ့ရဲ့ အသုံးဝင်ပုံကိုProblem 5.6မှာ တွေ့နိုင်ပါတယ်။ passကိုif၊loop၊function(သို့မဟုတ်)classတွေရေးတဲ့အခါ Code logic မထည့်ရသေးခင် နေရာဦးထားတဲ့သဘော (Placeholder) အနေနဲ့ သုံးလေ့ရှိကြပါတယ်။- ဒါပေမယ့် ဒီလိုနေရာတွေမှာ
passကိုသုံးတာ သိပ်မကောင်းလှပါဘူး။ သူ့အစား...ကို သုံးသင့်ပါတယ်။passကိုသုံးလိုက်ရင် တကယ်ပဲ ဘာမှမလုပ်ချင်တာလား (Intentionally do nothing)၊ ဒါမှမဟုတ် Code မရေးရသေးတာလားဆိုတာ ကွဲပြားမှုမရှိ ဖြစ်သွားနိုင်လို့ပါ။
5.7.1 Ellipsis¶
- Ellipsis ဆိုတာ Python ရဲ့ Built-in constant တစ်ခုဖြစ်ပြီး
...နဲ့ ကိုယ်စားပြုပါတယ်။ - Ellipsis ကို မသိရှိသေးတဲ့ တန်ဖိုး (Unknown value) တစ်ခုကို ကိုယ်စားပြုဖို့ အသုံးပြုပါတယ်။
if၊loop၊function(သို့မဟုတ်)classတွေမှာ Unimplemented code (ကုဒ်မရေးရသေးတဲ့နေရာတွေ) အတွက် Placeholder အနေနဲ့ အသုံးပြုလေ့ရှိပါတယ်။- Ellipsis (
...) နဲ့passက မတူပါဘူး။passက Statement တစ်ခုဖြစ်ပြီး၊...က Constant တစ်ခုဖြစ်ပါတယ်။
Problems¶
Problem 5.1¶
ပစ္စည်းဝယ်ယူရာတွင် အရေအတွက် (Quantity) သည် 1000 ထက်ကျော်လွန်ပါက 10% discount ရရှိမည်ဖြစ်သည်။ Quantity နှင့် ပစ္စည်းတစ်ခုဈေးနှုန်း (Price per item) ကို Keyboard မှ Input အဖြစ်လက်ခံပြီး ကျသင့်ငွေစုစုပေါင်း (Total expenses) ကို တွက်ချက်ပေးမည့် Program ကို ရေးသားပါ။
Program
Tips
input( )function က အမြဲတမ်း String ကိုပဲ Return ပြန်ပေးတဲ့အတွက်၊ လိုအပ်သလိုint(သို့မဟုတ်)floatအဖြစ် Convert လုပ်ပေးဖို့ လိုအပ်ပါတယ်။ တကယ်လို့ Convert မလုပ်ဘဲ ဒီတိုင်းထားမယ်ဆိုရင်qty > 1000လို့ စစ်တဲ့အခါ Error တက်ပါလိမ့်မယ်။ ဘာကြောင့်လဲဆိုတော့ String နဲ့ int ကို တိုက်ရိုက်နှိုင်းယှဉ် (Compare) လို့ မရလို့ပါ။+operator သုံးပြီး Concatenation (စာသားဆက်ခြင်း) မလုပ်ခင်မှာ၊totexp(Total Expenses) ကို String အဖြစ်ပြောင်းလဲဖို့str( )function ကို အသုံးပြုသင့်ပါတယ်။
Problem 5.2¶
ကုမ္ပဏီတစ်ခု၏ ဝန်ထမ်းလစာတွက်ချက်ပုံမှာ အောက်ပါအတိုင်းဖြစ်သည် -
- Basic Salary သည်
1500အောက်ဖြစ်ပါက -HRA = 10%,DA = 90% - Basic Salary သည်
1500နှင့်အထက်ဖြစ်ပါက -HRA = 500(Fixed),DA = 98%
ဝန်ထမ်း၏ Basic Salary ကို Input အဖြစ်လက်ခံပြီး Gross Salary (စုစုပေါင်းလစာ) ကို တွက်ချက်ပေးမည့် Program ကို ရေးသားပါ။
Program
Tips
ifblock နဲ့elseblock တွေထဲမှာ Statements တွေ အများကြီး ပါဝင်နိုင်ပါတယ်။ အဲဒီလိုရေးတဲ့အခါ သင့်လျော်တဲ့ Indentation (Space ခွာရေးသားခြင်း) လုပ်ပေးဖို့တော့ လိုအပ်ပါတယ်။
Problem 5.3¶
ကျောင်းသားတစ်ယောက်ရဲ့ စာမေးပွဲရမှတ် ရာခိုင်နှုန်း (Percentage) ကို Input အဖြစ်လက်ခံပြီး၊ အောက်ပါစည်းမျဉ်းများအတိုင်း Division သတ်မှတ်ပေးမယ့် Program ကို ရေးသားပါ။
- Percentage >= 60 : First division
- Percentage 50 to 59 : Second division
- Percentage 40 to 49 : Third division
- Percentage < 40 : Fail
Program
Problem 5.4¶
ကုမ္ပဏီတစ်ခုက ယာဉ်မောင်း (Driver) တွေကို အောက်ပါအခြေအနေတွေမှာ အာမခံ (Insurance) ထားပေးပါတယ် -
- အိမ်ထောင်ရှိသူ (Married) ဖြစ်လျှင်။
- အိမ်ထောင်မရှိသူ (Unmarried)၊ ကျား (Male) ဖြစ်ပြီး အသက် 30 နှစ်ထက်ကြီးလျှင်။
- အိမ်ထောင်မရှိသူ (Unmarried)၊ မ (Female) ဖြစ်ပြီး အသက် 25 နှစ်ထက်ကြီးလျှင်။
ကျန်တဲ့အခြေအနေတွေဆိုရင် အာမခံမပေးပါဘူး။ ဝန်ထမ်းရဲ့ Marital status, Sex နဲ့ Age ကို Input ယူပြီး အာမခံရနိုင်/မရနိုင် တွက်ချက်ပေးမည့် Program ကို ရေးသားပါ။
Program
Problem 5.5¶
w, x, y, z ဆိုတဲ့ Flag variables ၄ ခု ရှိပါတယ်။ အဲဒီအထဲက တစ်ခုခု (One of them) က True ဖြစ်နေသလားဆိုတာကို နည်းလမ်းမျိုးစုံသုံးပြီး စစ်ဆေးမည့် Program ကို ရေးသားပါ။
Program
Tips
any( )ဆိုတာ Built-in function တစ်ခုဖြစ်ပြီး၊ သူ့ဆီပေးလိုက်တဲ့ Parameter ထဲက Element တွေထဲက အနည်းဆုံးတစ်ခု (At least one) က True ဖြစ်နေရင် True ပြန်ပေးပါတယ်။any( )ကို အသုံးပြုတဲ့အခါ String, List, Tuple, Set (သို့မဟုတ်) Dictionary တစ်ခုခုကို Pass လုပ်ပေးရပါမယ် (Argument အနေနဲ့ ပေးပို့ရပါမယ်)။all( )လို့ခေါ်တဲ့ ဆင်တူတဲ့ Function တစ်ခုလည်း ရှိပါသေးတယ်။ သူကတော့ Parameter ထဲက Elements အားလုံး (All) က True ဖြစ်မှသာ True ပြန်ပေးတာပါ။ ဒီ Function ကိုလည်းany()လိုပဲ String, List, Tuple, Set (သို့မဟုတ်) Dictionary ပေးပို့အသုံးပြုရပါမယ်။
Problem 5.6¶
ကိန်းဂဏန်း n တစ်ခုကို အခြေခံပြီး အောက်ပါအတိုင်း လုပ်ဆောင်မည့် Program ကို ရေးသားပါ -
If n is positive - print n * n, set a flag to true
If n is negative - print n * n * n, set a flag to true
if n is 0 - do nothing
n = int(input('Enter a number: '))
if n > 0 :
flag = True
print(n * n)
elif n < 0 :
flag = True
print(n * n * n)
Answer
ဒါက ထင်ယောင်ထင်မှား ဖြစ်စေနိုင်တဲ့ Code ပါ။ နောက်တစ်ချိန် ဒီ Code ကို ပြန်ကြည့်တဲ့အခါ `flag = True` ကို `if` နဲ့ `else` ရဲ့ အပြင်ဘက်မှာ ထုတ်ရေးသင့်တယ်လို့ ထင်မြင်သွားနိုင်ပါတယ်။ ပိုကောင်းမယ့် Code ပုံစံကတော့ အောက်ပါအတိုင်း ဖြစ်ပါတယ် -Exercise¶
[A] Answer the following questions:¶
a. အောက်ပါတို့အတွက် Conditional expressions များကို ရေးသားပေးပါ
- If a < 10 b = 20, else b = 30
- Print 'Morning' if time < 12, otherwise print 'Afternoon'
- If marks >= 70, set remarks to True, otherwise False
pass statement တစ်ခုကို အသုံးပြုလိုက်တဲ့အခါ ဘာဖြစ်သွားမလဲ?
[B] အောက်ပါ Program တို့၏ Output ကို ဖော်ပြပါ¶
a.
i, j, k = 4, -1, 0
w = i or j or k
x = i and j and k
y = i or j and k
z = i and j or k
print(w, x, y, z)
c.
x, y, z = 20, 40, 45
if x > y and x > z :
print('biggest = ' + str(x))
elif y > x and y > z :
print('biggest = ' + str(y))
elif z > x and z > y :
print('biggest = ' + str(z))
d.
e. f. g. h. i.[C] အောက်ပါ Program တို့တွင် အမှားများရှိပါက ဖော်ပြပါ¶
a.
b. c. d. e.x, y = 30, 40
if x == y :
print('x is equal to y')
elseif x > y :
print('x is greater than y')
elseif x < y :
print('x is less than y')
[D] a = 10, b = 12, c = 0, ဖြစ်လျှင် အောက်ပါတို့၏ တန်ဖိုးများကို ဖော်ပြပါ¶
[E] အောက်ပါတို့အတွက် အဖြေများကို ရေးသားပေးပါ¶
Questions (မေးခွန်းများ)
a. ကိန်းပြည့် (Integer) တစ်ခုကို Keyboard မှ Input အဖြစ် ရိုက်ထည့်ပါ။ ထိုကိန်းဂဏန်းသည် မ (Odd) ဂဏန်းလား၊ စုံ (Even) ဂဏန်းလား ဆိုတာ ရှာဖွေပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
b. ခုနှစ် (Year) တစ်ခုကို Keyboard မှ Input အဖြစ် ရိုက်ထည့်ပါ။ ထိုခုနှစ်သည် ရက်ထပ်နှစ် (Leap year) ဟုတ်/မဟုတ် ဆုံးဖြတ်ပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
c. Ram, Shyam နှင့် Ajay တို့ (၃) ဦး၏ အသက်များကို Keyboard မှ Input အဖြစ် ရိုက်ထည့်ပါ။ ထို (၃) ဦးထဲတွင် အသက်အငယ်ဆုံး (Youngest) သူကို ရှာဖွေဆုံးဖြတ်ပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
d. တြိဂံတစ်ခု၏ ထောင့် (Angle) ၃ ခုကို Keyboard မှ Input အဖြစ် ရိုက်ထည့်ပါ။ ထိုတြိဂံသည် တည်ဆောက်၍ရသော Valid Triangle ဟုတ်/မဟုတ် စစ်ဆေးပေးမယ့် Program တစ်ပုဒ် ရေးပါ။ (မှတ်ချက် - ထောင့် ၃ ခုပေါင်းခြင်းသည် 180 ဒီဂရီနှင့် ညီမျှမှသာ Valid Triangle ဖြစ်သည်)
e. ကိန်းဂဏန်းတစ်ခုကို Keyboard မှ Input အဖြစ် ရိုက်ထည့်ပါ။ ထိုကိန်းဂဏန်း၏ ပကတိတန်ဖိုး (Absolute value) ကို ရှာဖွေပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
f. စတုဂံတစ်ခု၏ အလျား (Length) နှင့် အနံ (Breadth) တို့ကို ပေးထားသည်။ ထိုစတုဂံ၏ ဧရိယာ (Area) သည် ၎င်း၏ ပတ်လည်အနား (Perimeter) ထက် ကြီးမားခြင်း ရှိ/မရှိ ရှာဖွေပေးမယ့် Program တစ်ပုဒ် ရေးပါ။ (ဥပမာ - အလျား ၅ နှင့် အနံ ၄ ရှိသော စတုဂံ၏ ဧရိယာသည် ၎င်း၏ ပတ်လည်အနားထက် ပိုကြီးပါသည်)
g. (x1, y1), (x2, y2) နှင့် (x3, y3) ဆိုသော အမှတ် (Points) ၃ ခုကို ပေးထားသည်။ ထိုအမှတ် ၃ ခုစလုံးသည် မျဉ်းဖြောင့်တစ်ကြောင်းတည်း (Straight line) ပေါ်တွင် ကျရောက်ခြင်း ရှိ/မရှိ စစ်ဆေးပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
h. စက်ဝိုင်းတစ်ခု၏ ဗဟိုချက် (Center) Coordinates (x, y) နှင့် ၎င်း၏ အချင်းဝက် (Radius) တို့ကို ပေးထားသည်။ အခြားအမှတ် (Point) တစ်ခုသည် ထိုစက်ဝိုင်း၏ အတွင်းဘက် (Inside)၊ စက်ဝိုင်းမျဉ်းပေါ် (On) သို့မဟုတ် အပြင်ဘက် (Outside)၊ မည်သည့်နေရာတွင် ရှိနေသလဲဆိုတာ ဆုံးဖြတ်ပေးမယ့် Program တစ်ပုဒ် ရေးပါ။ (အရိပ်အမြွက်: sqrt( ) နှင့် pow( ) functions များကို အသုံးပြုပါ)
i. အမှတ် (Point) (x, y) တစ်ခုကို ပေးထားသည်။ ထိုအမှတ်သည် X-ဝင်ရိုး (X-axis) ပေါ်တွင်လား၊ Y-ဝင်ရိုး (Y-axis) ပေါ်တွင်လား သို့မဟုတ် မူလမှတ် (Origin) နေရာတွင်လား ဆိုတာ ရှာဖွေပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
j. ခုနှစ် (Year) တစ်ခုကို Keyboard မှ Input အဖြစ် ရိုက်ထည့်ပါ။ Logical operators များဖြစ်သော and နှင့် or တို့ကို အသုံးပြုပြီး ထိုခုနှစ်သည် ရက်ထပ်နှစ် (Leap year) ဟုတ်/မဟုတ် ဆုံးဖြတ်ပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
k. တြိဂံတစ်ခု၏ အနား (Side) ၃ ခုကို Keyboard မှ Input အဖြစ် ရိုက်ထည့်ပါ။ ထိုတြိဂံသည် တည်ဆောက်၍ရသော Valid Triangle ဟုတ်/မဟုတ် စစ်ဆေးပေးမယ့် Program တစ်ပုဒ် ရေးပါ။ (မှတ်ချက် - တြိဂံ၏ အနား ၂ ခုပေါင်းလဒ်သည် ကျန်ရှိနေသော အကြီးဆုံးအနားထက် ကြီးမားမှသာ Valid Triangle ဖြစ်သည်)
l. တြိဂံတစ်ခု၏ အနား (Side) ၃ ခုကို Keyboard မှ Input အဖြစ် ရိုက်ထည့်ပါ။ ထိုတြိဂံသည် နှစ်နားညီ (Isosceles)၊ သုံးနားညီ (Equilateral)၊ နားမညီ (Scalene) သို့မဟုတ် ထောင့်မှန် (Right angled) တြိဂံ၊ မည်သည့်အမျိုးအစားဖြစ်ကြောင်း စစ်ဆေးပေးမယ့် Program တစ်ပုဒ် ရေးပါ။
Chapter 6 Repetition Control Instructions¶
Keynote¶
6.1 What are Repetition Control Instructions?¶
It helps us a repeat a set of statements in a program. There are two types of repetition control instructions:
- while
- for
Unlike many other languages there is no do-while loop in Python.
while is used to repeatedly execute instructions as long as condition is true. It has two forms:
- else block is optional. If present, it is executed when condition fails.
- If the while loop is terminated abruptly using a break statement then the else block is not executed.
for is used to iterate over elements of a sequence such as string, tuple or list. It has two forms:
- During each iteration var is assigned the next value from the list.
- In place of a
listastring,tuple,setordictionarycan also be used. - else block is optional. If present, it is executed if loop is not terminated abruptly using break.
6.2 Usage of while loop¶
A while loop can be used in following three situations:
- Repeat a set of statements till a condition remains True.
- Repeat a set of statements a finite number of times.
- Iterate through a string, list and tuple.
When we use while loop to repeat a set of statements till a condition remains True, it means that when we do not know before-hand how many times the statements are to be executed.
num = int(input('Enter a number: '))
while num != 5 :
print(num, num * num)
num = int(input('Enter a number: '))
We can use a while loop to repeat a set of statements a finite number of times.
A while loop can also be used to iterate through a string, a list or a tuple using an index value as shown in the following program:
s = 'Mumbai'
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
tpl = (10, 20, 30, -20, -10)
i = 0
while i < len(lst) :
print(i, s[i], lst[i], tpl[i])
i += 1
- Since items in a set or a dictionary cannot be accessed using an index value, it is better to use a for loop to access their elements.
Of the three usages of while loop shown above, the most popular is the first usage—repeat statements an unknown number of times. The other two situations are usually handled using a for loop.
6.3 Usage of for loop¶
A for loop can be used in following two situations:
- Repeat a set of statements a finite number of times.
- Iterate through a
string,list,tuple,setordictionary.
To repeat a set of statements a finite number of times a built-in function range( ) is used.
range( ) function generates a sequence of integers.
range(10) - generates numbers from 0 to 9.
range(10, 20) - generates numbers from 10 to 19.
range(10, 20, 2) - generates numbers from 10 to 19 in steps of 2.
range(20, 10, -3) - generates numbers from 20 to 9 in steps of -3.
- Note that
range( )cannot generate a sequence offloats. In general,range(start, stop, step)
produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
The list of numbers generated using range( ) can be iterated through using a for loop.
for char in 'Leopard' :
print(char)
for animal in ['Cat', 'Dog', 'Tiger', 'Lion', 'Leopard'] :
print(animal)
for flower in ('Rose', 'Lily', 'Jasmine') :
print(flower)
for num in {10, 20, 30, -10, -25} :
print(num)
for key in {'A101' : 'Rajesh', 'A111' : 'Sunil', 'A112' : 'Rakesh'} :
print(key)
loop in each iteration of the loop char is assigned the next value from the string.
Similarly, in the second, third and fourth for loop, in each iteration of the loop animal/flower/num is assigned the next value form the
list/tuple/set.
- Note that in the last for loop we are printing only the keys in the dictionary. Printing values, or printing both keys and values are covered in Chapter 11.
If while iterating through a collection using a for loop if we wish to also get an index of the item we should use the built-in enumerate( )
function as shown below:
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
for i, ele in enumerate(lst) :
print(i, ele)
6.4 break and continue¶
breakandcontinuestatements can be used withwhileandfor.breakstatement terminates the loop without executing theelseblock.continuestatement skips the rest of the statements in the block and continues with the next iteration of the loop.
6.5 Else Block of a Loop¶
- else block of a while loop should be used in situations where you wish to execute some statements if the loop is terminated normally and not if it is terminated abruptly.
- Such a situation arises if we are to determine whether a number is prime or not.
-
Note the indentation of else. else is working for the while and not for if.
-
In the following example else block will not go to work as the list contains 3, a non-multiple of 10, on encountering which we terminate the loop.
6.6 Nested Loops¶
- A loop can be used inside another loop.
- The inner loop is executed completely for each iteration of the outer loop.
Problems¶
Problem 6.1¶
Write a program that receives 3 sets of values of p, n and r and calculates simple interest for each.
Program
Output
Problem 6.2¶
Write a program that prints numbers from 1 to 10 using an infinite loop. All numbers should get printed in the same line.
Tips
while 1creates an infinite loop, as 1 is non-zero, hence true.- Replacing 1 with any non-zero number will create an infinite loop.
- Another way of creating an infinite loop is
while True. end = ' ' in print( )prints a space after printing i in each iteration. Default value of end is newline ('\n').
Problem 6.3¶
Write a program that prints all unique combinations of 1, 2 and 3.
Program
Problem 6.4¶
Write a program that obtains decimal value of a binary numeric string. For example, decimal value of '1111' is 15.
Program
Tips
- ord(1) is 49, whereas ord('0') is 0.
- b = b[1:] strips the first character in b.
Problem 6.5¶
Write a program that generates the following output using a for loop: A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z, z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,
Program
Output
Tips
- Unicode values of alphabets A-Z are 65-90. Unicode values of alphabets a-z are 97-122.
- Each output of print statement ends with a comma.
- Empty print( ) statement positions the cursor at the beginning of the next line.
Exercise¶
[A] Answer the following questions:
a. When does the else block of a while loop go to work?
b. Can range( ) function be used to generate numbers from 0.1 to 1.0 in steps of 0.1?
c. Can a while loop be nested within a for loop and vice versa?
d. Can a while/for loop be used in an if/else and vice versa?
e. Can a do-while loop be used to repeat a set of statements?
f. How will you write an equivalent for loop for the following:
(g) What will be the output of the following code snippet? for index in range(20, 10, -3) : print(index, end = ' ') (h) Why should break and continue be always used with an if embedded in a while or for loop?
[B] Point out the errors, if any, in the following programs:¶
a.
b.
c. d. e. f. g.[C] Match the following for the values each range( ) function will generate¶
a. range(5) 1. 1, 2, 3, 4
b. range(1, 10, 3) 2. 0, 1, 2, 3, 4
c. range(10, 1, -2) 3. Nothing
d. range(1, 5) 4. 10, 8, 6, 4, 2
e. range(-2) 5. 1, 4, 7
[D] Attempt the following questions:¶
a. Write a program to print first 25 odd numbers using range( ). b. Rewrite the following program using for loop.
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
s = 'Mumbai'
i = 0
while i < len(lst) :
if i > 3 :
break
else :
print(i, lst[i], s[i])
i += 1
d. A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not.
e. Write a program to find the factorial value of any number entered through the keyboard.
f. Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 ).
g. Write a program to print all prime numbers from 1 to 300.
h. Write a program to print the multiplication table of the number entered by the user. The table should get displayed in the following form:
i. When interest compounds q times per year at an annual rate of r % for n years, the principal p compounds to an amount a as per the following formula: a = p ( 1 + r / q )nq Write a program to read 10 sets of p, r, n & q and calculate the corresponding as.
j. Write a program to generate all Pythagorean Triplets with side length less than or equal to 30.
k. Population of a town today is 100000. The population has increased steadily at the rate of 10 % per year for last 10 years. Write a program to determine the population at the end of each year in the last decade.
l. Ramanujan number is the smallest number that can be expressed as sum of two cubes in two different ways. Write a program to print all such numbers up to a reasonable limit.
m. Write a program to print 24 hours of day with suitable suffixes like AM, PM, Noon and Midnight.
Chapter 7 Console Input/Output¶
Keynote¶
7.1 Console Input/Output¶
Console Input/Output means input from keyboard and output to screen.
7.2 Console Input¶
Console input can be received using the built-in input( ) function.
General form of input( ) function is s = input('prompt')
- prompt is a string that is displayed on the screen, soliciting a value. input( ) returns a string. If 123 is entered as input, '123' is returned.
# receive full name
name = input('Enter full name')
# separate first name, middle name and surname
fname, mname, lname = input('Enter full name: ').split( )
split( ) function will split the entered fullname with space as a delimiter. The split values will then be assigned to fname, mname, lname.
If we are to receive multiple int values, we can receive them as strings and then convert them to ints.
n1, n2, n3 = input('Enter three values: ').split( )
n1, n2, n3 = int(n1), int(n2), int(n3)
print(n1 + 10, n2 + 20, n3 + 30)
The same thing can be done using in a more compact manner using a feature called list comprehension. It applies int( ) function to every element of the list returned by the split( ) function.
n1, n2, n3 = [int(n) for n in input('Enter three values: ').split( )]
print(n1 + 10, n2 + 20, n3 + 30)
input( ) can be used to receive arbitrary number of values.
numbers = [int(x) for x in input('Enter values: ').split( )]
for n in numbers :
print(n + 10)
input( ) can be used to receive different types of values at a time.
data = input('Enter name, age, salary: ').split( )
name = data[0]
age = int(data[1])
salary = float(data[2])
print(name, age, salary)
7.3 Console Output¶
- Built-in function
print( )is used to send output to screen.
print( ) function has this form:
- This means that by default objects will be printed on screen (sys.stdout), separated by space
(sep = ' ')and last printed object will be followed by a newline (end = '\n').flush = Falseindicates that output stream will not be flushed.
Python has a facility to call functions and pass keyword-based values as arguments. So while calling print( ) we can pass specific values for sep and end. In this case, default values will not be used; instead the values that we pass will be used.
print(a, b, c, sep = ',', end = '!') # prints ',' after each value, ! at end
print(x, y, sep = '...', end = '#') # prints '...' after each value, # at end
7.4 Formatted Printing¶
There are 4 ways to control the formatting of output:
- a. Using formatted string literals - easiest
- b. Using the format( ) method - older
- c. C printf( ) style - legacy
- d. Using slicing and concatenation operation - difficult
Today (a) is most dominantly used method followed by (b).
r, l, b = 1.5678, 10.5, 12.66
print(f'radius = {r}')
print(f'length = {l} breadth = {b} radius = {r}')
name = 'Sushant Ajay Raje'
for n in name.split( ) :
print(f'{n:10}') # print in 10 columns
r, l, b = 1.5678, 10.5, 12.66
name, age, salary = 'Rakshita', 30, 53000.55
# print in order by position of variables using empty {}
print('radius = {} length = {} breadth ={}'.format(r, l, b))
print('name = {} age = {} salary = {}'.format(name, age, salary))
# print in any desired order
print('radius = {2} length = {1} breadth ={0}'.format(r, l, b))
print('age={1} salary={2} name={0}'.format(name, age, salary))
# print name in 15 columns, salary in 10 columns
print('name = {0:15} salary = {1:10}'.format(name, salary))
# print radius in 10 columns, with 2 digits after decimal point
print('radius = {0:10.2f}'.format(r))
- On execution, the above code snippet will produce the following output:
Problems¶
Problem 7.1¶
Write a program to receive radius of a circle, and length and breadth of a rectangle in one call to input( ). Calculate and print the circumference of circle and perimeter of rectangle.
Program
Tips
input( )returns a string, so it is necessary to convert it into int or float suitably, before performing arithmetic operations.
Problem 7.2¶
Write a program to receive 3 integers using one call to input( ). The three integers signify starting value, ending value and step value for a range. The program should use these values to print the number, its square and its cube, all properly right-aligned. Also output the same values left-aligned.
Program
start, end, step = input('Enter start, end, step values: ').split( )
# right aligned printing
for n in range(int(start), int(end), int(step)) :
print(f'{n:>5}{n**2:>7}{n**3:>8}')
print( )
# left aligned printing
for n in range(int(start), int(end), int(step)) :
print('{0:<5}{1:<7}{2:<8}'.format(n, n ** 2, n ** 3))
Output
Tips
{n:>5}will print n right-justified within 5 columns. Use<to left-justify.{0:<5}will left-justify 0th parameter in the list within 5 columns. Use>to right-justify.
Problem 7.3¶
Write a program to maintain names and cell numbers of 4 persons and then print them systematically in a tabular form.
Program
Problem 7.4¶
Suppose there are 5 variables in a program—max, min, mean, sd and var, having some suitable values. Write a program to print these variables properly aligned using multiple fstrings, but one call to print( ).
Program
Problem 7.5¶
Write a program that prints square root and cube root of numbers from 1 to 10, up to 3 decimal places. Ensure that the output is displayed in separate lines, with number center-justified and square and cube roots, right-justified.
Program
Output
Exercises¶
[A] Attempt the following questions:¶
a. How will you make the following code more compact?
b. How will you print "Rendezvous" in a line and retain the cursor in the same line in which the output has been printed?
c. What will be the output of the following code snippet?
d. In the following statement what do > 5, > 7 and > 8 signify?
e. What will be the output of the following code segment?
f. How will you print the output of the following code segment using fstring?
g. How will you receive arbitrary number of floats from keyboard?
h. What changes should be made in
print(f'{'\nx = ':4}{x:>10}{'\ny = ':4}{y:>10}')
to produce the output given below:
x = 14.99
y = 114.39
i. How will you receive a boolean value as input?
j. How will you receive a complex number as input?
k. How will you display price in 10 columns with 4 places beyond decimal points? Assume value of price to be 1.5567894.
l. Write a program to receive an arbitrary number of floats using one input( ) statement. Calculate the average of floats received.
m. Write a program to receive the following using one input( ) statement.
Name of the person
Years of service
Diwali bonus received
Calculate and print the agreement deduction as per the following
formula:
deduction = 2 * years of service + bonus * 5.5 / 100
n. Which import statement should be added to use the built-in functions input( ) and print( )?
o. Is the following statement correct?
p. Write a program to print the following values as shown below:[B] Match the following pairs:¶
| Option A | Option B |
|---|---|
| a. Default value of sep in print( ) | 1. ' ' |
| b. Default value of end in print( ) | 2. Using fstring |
| c. Easiest way to print output | 3. Right justify num in 5 columns |
| d. Return type of split( ) | 4. Left justify num in 5 columns |
| e. print('{num:>5}') | 5. list |
| f. print('{num:<5}') | 6. \n |
Chapter 8 Lists¶
Keynote¶
8.1 Lists¶
Container is an entity which contains multiple data items. It is also known as a collection or a compound data type.
Python has following container data types:
- Lists Tuples
- Sets Dictionaries
A list can grow or shrink during execution of the program. Hence it is also known as a dynamic array. Because of this nature of lists they are commonly used for handling variable length data.
A list is defined by writing comma-separated elements within [ ].
List can contain dissimilar types, though usually they are a collection of similar types. For example:
Items in a list can be repeated, i.e. a list may contain duplicate items.
Like printing, * can be used to repeat an element multiple times. An empty list is also feasible.
ages = [25, 26, 25, 27, 26] # duplicates allowed
num = [10] * 5 # stores [10, 10, 10, 10, 10]
lst = [ ] # empty list, valid
8.2 Accessing List Elements¶
Entire list can be printed by just using the name of the list.
Like strings, individual elements in a list can be accessed using indices. Hence they are also known as sequence types. The index value starts from 0. Like strings, lists can be sliced.8.3 Looping in Lists¶
If we wish to process each item in the list, we should be able to iterate through the list. This can done using a while or for loop.
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
# using while loop
i = 0
while i < len(animals) :
print(animals[ i ])
i += 1
# using more convenient for loop
for a in animals :
print(a)
enumerate( ) function.
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
for index, a in enumerate(animals) :
print(index, a)
8.4 Basic List Operations¶
Mutability - Unlike strings, lists are mutable (changeable). So lists can be updated as shown below:
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
ages = [25, 26, 25, 27, 26, 28, 25]
animals[2] ='Rhinoceros'
ages[5] = 31
ages[2:5] = [24, 25, 32] # sets items 2 to 5 with values 24, 25, 32
ages[2:5] = [ ] # delete items 2 to 4
Concatenation - One list can be concatenated (appended) at the end of another as shown below:
lst = [12, 15, 13, 23, 22, 16, 17]
lst = lst + [33, 44, 55]
print(lst) # prints [12, 15, 13, 23, 22, 16, 17, 33, 44, 55]
s = [10, 20, 30]
t = [100, 200, 300]
z = s + t
print(z) # prints [10, 20, 30, 100, 200, 300]
Conversion - A string/tuple/set can be converted into a list using the list( ) conversion function.
lst = list('Africa') # converts the string to a list ['A', 'f', 'r', 'i', 'c', 'a']
Aliasing - On assigning one list to another, both refer to the same list. Changing one changes the other. This assignment is often known as shallow copy or aliasing.
lst1 = [10, 20, 30, 40, 50]
lst2 = lst1 # doesn't copy list. lst2 refers to same list as lst1
print(lst1) # prints [10, 20, 30, 40, 50]
print(lst2) # prints [10, 20, 30, 40, 50]
lst1[0] = 100
print(lst1[0], lst2[0]) # prints 100 100
Cloning - This involves copying contents of one list into another. After copying both refer to different lists, though both contain same values. Changing one list, doesn't change another. This operation is often known as deep copy.
lst1 = [10, 20, 30, 40, 50]
lst2 = [ ] # empty list
lst2 = lst2 + lst1 # lst1, lst2 refer to different lists
print(lst1) # prints [10, 20, 30, 40, 50]
print(lst2) # prints [10, 20, 30, 40, 50]
lst1[0] = 100
print(lst1[0], lst2[0]) # prints 100, 10
lst = ['a', 'e', 'i', 'o', 'u']
res = 'a' in lst # return True since 'a' is present in list
res = 'z' not in lst # return True since 'z' is absent in list
Identity - Whether the two variables are referring to the same list can be checked using the is identity operator as shown below:
lst1 = [10, 20, 30, 40, 50]
lst2 = [10, 20, 30, 40, 50]
lst3 = lst1
print(lst1 is lst2) # prints False
print(lst1 is lst3) # prints True
print(lst1 is not lst2) # prints True
num1 = 10
num2 = 10
s1 = 'Hi'
s2 = 'Hi'
print( num1 is num2) # prints True
print( s1 is s2) # prints True
Comparison - It is possible to compare contents of two lists. Comparison is done item by item till there is a mismatch. In following code it would be decided that a is less than b when 3 and 5 are compared.
Emptiness - We can check if a list is empty using not operator.
- Alternately, we can convert a list to a bool and check the result.
Also note that the following values are considered to be False:
None
Number equivalent to zero: 0, 0.0, 0j
Empty string, list and tuple: ' ', "", [ ], ( )
Empty set and dictionary: { }
8.5 Using Built-in Functions on Lists¶
Many built-in functions can be used with lists.
len(lst) # return number of items in the list
max(lst) # return maximum element in the list
min(lst) # return minimum element in the list
sum(lst) # return sum of all elements in the list
any(lst) # return True if any element of lst is True
all(lst) # return True if all elements of lst are True
del( ) # deletes element or slice or entire list
sorted(lst) # return sorted list, lst remains unchanged
reversed(lst) # used for reversing lst
sorted( ) and reversed( ) are discussed in section after next. del( ) function's usage is shown below:
lst1 = [10, 20, 30, 40, 50]
lst = del(lst[3]) # delete 3rd item in the list
del(lst[2:5]) # delete items 2 to 4 from the list
del(a[:]) # delete entire list
lst = [ ] # another way to delete an entire list
If multiple variables are referring to same list, then deleting one doesn't delete the others.
lst1 = [10, 20, 30, 40, 50]
lst3 = lst2 = lst1 # all refer to same list
lst1 = [ ] # lst1 refers to empty list; lst2, lst3 to original list
print(lst2) # prints [10, 20, 30, 40, 50]
print(lst3) # prints [10, 20, 30, 40, 50]
If multiple variables are referring to same list and we wish to delete all, we can do so as shown below:
lst2[:] = [ ] # list is emptied by deleting all items
print(lst2) # prints [ ]
print(lst3) # prints [ ]
8.6 List Methods¶
Any list is an object of type list. Its methods can be accessed using the syntax lst.method( ). Usage of some of the commonly used methods is shown below:
lst = [12, 15, 13, 23, 22, 16, 17] # create list
lst.append(22) # add new item at end
lst.remove(13) # delete item 13 from list
lst.remove(30) # reports valueError as 30 is absent in lst
lst.pop( ) # removes last item in list
lst.pop(3) # removes 3rd item in the list
lst.insert(3,21) # insert 21 at 3rd position
lst.count(23) # return no. of times 23 appears in lst
idx = lst.index(22) # return index of item 22
idx = lst.index(50) # reports valueError as 50 is absent in lst
8.7 Sorting and Reversing¶
Usage of list methods for reversing a list and for sorting is shown below:
lst = [10, 2, 0, 50, 4]
lst.reverse( )
print(lst) # prints [4, 50, 0, 2, 10]
lst.sort( )
print(lst) # prints [0, 2, 4, 10, 50]
lst.sort(reverse = True) # sort items in reverse order
print(lst) # prints [50, 10, 4, 2, 0]
- Note that
reverse( )andsort( )do not return a list. Both manipulate the list in place.
Usage of built-in functions for reversing a list and for sorting is shown below:
lst = [10, 2, 0, 50, 4]
print(sorted(lst)) # prints [0, 2, 4, 10, 50]
print(sorted(lst, reverse = True)) # prints [50, 10, 4, 2, 0]
print(list(reversed(lst))) # prints [4, 50, 0, 2, 10]
sorted( ) function returns a new sorted list and keeps the original list unchanged. Also, reversed( ) function returns a list_reverseiterator object which has to converted into a list to get a reversed list.
Reversal is also possible using a slicing operation as shown below:
8.8 List Varieties¶
It is possible to create a list of lists (nested lists).
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]
c = [a, b]
print(c[0][0], c[1][2]) # 0th element of 0th list, 2nd ele. of 1st list
A list may be embedded in another list.
It is possible to unpack a string or list within a list using the*operator.
s = 'Hello'
l = [*s]
print(l) # outputs ['H', 'e', 'l', 'l', 'o']
x = [1, 2, 3, 4]
y = [10, 20, *x, 30]
print(y) # outputs [10, 20, 1, 2, 3, 4, 30]
8.9 Stack Data Structure¶
A data structure refers to an arrangement of data in memory. Popular data structures are stack, queue, tree, graph and map.
Stack is a last in first out (LIFO) list, i.e. last element that is added to the list is the first element that is removed from it.
Adding an element to a stack is called push operation and removing an element from it is called pop operation. Both these operations are carried out at the rear end of the list.
Push and pop operations can be carried out using the append( ) and pop( ) methods of list object. This is demonstrated in Program 8.3.
8.10 Queue Data Structure¶
Queue is a first in first out (FIFO) list, i.e. first element that is added to the list is the first element that is removed from it.
Lists are not efficient for implementation of queue data structure.
With lists removal of items from beginning is not efficient, since it involves shifting of rest of the elements by 1 position after deletion.
Hence for fast additions and deletions, dequeue class of collections module is preferred.
Deque stands for double ended queue. Addition and deletion in a deque can take place at both ends.
Usage of deque class to implement a queue data structure is demonstrated in Program 8.4.
Problems¶
Problem 8.1¶
Perform the following operations on a list of names.
- Create a list of 5 names - 'Anil', 'Amol', 'Aditya', 'Avi', 'Alka'
- Insert a name 'Anuj' before 'Aditya'
- Append a name 'Zulu'
- Delete 'Avi' from the list
- Replace 'Anil' with 'AnilKumar'
- Sort all the names in the list
- Print reversed sorted list
Program
# Create a list of 5 names
names = ['Anil', 'Amol', 'Aditya', 'Avi', 'Alka']
print(names)
# insert a name 'Anuj' before 'Aditya'
names.insert(2,'Anuj')
print(names)
# append a name 'Zulu'
names.append('Zulu')
print(names)
# delete 'Avi' from the list
names.remove('Avi')
print(names)
# replace 'Anil' with 'AnilKumar'
i=names.index('Anil')
names[i] = 'AnilKumar'
print(names)
# sort all the names in the list
names.sort( )
print(names)
# print reversed sorted list
names.reverse( )
print(names)
Output
['Anil', 'Amol', 'Aditya', 'Avi', 'Alka']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Avi', 'Alka']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Avi', 'Alka', 'Zulu']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Alka', 'Zulu']
['AnilKumar', 'Amol', 'Anuj', 'Aditya', 'Alka', 'Zulu']
['Aditya', 'Alka', 'Amol', 'AnilKumar', 'Anuj', 'Zulu']
['Zulu', 'Anuj', 'AnilKumar', 'Amol', 'Alka', 'Aditya']
Problem 8.2¶
Perform the following operations on a list of numbers.
- Create a list of 5 odd numbers
- Create a list of 5 even numbers
- Combine the two lists
- Add prime numbers 11, 17, 29 at the beginning of the combined list
- Report how many elements are present in the list
- Replace last 3 numbers in the list with 100, 200, 300
- Delete all the numbers in the list
- Delete the list
Program
# create a list of 5 odd numbers
a = [1, 3, 5, 7, 9]
print(a)
# create a list of 5 even numbers
b = [2, 4, 6, 8, 10]
print(b)
# combine the two lists
a = a + b
print(a)
# add prime numbers 11, 17, 29 at the beginning of the combined list
a = [11, 17, 29] + a
print(a)
# report how many elements are present in the list
num = len(a)
print(num)
# replace last 3 numbers in the list with 100, 200, 300
a[num-3:num] = [100, 200, 300]
print(a)
# delete all the numbers in the list
a[:] = [ ]
print(a)
# delete the list
del a
Output
Problem 8.3¶
Write a program to implement a Stack data structure. Stack is a Last In First Out (LIFO) list in which addition and deletion takes place at the same end.
Program
Problem 8.4¶
Write a program to implement a Queue data structure. Queue is a First In First Out (FIFO) list, in which addition takes place at the rear end of the queue and deletion takes place at the front end of the queue.
Program
Output
Problem 8.5¶
Write a program to generate and store in a list 20 random numbers in the range 10 to 100. From this list delete all those entries which have value between 20 and 50. Print the remaining list.
Program
Output
Problem 8.6¶
Write a program to add two 3 x 4 matrices.
Program
mat1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
mat2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
mat3 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# iterate through rows
for i in range(len(mat1)) :
# iterate through columns
for j in range(len(mat1[0])) :
mat3[i][j] = mat1[i][j] + mat2[i][j]
print(mat3)
Exercises¶
[A] What will be the output of the following programs:¶
a.
b.
c.d.
e.
f.
num1 = [10, 20, 30, 40, 50]
num2 = num1
print(id(num1))
print(type(num2))
print(isinstance(num1, list))
print(num1 is num2)
g.
h. i. j.[B] Attempt the following questions:¶
a. Which of the following is a valid List?
b. What will happen on execution of the following code snippet?c. The following code snippet deletes elements 30 and 40 from the list:
In which other way can the same effect be obtained?d. Which of the following is an INCORRECT list?
e. From the list given below
How will you create the list num2 containing:f. Given a list
How will you sort it in descending order?g. Given a list
How will you check whether 30 is present in the list or not?h. Given a list
How will you insert 30 between 25 and 4?i. Given a string
How will you obtain a list['H', 'e', 'l', 'l', 'o'] from it?
[C] Answer the following questions:¶
a. Write a program to create a list of 5 odd integers. Replace the third element with a list of 4 even integers. Flatten, sort and print the list.
b. Suppose a list contains 20 integers generated randomly. Receive a number from the keyboard and report position of all occurrences of this number in the list.
c. Suppose a list has 20 numbers. Write a program that removes all duplicates from this list.
d. Suppose a list contains positive and negative numbers. Write a program to create two lists—one containing positive numbers and another containing negative numbers.
e. Suppose a list contains 5 strings. Write a program to convert all these strings to uppercase.
f. Write a program that converts list of temperatures in Fahrenheit degrees to equivalent Celsius degrees.
g. Write a program to obtain a median value of a list of numbers, without disturbing the order of the numbers in the list.
h. A list contains only positive and negative integers. Write a program to obtain the number of negative numbers present in the list.
i. Suppose a list contains several words. Write a program to create another list that contains first character of each word present in the first list.
j. A list contains 10 numbers. Write a program to eliminate all duplicates from the list.
k. Write a program to find the mean, median and mode of a list of 10 numbers.
Chapter 9 Tuples¶
Keynote¶
9.1 Tuples¶
What are Tuples?
- Though a list can store dissimilar data, it is commonly used for storing similar data.
- Though a tuple can store similar data it is commonly used for storing dissimilar data. The tuple data is enclosed within ( ) as shown below
a = ( ) # empty tuple
b = (10,) # tuple with one item. , after 10 is necessary
c = ('Sunny', 25, 34555.50) # tuple with dissimilar items
d = (10, 20, 30, 40) # tuple with similar items
- While creating the tuple
b, if we do not use the comma after 10,bis treated to be of typeint.
While initializing a tuple, we may drop ( ).
c = 'Sunny', 25, 34555.50 # tuple with multiple items
print(type(c)) # c is of the type tuple
Items in a tuple can be repeated, i.e. tuple may contain duplicate items. However, unlike list, tuple elements cannot be repeated using a *.
9.2 Accessing Tuple Elements¶
Entire tuple can be printed by just using the name of the tuple.
Tuple is an ordered collection. So order of insertion of elements in a tuple is same as the order of access. So like a string and list, tuple items too can be accessed using indices, starting with 0.
Like strings and lists, tuples too can be sliced to yield smaller tuples.
emp = ('Sunny', 23, 23000, 1760, 2040)
print(emp[1:3]) # prints (23, 23000)
print(emp[3:]) # prints (1760, 2040)
print(emp[:3]) # prints ('Sunny', 23, 23000)
9.3 Looping in Tuples¶
If we wish to process each item in a tuple, we should be able to iterate through it. This can be done using a while loop or for loop.
tpl = (10, 20, 30, 40, 50)
i = 0
while i < len(tpl) :
print(tpl[i])
i += 1
for n in tpl :
print(n)
While iterating through a tuple using a for loop, if we wish to keep track of index of the element that is being currently processed, we can do so using the built-in enumerate( ) function.
9.4 Basic Tuple Operations¶
Mutability - Unlike a list, a tuple is immutable, i.e. it cannot be modified.
msg = ('Fall', 'In', 'Line')
msg[0] ='FALL' # error
msg[1:3] = ('Above', 'Mark') # error
msg = ('Fall', 'In', 'Line')
msg.append('Like') # error
msg.remove('Line') # error
msg.insert(1, 'Above') # error
Though a tuple itself is immutable, it can contain mutable objects like lists.
If a tuple contains a list, the list can be modified since list is a mutable object.s = ([1, 2, 3, 4], [10, 20], 'Oynx')
s[1][1] = 45 # changes first item of first list, i.e. 20
print(s) # prints ([1, 2, 3, 4], [4, 45], 'Oynx')
# one more way to change first item of first list
p = s[1]
p[1] = 100
print(s) # prints ([1, 2, 3, 4], [4, 100], 'Oynx')
The other basic operations that are done on a tuple are very similar to the ones done on a list. These operations are discussed in Chapter 8. You may try the following operations on tuples as an exercise:
- Concatenation
- Merging
- Conversion
- Aliasing
- Cloning
- Searching
- Identity
- Comparison
- Emptiness
9.5 Using Built-in Functions on Tuples¶
Many built-in functions can be used with tuples.
t = (12, 15, 13, 23, 22, 16, 17) # create tuple
len(t) # return number of items in tuple t
max(t) # return maximum element in tuple t
min(t) # return minimum element in tuple t
sum(t) # return sum of all elements in tuple t
any(t) # return True if any element of tpl is True
all(t) # return True if all elements of tpl are True
sorted(t) # return sorted list (not sorted tuple)
reversed(t) # used for reversing t
9.6 Tuple Methods¶
Any tuple is an object of type tuple. Its methods can be accessed using the syntax tpl.method( ). Usage of two methods is shown below:
tpl = (12, 15, 13, 23, 22) # create tuple
print(tpl.count(23)) # return no. of times 23 appears in lst
print(tpl.index(22)) # return index of item 22
print(tpl.index(50)) # reports valueError as 50 is absent in lst
9.7 Tuple Varieties¶
It is possible to create a tuple of tuples.
a = (1, 3, 5, 7, 9)
b = (2, 4, 6, 8, 10)
c = (a, b)
print(c[0][0], c[1][2]) # 0th element of 0th tuple, 2nd ele of 1st tuple
records = (
('Priya', 24, 3455.50), ('Sunny', 25, 4555.50),
('Sunday', 25, 4505.50), ('Sonia', 27, 4455.55)
)
print(records[0][0], records[0][1], records[0][2])
print(records[1][0], records[1][1], records[1][2])
for n, a, s in records :
print(n,a,s)
*operator.
It is possible to create a list of tuples, or a tuple of lists.
lst = [('Priya', 24, 3455.50), ('Sunny', 25, 4555.50)]
tpl = (['Priya', 24, 3455.50], ['Sunny', 25, 4555.50])
import operator
# each embedded tuple/list contains name, age, salary
lst = [('Shailesh', 24, 3455.50), ('Priyanka', 25, 4555.50)]
tpl = (['Shailesh', 24, 3455.50], ['Priyanka', 25, 4555.50])
print(sorted(lst))
print(sorted(tpl))
print(sorted(lst, key = operator.itemgetter(2)))
print(sorted(tpl, key = operator.itemgetter(2)))
sorted( ) sorts by first item in list/tuple, i.e. name.
If we wish to sort by salary, we need to use the itemgetter( ) function of operator module.
The key parameter of sorted( ) requires a key function (to be applied to objects to be sorted) rather than a single key value.
operator.itemgetter(2) will give us a function that fetches salary from a list/tuple.
In general, operator.itemgetter(n) constructs a function that takes a list/tuple as input, and fetches the n-th element out of it.
Problems¶
Problem 8.1¶
Pass a tuple to the divmod( ) function and obtain the quotient and the remainder.
Tips
- If we pass t to divmod( ) an error is reported. We have to unpack the tuple into two distinct values and then pass them to
divmod( ).divmod( )returns a tuple consisting of quotient and remainder.
Problem 8.2¶
Write a Python program to perform the following operations:
- Pack first 10 multiples of 10 into a tuple
- Unpack the tuple into 10 variables, each holding 1 value
- Unpack the tuple such that first value gets stored in variable x, last value in y and all values in between into disposable variables _
- Unpack the tuple such that first value gets stored in variable i, last value in j and all values in between into a single disposable variable _
Program
Output
Tips
- Disposable variable _ is usally used when you do not wish to use the variable further, and is being used only as a place-holder.
Problem 8.3¶
A list contains names of boys and girls as its elements. Boys' names are stored as tuples. Write a Python program to find out number of boys and girls in the list.
Program
Tips
isinstance( )functions checks whether ele is an instance of tuple type.- Note that since the tuples contain a single element, it is followed by a comma.
Problem 8.4¶
A list contains tuples containing roll number, names and age of student. Write a Python program to gather all the names from this list into another list.
Program
Tips
nlstis an empty to begin with. During each iteration name is extracted from the tuple usingele[1]and added to the current list of names innlst.
Problem 8.5¶
Given the following tuple ('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd'), write a Python program to carry out the following operations:
- Add an ! at the end of the tuple
- Convert a tuple to a string
- Extract ('b', 'b') from the tuple
- Find out number of occurrences of 'e' in the tuple
- Check whether 'r' exists in the tuple
- Convert the tuple to a list
- Delete characters 'b, 'b', 'e', 'r' from the tuple
Program
tpl = ('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd')
# addition of ! is not possible as tuple is an immutable
# so to add ! we need to create a new tuple and then make tpl refer to it
tpl = tpl + ('!',)
print(tpl)
# convert tuple to string
s = ''.join(tpl)
print(s)
# extract ('b', 'b') from the tuple
t = tpl[3:5]
print(t)
# count number of 'e' in the tuple
count = tpl.count('e')
print('count = ', count)
# check whether 'r' exists in the tuple
print('r' in tpl)
# Convert the tuple to a list
lst = list(tpl)
print(lst)
# tuples are immutable, so we cannot remove elements from it
# we need to split the tuple, eliminate the unwanted element and then
merge the tuples
tpl = tpl[:3] + tpl[7:]
print(tpl)
Output
Exercises¶
[A] Which of the following properties apply to string, list and tuple?¶
- Iterable
- Sliceable
- Indexable
- Immutable
- Sequence
- Can be empty
- Sorted collection
- Ordered collection
- Unordered collection
- Elements can be accessed using their position in the collection
[B] Which of the following operations can be performed on string, list and tuple?¶
- a = b + c
- a += b
- Appending a new element at the end
- Deletion of an element at the 0th position
- Modification of last element
- In place reversal
[C] Answer the following questions:¶
a. Is this a valid tuple? tpl = ('Square')
b. What will be the output of the following code snippet?
num1 = num2 = (10, 20, 30, 40, 50)
print(id(num1), type(num2))
print(isinstance(num1, tuple))
print(num1 is num2)
print(num1 is not num2)
print(20 in num1)
print(30 not in num2)
c. Suppose a date is represented as a tuple (d, m, y). Write a program to create two date tuples and find the number of days between the two dates.
d. Create a list of tuples. Each tuple should contain an item and its price in float. Write a program to sort the tuples in descending order by price. Hint: Use operator.itemgetter( ).
e. Store the data about shares held by a user as tuples containing the following information about shares:
Write a program to determine:- Total cost of the portfolio.
- Total amount gained or lost.
- Percentage profit made or loss incurred.
f. Write a program to remove empty tuple from a list of tuples.
g. Write a program to create following 3 lists:
- a list of names
- a list of roll numbers
- a list of marks
Generate and print a list of tuples containing name, roll number and marks from the 3 lists. From this list generate 3 tuples—one containing all names, another containing all roll numbers and third containing all marks.
[D] Match the following pairs:¶
| Options A | Options B |
|---|---|
a. tpl1 = ('A',) |
1. tuple of length 6 |
b. tpl1 = ('A') |
2. tuple of lists |
c. t = tpl[::-1] |
3. Tuple |
d. ('A', 'B', 'C', 'D') |
4. list of tuples |
e. [(1, 2), (2, 3), (4, 5)] |
5. String |
f. tpl = tuple(range(2, 5)) |
6. Sorts tuple |
g. ([1, 2], [3, 4], [5, 6]) |
7. (2, 3, 4) |
h. t = tuple('Ajooba') |
8. tuple of strings |
i. [*a, *b, *c] |
9. Unpacking of tuples in a list |
j. (*a, *b, *c) |
10. Unpacking of lists in a tuple |
Chapter 27 Numpy Library¶
Keynote¶
NumPy ဆိုတာကတော့ Numerical Python ရဲ့ အတိုကောက်ဖြစ်ပြီး သိပ္ပံနဲ့ အင်ဂျင်နီယာပိုင်းဆိုင်ရာ ပြဿနာတွေကို ဖြေရှင်းတဲ့နေရာမှာ လူသုံးများတဲ့ Library တစ်ခုဖြစ်ပါတယ်။ သူက စွမ်းဆောင်ရည်မြင့်မားတဲ့ Multidimensional array object (ရှုထောင့်စုံ ဇယားကွက်) တွေနဲ့ အဲဒီ array တွေအပေါ်မှာ မြန်ဆန်သွက်လက်စွာ တွက်ချက်နိုင်မယ့် Method တွေကို ပံ့ပိုးပေးထားပါတယ်။ ဒီလိုလုပ်ဆောင်နိုင်တဲ့ လုပ်ငန်းစဉ်တွေထဲမှာ သင်္ချာဆိုင်ရာ၊ ယုတ္တိဗေဒ (Logic) ပိုင်း၊ ပုံသဏ္ဍာန် ပြုပြင်ပြောင်းလဲတာ၊ အစီအစဉ်ချတာ၊ ရွေးထုတ်တာ၊ Input/Output ကိစ္စတွေနဲ့ စာရင်းအင်း (Statistical) ပိုင်းဆိုင်ရာ တွက်ချက်မှုတွေ စသည်ဖြင့် ပါဝင်ပါတယ်။
27.1 Creation of Array¶
NumPy Library ကို အသုံးပြုချင်တယ်ဆိုရင်တော့ အောက်မှာပြထားတဲ့အတိုင်း အရင်ဆုံး download ဆွဲပြီး install လုပ်ထားဖို့ လိုပါမယ်။
NumPy Array တွေက ပုံစံကြည့်လိုက်ရင် Python List တွေနဲ့ တူသလိုလိုရှိပေမယ့်၊ တကယ်တမ်းကျတော့ List တွေထက် ပိုပြီး မြန်မြန်ဆန်ဆန် အလုပ်လုပ်နိုင်အောင် ဖန်တီးထားတာဖြစ်ပါတယ်။ List တွေနဲ့ မတူတဲ့အချက်ကတော့ NumPy array တစ်ခုထဲမှာပါတဲ့ element တွေအားလုံးဟာ data type အမျိုးအစား တူညီနေဖို့ လိုပါတယ်။ NumPy array တစ်ခု တည်ဆောက်ချင်ရင် np.array() function ကို သုံးရမှာဖြစ်ပြီး၊ အောက်ပါနမူနာအတိုင်း ကိန်းဂဏန်း list တစ်ခုကို ထည့်ပေးရပါမယ်။
import numpy as np
intarr = np.array([1,2,3,4]) # ကိန်းပြည့် (ints) array တစ်ခု တည်ဆောက်ခြင်း
floattarr = np.array([1.1,2.2,3.3,4.4]) # ဒသမကိန်း (floats) array တစ်ခု တည်ဆောက်ခြင်း
တကယ်လို့ ကိန်းပြည့် (ints) တွေနဲ့ ဒသမကိန်း (floats) တွေကို ရောရေးလိုက်မယ်ဆိုရင် NumPy က အားလုံးကို floats အဖြစ် အလိုအလျောက် ပြောင်းလဲသတ်မှတ်လိုက်မှာ ဖြစ်ပါတယ်။ Array တည်ဆောက်တဲ့အချိန်မှာ element တွေရဲ့ type ကို သီးခြား မသတ်မှတ်ပေးထားဘူးဆိုရင် NumPy က ပေးထားတဲ့ တန်ဖိုးတွေကိုကြည့်ပြီး type ကို ခန့်မှန်းပေးပါတယ်။ တကယ်လို့ ကိုယ်တိုင် type သတ်မှတ်ချင်တယ်ဆိုရင်လည်း အခုလို သတ်မှတ်ပေးလို့ ရပါတယ်။
2D array (matrix) ဆိုတာက 1D array တွေကို စုစည်းထားတာဖြစ်ပြီး၊ 3D array ဆိုတာကတော့ 2D array တွေကို ထပ်ပြီး စုစည်းထားတာ ဖြစ်ပါတယ်။ သူတို့ကို အောက်ပါအတိုင်း တည်ဆောက်နိုင်ပါတယ်။
a1 = np.array([[1,2,3],[4,5,6]]) # 2 rows x 3 columns ရှိတဲ့ array
a2 = np.array([[[1,2],[4,5]],[[6,7],[8,9]]]) # 2x2 အရွယ်အစားရှိတဲ့ array ၂ ခုပါဝင်တဲ့ 3D array
Complex number (ကိန်းရော) တွေပါဝင်တဲ့ array တွေကိုလည်း တည်ဆောက်နိုင်ပါသေးတယ်။
27.2 Creation of Filler Arrays¶
နောက်မှ တန်ဖိုးအစစ်တွေ အစားထိုးထည့်မယ့် နေရာဦးထားတဲ့ (initial placeholder) တန်ဖိုးတွေပါတဲ့ NumPy Array တွေကို ကြိုတင်တည်ဆောက်ထားလို့ ရပါတယ်။
ဥပမာ - 0 တွေချည်းပဲပါတာ၊ 1 တွေချည်းပဲပါတာ၊ ဒါမှမဟုတ် ကိုယ်လိုချင်တဲ့ ဂဏန်းသေချာသတ်မှတ်ပြီး ဖြည့်ထားတဲ့ array မျိုးတွေ ဖန်တီးနိုင်တယ်။ ဘာတန်ဖိုးမှန်းမသိတဲ့ (garbage values) တွေပါနေတဲ့ empty array မျိုးကိုလည်း ဖန်တီးလို့ရပါတယ်။
import numpy as np
a1 = np.empty((3,4)) # garbage values တွေပါတဲ့ 2D array တစ်ခု
a2 = np.zeros((3,4)) # သုည (0) တွေချည်းပဲပါတဲ့ 2D array
a3 = np.ones((3,4)) # တစ် (1) တွေချည်းပဲပါတဲ့ 2D array
a4 = np.full((2,2),7) # တန်ဖိုးအားလုံး 7 ဖြစ်နေတဲ့ 2D array
သတိပြုရန် - ဒီ function တွေထဲကို တန်ဖိုးထည့်တဲ့အခါ Tuple ပုံစံနဲ့ ထည့်ပေးရပါမယ်။ (3,4) တို့ (2,2) တို့ဆိုတာ ကိုယ်တည်ဆောက်ချင်တဲ့ array ရဲ့ ပုံသဏ္ဍာန် (Shape) ကို ညွှန်းဆိုတာ ဖြစ်ပါတယ်။ Random တန်ဖိုးတွေနဲ့ဖြစ်ဖြစ်၊ အကွာအဝေး ညီတူညီမျှခြားထားတဲ့ တန်ဖိုးတွေနဲ့ဖြစ်ဖြစ် array တွေကို တည်ဆောက်နိုင်ပါတယ်။
import numpy as np
a1 = np.random.random((4)) # random တန်ဖိုး ၄ ခုပါတဲ့ array
a2 = np.arange(5) # [0,1,2,3,4] ကို ဖန်တီးပေးတယ် (မူရင်းစာ text တွင် np.range ဟုပါသော်လည်း np.arange သာ အမှန်ဖြစ်သည်)
a3 = np.linspace(0,2,5) # [0.0 0.5 1.0 1.5 2.0] ကို ဖန်တီးပေးတယ်
arange() နဲ့ linspace() ရဲ့ ပထမ ကိန်းဂဏန်းနှစ်လုံး (parameters) က အစတန်ဖိုးနဲ့ အဆုံးတန်ဖိုးကို ညွှန်းတာပါ။ တတိယ parameter မှာကျတော့ arange() အတွက်ဆိုရင် ဘယ်လောက်စီ ခြားမလဲဆိုတဲ့ step value ဖြစ်ပြီး၊ linspace() အတွက်ဆိုရင်တော့ တန်ဖိုးစုစုပေါင်း ဘယ်နှလုံး လိုချင်တာလဲ ဆိုတာကို ညွှန်းတာဖြစ်ပါတယ်။
NumPy ကနေ Identity Matrix ကိုလည်း ဖန်တီးခွင့်ပေးထားပါတယ်။ Identity Matrix ဆိုတာက ထောင့်ဖြတ်မျဉ်း (principal diagonal) ပေါ်မှာ 1 တွေရှိပြီး ကျန်တဲ့နေရာတွေမှာ 0 ဖြစ်နေတဲ့ Matrix မျိုးပါ။
Identity matrix ဆိုတာ အနားညီစတုရန်း (Square) matrix ဖြစ်တဲ့အတွက် eye() နဲ့ identity() ကို သုံးတဲ့အခါ dimension တစ်ခုပဲ (ဂဏန်းတစ်လုံးပဲ) ထည့်ပေးဖို့ လိုပါတယ်။
27.3 Array Attributes¶
NumPy array တွေမှာ သူ့ရဲ့ element အမျိုးအစား (type)၊ အရွယ်အစား (size)၊ ပုံသဏ္ဍာန် (shape) စတာတွေကို ဖော်ပြပေးနိုင်တဲ့ attribute တွေ အများကြီး ပါဝင်ပါတယ်။
Array ထဲမှာ ဘာ data type တွေပါလဲ၊ size ဘယ်လောက်ရှိလဲ၊ memory ရဲ့ ဘယ်နေရာမှာ သိမ်းထားလဲ ဆိုတာတွေကို အောက်ပါအတိုင်း လှမ်းကြည့်လို့ရပါတယ်။
import numpy as np
a1 = np.array([1,2,3,4])
a2 = np.array([1.1,2.2,3.3,4.4])
print(a1.dtype) # int32 လို့ ထွက်လာမယ် (Integer type မို့လို့ပါ)
print(a2.dtype) # float64 လို့ ထွက်လာမယ် (Float type မို့လို့ပါ)
print(a1.itemsize) # 4 လို့ ပြမယ် (bytes)
print(a2.itemsize) # 8 လို့ ပြမယ် (bytes)
print(a1.nbytes) # 16 (စုစုပေါင်း bytes)
print(a2.nbytes) # 32 (မူရင်းစာ text တွင် 16 ဟုပါသော်လည်း float64 သည် 8 bytes x 4 elements ဖြစ်၍ 32 bytes ဖြစ်သင့်သည်)
print(a1.data) # Memory address ကို ပြပါလိမ့်မယ် (ဥပမာ <memory at ...>)
print(a1.strides) # (4,) လို့ ပြမယ်
print(a2.data) # Memory address ကို ပြပါလိမ့်မယ်
print(a2.strides) # (8,) လို့ ပြမယ်
- ဒီမှာဆိုရင် dtype က array ထဲမှာပါတဲ့ element အမျိုးအစားကို ပြပေးတာပါ။ Element တစ်လုံးချင်းစီက နေရာဘယ်လောက်ယူလဲဆိုတာကို itemsize နဲ့ ကြည့်နိုင်ပြီး၊ Array တစ်ခုလုံးအနေနဲ့ နေရာဘယ်လောက်ယူလဲ ဆိုတာကိုတော့ nbytes နဲ့ ကြည့်နိုင်ပါတယ်။
-
data ဆိုတာက memory ပေါ်မှာ array စတင်သိမ်းဆည်းထားတဲ့ လိပ်စာ (Base Address) ကို ပြပေးတာဖြစ်ပြီး၊ strides ကတော့ နောက်ထပ် element တစ်ခုဆီ ရောက်ဖို့အတွက် base address ကနေ byte ဘယ်လောက် ထပ်ပေါင်းထည့်ရမလဲ (ဘယ်လောက် ခုန်ကျော်သွားရမလဲ) ဆိုတာကို ညွှန်းပါတယ်။
-
ndim, shape နဲ့ size attributes တွေကတော့ array ရဲ့ dimension အရေအတွက်၊ array ရဲ့ ပုံသဏ္ဍာန်နဲ့ element စုစုပေါင်း အရေအတွက်တွေကို အသီးသီး ဖော်ပြပေးပါတယ်။
import numpy as np
a1 = np.array ([1,2,3,4])
a2 = np.array(([1,2,3,4],[5,6,7,8]))
print(a1.ndim) # 1 (1D array ဖြစ်လို့)
print(a2.ndim) # 2 (2D array ဖြစ်လို့)
print(a1.shape) # (4,) (Tuple ပုံစံနဲ့ ပြပါတယ်)
print(a2.shape) # (2,4) (2 rows နဲ့ 4 columns ရှိလို့ပါ)
print(a1.size) # 4 (element ၄ လုံးရှိလို့)
print(a2.size) # 8 (element ၈ လုံးရှိလို့)
27.4 Array Operations (Array ဆိုင်ရာ လုပ်ဆောင်ချက်များ)¶
NumPy Array တွေပေါ်မှာ လုပ်ဆောင်ချက် (Operations) တွေ အများကြီး လုပ်လို့ရပါတယ်။ ဒီ operations တွေက ရေးရတာ ကျစ်လျစ်သလို၊ အလုပ်လုပ်တာလည်း အရမ်းမြန်ပါတယ်။ ဘာလို့ ဒီလောက်မြန်လဲဆိုတော့ ဒီ Library ထဲမှာ ကြိုတင် compile လုပ်ပြီးသား ကုဒ်တွေ (precompiled routines) ပါနေလို့ပဲ ဖြစ်ပါတယ်။
Array operations အမျိုးမျိုးရှိတဲ့အထဲမှာ အောက်ပါခေါင်းစဉ်တွေ ပါဝင်ပါတယ် -
- (a) Arithmetic Operations: သင်္ချာဆိုင်ရာ ပေါင်းနှုတ်မြှောက်စား လုပ်ဆောင်ချက်များ
- (b) Statistical Operations: စာရင်းအင်းပိုင်းဆိုင်ရာ တွက်ချက်မှုများ
- © Linear Algebra Operations: Linear Algebra (ရိုးဖြောင့် အက္ခရာသင်္ချာ) ဆိုင်ရာ တွက်ချက်မှုများ
- (d) Bitwise Operations: Bit အလိုက် ကိုင်တွယ်တဲ့ လုပ်ဆောင်ချက်များ
- (e) Copying, Sorting: ကူးယူခြင်း နဲ့ အစီအစဉ်ချခြင်းများ
- (f) Comparison Operations: နှိုင်းယှဉ်ခြင်းဆိုင်ရာ လုပ်ဆောင်ချက်များ
27.4.1 Arithmetic Operations (သင်္ချာဆိုင်ရာ တွက်ချက်မှုများ)¶
Array နှစ်ခုကြားမှာ +, -, *, /, % စတဲ့ သင်္ချာ operator တွေကို အသုံးပြုပြီး တွက်ချက်မှုတွေ အများကြီး လုပ်လို့ရပါတယ်။
ဒီ operator တွေကို သုံးလိုက်တဲ့အခါ Array နှစ်ခုရဲ့ သက်ဆိုင်ရာ နေရာတူ element အချင်းချင်း (corresponding elements) ကို တိုက်ရိုက် တွက်ချက်သွားမှာ ဖြစ်ပါတယ်။
သင်္ကေတ (operator) တွေ မသုံးချင်ဘူးဆိုရင် add(), subtract(), multiply(), divide(), နဲ့ remainder() ဆိုတဲ့ function (method) တွေကို ပြောင်းသုံးလို့လည်း ရပါတယ်။ ဒီလို တွက်ချက်တာမျိုးကို Vector operations လို့လည်း ခေါ်ကြပါတယ်။
import numpy as np
a1 = np.array([[10,2,3,4],[5,6,7,8]])
a2 = np.array([[1,1,1,1],[2,2,2,2]])
a3 = a1 + a2 # a3 = np.add(a1,a2) နဲ့ အတူတူပါပဲ
a4 = a1 - a2
a5 = a1 * a2
a6 = a1 / a2
a7 = a1 % a2
a8 = a1 ** 2 # Element တိုင်းကို နှစ်ထပ်ကိန်း တင်လိုက်တာပါ
Array ထဲက element တွေကို ကိန်းဂဏန်းတစ်ခုတည်း (Scalar) နဲ့ ပေါင်းနှုတ်မြှောက်စား လုပ်တာမျိုးလည်း လုပ်လို့ရပါသေးတယ်။ (ဥပမာ - Array တစ်ခုလုံးကို 2 နဲ့ လိုက်ပေါင်းတာမျိုးပေါ့)
import numpy as np
a1 = np.array([[10,2,3,4],[5,6,7,8]])
a2 = a1 + 2 # Element တိုင်းကို 2 ပေါင်းထည့်လိုက်တာ
a3 = a1 ** 2 # Element တိုင်းကို 2 ထပ်ကိန်း တင်လိုက်တာ
+=, -=, /= စတဲ့ In-place operator တွေကို သုံးမယ်ဆိုရင်တော့ Array အသစ်တစ်ခု ထပ်မဆောက်တော့ဘဲ ရှိပြီးသား လက်ရှိ Array ကိုပဲ တိုက်ရိုက် ပြင်ဆင် (Modify) သွားမှာ ဖြစ်ပါတယ်။
a1 += a2 # a1 = a1 + a2 နဲ့ အတူတူပါပဲ (a1 ရဲ့ တန်ဖိုးကို တိုက်ရိုက်ပြောင်းသွားပါတယ်)
a3 += 5 # a3 = a3 + 5 နဲ့ အတူတူပါပဲ
Array element တွေအပေါ်မှာ တခြားလုပ်ဆောင်နိုင်တဲ့ operation တွေကတော့ exp() (ထပ်ကိန်းတင်ခြင်း)၊ sqrt() (နှစ်ထပ်ကိန်းရင်းရှာခြင်း)၊ cos(), sin() (တြီဂိုနိုမေတြီ တွက်ချက်ခြင်း) နဲ့ log() (Logarithm တွက်ချက်ခြင်း) စတာတွေပဲ ဖြစ်ပါတယ်။
27.4.2 Statistical Operations (စာရင်းအင်းဆိုင်ရာ တွက်ချက်မှုများ)¶
NumPy က Array တစ်ခုလုံးအပေါ်မှာဖြစ်ဖြစ်၊ ကိုယ်လိုချင်တဲ့ Axis (Dimension) တစ်ခုပေါ်မှာ မူတည်ပြီးတော့ဖြစ်ဖြစ် စာရင်းအင်းဆိုင်ရာ တွက်ချက်မှုတွေ (ဥပမာ - ပေါင်းခြင်း၊ အကြီးဆုံးရှာခြင်း) ကို လုပ်ပေးနိုင်ပါတယ်။
Axis ဆိုတာ Dimension (အတိုင်းအတာ) ကို ပြောတာပါ။ ဒါကြောင့် 1D array မှာ 1 axis ရှိပြီး၊ 2D array မှာ 2 axes ရှိတယ်လို့ မှတ်သားနိုင်ပါတယ်။
import numpy as np
a = np.array([[1,2,3,],[4,5,6]])
print(a.sum())
print(a.min()) # Array တစ်ခုလုံးရဲ့ အငယ်ဆုံးတန်ဖိုးကို ရှာမယ်
print(a.max(axis = 0)) # Column တစ်ခုစီအလိုက် အကြီးဆုံးကို ရှာမယ်
print(a.max(axis = 1)) # Row တစ်ခုစီအလိုက် အကြီးဆုံးကို ရှာမယ်
print(a.sum(axis = 1)) # Axis 1 (Row) အတိုင်း ပေါင်းမယ်
print(a.cumsum(axis = 1)) # ဆင့်ပေါင်း (Cumulative sum) ရလဒ်ကို ထုတ်ပေးမယ်
print(np.mean(a)) # ပျမ်းမျှတန်ဖိုး (Mean)
print(np.median(a)) # အလယ်ကိန်း (Median)
print(np.corrcoef(a)) # Correlation Coefficient (ဆက်နွယ်မှု ကိန်းညွှန်း)
print(np.std(a)) # Standard Deviation (စံသွေဖည်ကိန်း)
- ဒီနေရာမှာ max() လို function တွေသုံးရင် Axis သတ်မှတ်ပုံကို သဘောပေါက်ဖို့ အရေးကြီးပါတယ်။ ကျွန်တော်တို့ရဲ့ Array က 2 rows x 3 columns ရှိတဲ့ 2D array ပါ။
- axis = 0 လို့ ပြောလိုက်ရင် "Column အလိုက်ကြည့်မယ်"၊ "Row အလိုက်ကြည့်မယ်" ဆိုပြီး ကျက်မှတ်ထားတာထက် "Collapsing" (ချုံ့ပစ်လိုက်တာ/ဖျောက်လိုက်တာ) ဆိုတဲ့ သဘောတရားနဲ့ မှတ်တာ ပိုမှန်ပါတယ်။
- ဆိုလိုတာက axis = 0 သုံးလိုက်ရင် NumPy က ပထမ Dimension (Size 2 ရှိတဲ့ Row အထပ်လိုက်သဘောတရား) ကို ချုံ့ပစ်လိုက်ပါတယ်။ ဒါကြောင့် ရလဒ်က ကျန်ခဲ့တဲ့ Size 3 အတိုင်း Element ၃ လုံးပါတဲ့ [4,5,6] ဆိုပြီး ထွက်လာတာပါ။
- ဒီသဘောတရားအတိုင်းပဲ axis = 1 သုံးလိုက်ရင် ဒုတိယ Dimension (Size 3 ရှိတဲ့ Column ရေပြင်ညီသဘောတရား) ကို ချုံ့ပစ်လိုက်တဲ့အတွက် [3,6] ဆိုပြီး ရလာတာဖြစ်ပါတယ်။
27.4.3 Linear Algebra Operations¶
NumPy မှာ မြှောက်လဒ်ရှာတဲ့ Operation နှစ်ခုရဲ့ ကွာခြားချက်ကို သတိထားမှတ်သားဖို့ လိုပါတယ်။* ကိုသုံးရင် နေရာတူတဲ့ ကိန်းဂဏန်းချင်း (Element-wise) မြှောက်တာဖြစ်ပြီး၊@ ဒါမှမဟုတ် .dot() ကိုသုံးမှသာ တကယ့် Matrix မြှောက်ခြင်း (Matrix Multiplication) ကို လုပ်ဆောင်တာ ဖြစ်ပါတယ်။
a3 = a1 * a2 # နေရာတူတဲ့ element အချင်းချင်း မြှောက်ခြင်း (Element-wise)
a3 = a1 @ a2 # Matrix မြှောက်နည်းအတိုင်း မြှောက်ခြင်း (Matrix multiplication)
a4 = a1.dot(a2) # ဒါကလည်း Matrix multiplication ပါပဲ
Matrix တစ်ခုကို Transpose လုပ်ချင်တယ် (Row နဲ့ Column ပြောင်းပြန်လှန်ချင်တယ်) ဆိုရင်လည်း အလွယ်တကူ လုပ်လို့ရပါတယ်။
Trace ဆိုတာက Matrix တစ်ခုရဲ့ ထောင့်ဖြတ်မျဉ်း (Principal diagonal) ပေါ်မှာရှိတဲ့ element တွေကို ပေါင်းခြင်းဖြစ်ပါတယ်။ ဒါကို np.trace() နဲ့ ရှာနိုင်ပါတယ်။
Inverse Matrix ဆိုတာက မူရင်း Matrix နဲ့ ပြန်မြှောက်လိုက်ရင် Identity Matrix ရလာမယ့် Matrix အမျိုးအစားကို ပြောတာပါ။ NumPy ရဲ့ linalg (Linear Algebra) module အောက်က inv() ကိုသုံးပြီး ရှာနိုင်ပါတယ်။
Linear Simultaneous Equations (တစ်ပြိုင်နက်ညီမျှခြင်း) တွေကို ဖြေရှင်းတဲ့နေရာမှာလည်း NumPy ကို သုံးနိုင်ပါတယ်။ဥပမာ - $\(3x + y = 9\)$ $\(နဲ့\)$ $\(x + 2y = 8\)$ ဆိုတဲ့ ညီမျှခြင်းနှစ်ကြောင်းရဲ့ အဖြေကို လိုချင်ရင် အခုလို တွက်နိုင်ပါတယ်။
a = np.array([[3,1],[1,2]]) # x နဲ့ y ရဲ့ မြှောက်ဖော်ကိန်း (Coefficients) များ
b = np.array([9,8]) # ညီမျှခြင်းရဲ့ ရလဒ်များ
x = np.linalg.solve(a,b) # အဖြေရှာခြင်း
print(x)
27.4.4 Bitwise Operations¶
Array ထဲမှာရှိတဲ့ element တစ်လုံးချင်းစီအပေါ်မှာ Bitwise operations တွေကိုလည်း အောက်ပါအတိုင်း တွက်ချက်လုပ်ဆောင်နိုင်ပါသေးတယ်။
import numpy as np
a1 = np.array([[10,2,3,4],[5,6,7,8]])
a2 = np.array([[1,1,1,1],[2,2,2,2]])
# Bitwise AND, OR, XOR တွက်ချက်ခြင်းများ
a3 = np.bitwise_and(a1,a2)
a4 = np.bitwise_or(a1,a2)
a5 = np.bitwise_xor(a1,a2)
# Invert (NOT) လုပ်ခြင်း
a6 = np.invert(a1)
# Bit Shifting လုပ်ခြင်း
a7 = np.left_shift(a1,3) # element တစ်ခုစီကို ဘယ်ဘက်သို့ 3 bits ရွှေ့ခြင်း
a8 = np.right_shift(a1,2) # element တစ်ခုစီကို ညာဘက်သို့ 2 bits ရွှေ့ခြင်း
27.4.5 Copying and Sorting (ကူးယူခြင်းနှင့် အစီအစဉ်ချခြင်း)¶
NumPy မှာ Copy ကူးတဲ့နည်းလမ်း (၃) မျိုး ရှိပါတယ်။
-
No Copy: လုံးဝ Copy မကူးခြင်း (Reference သဘောမျိုး)။
-
Shallow Copy (View): အပေါ်ယံ အခွံပဲ ကူးယူခြင်း (Data က အတူတူပဲ)။
-
Deep Copy: အနှစ်ပါမကျန် တစ်စုံလုံး ပွားယူခြင်း။
No Copy: Object ကိုရော၊ Data ကိုရော ကူးယူတာ မဟုတ်ပါဘူး။ Array ရှိနေတဲ့ လိပ်စာ (Address) ကို Variable အသစ်တစ်ခုနဲ့ လှမ်းညွှန်းလိုက်တာမျိုးပဲ ဖြစ်ပါတယ်။
Shallow Copy (View): Array object အသစ်တစ်ခု ဖန်တီးလိုက်ပေမယ့်၊ အတွင်းက Data တွေကတော့ မူရင်း Array ရဲ့ Data တွေကိုပဲ မျှသုံးနေတာ (Point လုပ်နေတာ) ဖြစ်ပါတယ်။
Deep Copy: Array object အသစ်ရော၊ Data အသစ်ရော သီးသန့်ခွဲထုတ်ပြီး အကုန် ကူးယူလိုက်တာ ဖြစ်ပါတယ်။
အောက်ပါ Code ဥပမာမှာ d နဲ့ပတ်သက်တဲ့ အပိုင်း ကျန်ခဲ့လို့ ကျွန်တော် ဖြည့်စွက်ပြီး ရှင်းပြပေးထားပါတယ်ခင်ဗျာ။
import numpy as np
a = np.array([[3,3,7],[1,5,2]])
# --- No Copy (Reference) ---
b = a # Copy ကူးတာမဟုတ်ပါ၊ နာမည်နောက်တစ်ခု တပ်လိုက်တာပါ
print(b is a) # True (a နဲ့ b က အတူတူပါပဲ)
b[0][0] = 100 # b ကို ပြင်လိုက်ရင် a ပါ လိုက်ပြောင်းသွားမယ်
# --- Shallow Copy (View) ---
c = a.view() # View အနေနဲ့ ဖန်တီးလိုက်တာပါ
print(c is a) # False (Object ချင်း မတူတော့ပါဘူး)
c[0][0] = 50 # ဒါပေမယ့် c ကို ပြင်ရင် မူရင်း a မှာပါ လိုက်ပြောင်းသွားပါလိမ့်မယ်
# --- Deep Copy ---
d = a.copy() # (မူရင်းစာမှာ ဒီ line ကျန်ခဲ့လို့ ဖြည့်ထားပါတယ်)
print(d is a) # False (လုံးဝမဆိုင်တဲ့ Object တွေပါ)
d[0][0] = 150 # d ကို ပြင်လိုက်ရင် မူရင်း a မှာ လိုက်မပြောင်းတော့ပါဘူး
Sorting (အစီအစဉ်ချခြင်း) အတွက်လည်း အောက်ပါအတိုင်း လုပ်ဆောင်နိုင်ပါတယ်။
a = np.array([[3,7,6],[1,5,2]])
b = np.array([[3,7,6],[1,5,2]])
a.sort() # Row အလိုက် ငယ်စဉ်ကြီးလိုက် စီပေးသွားမယ်
b.sort(axis = 0) # Column အလိုက် (ဒေါင်လိုက်) ငယ်စဉ်ကြီးလိုက် စီပေးသွားမယ်
27.4.6 Comparison (နှိုင်းယှဉ်ခြင်းများ)¶
Array တွေမှာ ယှဉ်ကြည့်စရာ၊ တိုက်စစ်စရာ (Comparison) ပုံစံ (၃) မျိုး ရှိပါတယ်။
- One Value Comparison: Array ထဲက Element အားလုံးကို တန်ဖိုးတစ်ခုတည်းနဲ့ လိုက်ယှဉ်ကြည့်ပြီး ရလာတဲ့ အဖြေ (True/False) ကို Array ပြန်ထုတ်ပေးတာ။
- Corresponding Elements Comparison: Array နှစ်ခုမှာရှိတဲ့ နေရာတူ Element အချင်းချင်း လိုက်ယှဉ်ကြည့်ပြီး Boolean Array ပြန်ထုတ်ပေးတာ။
- Full Array Comparison: Array နှစ်ခုရဲ့ ပုံသဏ္ဍာန် (Shape) ရော၊ ပါဝင်တဲ့ Element တွေရော ထပ်တူညီမညီ စစ်ဆေးတာ (တူရင် True, မတူရင် False ပြပါတယ်)။
(1) Array Element အားလုံးကို တန်ဖိုးတစ်ခုနဲ့ လိုက်ယှဉ်ခြင်း
import numpy as np
a = np.array([[3,7,6],[1,5,2]])
print(a < 5) # 5 ထက်ငယ်လား လိုက်စစ်တာပါ
# အဖြေက [[True False False] [True False True]] ဆိုပြီး ထွက်ပါမယ်
(2) Array နှစ်ခုက နေရာတူ Element အချင်းချင်း ယှဉ်ခြင်း
import numpy as np
a = np.array([[3,7,6],[1,5,2]])
b = np.array([[3,1,2],[1,7,2]])
print(a < b) # a က b ထက် ငယ်သလား နေရာတူချင်း တိုက်စစ်တာပါ
# အဖြေက [[False False False] [False True False]] ဆိုပြီး ထွက်ပါမယ်
(3) Array နှစ်ခုလုံး ထပ်တူညီမညီ ယှဉ်ခြင်း
import numpy as np
a = np.array([[3,7,6],[1,5,2]])
b = np.array([[3,7,6],[1,5,2]])
c = np.array([[3,7],[6,1],[5,2]])
print(np.array_equal(a,b)) # True (Shape ရော Element တွေရော ကွက်တိတူလို့ပါ)
print(np.array_equal(a,c)) # False (Shape မတူတော့လို့ပါ)
27.4.7 Indexing and Slicing (Array ခန်းများ ညွှန်းဆိုခြင်းနှင့် အပိုင်းဖြတ်ခြင်း)¶
Python List တွေလိုပါပဲ၊ NumPy Array တွေကလည်း 0 ကနေစပြီး ရေတွက် (Indexing လုပ်) ပါတယ်။ အနောက်ဆုံးကနေ ပြန်ရေချင်ရင် အနုတ်လက္ခဏာ (Negative index) သုံးလို့ရပါတယ်။
a = np.array([3,7,6,1,5,2])
print(a[0], a[-1]) # 3 နဲ့ 2 ကို ထုတ်ပေးပါလိမ့်မယ် (ရှေ့ဆုံးနဲ့ နောက်ဆုံး)
Dimension တစ်ခုထက်ပိုတဲ့ Array (Multi-dimensional array) တွေမှာ အခန်းတစ်ခန်းချင်းစီကို လှမ်းယူချင်ရင် Index နံပါတ်တစ်ခုမက သုံးရပါတယ်။
a = np.array([[3,7,6],[1,5,9]])
print(a[1][2]) # 9 ကို ထုတ်ပေးပါလိမ့်မယ်
# (a[1] က ဒုတိယမြောက် Row [1,5,9] ဖြစ်ပြီး၊ အဲ့ဒီထဲက index 2 ဖြစ်တဲ့ 9 ကို ယူလိုက်တာပါ)
သတိပြုရန် - a[1][2] လို့ရေးတာက ကွန်ပျူတာအလုပ်လုပ်ပုံအရ နည်းနည်းကွာခြားပါတယ်။ သူက ပထမ a[1] အပိုင်းကို အရင်ဆွဲထုတ်ပြီး ယာယီ array (temporary array) တစ်ခုအရင်ဆောက်လိုက်တယ်၊ ပြီးမှ အဲ့ဒီအထဲက index 2 ကို ထပ်ဆွဲထုတ်တာ ဖြစ်ပါတယ်။ (NumPy မှာ ပိုမြန်ချင်ရင် a[1, 2] လို့ရေးတာက ပိုကောင်းပါတယ်)။
Slicing (အပိုင်းဖြတ်တာ) ကလည်း List တွေအတိုင်းပါပဲ။ ထူးခြားတာက Dimension တွေအများကြီးမှာ ကော်မာ (comma) ခံပြီး တပြိုင်နက် ဖြတ်လို့ရတာပါပဲ။
import numpy as np
a = np.array([8,2,4,1,5,9])
# b မှာ မူရင်းစာသားအရ Row 3 ကြောင်းရှိမယ်လို့ ယူဆရပါတယ် (ရှင်းလင်းချက်အရ)
b = np.array([[3,7,6,9,8], [1,5,9,2,4], [0,0,3,1,5]])
print(a[2:5]) # [4 1 5] (Index 2 ကနေ 5 မတိုင်ခင်ထိ)
print(a[:-4]) # [8 2] (အစကနေ နောက်ဆုံး 4 လုံးမတိုင်ခင်ထိ)
# 2D Slicing (Comma သုံးထားပုံကို သတိပြုပါ)
print(b[1:3, 2:4])
# Row 1 ကနေ 3 မတိုင်ခင်ထိ (Row 1, 2) ယူမယ်၊
# Column 2 ကနေ 4 မတိုင်ခင်ထိ (Col 2, 3) ယူမယ်။
# ရလဒ်က [[9 2], [3 1]] ဆိုပြီး ထွက်ပါမယ်။
အရေးကြီးတဲ့ အချက် (Common Mistake)
-
b[1:3][2:4] လို့ရေးတာနဲ့ b[1:3, 2:4] လို့ရေးတာ မတူပါဘူး။
-
b[1:3][2:4] လို့ရေးလိုက်ရင် ပထမ b[1:3] အရ Row 1 နဲ့ 2 ပါတဲ့ Array အသစ်တစ်ခု ထွက်လာမယ်။ ပြီးတော့မှ အဲ့ဒီ Array အသစ်ရဲ့ Row 2 ကနေ 4 ကို ထပ်ဖြတ်ဖို့ ကြိုးစားပါလိမ့်မယ်။ Array အသစ်မှာက Row 2 row ပဲရှိတော့ [2:4] ဆိုတဲ့ row တွေ မရှိတော့ပါဘူး။ ဒါကြောင့် အဖြေက Empty Array [ ] (အလွတ်) ထွက်လာတာ ဖြစ်ပါတယ်။
27.5 Array Manipulation (Array များကို ပုံစံပြောင်းလဲ ကိုင်တွယ်ခြင်း)¶
Reshaping (ပုံသဏ္ဍာန် ပြောင်းလဲခြင်း) Array တစ်ခုကို တည်ဆောက်ပြီးပြီဆိုရင် reshape() method ကိုသုံးပြီး သူ့ရဲ့ ပုံသဏ္ဍာန် (Shape) ကို ပြောင်းလဲနိုင်ပါတယ်။ ဒီ Method က Data တွေကို မထိခိုက်စေဘဲ Shape အသစ်နဲ့ Array တစ်ခုကို ပြန်ထုတ်ပေးတာပါ။
(မှတ်ချက် - မူရင်းစာသားပါ Code တွင် Element အရေအတွက် ကွဲလွဲမှုရှိနေသဖြင့် တွက်ချက်၍ရအောင် အနည်းငယ် ပြင်ဆင်ရှင်းပြပေးထားပါတယ်)
import numpy as np
# Element ၁၂ လုံးပါတဲ့ Array တစ်ခု (3 rows x 4 columns)
a = np.array([[3,7,6,9],[1,5,2,4],[0,3,1,5]])
# 2 rows x 6 columns ပုံစံ ပြောင်းမယ်
b = a.reshape(2,6)
print(b)
# ရလဒ်: [[3 7 6 9 1 5] [2 4 0 3 1 5]]
# Row 4 ကြောင်းလိုချင်တယ်၊ Column ကိုတော့ Auto တွက်ထည့်စေချင်ရင် '-1' သုံးရတယ်
c = a.reshape(4,-1)
print(c)
# ရလဒ်: [[3 7 6] [9 1 5] [2 4 0] [3 1 5]] (4 rows x 3 columns ဖြစ်သွားမယ်)
# 0-11 အထိ ဂဏန်းတွေကိုထုတ်ပြီး တန်းပြီး reshape လုပ်ခြင်း
d = np.arange(12).reshape(2,6)
print(d)
# ရလဒ်: [[0 1 2 3 4 5] [6 7 8 9 10 11]]
Flattening (ပြားချခြင်း) Multi-dimensional array (အထပ်ထပ်ပါတဲ့ array) တစ်ခုကို ravel() သုံးပြီး 1D array (တန်းတစ်တန်းတည်းဖြစ်သွားအောင်) ပြားချလိုက်လို့ ရပါတယ်။
import numpy as np
a = np.array([[3, 7, 6, 9],[1, 5, 2, 4],[0, 3, 1, 5]])
b = a.ravel()
print(b)
# ရလဒ်: [3 7 6 9 1 5 2 4 0 3 1 5] ဆိုပြီး တစ်တန်းတည်း ထွက်လာမယ်
Appending (ထပ်ဖြည့်ခြင်း) ရှိပြီးသား Array တစ်ခုရဲ့ အနောက်မှာ နောက်ထပ် တန်ဖိုးတွေ ထပ်ဖြည့်ချင်ရင် np.append() ကို သုံးနိုင်ပါတယ်။
import numpy as np
a = np.array([[3, 7, 6, 9],[1, 5, 2, 4]])
b = np.array([[0, 3, 1, 5],[1, 1, 1, 1]])
# Axis 0 (Row အလိုက်/အောက်ဘက်သို့) ဆက်မယ်
c = np.append(a, b, axis=0)
# ရလဒ်: Row ၄ ကြောင်း ဖြစ်လာမယ်
# Axis 1 (Column အလိုက်/ဘေးဘက်သို့) ဆက်မယ်
d = np.append(a, b, axis=1)
# ရလဒ်: Row 2 ကြောင်းပဲ ရှိမယ်၊ ဒါပေမယ့် Column တွေ များသွားမယ်
သတိပြုရန် -
append လုပ်လိုက်ရင် မူရင်း Array ကို သွားပြင်တာမဟုတ်ဘဲ၊ တန်ဖိုးသစ်တွေပါဝင်တဲ့ Array အသစ်တစ်ခု (Copy) ကို ထုတ်ပေးတာ ဖြစ်ပါတယ်။ ထပ်ဖြည့်မယ့် Array ဟာ မူရင်း Array နဲ့ Shape တူညီဖို့ လိုပါတယ်။ တကယ်လို့ axis မသတ်မှတ်ထားဘူးဆိုရင် Array တွေကို အရင်ဆုံး ပြားချ (Flatten) လိုက်ပြီးမှ ဆက်ပေးသွားမှာ ဖြစ်ပါတယ်။ ဒါ့အပြင် Array တွေထဲမှာ Element ကြားဖြတ်ထည့်တာ (Insert)၊ ဖျက်တာ (Delete) နဲ့ ခွဲထုတ်တာ (Split) လုပ်တဲ့ Function တွေလည်း ရှိပါသေးတယ်။ ဒါတွေကိုတော့ ကိုယ့်ဘာသာ ဆက်လက်လေ့လာကြည့်ဖို့ အကြံပြုထားပါတယ်။
Problems¶
Problem 27.1¶
Dimension 4 x 2 x 3 ရှိတဲ့ 3D Array တစ်ခုကို တည်ဆောက်တဲ့ Program ရေးပါ။ Array ထဲမှာ တန်ဖိုးတချို့ကို ကနဦးသတ်မှတ် (Initialize) ပါ။ ပြီးနောက် Axis တစ်ခုစီအလိုက် အကြီးဆုံးတန်ဖိုး (Maximum) တွေကို ရှာဖွေပါ။
Program
import numpy as np
# 4x2x3 Array တစ်ခု တည်ဆောက်ခြင်း
a = np.array([[[3,7,6],[1,5,2]],[[1,2,4],[7,2,9]],[[1,0,0],[5,4,3]],[[8,1,4],[2,7,8]]])
print('Maximum along axis 0')
print(np.max(a,axis = 0))
print('Maximum along axis 1')
print(np.max(a,axis = 1))
print('Maximum along axis 2')
print(np.max(a,axis = 2))
Output
Problem 27.2¶
၁ မှ ၂၀ ထိ ဂဏန်းများပါဝင်ပြီး Shape 5 x 4 ရှိသော Array တစ်ခုကို တည်ဆောက်ပါ။ Array တစ်ခုလုံးရဲ့ ပေါင်းလဒ်၊ Row အလိုက် ပေါင်းလဒ်များ နှင့် Column အလိုက် ပေါင်းလဒ်များကို ရှာဖွေသည့် Program ရေးပါ။
Program
Output
Problem 27.3¶
အောက်ပါလုပ်ဆောင်ချက်များ ရရှိရန် Program ရေးပါ
- Size 10 ရှိပြီး Element အားလုံး တန်ဖိုး 3 သတ်မှတ်ထားတဲ့ Array a ကို တည်ဆောက်ပါ။
- Array a ရဲ့ Memory Size နဲ့ Element တစ်ခုချင်းစီရဲ့ Size ကို ရှာပါ။
- 0 မှ 90 အထိ တန်ဖိုးများ ညီတူညီမျှ ကွာခြားပြီး (Evenly spaced) ပါဝင်တဲ့ Size 10 ရှိ Array b ကို တည်ဆောက်ပါ။
- Array b ရှိ Element များကို ပြောင်းပြန်လှန် (Reverse) ပါ။
- Array a နှင့် b ကို ပေါင်းပြီး ရလာဒ်ကို Array c ထဲသို့ သိမ်းဆည်းပါ။
Program
Output
Problem 27.4¶
အောက်ပါလုပ်ဆောင်ချက်များ ရရှိရန် Program ရေးပါ
- Size 5 x 5 ရှိတဲ့ 2D Array တစ်ခု တည်ဆောက်ပါ။ ဘောင် (Border) ပတ်လည်ရှိ Element များကို 1 ပေးပြီး၊ အတွင်းပိုင်း Element များကို 3 ပေးပါ။
- တန်ဖိုး 2 တွေချည်းပါဝင်တဲ့ 4 x 3 Matrix တစ်ခုနဲ့ မြှောက်ပါ။
- ပေးထားသော 1D Array တစ်ခုအတွင်းရှိ တန်ဖိုး 2 နှင့် 8 ကြားရှိသော Element များကို အနှုတ်လက္ခဏာ (Negate) ပြောင်းပါ။ (မူရင်း Array ထဲမှာပင် ပြောင်းလဲခြင်း - in place)။
Program
import numpy as np
# Note: Code logic requires modification to set inner elements to 3
a = np.ones((5,5))
# a[1:-1, 1:-1] = 3 # (This line is needed to match the description)
print(a)
b = np.ones((4,3)) # Creating 4x3 matrix
c = np.full((3,5),2) # Creating matrix for multiplication
d = b @ c # Matrix Multiplication
print(d)
e = np.arange(11)
print(e)
e[(2 < e) & (e < 8)] *= -1 # Negating elements between 2 and 8
print(e)
Output
Exercises¶
[A] အောက်ပါ ဖော်ပြချက်များသည် အမှန် (True) သို့မဟုတ် အမှား (False) ဖြစ်ကြောင်း ဖော်ပြပါ
- Python ကို Install လုပ်လိုက်တာနဲ့ Numpy library ပါ အလိုအလျောက် Install ဖြစ်ပြီးသား ဖြစ်သည်။
- Numpy array တွေက Python List တွေထက် ပိုမြန်သည်။
- Numpy array element တွေက အမျိုးအစား (Data Type) မတူညီတာတွေ ရောနှောပါဝင်လို့ ရသည်။
- Numpy array တစ်ခုကို တည်ဆောက်ပြီးသွားရင် သူ့ရဲ့ Size နဲ့ Shape ကို ပြောင်းလဲလို့ မရတော့ပါ။ (Dynamically cannot change)
- np.array_equal(a,b) သည် Array a နှင့် b ၏ Shape ရော Element တွေပါ တူညီမှသာ True ကို ပြန်ပေးသည်။
[B] အောက်ပါ မေးခွန်းများကို ဖြေဆိုပါ
- (a) ပထမဆုံး သဘာဝကိန်း (Natural numbers) ၁၀ လုံးပါဝင်တဲ့ Numpy Array ကို ဘယ်လို တည်ဆောက်မလဲ?
- (b) Numpy ကိုသုံးပြီး ကိန်းရှုပ် (Complex numbers) Array တွေကို တည်ဆောက်လို့ ရပါသလား?
- © Size 3 x 4 x 5 ရှိတဲ့ Array ၅ ခုကို တည်ဆောက်ပြီး တစ်ခုချင်းစီမှာ 0 တွေချည်း၊ 1 တွေချည်း၊ 5 တွေချည်း၊ Random တန်ဖိုးများနှင့် Garbage တန်ဖိုးများ အသီးသီး ဖြည့်သွင်းချင်ရင် ဘယ်လိုလုပ်မလဲ?
- (d) ၁ မှ စတင်သော မဂဏန်း (Odd numbers) များပါဝင်သည့် Element ၅၀ ရှိသော Array တစ်ခုကို ဘယ်လို တည်ဆောက်မလဲ?
- (e) Numpy array တစ်ခုရဲ့ Element အမျိုးအစား (Type)၊ အရေအတွက်၊ Base Address နှင့် နေရာယူထားသော Byte ပမာဏတို့ကို ဘယ်လို သိနိုင်မလဲ?
- (f) a1 = np.array([[1,2,3,4],[5,6,7,8]]) ဟု တည်ဆောက်ထားသော Array ၏ Dimension နှင့် Shape ကို ဘယ်လို သိနိုင်မလဲ?
- (g) 3 x 4 Matrix နှစ်ခု ပေးထားပါက ၎င်းတို့၏ သက်ဆိုင်ရာ Element အချင်းချင်း ပေါင်းခြင်း၊ နှုတ်ခြင်း၊ မြှောက်ခြင်း နှင့် စားခြင်းတို့ကို ဘယ်လို လုပ်ဆောင်မလဲ?
-
(h) အောက်ပါ Code များအနက် မည်သည်တို့သည် Numpy array ၏ Scalar arithmetic operations များ ဖြစ်ကြသနည်း?
[C] Match The Following pairs:
| ကုဒ် / လုပ်ဆောင်ချက် | ဖော်ပြချက် |
|---|---|
(a) s = np.trace(a) |
1. စာရင်းအင်းဆိုင်ရာ တွက်ချက်ခြင်း (Statistical Operation) |
(b) s = a.cumsum(axis = 1) |
2. Linear Algebra တွက်ချက်ခြင်း |
© a2 = np.copy(a1) |
3. Deep copy ပြုလုပ်ခြင်း |
(d) print(a1 < 2) |
4. သက်ဆိုင်ရာ Element အချင်းချင်း နှိုင်းယှဉ်ခြင်း |
(e) print(a1 > a2) |
5. တန်ဖိုးတစ်ခုတည်းနှင့် နှိုင်းယှဉ်ခြင်း (Scalar comparison) |
(f) print(a[1:3][3:6]) |
6. Bitwise လုပ်ဆောင်ချက် |
(g) a2 = invert(a1) |
7. Inversion ပြုလုပ်ခြင်း / Slicing ပြုလုပ်ခြင်း |
🦜 Hakha Chin
Python Cawnnak 🐍 - A Hramthok in Thiamnak Sang Tiang¶
📖 Konglam (Overview)¶
Python Mastery ah kan in don — hihi Joseph nih fiang tein a sermi le a khawmhsuatmi cawnnak thil kimchang a si. Joseph cu DataCamp Python Data Associate Certified professional a si i, Graphic Era Hill University ah AI, Cyber Security, le Data Science lei a lungtho tein a cawng liomi siangngakchia a si.
Hi repository hi Python programming cawn a duhmi hna caah ṭuan khawhmi, rinsan khawhmi, le a ṭha bikmi cawnnak lam pek dingin tuahmi a si. Nangmah cu programming a hramthok cawngmi na si ah, asiloah na Python thiamnak thukpi in cawn na duh a si ah, hi cawnnak nih hin Interactive Notebooks, a tak in hman khawhmi (practical examples), le fiang tein fianternak hmang in cawnnak hlawhtling le nuam a kan pek lai.
🚀 Na Cawn Dingmi Hna¶
Hi cawnnak chungah a hrampi in a sangmi (advanced) tiang a tel:
- A Hrampi Pawl: Variables, data types, loops le functions hngalhthiamnak.
- Control Flow: Code ṭial ningcang le a kal ning (Logic) ṭha tein hngalhnak.
- Data Structures: Python i a ṭhami lists, dictionaries le sets hmang in hlawhtling tein solution ṭialnak.
- A Ṭha Bikmi Hmannung: A thiangmi, hman a nuammi le Pythonic code ṭial ning.
- Scientific Computing: NumPy bantuk library ṭha pawl hngalhnak.
📚 Repository Chung Ummi¶
Hi repository nih cawnnak ṭha taktak a pek:
- Interactive Jupyter Notebooks: Code hman khawh ding in chapter dot in ṭialmi.
- A Dot Dot in Tuahmi: Python cawnnak a hmaanmi a kalning tein a um.
- A Tak in Hman Khawhmi: Vawlei taktak ah hman khawhmi code le practice.
- Fiang Tein Fianternak: A tlamtlingmi le hngalh a fawimi fianternak.
📌 Chapter Hmuh Khawhmi Hna¶
| Chapter | Tlangtar (Topic) | Fianternak |
|---|---|---|
| Chapter 1 | Python Konglam | Python tuanbia, a minthangnak le programming paradigms hngalhnak. Python cu developer hna caah zeicah a ṭhat, cun functional, procedural, object-oriented le event-driven programming models hna cawnnak. |
| Chapter 2 | Python A Hrampi | Variables, data types, operators le expressions hngalhthiamnak. Na Python khualtlawnnak caah a hrampi fek tein chiah. |
| Chapter 3 | Input le Output | User sinin input laknak le output hmuhternak caah thil herhmi hna. Formatting options le user interaction kong hngalhnak. |
| Chapter 4 | Strings | Text processing thukpi in cawnnak - string tuahnak, slicing, formatting le built-in methods ṭhatnak pawl. Application taktak caah a herhmi string manipulation techniques hngalhthiamnak. |
| Chapter 5 | Decision Control | Na program thiamnak pek - if, if-else, le elif statements hmang in. Conditional logic le decision-making na code chungah hman ning. |
| Chapter 6 | Repetition Control | Thil tuah ṭhan lengmangmi (repetitive tasks) automatic tuahnak for le while loops hmang in. Iteration techniques le loop control statements hngalhthiamnak. |
| Chapter 7 | Functions | Code thencheu in hman (modular) le hman ṭhan khawhmi (reusable) code ṭialnak. Parameters, return values, scope le advanced function concepts hngalhnak. |
| Chapter 8 | Lists | Python i a ṭha bikmi data structure pakhat cawnnak. List operations, methods, slicing le stack/queue data structures implement tuahnak. |
| Chapter 9 | Advanced Topics | Python concepts le techniques sang deuh pawl cawnnak, na programming thiamnak a san deuh nakhnga. |
| Chapter 27 | NumPy le Advanced Concepts | Scientific computing NumPy hmang in hngalhthiamnak. Advanced Python features - decorators, generators, context managers hna cawnnak. |
NOTE
Chapter dang pawl cu a dotdot in upload chap peng an si lai. Chapter tin ah a tak in hman khawhmi practical examples, exercises le vawlei taktak application hna an tel lai.
🎯 Aho Caah Dah A Si?¶
Hi repository hi a tanglei hna caah a ṭha bik:
- 🌱 A Thawkkami — Python programming a hramthok tein a cawngmi.
- 🎓 Siangngakchia — Python a hrampi fek tein hngalh a duhmi hna.
- 💼 Developer — Technical interview (Rian hmuh ding) caah aa timtuahmi.
- 🔄 I Hngalhter Ṭhan Duhmi — A hrampi a fekmi cawnnak hmuh a duhmi.
- 🚀 A Lungthomi — Python hmang in vawlei taktak project tuah a duhmi.
🛠️ Hman Ning¶
A Herhmi Hna¶
- Python 3.7 asiloah a sang deuh.
- Jupyter Notebook.
- Programming hngalhnak a hrampi (a um ahcun a ṭha, asinain a herh hrimhrim lo).
Install Tuah Ning¶
1️⃣ Repository Clone Tuah¶
2️⃣ Dependencies Install Tuah¶
# Jupyter Notebook install tuahnak
pip install jupyter
# Python libraries hna install tuahnak
pip install numpy pandas matplotlib
# Documentation caah MkDocs (duh ahcun)
pip install mkdocs-material
3️⃣ Jupyter Notebook On (Launch)¶
4️⃣ On Law Cawng Thawk¶
- Chapter notebooks kha on hna.
- Code cells kha run tuah in zoh.
- Na duh ning in thleng law cawng.
🌐 Online Documentation Zoh¶
📌 Documentation site dawh taktak ah kal ve:
🔗 https://rose1996iv.github.io/PythonWithJoe/
Asiloah docs kha na machine (local) zoh na duh ahcun:
Browser ah:
🔗 http://127.0.0.1:8000
📘 Cabu Konglam¶
"Python With Joe" cu mi thong tampi Python programming thiam dingin a bawmtu cabu ṭha a si. 5th Edition ah tu chan Python hmannak thar hna a tel:
- A hramthawk mi hna caah fianternak ṭha.
- Harnak level a dotdot in a kal.
- Code examples tam taktak a tel.
- Practice le challenge hna a tel.
- Vawlei taktak ah hman khawhmi projects.
A Ṭialtu Hna: Yashavant Kanetkar, Aditya Kanetkar, DataCamp, Python notes from GoalKicker
A Khawmhsuattu (Curated by): Joseph
🤝 I Tel Ve / Bawmhnak¶
Na kan bawmhnak nih hihi midang caah ṭhatnak a chuahter deuh lai — kan lawm 🙌
- 📝 Thil Ṭhatnak: Fianternak tling deuh, examples thar asiloah remhnak.
- 🐛 Bug Report: Palhnak na hmuh ahcun kan hrilh hram!
- 💡 Ruahnak: Chapter asiloah topic thar caah ruahnak thar.
- 🌟 Enhancements: Fianternak ṭha deuh asiloah code tling deuh.
Contribute na duh ahcun:¶
- Repository kha Fork tuah.
- Branch thar tuah (
git checkout -b feature/amazing-improvement). - Na remh duhmi kha remh.
- Commit tuah fiang tein (
git commit -m "Add detailed explanation for decorators"). - Na branch ah Push tuah (
git push origin feature/amazing-improvement). - Pull Request onh.
📞 Biaknak le Bawmhnak¶
Biahal duh asiloah feedback pek na duh ahcun kan lawm hle!
- 🛠️ Issues: https://github.com/rose1996iv/PythonWithJoe/issues
- 💬 Discussions: Na cawnnak khualtlawnnak chungah lungthin tlangtlennak.
- 📧 Repository: https://github.com/rose1996iv/PythonWithJoe
📄 License¶
Hi repository hi MIT License tang ah a um — LICENSE file ah zoh khawh a si.
Nuam tein cawng hna u! 🐍✨
Tuni ah na Python khualtlawnnak thawk law — a hramthawk in developer rintlak ah i chuah hram!
🗓️ Last Updated: January 3, 2026
Chapter 1 Introduction To Python¶
Keynote¶
1.1 Python Timi Cu Zeidah A Si?¶
- Python cu high-level programming language a si i, Guido Van Rossum nih a sermi a si — amah cu Benevolent Dictator For Life (Lung-ṭha mi Uktu Bawi Zungzal) tiah dawt tein an auh.
- Python cu 1991 kum ah a voikhatnak an rak chuah. Nihin ah cun Windows le Linux tel in Operating Systems tampi caah Python interpreters pawl hmuh khawh an si cang.
- Python a ṭialtu (programmers) pawl cu a caan ah Pythonists asiloah Pythonistas tiah an auh tawn hna.
1.2 Python A Lar Tuknak A Ruang Pawl¶
Python a lar tuknak a ruang tampi a um. Cu hna lak i a cheu cu:
(a) A Man Pek A Hau Lo (Free):
- Python cu hman le ṭhenh (distribute) a man a hau lo i community nih an bawmh/support.
- Python interpreter cu platform ngan pawl dihlak ah hmuh khawh a si.
(b) Software A Ṭhat Ning (Software Quality):
- Traditional le scripting languages dang nak in a ṭha deuh.
- Code rel a fawi, cucaah hman ṭhan (reusable) le zohkhenh (maintainable) a fawi.
- Advance reuse mechanisms caah bawmhnak (support) a um.
© Developer Pawl Rian Ṭuan A Raan (Developer Productivity):
- Statically typed languages dang nak in a ṭha deuh.
- Code a tawi/hme deuh.
- Type, debug le maintain tuah ding a tlawm deuh.
- A caan a la tukmi compile le link steps pawl a hau lo.
(d) Program A Dang Ah Ṭhial A Fawi (Program Portability):
- Python programs cu platforms tam deuh ah thlen hau lo in a ning tein (unchanged) a run kho.
- Python cu atu lio hman mi platforms ngan pawl dihlak ah a run kho.
- Program kha platform thar ah ṭhial tik ah a tlangpi in cut le paste tuah lawng a hau tawn. Hihi GUI, DB access, Web programming, OS interfacing, Directory access, tbk., ca zong ah a hmaan.
(e) Bawmtu Libraries Pawl (Support Libraries):
- Text pattern matching in networking tiang library support a ṭhawng.
- Third party libraries (midang tuah mi) tampi hmuh khawh a si.
- Web site sernak, Numeric programming, Game development, Machine Learning tbk. caah Libraries an um.
(f) Hmun Khat Ah Fonh Khawhnak (Component Integration):
- C, C++ libraries le Java components pawl a au/hmang kho.
- COM, .NET tbk. frameworks pawl he zong rian a ṭuan ṭi kho.
- Network cung ah SOAP, XML-RPC, CORBA hman in rian a ṭuan kho.
- Glue code (a benh tu code) ṭha tein hman ahcun, Python nih C++, Java, C# classes pawl a subclass kho, mah nih program a ngeih ciami kha a karh ter.
- Product sersiam (customization) le chap (extension) caah hman a si tawn.
(g) Nuamhnak (Enjoyment):
- Hman a fawi (Ease of use).
- Built-in toolset (hriamnam) ṭha a ngei.
- Programming tuah cu rian ṭuan nak in nuamhnak a si deuh.
1.3 Python Hi Zei Nih Dah A Dang ter?¶
(a) A Ṭhawng (Powerful):
- Dynamic typing.
- Variable declaration tuah a hau lo.
- Automatic allocation le Garbage Collection a ngei.
- Classes, modules le exceptions pawl a support.
- Componentization le reuse (hman ṭhan) a ngah ter.
- Containers a ṭhawng mi - Lists, Dictionaries, Tuples, tbk. an um.
(b) Tuah Cia Mi Thil Pawl (Ready-made stuff):
- Joining (i peh), slicing (a cheu), sorting (a ning cang in chiah), mapping (map tuah), tbk. caah support a um.
- Library a ṭhawng mi a ngei.
- Third-party utilities a phu in tampi a um.
© Hman A Fawi (Ease of use):
- Type le run (ca ṭial le tuahter) a ngah colh.
- Compile le link steps a hau lo.
- Interactive programming experience a si.
- Rapid turnaround (rian ṭuan a rang).
- Programs pawl cu an fawi deuh, an hme deuh, i an flexible deuh.
1.4 Python Hi Khoi Ka Ah Dah Hman A Si?¶
Python cu thil phunphun tuahnak ah hman a si. Cu hna cu:
- System programming
- GUI applications sernak
- Internet scripting
- Component integration
- Database programming
- Rapid prototyping
- Numeric le Scientific programming
- Game programming
- Robotics programming
1.5 Nihin Ah Ho Nih Dah Python An Hman?¶
Bu (Organizations) tampi nih Python cu thil phunphun caah an hman. Cu hna cu:
- Google - Web search system ah
- YouTube - Video i hrawmh (Sharing) nak rian ah
- Bit-torrent - Peer to Peer file sharing system
- Intel, HP, Seagate, IBM, Qualcomm - Hardware hneksaknak (testing)
- Pixar, Industrial Light and Magic - Movie animation
- JP Morgan, Chase, UBS - Financial market hmailei kong tuaknak (forecasting)
- NASA, FermiLab - Scientific programming
- iRobot - Commercial robot vacuum cleaners
- NSA - Cryptographic le Intelligence analysis
- IronPort - Email Servers
1.6 Programming Paradigms (Rian Ṭuan Ning Phunglam)¶
- Paradigm timi cu tawlrelnak phunglam (organization principle) a si. Model tiah zong an auh.
- Programming paradigm/model cu computer programs sersiam tik i a structure le a chung um mi thil (elements) sak ning style a si.
- Programming models tampi a um, tahchunhnak ah Functional, Procedural, Object-oriented, Event-driven, tbk.
- Language tampi nih paradigms pakhat asiloah cu nak tam hman khawh nak a pek. Tahchunhnak ah, Python nih Functional, Procedural, Object-oriented le Event-driven programming models a support.
- A caan ah Functional programming hman a ṭhat deuh nak a um i, a caan ah Procedural programming hman a ṭhat deuh nak a um ve.
- Paradigms pawl cu pakhat le pakhat i thleidan (mutually exclusive) a hau mi an si lo. Program pakhat chung ah paradigms phunphun cawh in hman khawh a si.
1.6.1 Functional Programming Model¶
- Functional programming nih buaibainak (problem) kha functions set ah a ṭhen. Mah functions pawl cu program i a logic hrampi an si.
- Functions nih input parameters an la i outputs an chuah. Python nih functional programming techniques a simi lambda, map, reduce le filter pawl a pek. Hi hna cu Chapter 15 ah fianh a si lai.
- Hi model ah, tuaknak (computation) kha mathematical functions tuaknak bantuk in chiah a si. Tahchunhnak ah, nambar pakhat i factorial value, asiloah nth Fibonacci nambar hmuh ding ah a tanglei functions hi hman khawh an si:
factorial(n) = 1 if n == 0
= n * factorial(n - 1) if n > 0
fibo(n) = 0 if n == 0
= 1 if n == 1
= fibo(n - 2) + fibo(n - 1) if n > 1
1.6.2 Procedural Programming Model¶
- Procedural programming nih buaibainak (problem) kha procedures set ah a ṭhen. Mah procedures pawl cu program i a logic hrampi an si.
- Procedures nih input parameters an la i outputs an chuah. Python nih functions, classes, modules, tbk. bantuk procedural programming techniques a pek. Hi hna cu Chapter 15 ah fianh a si lai.
- Hi model ah, tuaknak (computation) kha procedures tuaknak bantuk in chiah a si. Tahchunhnak ah, nambar pakhat i factorial value, asiloah nth Fibonacci nambar hmuh ding ah a tanglei procedures hi hman khawh an si:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def fibo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibo(n - 2) + fibo(n - 1)
- Procedure pakhat i a output value cu a arguments (input) cung lawng ah aa hngat, cucaah value aa khat mi argument in procedure auh a si paoh ah result aa khat mi zungzal a chuah. Cucaah, parallel execution (a rual in rian ṭuan) caah a ṭha tuk.
- Procedure nih variables dang cung ah side effects (hnorsuannak) a ngei lo (state kha thlen lo in a um).
- Procedural programming model cu a caan ah 'Imperative' programming paradigm tiah an auh, a ruang cu statements asiloah instructions (fialnak) hman in programming tuah a si, expressions asiloah declarations hman in a si lo.
- Procedural programming nih buaibainak kha statement pakhat hnu pakhat (procedure) tuah in a phit. A tuah ning (steps) kha a ningcang tein a zulh (specific order).
- Amah zong nih functions a hman ve, asinain functional programming i hmanmi mathematical functions bantuk an si lo. Functional programming cu expressions ah a lung a thi, Procedural programming cu statements ah a lung a thi.
- Statements pawl nih values (man) an ngei tawn lo; cu can ah, conceptual machine i a state (sining) tu an thlen.
- Language expression aa khat mi nih a caan aa dan tik ah values aa dang a chuah khawh, cucu program a kal lio i a global state cung ah aa hngat. Cun, functions nih program i a state an thlen khawh.
- Procedural programming model cu 'Imperative' programming tiah zong auh a si, a ruang cu statements hmang in state kha a ningcang tein (explicit sequence) a thlen caah a si.
1.6.3 Object-oriented Programming Model¶
- Hi model nih computer chung ah objects a ummi vawlei hmete ser in vawlei taktak (real world) a cawng (mimics).
- University system ah cun objects cu VC, Professors, Non-teaching staff (cachim lo in rian a ṭuanmi), students, courses, semesters, examinations, tbk. an si kho.
- Object pakhat cio nih state (values) le behavior (interface/methods) a ngei. Objects nih an state le behavior cu anmah sernak class sin in an ngah.
- Objects pawl cu pakhat le pakhat messages i kuat in pehtlaihnak an tuah, cucu pakhat le pakhat i an interface methods auh (calling) in a si.
1.6.4 Event-driven Programming Model¶
- Hi model hi windows, check boxes, buttons, combo-boxes, scroll bars, menus, tbk. a ngeimi GUI applications programming tuahnak ah hman a si tawn.
- Hi elements pawl he kan i tongh tik ah (tahchunhnak ah button hmeh, asiloah scrollbar ṭhial, asiloah menu item thim) events (thil cang) a chuak i hi elements pawl nih messages an chuah (emit). Hi GUI elements he register tuah mi listener methods an um i, cu hna nih events kha an lehrulh (react).
- Events a chuah ning hi a caan aa zulh ning a um lo (guaranteed sequence a um lo - GUI elements kan hman ning cung ah aa hngat), cucaah listeners pawl nih asynchronous (a caan aa khat lo in) manner in an tawlrel khawh a hau.
Exercises¶
[A] A tanglei biahalnak hna hi phi tuah:
- a. Python hman a sinak hmun (fields) 5 chim tuah.
- b. Event-driven programming hi khoi ka ah dah hman a si tawn?
- c. Zeicahdah Python hi portable language tiah an auh?
- d. Hi chapter ah fianh mi programming models phunphun hna i an feature a biapi bik cu zeidah a si?
- e. A tanglei lak ah a hnu lei hi Python i a feature a si lo mi a si?
- a. Static typing
- b. Dynamic typing
- c. Run-time ah error tawlrelnak (error numbers hmang in)
- d. Lists, Dictionaries, Tuples tbk. bantuk containers caah Library support
- f. A tanglei programming models pakhat cio caah hmannak tahchunhnak (example application) pe tuah:
- a. Functional model
- b. Procedural model
- c. Object-oriented model
- d. Event-driven model
[B] A tanglei bia hna hi a Hmaan (**True) le a Hmaan lo (False) chim tuah:**
- a. Python cu hman le ṭhenh a man a hau lo.
- b. Python program aa khat mi cu OS - microprocessor aa dang mi ah a run kho.
- c. Python program chung ah C++ asiloah Java libraries hman khawh a si.
- d. Python ah variable i a type cu kan hman ning cung ah aa hngat.
- e. Python cu GUI applications sernak ah hman khawh a si lo.
- f. Python nih functional, procedural, object-oriented le event-driven programming models a support.
- g. GUI applications cu event-driven programming model cung ah hrambunh mi an si.
- h. Functional programming model cu objects tampi i pehtlaihnak (interaction) a si.
[C] A tanglei pawl hi a kop in thleidan tuah:
- a. Functional programming → 1. GUI element cung ah hngat in pehtlaihnak
- b. Event-driven programming → 2. Objects i pehtlaihnak
- c. Procedural programming → 3. Statements
- d. OOP → 4. Maths bantuk functions
[D] A tanglei hmun lawng pawl hi phithlim tuah:
- a. Functional programming paradigm cu ________ programming model tiah zong hngalh a si.
- b. Procedural programming paradigm cu ________ programming model tiah zong hngalh a si.
- c. Python cu ________ nih a ser mi a si.
- d. Python programmers pawl cu a caan ah ________ tiah auh an si.
Chapter 2 Getting Started¶
Keynote¶
1.1 Python Specification¶
-
Python cu language (computer holh) caah specification (tial ning phunglam) a si i, lam phunphun in implemented (tuah/hman) khawh a si. Holh phunphun in tial mi hi specification i implementations tampi a um.
-
A lar mi Python implementations pawl cu:
- CPython - hi zohchunh awk implementation a si, C in tial a si.
- PyPy - Python language i a hmete a simi RPython in tial a si.
- Jython - Java in tial a si.
-
IronPython - C# in tial a si.
-
Hi implementations dihlak hi compilers an si i interpreters zong an si fawn. Compiler nih Python program kha a lailing a simi bytecode ah a thlen (converts). Mah bytecode cu interpreter nih a leh (interpreted) ṭhan.
1.2 Windows Cung Ah Python Installation Tuah Ning¶
-
Python cu kum tampi chung a ṭhangcho ve. Hi edition (cauk) ṭial lio i a thar bik version, Windows le Linux caah Python 3.14.1 a si.
-
Python cu Windows OS ah aa tel chih lo. Cucaah a dang tein install tuah a hau. Mah caah cun www.python.org/downloads/ in Python installer kha download tuah a hau.
-
Download na tuah tik ah, na hmanmi computer cu 32-bit machine a si maw 64-bit machine a si maw timi cung ah hngat in installer aa tlak mi thim ding a si:
- 64-bit machine: Windows x86-64 executable installer kha download tuah.
-
32-bit machine: Windows x86 executable installer kha download tuah.
-
Installer na thim i download na tuah dih in, file kha hmeh-hnih (double-clicking) in tuahter/on. Figure 2.1 ah langhter mi dialog (cakuang) kha screen cung ah a lang lai.

-
Mah dialog chung ah, interpreter kha na execution path chung ah a um nakhnga, 'Add Python 3.14 to PATH' asiloah 'Add python.exe to PATH' timi check box (kakuang te) kha hmanh-thut (check) tuah ding a biapi tuk.
-
'Install Now' kha hmet law minit tlawmpal chung ah installation cu a tlamtling lai. Python files pawl cu a tanglei directory (hmun) ah install tuah an si lai:
C:\Users\Joseph\AppData\Local\Programs\Python\Python314 -
Hi path chung i ‘Joseph’ timi cu user name (hman tu min) a si i ‘Python314’ timi cu na download i install tuah mi Python installation i a version number a si.
-
Check box kha hmanh-thut na philh sual a si ahcun, a cunglei i langhter mi path kha Control Panel | System | Environment Variables | Edit hmang in PATH variable ah na chap khawh. PATH variable chung ah values tampi semicolon (;) in ṭhen in an um cia. A cunglei path kha a um cia mi values hnu ah va chap.
-
Installation a dih tik ah, command prompt on in python --version tiah type tuah law na chek khawh.
-
Installation a tlam a tlin ahcun, na system chung i install tuah mi Python i a version na hmuh lai.
-
Windows 10 na hman a si ahcun, Settings > Apps > Apps & features > Python ah kal in installation kha na chek khawh.
-
Windows 11 na hman a si ahcun, Settings >Apps > Apps & features > Python ah kal in installation kha na chek khawh.
1.3 Linux Cung Ah Python Installation Tuah Ning¶
-
Linux distributions a tam deuh (tahchunhnak ah Ubuntu) ah cun Python a um cia. Asinain, a um cia mi Python version cu a thar bik a si lo kho men. A tanglei bantuk in version na chek khawh:
-
Version cu a thar bik a si lo tiah na hmuh ahcun, command hmang in a thar bik version (tahchunhnak ah Python 3.13) kha install na tuah khawh:
1.4 Python Resources (Bawmtu Thilri Pawl)¶
- Python source code, binaries le documentation (fianternak cauk) pawl cu a tanglei ah hmuh khawh an si:
- Python official website: www.python.org
-
Documentation website: www.python.org/doc
-
Python in Program development (Program sernak) cu lam 3 in tuah khawh a si:
- Built-in IDLE hman in.
- Third-party IDEs (Midang tuah mi IDE) hman in.
-
Online Python shells hman in.
-
Third-party development tools le download tuah khawhnak links pawl cu a tanglei ah pek an si:
- NetBeans IDE for Python: https://netbeans.apache.org/front/main/download/
- PyCharm IDE for Python: https://www.jetbrains.com/pycharm
-
Visual Studio Code IDE: https://code.visualstudio.com/download
-
Python development tool na computer ah install tuah na duh lo ahcun, a tanglei online Python shells pawl hi na hman khawh hna:
- https://www.python.org/shell/
- https://ideone.com/
- https://replit.com/languages/python3
1.5 Third-party Packages (Midang Tuah Mi Packages)¶
-
Python community chung i Pythonistas pawl nih packages (libraries) an ser i programmers dang hman khawh dingin an chiah. An packages ṭhenhnak caah PyPI—Python Package Index (www.pypi.org) an hmang.
-
PyPI nih third-party Python packages hmuh khawh mi cazin a ngei/kilkawicawi.
-
Thil tuahnak ding caah a herh mi third-party packages a phunphun a um. Data Science applications sernak caah hman tawn mi packages cheukhat cu:
- NumPy: Mathematical operations a sang mi tuahnak caah le multi-dimensional arrays le matrices ngan pipi support tuahnak caah a si.
- SciPy: Scientific computing library a si i optimization, integration, interpolation, signal processing, image processing, tbk. caah hman a si.
- Pandas: Numerical tables le time series tawlrelnak caah Library a si.
- MatPlotLib: 2D le 3D Data visualization library (Data hmanthlak in langhternak) a si.
- OpenCV: Open source Computer vision library a si.
1.6 Python Packages Le Development Tools¶
-
Nangmah zong PyPI ah register na tuah kho i na packages pawl na upload khawh ve. Package ser ning, build tuah ning le Python Package Index ah upload tuah ning kong he pehtlai in www.pypi.org ah lam hmuhsaknak an pek mi na zulh a hau.
-
pip cu PyPI in packages install tuahnak caah hman tawn mi tool a si. Python na install tik ah hi tool hi amah tein a ra chih.
1.6.1 Data Science Le AI Tools¶
- Python programmers pawl Data Science le Artificial Intelligence applications sernak le document tuahnak ah bawmtu ding tools tampi a um. Cu hna cu:
- Jupyter Notebook - Hi tool cu browser cung ah hman khawh mi a si i Python (le languages dang) he hman ṭi khawh a si. Python code, code nih a chuah mi output le visualization asiloah plot tbk. pawl kha Notebook tiah auh mi document pakhat chung ah chiah ṭi a ngah. Modular program development tuahnak caah tool ṭha taktak a si.
- Google Colab - Hi tool nih Google's cloud servers cung ah code execute (tuahter) nak ding caah Jupyter notebook environment kha a man pek hau lo in a pek. Cucaah, Google's hardware ṭhawnnak kha na hmang kho.
-
Spyder - Hi tool nih Scientific Python Development Environment kha testing le debugging features a ṭha mi he a pek.
-
Jupyter le Spyder cu Anaconda tiah auh mi software distribution a lar taktak mi chung i a tel mi an si. Cucaah Anaconda na download i install na tuah ahcun, Jupyter le Spyder kha a ready in na hmuh colh lai.
1.6.2 IDLE (Integrated Development and Learning Environment)¶
-
Python install na tuah dih in, amah he a ra chih mi Python Integrated Development and Learning Environment (IDLE) hmang in program development tuah khawh a si.
-
IDLE cu development tool ṭha a si. Amah nih syntax highlighting, context-sensitive help le debugging tbk. features ṭha a ngei.
- Syntax highlighting feature nih keywords, functions, methods le strings pawl kha a color (muizawng) a dang cio in a langhter hna caah hngalh an fawi.
- Context-sensitive help cu program na ṭial lio ah bawmhnak na herhnak zawn paoh ah Ctrl + Space hmeh in hmuh khawh a si. Functions, methods le an parameters min dihlak cinken dih ding a har tuk caah hi feature hi a ṭhahnem tuk.
- Debugger nih program a kal ning (flow of execution) a zulh (trace) i na program chung i logical errors (palhnak) um mi kawl khawhnak a pek. Hi tracing cu break points chiah in le single stepping (kar khat hnu kar khat) in tuah khawh a si. Cuti na tuah lio ah IDLE nih execution a kal lio i variables values aa thlen ning pawl a langhter.
1.6.3 Python Modes¶
- Python cu modes (lam) pahnih in hman khawh a si:
- Interactive mode - Python syntax hlathlai nak, bawmhnak hal nak le programs tawi te debug tuahnak caah hman a si.
-
Script mode - Python programs a tling mi ṭialnak caah hman a si.
-
Hi modes pahnih hi IDLE nih a support.
1.6.3.1 IDLE Kha Interactive Mode In Hman Ning:¶
- Windows ah IDLE tiah Windows search bar ah ṭial in kawl law enter hmet, asiloah IDLE icon kha double click tuah.
>>>Python shell prompt a um mi Python shell window a hong lai.-
A tanglei Python code hi prompt ah khan execute (tuahter) tuah.
-
'Keep calm and bubble on' timi message kha
>>>prompt hnu ah a langhter lai.
1.6.3.2 IDLE Kha Script Mode In Hman Ning:¶
-
IDLE kha on (Launch). IDLE shell window chung i menu in File | New File kha thim. Window thar a hong lai. A tanglei script hi ṭial:
-
File | Save kha hmang law script kha 'Test.py' tiah min pek in save tuah.
- Run menu hmang in asiloah F5 hmeh in script kha execute tuah. Message pahnih kha a print lai.
1.6.3.3 Other IDEs Hmannak¶
- IDLE hman lo in NetBeans asiloah Visual Studio Code hman na duh ahcun a tanglei steps hi zul:
- Python project thar ‘Test’ tiah min pek in ser law.
- Script kha Test.py chung ah ṭial.
- NetBeans ah F6 asiloah Visual Studio Code ah Ctrl + F5 hmang in script kha execute tuah.
- Execution a tuah tik ah catlang pahnih kha a print lai, cun project thar le script thar ser ding in a ready lai.
1.7 Python Version Cheknak¶
- Python cu kum tampi chung a ṭhangcho. Na machine cung i install tuah mi version kha Python script tawi te hmang in na hngalh khawh:
Exerciese¶
[A] A tanglei biahalnak hna hi phi tuah:
- a.
C:\>,$, le>>>prompts pawl nih zeidah an langhter (signify)? - b. IDLE cu zei modes (lam) pahnih in dah hman khawh a si?
- c. IDLE nih a pek mi programming modes pahnih hna i an hman-hnawhchan (purpose) cu zei dah a si?
- d. Third-party libraries pawl cu Python Program nih zeitin dah hman khawh an si?
[B] A tanglei pawl hi a kop in thleidan tuah (Match the following pairs):
| Section A | Section B |
|---|---|
a. pip |
1. Mathematical operations le matrices caah. |
b.CPython |
2. Scientific Python Development Environment** a si caah Scientific Computing he aa tlak bik. |
c. Spyder |
3.Numerical tables le time series tawlrelnak. |
d.PyPI |
4. 2D le 3D Data visualization (Data hmanthlak in langhter). |
e.NumPy |
5. Computer vision library. |
f.SciPy |
6. PyPI in packages install tuahnak hriamnam. |
g.Pandas |
7. Code le visualization tial ṭi nak document sernak. |
h.MatPlotlib |
8. Scientific computing library a si. |
i.OpenCV |
9.Third-party packages ṭhenhnak hmun. |
Answers
| Section A | Section B (A Phi) | A Sullam (Reference) |
|---|---|---|
a. pip |
6. Package installation tool | PyPI in packages install tuahnak hriamnam. |
b. Jupyter |
7. Build and document applications | Code le visualization tial ṭi nak document sernak. |
c. Spyder |
2. Scientific Computing | Scientific Python Development Environment a si caah Scientific Computing he aa tlak bik. |
d. PyPI |
9. Python Package index | Third-party packages ṭhenhnak hmun. |
e. NumPy |
1. Advanced mathematical operations | Mathematical operations le matrices caah. |
f. SciPy |
8. Scientific Library | Scientific computing library a si. |
g. Pandas |
3. Manipulation numerical tables | Numerical tables le time series tawlrelnak. |
h. MatPlotlib |
4. Visualization | 2D le 3D Data visualization (Data hmanthlak in langhter). |
i. OpenCV |
5. Computer Vision | Computer vision library. |
[C] A tanglei bia hna hi a Hmaan (True) le a Hmaan lo (False) chim tuah:
- a. Python cu specification a si i Python (PyPy), C# (IronPython), Java (Jython), tbk. hmang in implementation tuah khawh a si.
-
A Phi: True (Hmaan).
-
b. CPython cu Python specification i implementation a si i, C in ṭial a si.
-
A Phi: True (Hmaan).
-
c. Python program cu byte code ah compile tuah hmasa a si i, cu hnu ah interpreted (leh) a si.
-
A Phi: True (Hmaan).
-
d. Linux distributions a tam deuh nih Python an ngei cia.
-
A Phi: True (Hmaan).
-
e. Windows system nih Python a ngei lo i a dang tein install tuah a hau.
-
A Phi: True (Hmaan).
-
f. Python programs pawl cu IDLE, Netbeans, PyCharm le Visual Studio Code hmang in ser khawh a si.
-
A Phi: True (Hmaan).
-
g. Third-party Python packages pawl cu PyPI hmang in ṭhenh (distributed) an si.
- A Phi: True (Hmaan).
Chapter 3 Python Basics¶
Keynote¶
3.1 Identifiers Le Keywords¶
Python cu case sensitive (ca ngan le ca hme a thleidan mi) language a si. Python identifier cu variable, function, class, module, asiloah object dang hngalh/thleidan nak caah hman mi min a si.
Identifiers ser nak phunglam pawl:
-
Alphabet (ca) asiloah underscore (_) in aa thawk a hau.
-
A hnu ah letters, _, le digits (nambar) an zul kho.
-
keyword cu identifier in hman khawh a si lo.
Keywords dihlak cu lowercase (ca hme) in an si (Note: False, None le True ti lo). Python nih Table 3.1 ah hmuh sak mi keywords 33 a ngei.
| Table 3.1 Keywords list | |||
|---|---|---|---|
| False | continue | from | not |
| None | def | global | or |
| True | del | if | pass |
| and | elif | import | raise |
| as | else | in | return |
| assert | except | is | try |
| break | finally | lambda | while |
| class | for | nonlocal | with |
| yield |
A tanglei statements hmang in Python keywords list kha na print khawh:
import keyword # makes the module 'keyword' available
print(keyword.kwlist) # syntax modulename.object/function
3.2 Python Types¶
Python nih data types phun 3 a support:
- Basic Types:
- int, float, complex, bool, string, bytes
- Container Types:
- list, tuple, set, dict
- User-defined types:
- class
Hi hna lak ah, basic types kong cu hi chapter ah a tling tein fianh a si lai. Container types kong cu a tawi nak in fianh a si lai. Container type pakhat cio caah a dang tein chapter ser a si, cuka ah cun a tling tein fianh a si lai. User-defined types cu hi chapter ah fianh a si lai lo. Chapter 17 ah zeitin dah ser le hman ding an si ti kha fianh a si.
3.2.1 Basic Types¶
Basic types aa dangdang hna i tahchunhnak cu a tanglei ah pek an si:
- int cu binary, decimal, octal, hexadecimal in langhter khawh a si.
- binary cu 0b/0B in aa thawk, octal cu 0o/0O in, hex cu 0x/0X in aa thawk (tahchunhnak: 0b10111, 156, 0o432, 0x4A3).
- float cu fractional asiloah exponential form in langhter khawh a si (tahchunhnak: 314.1528, 3.141528e2, 3.141528E2).
- complex ah real le imaginary part an um (tahchunhnak: 3 + 2j, 1 + 4J).
- bool cu Boolean values pahnih lak ah pakhat paoh a si kho i an pahnih in ca lian in an i thawk (tahchunhnak: True, False).
- string cu Unicode characters a hlawm a si i thlen khawh a si lo (immutable),
' '," ", asiloah""" """chung ah chiah a si. 'Rosanna', "Rosanna", """Rosanna""". - bytes nih binary data a aiawh.
print(type(35)) # <class 'int'> tiah a print/langhter
print(type(3.14)) # <class 'float'> tiah a print/langhter
3.2.2 Integer Le Float Ranges¶
- int cu a duh zahzah a ngan a si kho (limit a um lo).
Floats cu computer chung ah IEEE 754 standard ning in 64-bit double-precision values in binary ah chiah/langhter an si. Hi standard ning in cun, float nih a ngeih khawh mi a ngan bik value cu 1.8 x 10^308 hrawng a si. Hi nak in a ngan mi nambar cu inf (short for infinity - tawpnak ngei lo) in langhter a si.
Floats tampi cu binary form in 'a dik thlap in' (exactly) langhter khawh an si lo. Cucaah a chung i chiah ning (internal representation) cu a taktak value he 'aa lo nawn' (approximation) in chiah a si tawn.
A taktak value le an langhter mi value i an i dannak cu a hme tuk, cucaah buaibainak nganpi a chuahter tawn lo.
3.3 Variable Type Le Assignment¶
Variable i a type kha khiah/chimh cia a hau lo. Execution a tuah lio ah variable i a type cu zeitin dah hman a si timi context zoh in amah tein a lak (inferred). Cucaah Python cu dynamically-typed language tiah auh a si.
a = 25 # a i type cu int tiah a lak/hngalh
a = 31.4 # a i type cu float tiah a lak/hngalh
a = 'Hi' # a i type cu str tiah a lak/hngalh
Variable pakhat i a type kha type() timi built-in function hmang in chek khawh a si.
A fawi mi variable assignment (value pek ning):
Variables tampi a voikhat ah assignment tuah ning (value pek ning):
a = 10 ; pi = 31.4 ; name = 'Rosanna' # ; hi statement separator in hman a si
a, pi, name = 10, 3.14, 'Rosanna'
a = b = c = d = 5
3.3.1 Arithmetic Operators¶
Arithmetic Operators: +, - , * , /, %, //, **
a = 4 / 2 # true division a tuah i float 2.0 a chuah
a = 7 % 2 # % nih a taang mi (remainder) 1 a chuah
b = 3 ** 4 # ** nih 3 a voi 4 nak a chuah (exponentiation)
c = 4 // 3 # // nih fractional part (a cheu) hlawt in quotient 1 a chuah
In-place assignment operators nih arithmetic operations (tuaknak) caah shortcut (lam tawi) ṭha taktak a pek. Cu hna cu +=, -=, *=, /=, %=, //=, **= an si.
3.3.2 Operation Nuances (Tuaknak I A Sining Pawl)¶
Floor division a//b kan tuah tik ah, a chuak mi result (a phi) cu quotient (a cheu mi a phi taktak) nak in a niam deuh mi asiloah aa khat mi integer (nambar tling) a ngan bik kha a si. // cu floor division operator tiah an auh.
(Note: Negative nambar a um tik ah a niam lei/thlang lei ah a kal. Tahchunhnak ah -10 kha 3 in cheu ah -3.33 a si, asinain floor division nih cun -3.33 nak in a niam deuh mi -4 tu a laak).
print(10 // 3) # 3 a chuah
print(-10 // 3) # -4 a chuah
print(10 // -3) # -4 a chuah
print(-10 // -3) # 3 a chuah
print(3 // 10) # 0 a chuah
print(3 // -10) # -1 a chuah
print(-3 // 10) # -1 a chuah
print(-3 // -10) # 0 a chuah
-10 // 3 ah, -10 hmuh ding in 3 i a let cu -3.333 a si, a floor value cu -4 a si. 10 // -3 ah, 10 hmuh ding in -3 i a let cu -3.333 a si, a floor value cu -4 a si. -10 // -3 ah, -10 hmuh ding in -3 i a let cu 3.333 a si, a floor value cu 3 a si.
print( ) cu function a si i screen cung ah output langhter ding ah hman a si. Lam phunphun in hman khawh a si. Cu hna cu Chapter 7 ah fianh a si lai.
a % b timi operation cu a - (b * (a // b)) tiah tuak a si. Hihi a tanglei tahchunhnak pawl hman hian fawi tein hngalh khawh a si:
print(10 % 3) # 1 a chuah
print(-10 % 3) # 2 a chuah
print(10 % -3) # -2 a chuah
print(-10 % -3) # -1 a chuah
print(3 % 10) # 3 a chuah
print(3 % -10) # -7 a chuah
print(-3 % 10) # 7 a chuah
print(-3 % -10) # -3 a chuah
a % b cu a - (b * (a // b)) tiah tuak a si caah, -10 % 3 cu -10 - (3 * (-10 // 3)) tiah tuak a si i, 2 a chuak. 10 % -3 cu 10 - (-3 * (10 // -3)) tiah tuak a si i, -2 a chuak. -10 % -3 cu -10 - (-3 * (-10 // -3)) tiah tuak a si i, -1 a chuak.
Mathematical rule a / b x c le a x c / b hi an i khat tawn, asinain a zungzal in a si lo (Computer chung ah cun).
# a tanglei expressions hna hi an result (a phi) aa khat
a = 300 / 100 * 250
a = 300 * 250 / 100
# Asinain, a tanglei hna hi cu an i khat lo
b = 1e210 / 1e200 * 1e250
b = 1e210 * 1e250 / 1e200 # INF (tawpnak ngei lo) a chuak
True cu 1 a si i False cu 0 a si caah, an pahnih in belh (add) khawh an si.
3.4 Precedence Le Associativity¶
Arithmetic expression pakhat chung ah operators tampi hman an si tik ah, hman mi operators pawl i an precedence (priority - biapi ah chiah in tuak hmasa ding) cung ah hngat in tuak a si.
Priority a sang bik in a niam bik lei operators pawl (PEMDAS):
( ) # Parentheses (Kuek)
** # Exponentiation (A let)
*, /, //, % # Multiplication, Division (Tuk, Cheu)
+, - # Addition, Subtraction (Belh, Thwn)
Precedence (priority) aa khat mi operators pahnih an um a si ahcun, associativity hmang in biakhiahnak tuah a si (aho dah tuah hmasa ding ti kha).
Operator pakhat cio nih left to right associativity (Keh lei in Orh lei) asiloah right to left associativity (Orh lei in Keh lei) an ngei.
Tahchunhnak ah c = a * b / c ah, * kha / nak in tuah hmasa a si, a ruang cu arithmetic operators nih left to right associativity an ngeih caah a si (Keh lei in a rat tik ah * nih a hmuh hmasa).
Python operators dihlak, an priority le an associativity cazin tling cu Appendix A ah pek a si.
3.4.1 Conversions (Thlen Ning)¶
Mixed mode operations (Cawh-nuk in tuahnak):
- int le float karlak ah tuah a si ahcun float a chuak.
- int le complex karlak ah tuah a si ahcun complex a chuak.
- float le complex karlak ah tuah a si ahcun complex a chuak.
Numeric type pakhat in a dang pakhat ah thlen ding caah int( ), float( ), complex( ) le bool( ) timi built-in functions hna hi hman khawh an si.
Type conversions:
int(float/numeric string) # float asiloah numeric string in int ah thlen
int(numeric string, base) # numeric string kha base a um mi int ah thlen
float(int/numeric string) # int asiloah numeric string in float ah thlen
float(int) # int in float ah thlen
complex(int/float) # complex ah thlen (imaginary part 0 in)
complex(int/float, int/float) # complex ah thlen (real le imaginary he)
bool(int/float) # int/float in True/False (1/0) ah thlen
str(int/float/bool) # string ah thlen
chr(int) # int he aa tlak mi character (ca) ah thlen
int( ) nih a cheu mi (quotient) i a point hnu (decimal portion) kha a hlonh, cucaah zero lei ah a round (a tling mi ah a thlen) zungzal.
3.4.2 Built-in Functions (A Chung Um Cia Functions)¶
Python nih built-in functions (amah chung ah a um cia mi) tampi a ngei, cu hna cu program chung khoika hmun paoh ah hman khawh an si. Screen cung ah output langhter ding caah kan hman tawn mi print( ) function zong kha built-in function pakhat a si.
Built-in function pakhat paoh kong he pehtlai in bawmhnak (help) hmuh na duh ahcun help(function) kha hman khawh a si.
Nambar he hman tawn mi Built-in functions pawl cu a tanglei ah pek an si:
abs(x) # x i a absolute value (a man taktak) a chuah
pow(x, y) # x a voi y nak (x raised to y) a chuah
min(x1, x2,...) # arguments lak ah a hme bik a chuah
max(x1, x2,...) # arguments lak ah a ngan bik a chuah
divmod(x, y) # (x // y, x % y) kha pair (a kop) in a chuah
round(x [,n]) # point hnu ah n digits um ding in x kha a round
bin(x) # x he aa khat mi binary a chuah
oct(x) # x he aa khat mi octal a chuah
hex(x) # x he aa khat mi hexadecimal a chuah
A tanglei Python program nih hi built-in functions cheukhat hman ning a hmuhsak:
a = abs(-3) # a ah 3 a chiah (assign)
print(min(10, 20, 30, 40)) # 10 a print/langhter
print(hex(26)) # 1a a print/langhter (Python taktak ah cun 0x1a tiah a lang)
3.4.3 Built-in Modules¶
Built-in functions leng ah, Python nih built-in modules tampi a pek. Module pakhat cio ah functions tampi an um. Mathematical operations a sang deuh mi tuah ding caah built-in modules a simi math, cmath, random, decimal chung i functions pawl kha hman khawh an si.
math - hman a ṭhahnem mi mathematics functions tampi.
cmath - complex numbers cung ah operations tuahnak functions.
random - random number (nambar can-u-nan) sernak he aa tlai mi functions.
decimal - arithmetic operations a dik thlap in (precise) tuahnak functions.
math module chung i Mathematical functions pawl:
pi, e # constants pi le e i an values (man)
sqrt(x) # x i square root
factorial(x) # x i factorial
fabs(x) # float x i absolute value (a man taktak)
log(x) # x i natural log (base e hman in log)
log10(x) # x i base-10 logarithm
exp(x) # e a voi x nak (e raised to x)
trunc(x) # integer ah thlen/tan (point hnu hlonh)
ceil(x) # x nak in a ngan deuh asiloah aa khat mi integer a hme bik
floor(x) # x nak in a niam deuh asiloah aa khat mi integer a ngan bik
modf(x) # x i a fractional (a cheu) le integer parts (a tling) pawl
round( ) timi built-in function cu decimal places (point hnu) a biaki mi zah tiang round tuah khawh a si, asinain math module i library functions trunc( ), ceil( ) le floor( ) pawl nih cun decimal places zero (point hnu um lo) tiang lawng an round zungzal.
math module chung i Trigonometric functions pawl:
degrees(x) # radians in degrees ah thlen
radians(x) # degrees in radians ah thlen
sin(x) # x radians i sine
cos(x) # x radians i cosine
tan(x) # x radians i tan
sinh(x) # x i hyperbolic sine
cosh(x) # x i hyperbolic cosine
tanh(x) # x i hyperbolic tan
acos(x) # x i cos inverse, radians in
asin(x) # x i sine inverse, radians in
atan(x) # x i tan inverse, radians in
hypot(x, y) # sqrt(x * x + y * y) (Hypotenuse tuaknak)
random module chung i Random number generation functions pawl:
random( ) # 0 le 1 karlak ah random number (nambar can-u-nan)
randint(start, stop) # start le stop karlak (range) ah random number
seed( ) # random number sernak hram (seed) caah atu lio caan (current time) kha a hman
seed(x) # random number sernak hram (seed) caah x kha a hman
A tanglei Python program nih math module le random module chung i functions cheukhat hman ning a hmuhsak:
import math
import random
print(math.factorial(5)) # 120 a print/langhter
print(math.degrees(math.pi)) # 180.0 a print/langhter
print(random.random( )) # 0.8960522546341796 a print/langhter
import math
print(dir(__builtins__)) # builtins hmailei le hnulei ah underscore pahnih cio an um
print(dir(math))
3.5 Container Types¶
Container types tiah chim tik ah a tlangpi in values tampi hmun khat ah chiah ṭi kha a chim duh mi a si. Basic types aa dangdang hna i tahchunhnak cu a tanglei ah pek an si:
# list cu index in kawl khawh mi, thilri a phunphun chiah ṭi nak a si
[10, 20, 30, 20, 30, 40, 50, 10], ['She', 'sold', 10, 'shells']
# tuple cu thlen khawh lo mi (immutable) hlawm a si
('Rosanna', 34, 4500.55), ('Python With Joe', 350, 195.00)
# set cu values aa dang cio (unique) lawng chiah ṭi nak a si
{10, 20, 30, 40}, {'Rosanna', 34, 45000}
# dict cu key-value pairs hlawm a si, a unique mi key kha '' chung ah chiah a si
{'ME101' : 'Strength of materials', 'EE101' : 'Electronics'}
lst = [10, 20, 30, 20, 30, 40, 50, 10]
tpl = ('Python With Joe', 350, 195.00)
s = {10, 20, 30, 40}
dct = {'ME101' : 'SOM', 'EE101' : 'Electronics'}
print(lst[0], tpl[2]) # 10 195.0 a print/langhter
print(dct['ME101']) # SOM a print/langhter
3.5.1 Python Type Jargon (Biafang Hman Mi Pawl)¶
Python types kong chim tik ah a tanglei biafang pawl hi hman an si tawn:
- Collection - container types caah hman mi biafang a si.
- Iterable - loop hman in a chung thil pakhat hnu pakhat kal khawh mi/lanh khawh mi collection a si.
- Ordered collection - elements (a chung thil) kha kan khumh ning tein an um. Cucaah index (a umnak hmun) hmang in lak khawh an si.
- Unordered collection - elements kha kan khumh ning tein an um lo. Cucaah element pakhat hi khoika hmun ah dah a um ti kan chim kho lo. Cucaah position based index hmang in lak khawh a si lo.
- Sequence - ordered collection caah hman mi biafang a si.
- Immutable - thlen khawh lo mi collection (unchangeable).
- Mutable - thlen khawh mi collection (changeable).
Atu ah cun kan hmuh ciami types pawl hi zeibantuk sining dah an ngeih ti zoh hna usih:
- String - ordered collection, immutable, iterable.
- List - ordered collection, mutable, iterable.
- Tuple - ordered collection, immutable, iterable.
- Set - unordered collection, mutable, iterable.
- Dictionary - unordered collection, mutable, iterable.
3.5.2 Comments Le Indentation¶
Comments cu # in an i thawk.
# calculate gross salary (gross salary tuaknak)
gs = bs + da + hra + ca
si = p * n * r / 100 # calculate simple interest (simple interest tuaknak)
Catlang tampi a um mi comments (Multi-line comments) pawl cu ''' (triple single quotes) asiloah """ (triple double quotes) chung ah ṭial a hau.
''' Additional program: Calculate bonus to be paid
URL: [https://github.com/rose1996iv/PythonWithJoe](https://github.com/rose1996iv/PythonWithJoe) ([https://github.com/rose1996iv/PythonWithJoe](https://github.com/rose1996iv/PythonWithJoe))
Author: Joseph, Date: 7 Dec 2025 '''
Indentation (catlang hram ṭhawn) hi a biapi tuk! Na duh poh in hmang hlah. A tanglei code nih 'Unexpected indent' error a chuahter lai.
a = 20
b = 45 # Indentation a herh lo nak hmun ah tuah a si caah Error a piah lai
Multi-lining (Catlang Tampi In Ṭial)
Statements an sau tuk a si ahcun, catlang tampi ah ṭhen in ṭial khawh an si. A tawpnak catlang dah ti lo, a dang catlang donghnak paoh ah \ (backslash) chiah a hau.
total = physics + chemistry + maths + \
english + myanmar + history + \
geography + civics
[ ], { }, asiloah ( ) chung ah statements kha catlang tampi (multi-line) in ṭial a si tik ah \ (backslash) hman a hau lo.
3.6 Classes Le Objects¶
Python ah type paoh cu class an si. Cucaah int, float, complex, bool, str, list, tuple, set, dict pawl hi classes an si dih. Hi hna cu hman ding in a um cia mi (ready-made) classes an si. Python nih kanmah tein class ser (user-defined classes) zong a kan onh, hihi Chapter 18 ah kan hmuh te lai.
Object cu class in ser a si. Class nih thil pahnih a fianter — cu class in ser mi object cu zeidah a lawh lai (a sining) le cu object laknak le tawlrelnak caah hman khawh mi methods (functions) pawl an si.
Class pakhat in objects tampi ser khawh a si. Class in object ser a si tik ah, class i instance ser a si tiah chim a si.
Class nih min a ngei, asinain objects nih min an ngei lo. Objects nih min an ngeih lo caah, memory chung i an umnak addresses (hmun) hmang in auh asiloah hngalh an si.
A cunglei chim mi dihlak hi a tanglei program hmang hian hneksak/hmuh khawh a si. A sullam ṭha tein hngalh ding in Observation (Hmuhning) kha zoh.
a = 30
b = 'Good'
print(a, b) # 30 Good tiah a print
print(type(a), type(b)) # <class 'int'> <class 'str'> tiah a print
print(id(a), id(b)) # 1356658640 33720000 (Memory address pawl) tiah a print
print(isinstance(a, int), isinstance(b, str)) # True True tiah a print
3.7 Python Object Reference Visualization (Python Object Pawl Hmuhning)¶
Python ah variables nih memory chung i objects an hngaih/lak ning hngalh hi a biapi tuk.
Key Concept (A Biapi Mi):
- Python ah cun, variables cu memory chung i a um mi objects a kawhhmuhtu references (asiloah pointers) an si. Values (a man) kha anmah chung ah an chiah lo, value umnak memory location (hmun) tu kha an kawk.
Memory Reference Breakdown¶
A tanglei table nih diagram chung i references pawl kha a tial:
| Variable Name | Reference ID (Address) | Points To (Object Type) | Object Value | Object Memory Address |
|---|---|---|---|---|
a |
1356658640 |
int object | 30 |
1356658640 |
b |
33720000 |
str object | Good |
33720000 |
Observation (Hmuhning):
- Variable
anih reference ID1356658640a ngei, cucu Integer Object30i a address he aa khat. - Variable
bnih reference ID33720000a ngei, cucu String Object'Good'i a address he aa khat.
Hi program chung ah objects pahnih kan ser — pakhat cu ready-made class a simi int in le a dang pakhat cu ready-made class a simi str in kan ser.
int type object nih 30 a ngei, cun str type object nih 'Good' a ngei.
Object pahnih hna hi min an ngei lo. Memory chung i an addresses 1356658640 le 33720000 kha a le b chung ah chiah an si.
Hi addresses pawl cu built-in function a simi id( ) hmang in hmuh khawh an si. Program na execute (tuahter) tik ah addresses aa dang na hmuh kho men (computer aa dan ah aa dang kho).
a le b nih addresses an ngeih caah, cu addresses ah a um mi objects kha an refer (kawk/hngaih) tiah chim a si. A fawi nak in chim ahcun objects a kawktu pointers an si.
a le b nih an refer mi objects i an type kha built-in function a simi type( ) hmang in hmuh khawh a si.
a hi class int i instance a si le si lo kha built-in function a simi isinstance( ) hmang in chek khawh a si.
Multiple Objects
A tanglei program hi zoh hmanh:
a = 3
b = 3
print(id(a), id(b)) # 1356658640 1356658640 tiah a print (an id aa khat)
print(a is b) # True tiah a print (object khat an si caah)
a = 30 # atu ah cun a nih object dang a refer cang
print(id(a)) # 1356659072 (address thar) tiah a print
int object pahnih kan ser maw? A si lo. int object chung i um mi value (3) aa khat mi a si caah, int object 1 lawng ser a si. a le b nih int object a um cia mi kha an hngaih/kawk veve. Cucaah id(a) le id(b) nih address aa khat an chuahnak a si.
Hihi is operator hmang in hneksak khawh a si. a le b nih object khat an hngaih caah True a chuah.
a chung ah value thar chiah kan i zuam tik ah, value aa dang (30) a si caah int object thar ser a si. Atu ah cun a nih int object thar kha a hngaih cang, asinain b nih cun int object value 3 kha a hngaih rih ko.
a nih value 3 a ngei mi int object a hngaih tiah chim nak in, a cu int object a si, asiloah 3 cu a ah assigned kan tuah tiah chim a si tawn.
Programmers tampi nih a le b cu int variables an si tiah an zumh, asinain atu ah cun a si lo ti kan hngalh cang.
Problem 3.1¶
Integer types le operators hman ning hmuhsaknak.
Program
Tips
- ¾ nih 0 a chuah lo (Python 3 ah cun 0.75 a chuah, a tling lo mi nambar zong a tuak khawh).
- Catlang khat chung ah statements tampi an um ahcun ; (semicolon) hman in ṭhen ding a si.
- print(w, x, y) nih values pawl kha space (karkhat) in ṭhen in a print/langhter.
Problem 3.2¶
float, complex le bool types hman ning le cu hna he hman khawh mi operators hmuhsaknak.
Program
# use of float (float hman ning)
i = 3.5
j = 1.2
print(i % j) # 1.1 a chuah (approx)
# use of complex (complex number hman ning)
a = 1 + 2j
b = 3 *(1 + 2j)
c = a * b
print(a)
print(b)
print(c)
print(a.real) # a i a real part (1.0)
print(a.imag) # a i a imaginary part (2.0)
print(a.conjugate( )) # a i a conjugate (1-2j)
print(a)
# use of bool (boolean hman ning)
x = True
y = 3 > 4
print(x) # True
print(y) # False

Tips
- % (Modulus operator) hi floats cung zong ah a ṭuan kho.
- Complex number pakhat in real le imag part kha lak khawh an si.
- Condition (sining) pakhat chek a si tik ah True asiloah False in thlen a si.
Problem 3.3¶
Number type pakhat in a dang ah thlen ning hmuhsaknak.
Program
# convert to int (int ah thlen)
print(int(3.14)) # float in int ah (point hnu a hlonh)
a = int('485') # numeric string in int ah
b = int('768') # numeric string in int ah
c = a + b
print(c)
print(int('1011', 2)) # binary in decimal int ah thlen
print(int('341', 8)) # octal in decimal int ah thlen
print(int('21', 16)) # hex in decimal int ah thlen
# convert to float (float ah thlen)
print(float(35)) # int in float ah
i = float('4.85') # numeric string in float ah
j = float('7.68') # numeric string in float ah
k = i + j
print(k)
# convert to complex (complex ah thlen)
print(complex(35)) # int in complex ah
x = complex(4.85, 1.1) # numeric string in complex ah
y = complex(7.68, 2.1) # numeric string in complex ah
z = x + y
print(z)
# convert to bool (bool ah thlen)
print(bool(35)) # True (0 a si lo mi paoh True an si)
print(bool(1.2)) # True
print(int(True)) # 1
print(int(False)) # 0
Tips
- Binary numeric string, octal numeric string asiloah hexadecimal numeric string pawl kha a he aa khat mi decimal integer ah thlen khawh a si. Hi thil hi float caah tuah khawh a si lo.
- complex ah thlen tik ah argument pakhat lawng hman a si ahcun, imaginary part cu
0ah chiah a si. - Zero a si lo mi nambar (int asiloah float) paoh cu True tiah lak a si.
0cu False tiah lak a si.
Problem 3.4¶
Built-in mathematical functions (A chung um cia mi mathematical functions) hman ning hmuhsaknak program.
Program
# built-in math functions (math functions hman ning)
print(abs(-25)) # 25 (Negative kha positive ah a thlen/Absolute value)
print(pow(2, 4)) # 16 (2 a voi 4 nak)
print(min(10, 20, 30, 40, 50)) # 10 (A hme bik)
print(max(10, 20, 30, 40, 50)) # 50 (A ngan bik)
print(divmod(17, 3)) # (5, 2) (Quotient 5 le Remainder 2 kha tuple in a chuah)
print(bin(64), oct(64), hex(64)) # Binary, Octal, Hexadecimal ah a thlen hna
print(round(2.567), round(2.5678, 2)) # 3 (A tling ah round a tuah), 2.57 (Point hnu 2 tiang round a tuah)
Tips
- divmod(a, b) nih a kop in (a // b, a % b) a chuah.
- bin( ), oct( ), hex( ) nih binary, octal le hexadecimal he aa khat mi values an chuah.
- round(x) nih decimal point hnu ah 0 places (zeihmanh a um lo) tiang round tuah ding a si tiah a laak.
Problem 3.5¶
Math module chung i functions hmang in program ṭial ning.
Program
# mathematical functions from math module (math module chung i mathematical functions)
import math
x = 1.5357
print ( math.pi, math.e) # pi le e i an man pawl
print(math.sqrt( x)) # x i a square root
print(math.factorial(6)) # 6 i a factorial
print(math.fabs(x)) # x i a absolute value (float in)
print(math.log(x)) # x i a natural log
print(math.log10(x)) # x i a base-10 logarithm
print(math.exp(x)) # e a voi x nak (e raised to power x)
print(math.trunc(x)) # Integer ah thlen (point hnu hlonh)
print(math.floor(x)) # A niam deuh mi integer ah round (1)
print(math.ceil(x)) # A ngan deuh mi integer ah round (2)
print(math.trunc(-x)) # Integer ah thlen (-1)
print(math.floor(-x)) # A niam deuh mi integer ah round (-2)
print(math.ceil(-x)) # A ngan deuh mi integer ah round (-1)
print(math.modf(x)) # Fractional part le Integer part ṭhen in tuple in a chuah
Output
Tips
- floor( ) nih negative infinity lei (a niam lei) ah a round, ceil( ) nih positive infinity lei (a san lei) ah a round, trunc( ) nih 0 lei ah a round (a niam lei asiloah a san lei siseh 0 umnak lei hoih in).
- Positive numbers caah cun trunc( ) cu floor( ) he an i lo.
- Negative numbers caah cun trunc( ) cu ceil( ) he an i lo.
- modf( ) nih nambar kop
(f, i)a chuah, cu tik ahx = f + ia si i0 <= f < 1a si.
Problem 3.6¶
Float le integer random numbers (nambar can-u-nan) sernak program ṭial tuah.
Program
# random number operations using random module (random module hman ning)
import random
import datetime
# datetime.time() hmang in seed tuah
# (Note: A ṭha deuh mi cu datetime.datetime.now() hman asiloah a lawng in chiah a si)
random.seed(datetime.time( ))
print(random.random( )) # 0.0 le 1.0 karlak ah random float a chuah
print(random.random( )) # 0.0 le 1.0 karlak ah random float a chuah
print(random.randint(10, 100)) # 10 le 100 karlak ah random integer a chuah
Tips
- seed( ) hi random number generator hram thoknak (initialize) caah hman a si.
- random.random( ) nih 0.0 in 1.0 karlak ah a um mi float value a chuah.
- random.randint(a, b) nih a le b karlak ah a um mi integer value a chuah (a le b zong aa tel).
Tips
- random module kha import tuah a hau.
- Random number generation logic kha atu lio caan (current time) he seed kan tuah ahcun, program kan execute (tuahter) fatin random numbers aa dang mi kan hmuh lai.
- random.seed( ) kha parameter tel lo in kan hman ahcun amah tein current time kha seed caah a hman.
Problem 3.7¶
A tanglei hna hi string, list, tuple, set asiloah dictionary an si le si lo zeitin dah na hngalh/thleidan lai?
{10, 20, 30.5}
[1, 2, 3.14, 'Nagpur']
{12 : 'Simple', 43 : 'Complicated', 13 : 'Complex'}
"Check it out!"
3 + 2j
Program
Tips
- type( ) cu built-in function a si i, zeibantuk data (built-in, container asiloah user-defined) paoh i a type (a phun) kha a hngalh/thleidan khawh.
Exercises¶
[A] A tanglei biahalnak hna hi phi tuah:¶
- a. Variable
alebi an values (man) kha thlen (swap) nak program ṭial tuah. Variable pathumnak hman a ngah lo.alebcung ah arithmetic (tuaknak) tuah a ngah lo. - b.
mathmodule chung i a um mi trigonometric functions hman ning hmuhsaknak program ṭial tuah. - c. 10 le 50 karlak ah random numbers (nambar can-u-nan) 5 sernak program ṭial tuah. Seed value ah 6 hmang tuah. Cun, program na execute (tuahter) fatin seed value aa thlen nakhnga time (caan) he pehtlai in tuah tuah?
- d.
trunc( ),floor( )leceil( )hna i an i dannak hngalh ding ah-2.8,-0.5,0.2,1.5le2.9pawl hmang in program ṭial tuah. - e. City (Khuapi) pakhat i a lum-sik (temperature) kha Fahrenheit in chiah law (suum law), cucu Centigrade ah thlen nak program ṭial tuah. An pahnih in print (langhter) tuah.
- f. Triangle (Tukum) pakhat i a sir (sides)
a,b,cngeih a si. A kil (angles) pathum tuak nak program ṭial tuah, a phi cu a niam bik integer (next integer) ah round tuah. A tanglei formulae hi hmang:
[B] A tanglei rian pawl hi zeitin dah na tuah hna lai:¶
- a.
2 + 3ji a imaginary part kha print tuah. - b.
4 + 2ji a conjugate kha la/chuah. - c. Binary
1100001110he aa khat mi decimal kha print tuah. - d. Float value
4.33kha numeric string ah thlen. - e.
29kha5in cheu tik i a chuak mi integer quotient (a cheu tu) le remainder (a taang mi) kha lak ding. - f. Decimal
34567he aa khat mi hexadecimal kha lak ding. - g.
45.6782kha decimal place pahnihnak tiang round-off tuah. - h.
3.556chung in4lak ding. - i.
16.7844chung in17lak ding. - j.
3.45kha1.22in cheu tik i a remainder (a taang mi) lak ding.
[C] A tanglei pawl lak ah a khoi mi hi dah variable min caah hman a ngah lo (invalid), cun zeiruang ah dah?¶
| Column 1 | Column 2 | Column 3 | Column 4 |
|---|---|---|---|
| BASICSALARY | _basic | basic-hra | #MEAN |
| group. | 422 | pop in 2020 | over |
| timemindovermatter | SINGLE | hELLO | queue. |
| team'svictory | Plot#3 | 2015_DDay |
[D] A tanglei expressions pawl hi tuak hna:¶
- a.
2 ** 6 // 8 % 2 - b.
9 ** 2 // 5 - 3 - c.
10 + 6 - 2 % 3 + 7 - 2 - d.
5 % 10 + 10 - 23 * 4 // 3 - e.
5 + 5 // 5 - 5 * 5 ** 5 % 5 - f.
7 % 7 + 7 // 7 - 7 * 7
[E] A tanglei expressions pawl hi tuak hna:¶
- a.
min(2, 6, 8, 5) - b.
bin(46) - c.
round(10.544336, 2) - d.
math.hypot(6, 8) - e.
math.modf(3.1415)
[F] A tanglei pawl hi a kop in thleidan/peh hna:¶
| Section A | Section B |
|---|---|
| a. complex | 1. \ |
| b. Escape special character (Special character hrialnak) | 2. Container type |
| c. Tuple | 3. Basic type |
| d. Natural logarithm | 4. log( ) |
| e. Common logarithm | 5. log10( ) |
Chapter 4 Strings¶
Keynote¶
4.1 Strings cu zeidah an si?¶
Python string kan ti mi cu Unicode characters pawl collection an si (cafa a bu in an um tinak a si).
Python strings pawl cu single (' '), double (" "), asiloah triple quotes (''' ''') chung ah kan khumh khawh hna.
Special Characters pawl Hmannak
Python string chungah ', ", asiloah \ tibantuk special characters (cafa hleice) pawl a um ahcun, lam phun hnih in kan tuah khawh:
Escape Sequence: Cafa hmaiah \ (backslash) chiah in escape kan tuah (kham/thianh) a hau.
Raw String: String hmailam te ah r kan chiah ahcun raw string (string a si ning tein lak) a si lai.
# (a) Quotes pawl thianh dingah Backslash hman
msg_escape = 'He said, \'Python With Joe.\''
print(msg_escape)
# Output: He said, 'Python With Joe.'
# (b) Raw String (r prefix) hman
# Backslash tampi a um tikah hman a ṭha (Tahchunhnak: File paths asiloah regex)
path = r"C:\Users\Name\Documents"
print(path)
# Output: C:\Users\Name\Documents
Catlang Tampi Ummi String (Multiline Strings)
Python ah string pakhat kha ca-tlang (line) tampi in ṭial na duh ahcun lam phun 3 a um:
- Backslash
(\)Hman: Ca-tlang donghnak kip ah\na chiah lai (a donghnak taktak dah ti lo). - Triple Quotes:
"""..."""asiloah'''...'''chungah na khumh lai. - Parentheses
(Kulhnak):()chung ah string na ṭial ahcun amah tein a fawnh (concatenate) chih lai.
# Method 1: Backslash (\) hman
# Note: Backslash hnu ah 'space' na chiah lai lo
msg1 = 'one msg ' \
'another msg'
# Output: 'one msg another msg' (Ca-tlang khat ah a fonh)
# Method 2: Triple Quotes
# Mah hi nih cun ca-tluan thar (newline) a um ning tein a kilven
msg2 = """one msg
another msg"""
# Output:
# one msg
# another msg
# Method 3: Parentheses () hman
# Note: Parentheses hnu ah 'space' na chiah lai lo
msg3 = ('one msg '
'another msg')
# Output: 'one msg another msg' (Ca-tlang khat ah a fonh)
4.2 String Chung Cafa (asiloah Cafang) Laknak (Accessing String Elements)¶
String elements (cafa pawl) cu index value hmang in kan lak khawh hna. Index cu 0 in a thawk (1 in a thawk lo).
Negative index (nambar ṭil/minus) zong hman khawh a si. Cafa a donghnak bik kha index -1 in kan rel.
4.2.1 Index Umning Hmuhternak¶
Positive (0 in kal) le Negative (-1 in kir) index an i pehtlaih ning cu a tanglei "PYTHON" tahchunhnak ah kan hmuh khawh:
| Character | P | Y | T | H | O | N |
|---|---|---|---|---|---|---|
| Positive Index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative Index | -6 | -5 | -4 | -3 | -2 | -1 |
s = "PYTHON"
# Cafa hmasa bik laknak (First character)
print(s[0]) # Output: P (0 hi a hmasa bik a si)
print(s[-6]) # Output: P (-6 hi hnu lei in rel tikah a donghnak a si)
# Cafa donghnak bik laknak (Last character)
print(s[5]) # Output: N
print(s[-1]) # Output: N (Hnu lei in pakhatnak/Last character)
4.2.2 String Slicing (A Cheu Laknak)¶
String pakhat chung in a cheu (sub-string) lak na duh tikah [start : end] (a thawk : a dongh) ti in kan ṭial.
Hman Tawnmi Slicing Phatun Pawl
| Syntax | Description |
|---|---|
s[start : end] |
start in end - 1 tiang a lak. |
s[start :] |
start in a dongh tiang a lak. |
s[: end] |
A hram in end - 1 tiang a lak. |
s[-start :] |
-start (hnu lei) in a dongh tiang a lak. |
s[: -end] |
A hram in -end - 1 tiang a lak. |
Index A Pel Sual Tikah (Handling Out-of-Bounds Indices)
Python i Slicing (a cheu lak) kan hman tikah a ṭhatnak pakhat cu, index nambar kha string saunak nak in a ngan deuh na ṭial sual zong ah Error a piah lo.
Slicing le Direct Indexing Dannak
- Direct Indexing (msg[100]): Index nambar kha a lian tuk ahcun Error a chuak (Program a nuar lai).
- Slicing (msg[3:100]): Mah hi cu a him (handled elegantly). String a dongh tiang lawng kha a lak lai i, program a nuar lai lo.
msg = 'Rafting'
# 1. Slicing hmang in index ngan deuh tial (A him)
# Index 100 hi 'Rafting' chung ah a um lo nain, a dongh tiang a lak ko.
print(msg[3:100])
# Output: 'ting'
# 2. Direct indexing hmang in index ngan deuh tial (A him lo)
# Mah hi cu Error a piah lai.
# print(msg[100])
# Error: IndexError: string index out of range
4.3 String Sining Pawl (Properties)¶
Python strings cu immutable an si — ser dih hnu ah thlen khawh an si ti lo.
- Immutability (Thlen khawh lo): Python strings cu immutable an si—ser dih hnu ah a umning tein thlen (change in place) khawh a si lo.
- Concatenation (Fawnh): String pawl cu
+hmang in fonh khawh an si. - Replication (Karhter): String pawl cu
*hmang in a let in karhter (repeat) khawh an si. - Membership (A chung um zoh): String chungah cafang/biafang a um le um lo zoh dingah in hman khawh a si.
String Hmanning A Hrampi (Basic String Operations)
Python nih string pawl fawi tein hman khawhnak dingah operators ṭha ṭha a kan pek.
1.Concatenation (+) - Fawnhnak String pawl cu + operator hmang in pakhat le pakhat fonh (concatenated) khawh an si.
msg1 = "Hello "
msg2 = "World"
msg3 = msg1 + msg2
print(msg3)
# Output: Hello World
2.Replication (*) - Karhter
String pawl cu * operator hmang in a let in karhter (replicated/repeated) khawh an si. Mah hi ca-tlang ṭhennak (separator lines) ser tikah a ṭha tuk le hman a nuam tuk.
Hman Ning Ralrin Ding (Syntax Note)
String karhter na duh tikah comma , hmang lo in asterisk * na hman a hau.
print('-', 50)tiah na ṭial ahcun dash pakhat le nambar 50 kha a ṭial sawhsawh lai (e.g.,- 50).print('-' * 50)tiah na ṭial ahcun dash kha voi 50 a ṭial lai.
# Dash (-) voi 50 a tial lai
print('-' * 50)
# Output: `--------------------------------------------------`
3.Membership Testing (in) - A chung um zoh
String chungah cafang/biafang a um le um lo zoh dingah in hman khawh a si.
s = "Hello World"
print('World' in s) # Output: True
print('Python' in s) # Output: False
String Length (len())
len() function hi string pakhat chungah cafang (characters) zeizat dah a um ti zohnak ah hman a si.
s = "Hello World"
print(len(s)) # Output: 11
# "Hello" (5) + Space (1) + "World" (5) = 11
String Indexing
String indexing hmang in string chung i cafang pakhat cio kha an umnak hmun (index) hmang in lak khawh a si.
s = "Hello World"
print(s[0]) # Output: H (A hmasa bik)
print(s[-1]) # Output: d (A donghnak bik)
String Slicing
String slicing hmang in string chung i a cheu (portion) kha index hramthawk le a donghnak (range) pek in lak khawh a si.
s = "Hello World"
print(s[0:5]) # Output: Hello (0 in 4 tiang)
print(s[-6:-1]) # Output: World (Hnu lei in chut tikah)
# Note: s[-6:] ti deuh ding a si, '-1' tiang lawng si lo in.
Modern String Formatting (f-strings)
A Thar Hmanmi (Python 3.6+)
- Hlan Hmaning: String le variable (thilri) fonh tikah + (Concatenation) asiloah
.format()kan hmang tawn. - Tu Chan Hmaning:
f-strings(Formatted String Literals) hi hman a si deuh cang. A ruang cu:- Rel a fawi deuh (More readable).
- Riantuan a rang deuh (Faster).
name = "Joseph"
age = 25
# Hlan Hmaning (Concatenation)
# Nambar '25' kha string 'str(25)' ah thlen a hau hmasa.
msg_old = "My name is " + name + " and I am " + str(age) + " years old."
# Tu Chan Hmaning (f-string)
# Hmaiah 'f' chiah law, variable kha {} chungah khumh ko.
msg_new = f"My name is {name} and I am {age} years old."
print(msg_new)
# Output: My name is Joseph and I am 25 years old.
4.5 Function le Method Hmang in String Tuah-hman-nak¶
Python ah String kan hman tikah a chungum zohfel, thianh, le thlen dingah a a thar in hman khawhmi Functions le Methods tampi a um.
1. Built-in Functions (Amah a um cia mi)
Hihna hi string he lawng siloin thil dang (List, Tuple) he zong hman khawh an si.
len(s): String saunak (cafa zeizat dah a um) a piah.
min(s): Unicode value niam bik (a hme bik) a piah. (Tahchunhnak: 'a' le 'b' ah 'a' a hme deuh).
max(s): Unicode value sang bik (a ngan bik) a piah.
2. Content Test Methods (A Chung Ummi Zohfelnak)
Hihna hi "Mah string cu hitin a si maw?" tiah halnak an si. True (A hmaan) asiloah False (A hmaan lo) in an leh lai.
| Method | Sullam/Riantuan Ning |
|---|---|
isalpha() |
Cafa (Alphabets) lawng an si maw? (Nambar/Space a um lai lo). |
isdigit() |
Nambar (Digits) lawng an si maw? |
isalnum() |
Cafa asiloah Nambar (Alphanumeric) lawng an si maw? (Space/Special char a um lai lo). |
islower() |
Ca-hme (lowercase) lawng an si maw? |
isupper() |
Ca-ngan (uppercase) lawng an si maw? |
startswith(x) |
x in a thawk maw? (Tahchunhnak: "Mr." in a thawk maw?) |
endswith(x) |
x in a dong maw? (Tahchunhnak: ".pdf" in a dong maw?) |
3. Search and Replace (Kawl le Thlen)
find(sub): String chungah kan duhmi biafang (substring) a umnak index a kawl. A hmuh lo ahcun -1 a piah.
replace(old, new): A hlun kha a thar in a thleng.
msg = "I love Java"
print(msg.find("Java")) # Output: 7 (Index 7 ah a um)
print(msg.replace("Java", "Python")) # Output: I love Python
4. Trimming & Splitting (Thianh le Then)
strip(): Hmai le hnu i Space (awl) a ummi a thianh (Hmai lawng thianh duh ah lstrip, hnu lawng duh ah rstrip).
split(sep): String kha biafang (list) ah a ṭhen (Tahchunhnak: Biafang pakhat le pakhat kar ah).
join(iterable): List chung i biafang pawl kha string pakhat ah a fonh ṭhan.
s = "Python-is-Fun"
# 1. Split (Then)
lst = s.split("-")
print(lst) # Output: ['Python', 'is', 'Fun']
# 2. Join (Fonh)
new_s = " ".join(lst)
print(new_s) # Output: Python is Fun
Modern Python: removing prefix/suffix (Python 3.9+)
strip()method hi hman a fawi nain, cafang pakhat cio a zoh caah a him lo kho men. Cucaah Python 3.9 in method thar an hun chuah.removeprefix(): A hmaita biafang kha a thianh.removesuffix(): A donghta biafang kha a thianh.
filename = "report.pdf"
print(filename.removesuffix(".pdf")) # Output: report
print(filename.removeprefix("report")) # Output: .pdf
4.6 String Thlennak le Tah-thimnak (String Conversions & Comparison)¶
Python ah string pakhat le pakhat thlen (convert) ning le tah-thim (compare) ning hi a biapi ngaimi an si.
1.Case Conversion (Ca Ngan le Ca Hme Thlennak)Ca ṭial ning (Case) thlennak dingah a tanglei method pawl kan hmang kho:
-
upper(): Ca ngan in a thleng dih (e.g., 'abc' \(\rightarrow\) 'ABC'). -
lower(): Ca hme in a thleng dih (e.g., 'ABC' \(\rightarrow\) 'abc'). -
capitalize(): String a hramthawk cafang pakhat te lawng ca ngan in a thleng. -
title(): Biafang kip a hramthawk cafang paoh ca ngan in a thleng. -
swapcase(): Ca ngan a si mi paoh ca hme in, ca hme a si mi paoh ca ngan in a thleng.
s = "Hello World"
print(s.upper()) # Output: HELLO WORLD
print(s.lower()) # Output: hello world
print(s.capitalize()) # Output: Hello world
print(s.title()) # Output: Hello World
print(s.swapcase()) # Output: hELLO wORLD
2. Type Conversion (Data Phun Dang Ah Thlennak)
String le nambar pawl hi pakhat le pakhat kan thlen (convert) a hau tawn.
str(x): Zei data paoh String ah a thleng.int(s): String (nambar he aa lomi) kha Integer (Nambar tling) ah a thleng.float(s): String kha Float (Decimal nambar) ah a thleng.
num = 10
# print("Age: " + num) <-- Error a chuak lai (String le Int fonh khawh a si lo)
# A hmaan mi (Int kha String ah thlen hmasa)
print("Age: " + str(num)) # Output: Age: 10
3. ASCII / Unicode (Computer Hngalhning)
Computer nih cun cafang (A, B, C) hi a hngal lo, nambar in a hngalh dih. Cu nambar pawl cu ASCII asiloah Unicode kan ti.
ord(c): Cafang pakhat a Unicode nambar a kawl.chr(n): Nambar pakhat a Cafang a kawl.
print(ord('A')) # Output: 65 ('A' hi computer nih 65 in a hngalh)
print(chr(65)) # Output: A
4. Comparison (Tah-thimnak)
String pahnih kan tah-thim tikah Lexicographically (Dictionary umning) in a zoh.
Dictionary Order: A hmasa deuh mi cu a hme deuh, a hnu deuh mi cu a ngan deuh.
Unicode Value: Ca ngan ('A'=65) hi Ca hme ('a'=97) nak in a nambar a niam deuh/hme deuh.
print('Apple' < 'Banana') # Output: True ('A' cu 'B' hlan ah a um caah a hme deuh)
print('apple' > 'Apple') # Output: True ('a' (97) cu 'A' (65) nak in a ngan deuh)
Solved Problems¶
Problem 4.1¶
Question: String sawhsawh le ca-tluan tampi (multi-line) ummi string serning piah law, cun string cu ser dih hnu ah thlen khawh a si maw si lo (immutability) timi zong langhter. Cun len(), min() le max() tibantuk built-in function pawl string he hmanning zong piah chih.
Program
# simple strings
msg1 = 'Hoopla'
print(msg1)
# strings with special characters
msg2 = 'He said, \'Python With Joe\'.'
file1 = 'C:\\temp\\newfile'
file2 = r'C:\temp\newfile' # raw string - prepend r
print(msg2)
print(file1)
print(file2)
# multiline strings
# whitespace at beginning of second line becomes part of string
msg3 = 'What is this life if full of care...\
We have no time to stand and stare'
# enter at the end of first line becomes part of string
msg4 = """What is this life if full of care...
We have no time to stand and stare"""
# strings are concatenated properly.( ) necessary
msg5 = ('What is this life if full of care...'
'We have no time to stand and stare')
print(msg3)
print(msg4)
print(msg5)
# string replication during printing
msg6 = 'MacLearn!!'
print(msg1 * 3)
# immutability of strings
# Utopia cannot change, msg7 can
msg7 = 'Utopia'
msg8 = 'Today!!!'
msg7 = msg7 + msg8 # concatenation using +
print(msg7)
# use of built-in functions on strings
print(len('Hoopla'))
print(min('Hoopla'))
print(max('Hoopla'))
Output
Hoopla
He said, 'Python With Joe'.
C:\temp\newfile
C:\temp\newfile
What is this life if full of care... We have no time to stand and stare
What is this life if full of care...
We have no time to stand and stare
What is this life if full of care...We have no time to stand and stare
HooplaHooplaHoopla
UtopiaToday!!!
6
H
p
Biapi Theih Ding (Tips)
- Special characters (cafa hleice) pawl kha string chungah chiah na duh ahcun
\(backslash) hmang in escape tuah khawh a si, asiloahrhmang in raw string in tuah khawh a si. - String cu ser dih hnu ah thlen khawh a si lo (immutable), asinain a khumhtu variable tu kha cu thlen khawh a si (thil thar khumh ṭhan khawh a si).
len()nih string chungah cafang zeizat dah a um ti a piah.min()lemax()nih string chung i Unicode value a niam bik le a sang bik cafang an piah.
Problem 4.2¶
Question: String 'Bamboozled' kan pek mi hmang in, a tanglei output pawl hmuh nakhnga Program ṭial tuah. A tanglei output pawl hmuh khawh nakhnga, lam phun dang dang (multiple ways) hmang in tuah khawh asi.
B a
e d
e d
mboozled
mboozled
mboozled
Bamboo
Bamboo
Bamboo
Bamboo
delzoobmaB
Bamboozled
Bmoze
Bbzd
Boe
BamboozledHype!
BambooMonger!
Program
s = 'Bamboozled'
# extract B a
print(s[0], s[1])
print(s[-10], s[-9])
# extract e d
print(s[8], s[9])
print(s[-2], s[-1])
# extract mboozled
print(s[2:10])
print(s[2:])
print(s[-8:])
# extract Bamboo
print(s[0:6])
print(s[:6])
print(s[-10:-4])
print(s[:-4])
# reverse Bamboozled
print(s[::-1])
print(s[0:10:1])
print(s[0:10:2])
print(s[0:10:3])
print(s[0:10:4])
s = s + 'Hype!'
print(s)
s = s[:6] + 'Monger' + s[-1]
print(s)
Biapi Theih Ding (Tips)
- Special characters (cafa hleice) pawl kha string chungah chiah na duh ahcun (backslash) hmang in escape tuah khawh a si, asiloah r hmang in raw string in tuah khawh a si.
- s[4:8] le s[4:8:1] hi an i khat. A ruang cu a hnu bik nambar (step) kha na ṭial lo ahcun 1 (default) in a rel.
- s[4:8:2] kan ti tikah cun cafang pakhat a lak hnu ah kar 2 (2 positions) in a hlan/kal tinak a si.
Problem 4.3¶
Question: A tanglei String pawl chungah hin:
- khoi kaa dah Cafang (Alphabets) lawng a si?
- khoi kaa dah Nambar (Numeric) lawng a si?
- khoi kaa dah Cafang le Nambar (Alphanumeric) an si?
- khoi kaa dah Ca-hme (Lowercase) a si?
- khoi kaa dah Ca-ngan (Uppercase) a si? timi pawl kha kawl hna.
Cun, 'And Quiet Flows The Don' timi string hi 'And' in a thawk (begins) maw, asiloah 'And' in a dong (ends) maw timi zong kawl chih: 'NitiAayog' 'And Quiet Flows The Don' '1234567890' 'Make $1000 a day'
Program
s1 = 'NitiAayog'
s2 = 'And Quiet Flows The Don'
s3 = '1234567890'
s4 = 'Make $1000 a day'
print('s1 = ', s1)
print('s2 = ', s2)
print('s3 = ', s3)
print('s4 = ', s4)
# Content test functions
print('check isalpha on s1, s2')
print(s1.isalpha( ))
print(s2.isalpha( ))
print('check isdigit on s3, s4')
print(s3.isdigit( ))
print(s4.isdigit( ))
print('check isalnum on s1, s2, s3, s4')
print(s1.isalnum( ))
print(s2.isalnum( ))
print(s3.isalnum( ))
print(s4.isalnum( ))
print('check islower on s1, s2')
print(s1.islower( ))
print(s2.islower( ))
print('check isupper on s1, s2')
print(s1.isupper( ))
print(s2.isupper( ))
print('check startswith and endswith on s2')
print(s2.startswith('And'))
print(s2.endswith('And'))
Output
s1 = NitiAayog
s2 = And Quiet Flows The Don
s3 = 1234567890
s4 = Make $1000 a day
check isalpha on s1, s2
True
False
check isdigit on s3, s4
True
False
check isalnum on s1, s2, s3, s4
True
False
True
False
check islower on s1, s2
False
False
check isupper on s1, s2
False
False
check startswith and endswith on s2
True
False
Problem 4.4¶
Question: A tanglei String pawl an pek:
'Bring It On'
' Flanked by spaces on either side '
'C:\Users\Joseph\Documents'
A herhmi string functions pawl hmang in, a tanglei output pawl hmuh khawh nakhnga program ṭial tuah.
Output hmuh dingmi pawl:
BRING IT ON
bring it on
Bring it on
Bring It On
bRING iT oN
6
9
Bring Him On
Flanked by spaces on either side
Flanked by spaces on either side
['C:', 'Users', 'Joseph', 'Documents']
('C:', '\\', 'Users\\Joseph\\Documents')
Program
s1 = 'Bring It On'
# Conversions
print(s1.upper( ))
print(s1.lower( ))
print(s1.capitalize( ))
print(s1.title( ))
print(s1.swapcase( ))
# search and replace
print(s1.find('I'))
print(s1.find('On'))
print(s1.replace('It', 'Him'))
# trimming
s2 = ' Flanked by spaces on either side '
print(s2.lstrip( ))
print(s2.rstrip( ))
# splitting
s3 = 'C:\\Users\\Joseph\\Documents'
print(s3.split('\\'))
print(s3.partition('\\'))
Problem 4.5¶
Question: String 'The Terrible Tiger Tore The Towel' chungah hin 'T' cafang a umnak hmun vialte kha kawl hna. Cun 'T' a umnak vialte kha 't' in thleng dih hna.
Program
s = 'The Terrible Tiger Tore The Towel'
pos = s.find('T', 0)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos, s[pos])
pos = s.find('T', pos + 1)
print(pos)
c = s.count('T')
s = s.replace('T', 't', c)
print(s)
Biapi Theih Ding (Tips)
search()voikhatnak kan hman tikah 'T' a hmuh hmasa biknak hmun (position/index) kha a piah. A changtu 'T' pawl kawl ṭhan dingah cun, kawlnak kha pos + 1 in thawk a si.- 'T' kha hmuh a si lo ahcun
search()nih -1 a piah. count()nih string chungah 'T' voi zeizat dah a um (a um zat) kha a piah.replace()kan hman tikah parameter pathumnak (third parameter) kan pekmi nih 'voi zeizat dah thlen ding a si' ti a hmuhter.
Exercise¶
[A] Answer the following questions:
a. String 'Shenanigan' hmang in a tanglei output pawl hmuh khawh nakhnga program ṭial tuah.
b. A tanglei string 'Visit ykanetkar.com for online courses in programming' hi 'Visit Ykanetkar.com For Online Courses In Programming' ah thleng nakhnga program ṭial tuah.
c. A tanglei string 'Light travels faster than sound. This is why some people appear bright until you hear them speak.' hi 'LIGHT travels faster than SOUND. This is why some people appear bright until you hear them speak.' ah thleng nakhnga program ṭial tuah.
d. A tanglei program i a phichuak (output) hi zei dah a si lai?
s = 'HumptyDumpty'
print('s = ', s)
print(s.isalpha( ))
print(s.isdigit( ))
print(s.isalnum( ))
print(s.islower( ))
print(s.isupper( ))
print(s.startswith('Hump'))
print(s.endswith('Dump'))
f. A tanglei string chung i biafang pakhat cio he riantuan kan duh ahcun, zeitinda kan ṭhen (separate) hna lai:
'The difference between stupidity and genius is that genius has its limits'
g. A tanglei string He said, "Python With Joe" khumh (store) ning lam phun hnih langhter tuah.
h. A tanglei code (code snippet) i a phichuak (output) hi zei dah a si lai?
i. A tanglei code (code snippet) i a phichuak (output) hi zei dah a si lai?j. Python ah String cu iterable (pakhat hnu pakhat kal khawh), sliceable (ah cheu khawh), le immutable (ser hnu thlen khawh lo) an si. (A hmaan / A hmaan lo)
k. String 'ThreadProperties' chung in 'TraPoete' kha zeitindah na lak (extract) lai?
l. String ' Flanked by spaces on either side ' i a sir tuak (a hmai le a hnu) i a ummi space (awl) pawl kha zeitindah na thianh (eliminate) hna lai?
m. A tanglei code (code snippet) i a phichuak (output) hi zei dah a si lai?
n. A tanglei code chungah hin ch ah zeidah khumh a si lai?
msg = 'Keep yourself warm':
| Option A | Description (Fianternak) | Option B | Match |
|---|---|---|---|
a. msg.partition(' ') |
Space hmasa bik a umnak ah a cheu i 3-tuple in a chuah. | ('Keep', ' ', 'yourself warm') | 8 |
b. msg.split(' ') |
Space a umnak paoh ah cheu in list in a chuah. | ['Keep', 'yourself', 'warm'] | 7 |
c. msg.startswith('Keep') |
String cu "Keep" in a thawk maw ti zohfelnak. | True | 5 |
d. msg.endswith('Keep') |
String cu "Keep" in a dong maw ti zohfelnak. | False | 6 |
e. msg.swapcase() |
Ca ngan in Ca hme ah, Ca hme in Ca ngan ah thlennak. | kEEP YOURSELF WARM | 2 |
f. msg.capitalize() |
Cafa hmasa bik Ca ngan in, a dang vialte Ca hme in thlennak. | Keep yourself warm | 3 |
g. msg.count('e') |
'e' voi zeizat dah a um ti relnak. | 3 | 4 |
h. len(msg) |
String i a saunak dihlak (length) piah/chuahnak. | 18 | 1 |
i. msg[0] |
Cafa hmasa bik laknak. | K | 11 |
j. msg[-1] |
Cafa hnu bik laknak. | m | 13 |
k. msg[1:1:1] |
Start le End index aa khat ahcun zeihmanh a chuak lo (empty). | empty string | 12 |
l. msg[-1:3] |
Step a positive (+1) si lio ah Orh lei in Keh lei lak khawh a si lo. | empty string | 15 |
m. msg[:-3] |
A hram in a donghnak cafa 3 chiah ta in laknak. | Keep yourself w | 9 |
n. msg[-3:] |
A donghnak cafa 3 laknak. | arm | 14 |
o. msg[0:-2] |
A hram in a donghnak cafa 2 chiah ta in laknak. | Keep yourself wa | 10 |
Chapter 5 Decision Control Instructions¶
Keynote¶
5.1 Decision Control Instructions Cu Zei Dah An Si?¶
Atu tiang kan program ṭialmi chung i bia (statements) paoh cu a chang chang in (sequentially) asiloah pakhat hnu pakhat in tuah (executed) an si. Program chung i rian ṭuan ning a kal ning (sequence) kha a tanglei pawl hmang in thlen khawh a si:
- Decision Control Instruction (Biatluknak Tuahnak Lamhruai)
- Repetition Control Instruction (Tuah Ṭhan Lengmangnak Lamhruai)
Decision Control Instruction
Program chungah biatluknak (decision) tuahnak lam phun thum a um:
if condition : else
if condition1 : elif condition2 : elif condition3 : else :
-
if,else,elifhnu ah colon (:) hi chiah hrimhrim a herh. -
ifblock,elseblock,elifblock chung i bia (statements) paoh cu indented (chung lei ah tawlh) tuah a hau. Indent tuahmi bia/code pawl kha block pakhat in rel an si. -
Indentation cu bia (statements) fawnh/khawmh nak caah hman a si. Indentation caah Space 4 asiloah Tab 1 hman khawh a si. Tab le Space cawh in hman lo ding. Screen ah a hmaan lio bantuk in a lang nain, Error (palhnak) a chuak lai.
-
A cunglei i kan langhtermi a hmasa bik (first form) ah khin, else le elif telh a hau hrimhrim lo (optional an si).
-
A cunglei i kan langhtermi a pahnihnak (second form) ah khin, condition a True (hmaan) ahcun if block chung i bia pawl tuah an si lai. condition a False (hmaan lo) ahcun else block chung i bia pawl tuah an si lai.
-
A cunglei i kan langhtermi a pathumnak (third form) ah khin, condition pakhat a Fail (hmaan lo) ahcun, a changtu elif block chung i condition kha zohfel ṭhan a si. Condition vialte an hmaan lo dih (fail) lawng ah else block kha tuah a si.
-
if-elsestatement pawl hi nested (a chung ah a dang chiah) in tuah khawh an si. Program logic nih a herh ning in a thuk khawh chung thuk in nesting tuah khawh a si.
5.2 Nuances of Conditions¶
Condition cu relational operators <, >, <=, >=, ==, != pawl hmang in ser a si.
10 < 20 # True a chuak (yields True)
'Santosh' < 'Adi' # False a chuak, alphabetical order (ca tlar ning) in a zoh
'gang' < 'God' # False a chuak, Ca hme (lowercase) cu Ca ngan (uppercase) nak in a ngan deuh
a = b cu value pek/chiah (assignment) a si, a == b cu tahchunh (comparison) a si.
A kar (Ranges) asiloah aa khat mi tampi zohfel kha fawi tein/ningcang tein tuah khawh a si.
if a < b < c # b hi a le c kar ah a um maw ti a zoh
if a == b == c # an pathum in an i khat maw ti a zoh
if 10 != 20 != 10 # True a chuak, 10 != 10 cu False a si nain
Fianternak (Note)
- A pathumnak (10 != 20 != 10) hi a lungre a thei kho mi a si. Python nih a zoh ning cu:
- 10 != 20 (10 le 20 an i khat lo) -> True
- 20 != 10 (20 le 10 an i khat lo) -> True
- A hmasa bik 10 le a donghnak 10 kha direct in a tahchunh hna lo, a laifang 20 tu kha a hmai le a hnu he a tahchunh hna. Cucaah True a chuak.
Nambar zero (0) a si lo mi paoh (positive, negative, integer, float) cu True tiah lak a si, cun 0 cu False tiah lak a si.
print(bool(3.14)) # True a chuak (zero a si lo caah)
print(bool(25)) # True a chuak
print(bool(0)) # False a chuak
5.3 Logical Operators¶
Biachahnak (decision) har deuh le thuk deuh tuah kan duh tikah logical operators and, or le not te hi hman khawh an si.
Condition pawl kha and le or hmang in a tanglei bantuk in fonh (combine) khawh an si:
cond1 and cond2
# An pahnih in an hmaan (True) lawng ah True a chuak, a dang paoh ahcun False.
cond1 or cond2
# Pakhatkhat a hmaan (True) ahcun True a chuak, an pahnih in an hmaan lo lawng ah False.
A taktak ti ahcun, and/or pawl hi conditions he lawng hman ding an si lo. Conditions hmun ah a hmaanmi expression paoh hman khawh an si. Cucaah expressions he kan hman tikah True/False lawng si loin a dang zong kan hmuh khawh men.
and operator nih expressions vialte kha a zohfel (evaluate) hna:
- Expressions vialte an hmaan (
True) ahcun, a hnu bik expression kha a chuah. - Asiloah a hmaan lo (
False) a um ahcun,Falsea si mi hmasa bik kha a chuah.
a = 40
b = 30
x = 75 and a >= 20 and b < 60 and 35 # assigns 35 to x
y = -30 and a >= 20 and b < 15 and 35 # assigns False to y
z = -30 and a >= 20 and 0 and 35 # assigns 0 to z
Fianternak (Note)
-
A tanglei code chungah x, y, le z an value a chuakmi hna hi and operator nih a rianṭuan ning (logic) a si.
-
andoperator nih a zoh ning cu:-
A hmasa bik in a zoh. A hmaan (
True) ahcun a changtu a zoh ṭhan. -
A hmaan lo (
False) a hmuh bak in a tawp, cun kha False value kha a chuah. -
A hmaan lo (
False) a hmuh bak in a tawp, cun kha False value kha a chuah. -
A hmaan lo (
False) a hmuh bak in a tawp, cun kha False value kha a chuah.
-
or operator nih expressions vialte kha a zohfel (evaluate) hna i, a hmaan (True) mi a hmasa bik value kha a chuah. Cutin a si lo i an dihlak in an hmaan lo (False) ahcun, a hmaan lo (False) mi a donghnak bik value kha a chuah.
a = 40
b = 30
x = 75 or a >= 20 or 60 # assigns 75 to x
y = a >= 20 or 75 or 60 # assigns True to y
z = a < 20 or 0 or 35 # assigns 35 to z
Fianternak (Note)
A tawinak in chim ahcun:
andcu False a kawl (False a hmuh le cangka a tawp).orcu True a kawl (True a hmuh le cangka a tawp).
Condition pakhat i a phichuak (result) kha not operator hmang in lethah (negate/reverse) khawh a si.
not operator cu a sullam a let in a tuah:
- True kha False ah a thlen.
- False kha True ah a thlen.
a = not b nih b i a value kha a thleng lo.
Operator pakhat nih operand pakhat lawng a herh ahcun Unary operator tiah auh a si. Pahnih a herh ahcun, Binary operator a si.
not - operand pakhat lawng a herh, cucaah unary operator a si.
+, -, <, >, and, or, etc. - operand pahnih an herh, cucaah binary operators a si.
5.4 Conditional Expressions¶
Python nih biatluknak tuahnak (decision-making) caah hmanrua a dang pakhat a ngeih rih, cucu conditional expression a si.
Conditional expressions tahchunhnak pawl:
age = 15
status = 'minor' if age < 18 else 'adult' # 'minor' ah a chiah
sunny = False
print("Let's go to the", "beach" if sunny else "room")
humidity = 76.8
setting = 25 if humidity > 75 else 28 # 25 ah a chiah
# 'Prim' kha a chiah (assigns Prim)
wt = 55
msg = 'Obese' if wt > 85 else 'Hefty' if wt > 60 else 'Prim'
Fianternak (Note)
- wt > 85 a si maw? A si lo (55 a si caah).
- A changtu else ah a kal: wt > 60 a si maw? A si lo.
- Cucaah a donghnak else i a ummi 'Prim' kha a lak.
5.5 all( ) le any( )¶
and le or logical operators pawl hman can ah, Python chung i a um ciami function all( ) le any( ) te hi hman khawh an si i, cu nih cun anmah he aa lo mi phichuak a ser ve. An hmanning cu a tanglei program ah hin hmuh khawh a si:
a, b, c = 10, 20, 30
# all() = Vialte an hmaan (True) dih lawng ah True a chuak
res = all((a > 5, b > 20, c > 15))
print(res) # False a chuak, a ruang cu condition pahnihnak (b > 20) kha False a si caah
# any() = Pakhatkhat a hmaan (True) ahcun True a chuak
res = any((a > 5, b > 20, c > 15))
print(res) # True a chuak, a ruang cu condition pakhatkhat kha True a si caah
all() le any() hna nih hin parameter (a chung i chiahmi) pakhat lawng an lak, cucu string, list, tuple, set asiloah dictionary an si a hau. A cunglei tahchunhnak ah khan condition 3 a ummi tuple kan pek hna.
-
A chung i chiahmi (argument) kha dictionary a si ahcun, a keys pawl kha an hmaan (True) maw hmaan lo (False) ti a zohfel (a values a zoh lo).
-
any()function nih a chung i ummi element pawl lakah a tlawm bik pakhat a hmaan (True) ahcun True a chuah. -
all()function nih a chung i ummi element vialte/dihlak an hmaan (True) lawng ah True a chuah.
5.6 Input Laknak (Receiving Input)¶
print() function cu screen ah value chuahnak/langhternak caah hman a si bantuk in, input() function (a um ciami) hi keyboard in input value laknak caah hman a si.
input() function nih string (ca) in a chuah/returns. Tahchunhnak ah, 23 kan ṭial ahcun '23' (ca bantuk) in a chuah. Cucaah kan nambar ṭialmi cungah khan nambar rian (arithmetic) ṭuan kan duh ahcun, a tanglei bantuk in string kha int asiloah float ah kan thlen a hau.
# Hmannak:
# 'n' kha 'name' tiah kan thleng lai, print nak ah 'name' kan hman caah.
name = input('Enter your name: ')
# Ca lawng a si caah thlen a hau lo.
age = int(input('Enter your age: '))
# 'int' ah thlen a hau, kum cu nambar a si caah.
salary = float(input('Enter your salary: '))
# 'float' ah thlen a hau, tangka cu a cheu (decimal) a um khawh caah.
print(name, age, salary)
5.7 Pass Statement¶
-
passstatement cu code kan run tikah zeihmanh a tuah lo (do nothing). Cucaah a caan ah no-op (no operation) instruction tiah auh a si. -
Code pakhatkhat kan run lio ah zeihmanh cang lo in um seh ti kan duh ahcun, pass statement hi kan hman khawh. A hmannak cu Problem 5.6 ah hmuh khawh a si.
-
A caan ah if, loop, function asiloah class chungah code kan ṭial rih lo mi caah hmun khiah ta nak (placeholder) ah hman a si tawn. Asinain hitin pass hman hi a ṭha tuk lo. Cucaah a hmun ah ... (Ellipsis) hi hman deuh ding a si.
-
Pass na hman ahcun, midang nih "mah if/loop/function/class chungah hin zeihmanh tuah a duh lo taktak/a herh lo" tiah an ruah khawh (code ṭial ding a um rih ti si lo in).
5.7.1 Ellipsis¶
-
Ellipsis cu Python chungah a um ciami constant (value hmaan/thleng lomi) a si. ... in langhter a si.
-
Ellipsis cu value kan theih rih lo mi aiawh (represent) nak ah hman a si.
-
if, loop, function, asiloah class chungah code kan ṭial rih lo mi caah hmun khiah ta nak (placeholder) ah hman a si tawn.
pass he an i dannak:
-
Ellipsislepasscu an i lo lo. -
passcu Statement (Bia/Rian) a si. -
...(Ellipsis) cu Constant (Value) a si.
Zeiruangah pass nak in ... hman a ṭhat deuh?
Code kan ṭial lio ah "Hi ka ah hin hmailei ah code ṭial a hau rih" ti kan theih khawh nak caah ... hman hi a ṭha deuh. pass kan hman ahcun "Hi ka ah hin zeihmanh ṭial ka tum lo" ti sullam a ngei kho.
def calculate_tax():
... # Hmailei ah ka tial te lai
class UserAccount:
... # Hmailei ah ka tial te lai
Problems¶
Problem 5.1¶
Thil cheukhat cawk tikah, cawkmi zat (quantity) kha 1000 nak in a tam ahcun 10% discount (man zuut) pek a si. Cawkmi zat (quantity) le thil pakhat man (price per item) kha keyboard in ṭial lut (input) a si ahcun, a man dihlak (total expenses) tuaknak ding program ṭial hna.
Program
qty = int(input('Enter value of quantity: ')) # Cawkmi zat (quantity) kha nambar in lak
price = float(input('Enter value of price: ')) # A man (price) kha float in lak
if qty > 1000 : # Quantity cu 1000 nak in a tam maw?
dis = 10 # A tam ahcun Discount cu 10
else : # A tam lo ahcun
dis = 0 # Discount cu 0
# A man dihlak tuaknak: (Quantity * Price) - (Discount)
totexp = qty * price - qty * price * dis / 100
# A phichuak (Total Expenses) chuahnak
print('Total expenses = Rs. ' + str(totexp))
Ruahding (Tips)
- input( ) nih string a chuah, cucaah int asiloah float ah a herh ning in thlen a hau. Kan thlen lo ahcun, qty > 1000 nih error a chuah lai, a ruang cu string le int cu tahchunh (compare) khawh an si lo.
-
- hmang in fonh (concatenation) kan tuah hlan ah totexp kha string ah thlen awkah str( ) hman ding a si.
Problem 5.2¶
Company pakhat ah rianṭuantu hlawh pek ning cu hitin a si:
-
A hrampi hlawh (basic salary) cu
Rs. 1500nak in a tlawm a si ahcun,HRA = 10%(basic salary in) leDA = 90%(basic salary in) a si lai. -
A hlawh cu
Rs. 1500he aa khat asiloah a tam deuh a si ahcun,HRA = Rs. 500leDA = 98%(basic salary in) a si lai.
Rianṭuantu i a hlawh kha keyboard in ṭial lut (input) a si ahcun, a hlawh dihlak (gross salary) kawlnak ding program ṭial hna.
Program
bs = int(input('Enter value of bs: ')) # Basic Salary (bs) kha nambar in lak
if bs > 1500 : # Basic Salary cu 1500 nak in a tam maw?
hra = bs * 15 /100 # A tam ahcun HRA cu 15%
da = bs * 95 / 100 # DA cu 95%
ca = bs * 10 / 100 # CA cu 10%
else: # A tam lo ahcun (1500 he aa khat asiloah a tlawm deuh)
hra = bs * 10 / 100 # HRA cu 10%
da = bs * 90 / 100 # DA cu 90%
ca = bs * 5 / 100 # CA cu 5%
gs = bs + da + hra + ca # Gross Salary (Hlawh Dihlak) tuaknak
print('Gross Salary = Rs. ' + str(gs)) # A phichuak chuahnak
Ruahding (Tips)
ifblock leelseblock chungah statement tampi chiah khawh an si, nain a herh ning in indent (tep luh) tuah a hau.
Problem 5.3¶
Student pakhat nih a hmuhmi percentage kha keyboard in ṭial lut (input) a si. A tanglei phung (rules) hmang in a hmuhmi division kha tuak ding a si:
-
60 asiloah 60 nak tam: First Division
-
50 in 59 kar: Second Division
-
40 in 49 kar: Third Division
-
40 nak tlawm: Fail
Program
per = int(input('Enter value of percentage: ')) # Percentage kha nambar in lak
if per >= 60 : # 60 nak in a tam asiloah aa khat maw?
print('First Division') # A si ahcun First Division
elif per >= 50 : # 60 nak tlawm si i, 50 nak tam a si maw?
print('Second Division')
elif per >= 40 : # 50 nak tlawm si i, 40 nak tam a si maw?
print('Third Division')
else : # 40 nak in a tlawm ahcun
print('Fail')
Problem 5.4¶
Company pakhat nih a driver pawl insurance a tuahpiak hnanak phung (rules) cu a tanglei bantuk a si:
-
Driver cu thit-um (married) mi a si ahcun.
-
Driver cu thit-um lomi (unmarried), pa (male) a si i, kum 30 nak in a upa deuh a si ahcun.
-
Driver cu thit-um lomi (unmarried), nu (female) a si i, kum 25 nak in a upa deuh a si ahcun.
-
A dang (case) vialte ahcun insurance pek a si lo.
Marital status (Thit-um/Um-lo), Sex (Nu/Pa) le Age (Kum) kha input in lak a si ahcun, insurance a ngah lai maw ngah lai lo ti tuaknak program ṭial hna.
Program
# Input laknak
ms = input("Thit-um cang maw? (Enter Marital Status - M/U): ")
sex = input("Nu/Pa (Enter Sex - M/F): ")
age = int(input("Kum zeizat (Enter Age): "))
# Insurance rule check tuahnak
# 1. Thit-um (Married) a si ahcun
if ms == 'M':
print("Driver is Insured (Insurance a ngah)")
# 2. Thit-um lo (Unmarried), Pa (Male) le Kum 30 nak tam
elif ms == 'U' and sex == 'M' and age > 30:
print("Driver is Insured (Insurance a ngah)")
# 3. Thit-um lo (Unmarried), Nu (Female) le Kum 25 nak tam
elif ms == 'U' and sex == 'F' and age > 25:
print("Driver is Insured (Insurance a ngah)")
# 4. A dang vialte (Insurance ngah lo)
else:
print("Driver is Not Insured (Insurance a ngah lo)")
Output
Problem 5.5¶
Flag variable pali w, x, y, z kan ngei. An lak ah a tlawm bik pakhat a hmaan (True) maw ti zohnak lam phunphun in program ṭial hna.
Program
# Flag variable pawl zohnak lam phunphun
w, x, y, z = 0, 1, 0, 1
# Lam 1: Value 1 he aa khat maw ti zoh
if w == 1 or x == 1 or y == 1 or z == 1 :
print('True')
# Lam 2: Boolean value (0 asiloah 1) in zoh (A fawi bik)
if w or x or y or z :
print('True')
# Lam 3: any() function hman (Tuple chungah pakhat tal True a um maw)
if any((w, x, y, z)):
print('True')
# Lam 4: 'in' operator hman (Tuple chungah 1 a um maw)
if 1 in (w, x, y, z) :
print('True')
Ruahding (Tips)
any( )cu function a um ciami a si i, a parameter chung i element a tlawm bik pakhat a hmaan (True) ahcun True a chuah.any( )sinah hinstring,list,tuple,setasiloahdictionarypek a hau.- Aa lo mi function dang
all( )a um rih, mah nih cun a parameter chung i element vialte/dihlak an hmaan (True) lawng ah True a chuah. Hi function zong histring,list,tuple,setasiloahdictionarypek ve a hau.
Problem 5.6¶
Nambar n pakhat kan ngei i, a tanglei bantuk in tuah kan duh:
-
ncu positive (0 nak in a tam) a si ahcun -n * nchuah (print), cun flag kha true ah chiah/thleng. -
ncu negative (0 nak in a tlawm) a si ahcun -n * n * nchuah (print), cun flag kha true ah chiah/thleng. -
ncu 0 a si ahcun - zeihmanh tuah lo (do nothing).A tanglei i pekmi code hi, mah logic (a kal ning) caah hin a hmaan maw? ```python n = int(input('Enter a number: ')) # Nambar kha keyboard in lak if n > 0 : # n cu 0 nak in a tam (Positive) a si ahcun flag = True # Flag kha True ah chiah print(n * n) # n * n (Square) chuah elif n < 0 : # n cu 0 nak in a tlawm (Negative) a si ahcun flag = True # Flag kha True ah chiah print(n * n * n) # n * n * n (Cube) chuah # Note: n = 0 a si ahcun zeihmanh a tuah lo (implicit pass)
Answer
Hi code hi lungawh a chuahter khawh (misleading). Hmailei ah, mi pakhatkhat nih hi code a zoh tikah `flag = True` hi `if` le `else` leng ah ṭial ding a si tiah a ruah khawh. Code ṭha deuh cu a tanglei bantuk hi a si lai:Exercise¶
[A] A tanglei biahalnak hna hi leh hna:¶
a. A tanglei hna caah hin conditional expressions ṭial hna:
# - a < 10 a si ahcun b = 20, a si lo ahcun b = 30
b = 20 if a < 10 else 30
# - time < 12 a si ahcun 'Morning' chuah, a si lo ahcun 'Afternoon' chuah
print('Morning') if time < 12 else print('Afternoon')
# - marks >= 70 a si ahcun remarks cu True, a si lo ahcun False
remarks = True if marks >= 70 else False
[B] A tanglei program hna i an phichuak (output) hi zeidah a si lai:¶
a.
i, j, k = 4, -1, 0
w = i or j or k
x = i and j and k
y = i or j and k
z = i and j or k
print(w, x, y, z)
c.
x, y, z = 20, 40, 45
if x > y and x > z :
print('biggest = ' + str(x))
elif y > x and y > z :
print('biggest = ' + str(y))
elif z > x and z > y :
print('biggest = ' + str(z))
d.
e. f. g. h. i.[C] A tanglei program hna ah palhnak (errors) a um ahcun sawh/langhter hna:¶
a.
b. c. d. e.x, y = 30, 40
if x == y :
print('x is equal to y')
elseif x > y :
print('x is greater than y')
elseif x < y :
print('x is less than y')
[D] a = 10, b = 12, c = 0 an si ahcun, a tanglei expression pawl i an value (phi) kawl hna:¶
[E] A tanglei biahalnak hna hi tuah/phi hna:¶
- a. Integer (nambar) pakhat keyboard in ṭial lut a si. Cucu nambar ya (even) a si maw, nambar khing (odd) a si maw ti zohnak program ṭial.
- b. Kum pakhat keyboard in ṭial lut a si. Cu kum cu leap year a si maw, si lo maw ti zohnak program ṭial.
- c. Ram, Shyam le Ajay hna i an kum keyboard in ṭial lut a si ahcun, an pathum lak ah a ngakchia bik zohnak program ṭial.
- d. Triangle (kili) pakhat i a kil (angle) pathum keyboard in ṭial lut a si. Cu triangle cu a hmaan/si kho mi a si maw si lo ti zohnak program ṭial. Angle pathum an fonh (sum) kha 180 degrees he aa khah ahcun triangle cu a hmaan/si kho.
- e. Keyboard in ṭial lutmi nambar i a absolute value kawlnak program ṭial.
- f. Rectangle pakhat i a dung (length) le a vang (breadth) pek a si. A area (a chung kauh) kha a perimeter (a velchum) nak in a ngan deuh maw ti zohnak program ṭial. Tahchunhnak ah, length = 5 le breadth = 4 a ngeimi rectangle i a area cu a perimeter nak in a ngan deuh.
- g. Point pathum (x1, y1), (x2, y2) le (x3, y3) pek a si. Hi point pathum hna hi line tluang (straight line) pakhat cungah an um dih maw ti zohnak program ṭial.
- h. Circle (kew) pakhat i a lai (center) coordinates (x, y) le a radius pek a si. Point pakhat cu circle chungah (inside) a um maw, circle cungah (on) a um maw, asiloah circle lengah (outside) a um maw ti zohnak program ṭial. (Ruahding: sqrt( ) le pow( ) functions hmang hna).
- i. Point (x, y) pakhat pek a si, cu point cu X-axis cungah a um maw, Y-axis cungah a um maw, asiloah origin cungah a um maw ti zohnak program ṭial.
- j. Kum pakhat keyboard in ṭial lut a si, cu kum cu leap year a si maw si lo ti zohnak program ṭial. Logical operators and le or hmang hna.
- k. Triangle i a tlang/kap pathum keyboard in ṭial lut a si, cu triangle cu a hmaan/si kho mi a si maw si lo ti zohnak program ṭial. A tlang pahnih fonh (sum) kha a tlang a sei bik nak in a ngan deuh ahcun triangle cu a hmaan/si kho.
- l. Triangle i a tlang/kap pathum keyboard in ṭial lut a si, cu triangle cu Isosceles (tlang 2 aa khat), Equilateral (tlang 3 aa khat), Scalene (tlang 3 aa khat lo), asiloah Right angled (kil 90 a ngeimi) triangle a si maw ti zohnak program ṭial.
Chapter 6 Repetition Control Instructions¶
Keynote¶
6.1 Repetition Control Instructions (Zei dah an si?)¶
Program chungah statement (tuah dingmi) pawl a nawn in tuah ṭhan lengmang kan duh tikah hman a si. Repetition control instruction phun hnih a um:
- while
- for
Language dang (C, C++, Java) bantuk in do-while loop hi Python ah a um lo.
while loop cu condition a hman (true) chung paoh kha instruction a tuah ṭhan lengmang. Phun hnih in kan hman khawh:
1. The while Loop¶
while loop cu condition a hman (true) chung paoh kha statement pawl a tuah ṭhan lengmang. Condition kha thil tuah hlan ah a check hmasa, cucaah entry-controlled loop tiah auh a si.
A Umtu Ning (Syntax):
Phun hnih in while loop hi hman khawh a si:
A. A Umtu Ning Pang (Basic Structure)
while condition:
# Loop chungah tuah dingmi
statement1
statement2
# Condition kha a donghnak ah False a si a hau,
# lo cun a tawp ti lomi (infinite loop) a chuak lai!
elseblock hi hman a hau hrimhrim lo (optional). Asinain kan hman ahcun, condition a 'false' tikah a chung i statement pawl kha a tuah lai.breakstatement hman inwhileloop kha kan hrawh/donghter sual ahcun,elseblock kha a tuah lai lo.
for cu string, tuple asiloah list bantuk sequence (thil tlar) chung i element pawl pakhat hnu pakhat lakin tuah ṭhan lengmang nak ah hman a si. Phun hnih in a um:
- Loop a kal fatin
varkhalistchung in a changtu value (hmet) pek a si. listhmun ahstring,tuple,setasiloahdictionaryzong hman khawh a si.elseblock cu hman a hau hrimhrim lo (optional). Kan hman ahcun, break hman in loop kan hrawh lo poh ahcunelsechung i statement pawl kha a tuah lai.
6.2 While loop hman ning¶
while loop hi a tanglei thil sining pathum ah hman khawh a si:
- Condition a hman (True) chung paoh statement pawl tuah ṭhan lengmang.
- Statement pawl kha kan duh zat tiang (voi zeizat dah ti hngalh cia in) tuah ṭhan lengmang.
- String, list, le tuple chung i element pawl lakin kal.
Condition a hman chung paoh statement tuah ṭhan lengmang kan ti tikah, statement kha voi zeizat dah tuah a hau lai ti a hngalh cia lomi caah hman a si.
num = int(input('Enter a number: '))
while num != 5 :
print(num, num * num)
num = int(input('Enter a number: '))
Statement pawl kha voi zeizat dah tuah ding ti hngalh cia in (finite number of times) tuah ṭhan lengmang nan while loop kan hman khawh.
while loop cu index nambat (index value) hman in string, list, asiloah tuple chung i thil ummi pawl lakin kal nan hman khawh a si, a tanglei program ah kan hmuh bantuk in:
s = 'Mumbai'
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
tpl = (10, 20, 30, -20, -10)
i = 0
while i < len(lst) :
print(i, s[i], lst[i], tpl[i])
i += 1
Theih ding (Note):
Hi program ah hin tpl (tuple) hi element 5 lawng a ngei, asinain lst (list) hi element 6 a ngei. Loop hi lst sau (length) chung a kal lai caah, a donghnak ah tpl index a tlauh sual (IndexError) kho.
SetasiloahDictionarychung i thil pawl cu index nambat hman in lak khawh an si lo caah,forloop hman hi a ṭha deuh.
Cunglei i while loop hman ning pathum kan hmuhmi chung ah, a pakhatnak (voi zeizat dah tuah ding hngalh cia lo, condition hman chung paoh) hi hman a tam bik a si. A dang pahnih cu for loop hman in tuah a tlangpi a si.
6.3 For loop hman ning¶
for loop cu a tanglei thil sining pahnih ah hman khawh a si:
- Statement pawl kha voi zeizat dah tuah ding ti hngalh cia in (finite number of times) tuah ṭhan lengmang.
string,list,tuple,setasiloahdictionarychung i thil ummi pawl lakin kal.
Statement pawl kha voi zeizat dah tuah ding ti hngalh cia in tuah ṭhan lengmang kan duh tikah, a chungah a um ciami function range() hi hman a si.
range() function nih integer (nambat tling) tlar a chuah.
range(10)- 0 in 9 tiang nambat a chuah.range(10, 20)- 10 in 19 tiang nambat a chuah.range(10, 20, 2)- 10 in 19 tiang, 2 in karh in a chuah (10, 12, 14...).-
range(20, 10, -3)- 20 in 9 tiang, 3 in zor in a chuah (20, 17, 14...). -
Theih ding:
range()nihfloat(point nambat) tlar a chuah kho lo.
A tlangpi in,
range(start, stop, step)
Hi nih hin integer nambat tlar kha start in a thawk lai i stop tiang a kal lai (asinain stop nambat taktak kha a tel lo/exclusive), cun step zat in a karh/zor lai.
range() hman in nambat tlar kan chuahmi pawl kha for loop hman in kan lak khawh.
for char in 'Leopard' :
print(char)
for animal in ['Cat', 'Dog', 'Tiger', 'Lion', 'Leopard'] :
print(animal)
for flower in ('Rose', 'Lily', 'Jasmine') :
print(flower)
for num in {10, 20, 30, -10, -25} :
print(num)
for key in {'A101' : 'Rajesh', 'A111' : 'Sunil', 'A112' : 'Rakesh'} :
print(key)
for loop ah khan, loop a kal fatin char kha string chung in a changtu value (cafang) pek a si.
Cu bantuk ṭhiamṭhiam in, pahnihnak, pathumnak le palinak for loop ah, loop a kal fatin animal/flower/num kha list/tuple/set chung in a changtu value pek an si.
- Theih ding: A donghnak
forloop ah dictionarykey(a bi) lawng kan chuah (print) kha na hmuh lai. A value (a man) chuah, asiloah a key le a value chuah ṭi kha cu Chapter 11 ah kan cawng te lai.
for loop hman in thil tlar chung kan kal lio ah, a umnak hmun (index) zong hngalh chih kan duh ahcun, a tanglei bantuk in a chungah a um ciami enumerate() function hi hman ding a si:
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
for i, ele in enumerate(lst) :
print(i, ele)
6.4 break le continue¶
breaklecontinuestatement pawl hiwhileleforhe hman khawh an si.breakstatement nihelseblock tuah lo in loop kha a donghter/hrawh.continuestatement nih block chung i statement dang pawl kha a hlut (skip) i, loop a changtu iteration ah a kal colh.
6.5 Loop i Else Block¶
whileloop ielseblock cu, loop kha a pang tein a dih (normally terminated) lawngah thil tuah ter kan duh i,breakhman in a tawp tikah tuah ter kan duh lo caan ah hman a si.- Cu bantuk thil sining cu nambat pakhat hi prime number a si le si lo kan check tikah a chuak tawn.
num = int(input('Enter an integer: '))
i = 2
while i <= num - 1 :
if num % i == 0 :
print(num, 'is not a prime number')
break # Hika ah a break ahcun else block a tuah lai lo
i += 1
else :
print(num, 'is a prime number')
else kan ṭialnak hmun (indentation) kha ṭha tein zoh. Hi else hi while loop ta a si, if statement ta a si lo.
- A tanglei tahchunhnak ah hin
elseblock cu a tuah lai lo, zeicatiah list chungah3a um.3cu 10 in hrawm khawh a si lo (non-multiple), cucaah3kan hmuh bak in loop kha kan hrawh (break) lai.
for ele in [10, 20, 30, 3, 40, 50] :
if ele % 10 != 0 :
print(ele, 'is a not a multiple of 10')
break
else :
print('all numbers in list are multiples of 10')
6.6 Nested Loops (Loop chungah loop dang)¶
- Loop pakhat chungah loop dang kan hman chih khawh.
- A leng loop (outer loop) voi khat a kal fatin, a chung loop (inner loop) kha a tling tein (a thawk in a dongh tiang) a kal dih lai.
Problems¶
Problem 6.1¶
p, n, le r value set 3 la law, set pakhat cio caah simple interest tuaknak program ṭial.
Program
Output
Problem 6.2¶
Problem 6.2¶
Infinite loop hman in nambat 1 in 10 tiang chuahnak (print) program ṭial. Nambat vialte kha tlar khat (same line) ah an chuak dih lai.
Tips
while 1nih infinite loop a ser, zeicatiah 1 cu 'zero' a si lo, cucaah 'true' in a hmuh.- 1 hmun ah nambat dang (zero a si lomi paoh) na hman ahcun infinite loop a ser thiamthiam lai.
- Infinite loop sernak lam dang cu
while Truehman hi a si. print()chung iend = ' 'nih khan iteration pakhat a kal fatinia chuah (print) hnu ah 'space' a chiah. A sawhsawh (default) in cunendhinewline('\n') a si.
Problem 6.3¶
Nambat 1, 2 le 3 hman in an i lo lomi (unique) combinations vialte chuahnak program ṭial.
Program
Problem 6.4¶
Binary numeric string (nambat '0' le '1' lawng ummi) pakhat la law, cu nambat i a decimal value (kan hman tawnmi nambat) kawlnak program ṭial. Tahchunhnak ah, '1111' i a decimal value cu 15 a si.
Program
Tips
ord('1')cu 49 a si,ord('0')cu 48 a si. (Cucaahord('1') - ord('0')kan tuah tikah1a chuak,ord('0') - ord('0')tikah0a chuak).b = b[1:]nihbstring chung i a hmasa bik cafang kha a hlonh (strip).
Problem 6.5¶
for loop hman in a tanglei bantuk cafang pawl chuahnak (output) program ṭial:
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,
z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,
Program
Output
Tips
- Cafang A-Z i an Unicode value (nambat) cu 65 in 90 an si. Cafang a-z i an Unicode value cu 97 in 122 an si.
- Print statement in a chuakmi paoh a donghnak ah comma (,) a tel lai.
- A chungah zeihmanh a um lomi
print( )statement nih cursor kha tlar thar (next line) a thawknak ah a chiah.
Exercise¶
[A] Answer the following questions (A tanglei biahalnak pawl hi phi):¶
a. When does the else block of a while loop go to work?
(while loop i else block kha zeitik ah dah a tuah?)
- Phi:
whileloop ielseblock cu loop condition kha a pang tein a False tikah (loop a dih tikah) tuah a si. Asinain, loop khabreakstatement hman in kan hrawh (terminate) ahcunelseblock cu a tuah lai lo.
b. Can range( ) function be used to generate numbers from 0.1 to 1.0 in steps of 0.1?
(range() function hi 0.1 in 1.0 tiang, 0.1 in karh nakhnga hman khawh a si maw?)
- Phi: A ngah lo. Python ah
range()function cu Integer (nambat tling) lawng caah hman khawh a si. Point nambat (float) caah cunnumpybantuk library hman a hau.
c. Can a while loop be nested within a for loop and vice versa?
(while loop chungah for loop chiah a ngah maw, asiloah a let in a ngah maw?)
- Phi: A ngah. Loop pakhat chungah loop phun dang chiah (Nested) hi a ngah.
d. Can a while/for loop be used in an if/else and vice versa?
(if/else chungah loop hman a ngah maw, asiloah loop chungah if/else hman a ngah maw?)
- Phi: A ngah. Control instruction pawl (loop, if-else) cu duh paoh in chawh in hman (nest) khawh an si.
e. Can a do-while loop be used to repeat a set of statements?
(Statement pawl tuah ṭhan lengmang nakhnga do-while loop hman khawh a si maw?)
- Phi: A ngah lo. Python language ah do-while loop a um lo.
f. How will you write an equivalent for loop for the following:
(A tanglei while loop he a i tlukmi for loop zeitindah na ṭial lai?)
(g) What will be the output of the following code snippet? (A tanglei code snippet nih zei output dah a chuah lai?)
* Phi: 20 17 14 11(h) Why should break and continue be always used with an if embedded in a while or for loop?
(Zeicah break le continue hi while asiloah for loop chungah if he (condition he) hman a herh zungzal?)
- Phi:
if(condition) tel lo inbreakasiloahcontinuekan hman ahcun, loop a kal hmasa bik (first iteration) ah a tawp colh lai (break) asiloah a hlut colh lai (continue). - Cu tikah, loop chung i statement dang pawl kha zeitik hmanh ah a tuah kho ti lai lo (Unreachable code an si lai).
- Cucaah, thil sining (condition) pakhatkhat a tlin lawngah loop hrawh/hlut kan duh tawn caah
ifhe hman a herh.
[B] Point out the errors, if any, in the following programs:¶
(A tanglei program pawl ah hin a palhmi an um ahcun kawl/chim:)
a.
b.
c. d. e. f. g.[C] Match the following for the values each range( ) function will generate¶
(A tanglei range() function cio nih a chuah dingmi value (nambat tlar) pawl hi, a hmanmi he pehtlaih hna.)
a. range(5) 1. 1, 2, 3, 4
b. range(1, 10, 3) 2. 0, 1, 2, 3, 4
c. range(10, 1, -2) 3. Nothing
d. range(1, 5) 4. 10, 8, 6, 4, 2
e. range(-2) 5. 1, 4, 7
[D] Attempt the following questions:¶
(A tanglei biahalnak pawl hi phi i zuam:)
a. Write a program to print first 25 odd numbers using range( ).
(range() function hman in odd number (nambat cawh) a hmasa bik 25 chuahnak program ṭial.)
b. Rewrite the following program using for loop.
(for loop hman in a tanglei program hi ṭial ṭhan.)
lst = ['desert', 'dessert', 'to', 'too', 'lose', 'loose']
s = 'Mumbai'
i = 0
while i < len(lst) :
if i > 3 :
break
else :
print(i, lst[i], s[i])
i += 1
d. A five-digit number is entered through the keyboard. Write a program to obtain the reversed number and to determine whether the original and reversed numbers are equal or not. (Keyboard in digit-5 ummi nambat ṭial a si. Cu nambat cu letthlit (reverse) in tuahnak le, a letthlit kan tuahmi le a hramthawk nambat kha an i luk maw luk lo ti check-nak program ṭial.)
e. Write a program to find the factorial value of any number entered through the keyboard. (Keyboard in ṭialmi nambat paoh i a 'factorial value' kawlnak program ṭial.)
f. Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number. For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 ). (1 le 500 kar ah a ummi Armstrong number vialte chuahnak program ṭial. Nambat pakhat i a digit paoh kha voi 3 karh (cube) in kan fonh (sum) tikah, a hramthawk nambat he an i luk ahcun, cu nambat cu Armstrong number ti a si. Tahchunhnak: 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 ).)
g. Write a program to print all prime numbers from 1 to 300. (1 in 300 kar ah a ummi prime number vialte chuahnak program ṭial.)
h. Write a program to print the multiplication table of the number entered by the user. The table should get displayed in the following form: (User nih a ṭialmi nambat i a a-li (multiplication table) chuahnak program ṭial. Table cu a tanglei bantuk in langhter ding:)
i. When interest compounds q times per year at an annual rate of r % for n years, the principal p compounds to an amount a as per the following formula:
\(a = p ( 1 + \frac{r}{q} )^{nq}\)
Write a program to read 10 sets of p, r, n & q and calculate the corresponding as.
(Kum khat ah q voi a karh (compound) mi interest r% in kum n chung a um tikah, a hram p cu a tanglei formula ning in a ah a cang: \(a = p ( 1 + \frac{r}{q} )^{nq}\). p, r, n le q set 10 la law, a chuakmi a tuaknak program ṭial.)
j. Write a program to generate all Pythagorean Triplets with side length less than or equal to 30. (Sir (side) pakhat cio 30 nak in a tlawm deuh asiloah a tlukmi Pythagorean Triplets vialte chuahnak program ṭial.)
k. Population of a town today is 100000. The population has increased steadily at the rate of 10 % per year for last 10 years. Write a program to determine the population at the end of each year in the last decade. (Tuchun ah khua pakhat i milu cu 100,000 an si. A luan ciami kum 10 chung khan, kum khat ah 10% in hma a panh (karh) lengmang. A luan ciami kum 10 chung i kum khat a dih fatin milu zeizat dah an si ti kawlnak program ṭial.)
l. Ramanujan number is the smallest number that can be expressed as sum of two cubes in two different ways. Write a program to print all such numbers up to a reasonable limit. (Ramanujan number timi cu nambat pahnih i an cube (voi thum karh) fonh in, lam phun hnih in hmuh khawhmi nambat hme bik a si. Cu bantuk nambat pawl cu a niamnak tawk (reasonable limit) tiang chuahnak program ṭial.)
m. Write a program to print 24 hours of day with suitable suffixes like AM, PM, Noon and Midnight. (Nikhat chung suimilam 24 kha AM, PM, Noon le Midnight tiah a hmanmi ṭhiam in chuahnak program ṭial.)
Chapter 7 Console Input/Output¶
Keynote¶
7.1 Console Input/Output¶
Console Input/Output timi cu keyboard in thil ṭial luh (input) le screen cungah chuah (output) kha a si.
7.2 Console Input¶
Console input cu Python chungah a um ciami input() function hman in lak khawh a si.
input() function i a hman ning (general form) cu:
s = input('prompt')
promptcu screen cungah a lang dingmi ca (string) a si, user kha value a hal.input()nih string a chuah (return). Tahchunhnak ah123kha input ah kan ṭial ahcun,'123'(string) in a laak.
# Min tling laknak
name = input('Enter full name')
# Min hmasa, min laifang le min donghnak ṭhennak (split hman in)
fname, mname, lname = input('Enter full name: ').split( )
split() function nih na ṭialmi min tling kha "space" (ca hmai) hman in a ṭhen hna lai. Cu a ṭhenmi value pawl cu fname, mname, le lname ah a chiah (assign) hna lai.
int (nambat) value tam deuh lak kan duh ahcun, string in kan lak hmasa lai i, cu hnu ah int ah kan thlen hna lai.
n1, n2, n3 = input('Enter three values: ').split( )
# String in a ummi kha int ah thlen
n1, n2, n3 = int(n1), int(n2), int(n3)
print(n1 + 10, n2 + 20, n3 + 30)
Mah thil ṭhiamṭhiam cu list comprehension timi hman in tawi deuh le fawi deuh in kan tuah khawh.
split() function nih a chuahmi list chung i thil (element) pakhat cio kha int() function a hmanpiak hna (nambat ah a thlen hna).
# Input lak, split tuah, le int ah thlen colh
n1, n2, n3 = [int(n) for n in input('Enter three values: ').split( )]
print(n1 + 10, n2 + 20, n3 + 30)
[ ] chung i ṭialmi expression kha list comprehension ti a si. Hi kong hi Chapter 12 ah tling deuh in kan cawng te lai.
input() hi value zeizat kan duh zat (arbitrary number) lak nakhnga hman khawh a si.
# User nih a duh zat value a ṭialmi paoh list ah chiah
numbers = [int(x) for x in input('Enter values: ').split( )]
for n in numbers :
print(n + 10)
input() hi value phun (type) a i dangmi pawl a voikhat tein lak nakhnga hman khawh a si.
data = input('Enter name, age, salary: ').split( )
name = data[0] # Min cu string a si cia
age = int(data[1]) # Kum cu integer ah thlen
salary = float(data[2]) # Lahkhah cu float ah thlen
print(name, age, salary)
7.3 Console Output¶
- A chungah a um ciami function
print( )cu screen cungah output chuah nakhnga hman a si.
print( ) function nih a tanglei bantuk sining (form) a ngei:
- Himi a sullam cu, a sawhsawh (default) in thil (objects) pawl cu screen (
sys.stdout) ah an chuak lai, 'space' (sep = ' ') in a ṭhen hna lai, cun a donghnak ah tlar thar (end = '\n') in a zui lai.flush = Falsetimi nih output stream cu a thianh (flush) lai lo ti a langhter.
Python nih function kan auh tikah a min (keyword) hman in value pek khawhnak a ngei. Cucaah print( ) kan hman tikah sep le end caah kan duhmi value kan pek khawh hna. Cu tikah, a sawhsawh (default) value pawl kha hman an si ti lo i, kan pekmi value tu kha hman an si lai.
# Value pakhat cio hnu ah ',' a um lai, a donghnak ah '!' a um lai
print(a, b, c, sep = ',', end = '!')
# Value pakhat cio hnu ah '...' a um lai, a donghnak ah '#' a um lai
print(x, y, sep = '...', end = '#')
7.4 Formatted Printing¶
Output a sining (formatting) uk nakhnga lam 4 a um:
- a. Formatted string literals hman - a fawi bik.
- b. format( ) method hman - a hlun deuh.
- c. C printf( ) style - a hlun tuk cang (legacy).
- d. Slicing le concatenation hman - a har.
Tuchun ni ah (a) hi hman bik a si i, (b) nih a chang.
r, l, b = 1.5678, 10.5, 12.66
# f-string hman tikah f'' kan ṭial i a chungah {variable} kan chiah
print(f'radius = {r}')
print(f'length = {l} breadth = {b} radius = {r}')
name = 'Sushant Ajay Raje'
for n in name.split( ) :
print(f'{n:10}') # column 10 chungah chuah ding (space 10 a lak lai)
Using format( ) method¶
String object i format( ) method hman ning:
Hi method ah hin string chungah {} (curly braces) kan chiah i, cu chungah value kan duhmi format() in kan pek (pass).
r, l, b = 1.5678, 10.5, 12.66
name, age, salary = 'Rakshita', 30, 53000.55
# 1. A um ning (position) tein chuah - {} chungah zeihmanh ṭial lo
# A hmasa bik {} ah r, a pahnihnak ah l, a pathumnak ah b a um lai.
print('radius = {} length = {} breadth ={}'.format(r, l, b))
print('name = {} age = {} salary = {}'.format(name, age, salary))
# 2. Kan duhmi order in chuah (Index hman in)
# {0} = r, {1} = l, {2} = b
print('radius = {2} length = {1} breadth ={0}'.format(r, l, b))
print('age={1} salary={2} name={0}'.format(name, age, salary))
# 3. Hmun (width) zeizat dah a lak lai ti khiah
# {0:15} = Index 0 (name) nih column 15 (space 15) a lak lai.
print('name = {0:15} salary = {1:10}'.format(name, salary))
# 4. Point hnu nambat zeizat dah a lak lai ti khiah
# {0:10.2f} = Index 0 (r) nih column 10 a lak lai, point hnu ah nambat 2 a lang lai.
print('radius = {0:10.2f}'.format(r))
radius = 1.5678 length = 10.5 breadth =12.66
name = Rakshita age = 30 salary = 53000.55
radius = 12.66 length = 10.5 breadth =1.5678
age=30 salary=53000.55 name=Rakshita
name = Rakshita salary = 53000.55
radius = 1.57
Zohchih ding (Note)
- Space:
name = Rakshitahnu ah space a um, zeicatiah{0:15}kan hman caah a tlawm bik cafang 15 hmun a lak. - Rounding:
radius = 1.57a si, zeicatiah{0:10.2f}kan hman..2fnih point hnu ah nambat 2 lawng a lak i,1.5678kha1.57ah a round (a naihniam bik ah a thlen). - Alignment: Nambat (number) pawl cu a sawhsawh in a orh lei (right) ah an i align (tlar).
Problems¶
Problem 7.1¶
Circle pakhat i a radius, le Rectangle pakhat i a dung (length) le a vang (breadth) kha input( ) voikhat hman in laknak program ṭial. Cun, Circle i a circumference (a vel) le Rectangle i a perimeter (a vel) kha tuak law chuah (print).
Program
# Input lak i 'space' hman in ṭhen (split)
r, l, b = input('Enter radius, length and breadth: ').split( )
# String in Integer (nambat) ah thlen
radius = int(r)
length = int(l)
breadth = int(b)
# Formula hman in tuak
circumference = 2 * 3.14 * radius
perimeter = 2 * ( length + breadth )
# A chuakmi result chuah
print(circumference)
print(perimeter)
Tips
input( )nih string a chuah (return) caah, nambat tuaknak (arithmetic operations) tuah hlan ahintasiloahfloatah thlen (convert) a herh.
Problem 7.2¶
input( ) voikhat hman in integer 3 lak ding. Cu nambat 3 hna cu thawk (start), dongh (end), le karh (step) an si lai. Cu nambat pawl hman in: Nambat (number), a square (voi hnih karh), le a cube (voi thum karh) kha Orh lei tlar (Right-aligned) le Keh lei tlar (Left-aligned) in chuahnak program ṭial.
Program
start, end, step = input('Enter start, end, step values: ').split( )
# Right aligned printing (Orh lei tlar in chuah)
# > symbol nih orh lei (right) ah a chiah
print("Right Aligned:")
for n in range(int(start), int(end), int(step)) :
print(f'{n:>5}{n**2:>7}{n**3:>8}')
print( ) # Tlar thar
# Left aligned printing (Keh lei tlar in chuah)
# < symbol nih keh lei (left) ah a chiah
print("Left Aligned:")
for n in range(int(start), int(end), int(step)) :
print('{0:<5}{1:<7}{2:<8}'.format(n, n ** 2, n ** 3))
Output
Tips
{n:>5}nihnkha column 5 chungah orh lei tlar (right-justified) in a chuah lai. Keh lei tlar (left-justify) na duh ahcun<hmang.{0:<5}nih parameter 0-nak (a hmasa bik) kha column 5 chungah keh lei tlar (left-justify) in a chuah lai. Orh lei tlar (right-justify) na duh ahcun>hmang.
Problem 7.3¶
Min le phone nambat 4 chiah nakhnga le, cu hna cu a tlar tein (table bantuk in) chuahnak program ṭial.
Program
contacts = {
'David' : 9823077892,
'Shine' : 6784512345,
'Vivad' : 9823011245,
'Rosanna' : 9766556779
}
# Dictionary chung i min le nambat lak
for name, cellno in contacts.items( ) :
# name:15 = Min caah space 15 (String cu left align a si)
# cellno:10d = Nambat caah space 10 (d = decimal integer)
print(f'{name:15} : {cellno:10d}')
Problem 7.4¶
Program pakhat chungah variable 5 - max, min, mean, sd le var - an um i, value ṭha tein an ngei ti u sih. print( ) voikhat lawng auh in, nain f-string tam nawn hman in, hi variable pawl hi a tlar tein (properly aligned) chuahnak program ṭial.
Program
min, max = 25, 75
mean = 35
sd = 0.56
var = 0.9
# Print voikhat lawng kan hman, comma (,) in kan peh
print(
f'\n{"Max Value:":<15}{max:>10}', # Label keh lei, Value orh lei
f'\n{"Min Value:":<15}{min:>10}',
f'\n{"Mean:":<15}{mean:>10}',
f'\n{"Std Dev:":<15}{sd:>10}',
f'\n{"Variance:":<15}{var:>10}'
)
A tuah ning (Explanation):
- Comma
,:print()chungah argument tam nawn kan pek khawh. Hika ah f-string 5 kha comma in kan ṭhen hna. \n: Line thar (New line) a si.printnih space a pek (default separator) nain,\nkan hman caah a tanglei ah a thla."Max Value:":<15: "Max Value:" timi ca kha column 15 chungah Keh lei tlar (Left align) in a chiah.max:>10:maxvariable i a value kha column 10 chungah Orh lei tlar (Right align) in a chiah.
Problem 7.5¶
1 in 10 tiang nambat pawl i an Square Root le Cube Root kha point hnu ah nambat 3 (3 decimal places) tiang chuahnak program ṭial. Nambat kha a lai (center) ah um sehlaw, root pawl cu orh lei tlar (right-justified) in um hna seh.
Program
import math
# Formatting settings
width = 10
precision = 3 # Point hnu nambat 3
print(f'{"Num":^5}{"Sqrt":>10}{"Cbrt":>10}') # Header
# 1 in 10 tiang (range cu a donghnak a tel lo caah 11 kan ṭial)
for n in range(1, 11) :
s = math.sqrt(n)
c = math.pow(n, 1/3) # Cube root (1/3 power)
# ^5 = Width 5 chungah Center align
# 10.3f = Width 10, point hnu nambat 3 (f=fixed point)
print(f'{n:^5}{s:10.3f}{c:10.3f}')
A tuah ning (Explanation):
import math: Square root (sqrt) le power (pow) hman khawh nakhnga math library kan auh.range(1, 11): 1 in 10 tiang kal ding a si (Python range ah a donghnak nambat a tel lo, cucaah 11 kan ṭial a hau).^5: Nambatnkha column 5 chungah A Lai (Center) ah a chiah.10.3f:10: Column 10 hmun a lak lai..3: Point hnu ah nambat 3 a lang lai.f: Fixed point (decimal nambat) a si lai. Nambat a si caah a sawhsawh in Orh lei (Right) ah a tlar.
Output
Exercises¶
[A] Attempt the following questions:¶
a. How will you make the following code more compact? (A tanglei code hi zeitinda na tawiter deuh lai?)
input() le split() function hman in tlar khat (one line) ah kan tawiter khawh:
b. How will you print "Rendezvous" in a line and retain the cursor in the same line in which the output has been printed? ("Rendezvous" timi kha tlar khat ah zeitinda na print lai i, output a chuahnak tlar thiamthiam ah cursor kha zeitinda na umter peng lai?)
c. What will be the output of the following code snippet? (A tanglei code snippet i a output hi zeidah a si lai?)
d. In the following statement what do > 5, > 7 and > 8 signify?
(A tanglei statement chungah hin > 5, > 7 le > 8 nih zeidah an chim duh (sullam an ngeih)?)
e. What will be the output of the following code segment? (A tanglei code segment i a output hi zeidah a si lai?)
f. How will you print the output of the following code segment using fstring?
(A tanglei code segment i a output hi fstring hmang in zeitinda na chuah (print) lai?)
g. How will you receive arbitrary number of floats from keyboard? (Keyboard in na duh zat point nambat (floats) kha zeitinda na lak lai?)
h. What changes should be made in (Zei dah remh a hau mi a si lai?)
i. How will you receive a boolean value as input? (Boolean value (True/False) kha input in zeitinda na lak lai?)
j. How will you receive a complex number as input? (Complex number kha input in zeitinda na lak lai?)
k. How will you display price in 10 columns with 4 places beyond decimal points? Assume value of price to be 1.5567894.
(price kha column 10 chungah, point hnu nambat 4 (4 decimal places) tiang langhter in zeitinda na chuah lai? price i a value cu 1.5567894 a si tiah ruat.)
l. Write a program to receive an arbitrary number of floats using one input( ) statement. Calculate the average of floats received.
(input( ) statement voikhat hman in point nambat (floats) na duh zat laknak program ṭial. Cun, na lakmi point nambat pawl i an average (vawle) kha tuak.)
m. Write a program to receive the following using one input( ) statement.
(A tanglei hna hi input( ) statement voikhat hman in laknak program ṭial.)
Name of the person (Minung Min)
Years of service (Rian a ṭuan kum zat)
Diwali bonus received (Diwali bonus a hmuhmi)
n. Which import statement should be added to use the built-in functions input( ) and print( )?
(Built-in function input( ) le print( ) hman khawh nakhnga zei import statement dah chap a herh?)
o. Is the following statement correct? (A tanglei statement hi a hman maw?)
p. Write a program to print the following values (A tanglei value pawl hi chuahnak (print) program ṭial) as shown below:[B] Match the following pairs:¶
(A tanglei hna hi a kawp tein a hmanmi thim hna:)
| Option A | Option B |
|---|---|
a. Default value of sep in print( ) ( print( ) ah sep i a default value) |
1. ' ' |
b. Default value of end in print( ) ( print( ) ah end i a default value) |
2. Using fstring (fstring hman) |
| c. Easiest way to print output (Output chuahnak lam a fawi bik) |
3. Right justify num in 5 columns (Column 5 chungah num orh lei tlar) |
d. Return type of split( ) ( split( ) nih a chuahmi (return type)) |
4. Left justify num in 5 columns (Column 5 chungah num keh lei tlar) |
e. print('{num:>5}') |
5. list |
f. print('{num:<5}') |
6. \n |
A Phi (Answers)
| Option A | Option B |
|---|---|
| a — 1 | (sep default value cu space ' ' a si) |
| b — 6 | (end default value cu new line \n a si) |
| c — 2 | (fstring hman hi a fawi bik) |
| d — 5 | (split() nih list a chuah) |
| e — 3 | (> symbol cu Right Justify/Align a si) |
| f — 4 | (< symbol cu Left Justify/Align a si) |
Chapter 8 Lists¶
Keynote¶
8.1 Lists¶
Container timi cu data item tam nawn a khongtu (a chungah a chiahtu) a si. "Collection" asiloah "Compound data type" tiah auh a si.
Python nih a tanglei Container phun hna hi a ngei:
- Lists
- Tuples
- Sets
- Dictionaries
List cu program a kal lioah a ṭhang (grow) kho i a zor (shrink) kho. Cucaah Dynamic Array tiah auh a si. Hi a sining ruangah hin, data zeizat dah an si ti hngalh lomi (variable length data) tawlrel nak ah hman a si.
List cu [ ] (Square brackets) chungah element pawl comma , in ṭhen in ṭial a si.
# Nambat (Integer) list
num = [10, 25, 30, 40, 100]
# Cafang (String) list
names = ['Shine', 'Anna', 'Rosanna', 'Superior']
List chungah data phun aa lo lomi (dissimilar types) zong chiah khawh a si. Nain a tlangpi in cun data phun aa lomi lawng chiah tawn a si.
List chungah item pawl hi an i nawn (repeat) kho, a sullam cu list nih duplicate items a ngei kho.
String ah kan hman bantuk in, * hman in element kan duh zat kan karh (repeat) khawh. List a lawng (Empty list) zong tuah khawh a si.
ages = [25, 26, 25, 27, 26] # Duplicate (aa nawnmi) a ngah
num = [10] * 5 # [10, 10, 10, 10, 10] tiah a chiah lai
lst = [ ] # List a lawng (Empty list), a hman
8.2 Accessing List Elements¶
List min hman in list chung ummi dihlak chuah (print) khawh a si.
String bantuk in, list chung i element pakhat cio kha indices (index pawl) hman in lak khawh an si. Cucaah Sequence types tiah auh an si. Index value cu 0 in a thawk. String bantuk in, List zong kan tan (slice) khawh.# Index 1 in thawk, Index 3 hlan ah ngol (Index 3 a tel lo)
print(animals[1:3])
# Index 3 in thawk, a dongh tiang lak
print(ages[3:])
8.3 List Chung I Kalnak (Looping in Lists)¶
List chung i item pakhat cio kha tawlrel (process) kan duh ahcun, list chungah khan a nung in kan kal (iterate) khawh a hau. Hihi while loop asiloah for loop hman in tuah khawh a si.
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
# while loop hman in
i = 0
while i < len(animals) :
print(animals[i])
i += 1
# hman a fawi deuhmi for loop hman in
for a in animals :
print(a)
for loop hman in list chung kan kal lioah, element pakhat cio i a index (a umnak nambat) kha hngalh chih kan duh ahcun, built-in enumerate( ) function kha kan hman khawh.
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
# enumerate nih index (nambat) le a value (sata) kha a peh hna
# index = 0, 1, 2...
# a = Zebra, Tiger...
for index, a in enumerate(animals) :
print(index, a)
8.4 Basic List Operations (List Tuah Khawhmi Thil Hna)¶
Mutability (Thlen Khawh Sining) - String he i lo loin, List hna cu mutable (thlen khawh) an si. Cucaah list hna cu a tanglei bantuk in thlen asiloah update khawh an si:
animals = ['Zebra', 'Tiger', 'Lion', 'Jackal', 'Kangaroo']
ages = [25, 26, 25, 27, 26, 28, 25]
# 1. Element pakhat thlen (Update single item)
animals[2] ='Rhinoceros' # Index 2 (Lion) kha 'Rhinoceros' ah a thleng
ages[5] = 31 # Index 5 kha 31 ah a thleng
# 2. Slice hman in element tam nawn thlen
# Index 2 in 4 tiang (2, 3, 4) kha [24, 25, 32] in a thleng
ages[2:5] = [24, 25, 32]
# 3. Slice hman in element hrawh (Delete)
# Index 2 in 4 tiang kha a hlonh/hrawh (Empty list in thlen)
ages[2:5] = [ ]
Concatenation (Peh/Fonk) - List pakhat cu list dang a donghnak ah a tanglei bantuk in kan peh (concatenate) khawh:
lst = [12, 15, 13, 23, 22, 16, 17]
# List hlun (+ sign) List thar
lst = lst + [33, 44, 55]
print(lst)
# A chuahmi: [12, 15, 13, 23, 22, 16, 17, 33, 44, 55]
s = [10, 20, 30]
t = [100, 200, 300]
# s le t kan fonh i z ah kan chiah
z = s + t
print(z) # [10, 20, 30, 100, 200, 300] tiah a chuah lai
Conversion (Thlen) - String, tuple, asiloah set hna cu list( ) function hman in List ah kan thlen khawh hna.
lst = list('Africa')
# String kha list ['A', 'f', 'r', 'i', 'c', 'a'] ah a thlen
print(lst)
Aliasing - List pakhat kha list dang ah kan chiah (assign) tikah, an pahnih in list khat kha an sawh (refer). Pakhat kan thlen ahcun a dang pakhat zong kha a thleng ve. Hi thil hi Shallow copy asiloah Aliasing tiah auh a si.
lst1 = [10, 20, 30, 40, 50]
lst2 = lst1 # List a copy lo. lst2 nih lst1 he list khat a sawh.
print(lst1) # [10, 20, 30, 40, 50] tiah a chuah
print(lst2) # [10, 20, 30, 40, 50] tiah a chuah
lst1[0] = 100 # lst1 kan thlen
print(lst1[0], lst2[0]) # lst2 zong a thleng ve. 100 100 tiah a chuah
Cloning - Mah hi cu list pakhat i a chung thil pawl kha list dang ah copy tuah a si. Copy kan tuah hnu ahcun, an pahnih in list dang dang an sawh (refer), nain a chung value tu cu an i khat. List pakhat kan thlen ahcun, a dang pakhat kha a thleng ve lo. Hi thil hi Deep copy tiah auh a si.
lst1 = [10, 20, 30, 40, 50]
lst2 = [ ] # list a lawng
lst2 = lst2 + lst1 # lst1 le lst2 cu list dang dang an si cang
print(lst1) # [10, 20, 30, 40, 50] tiah a chuah
print(lst2) # [10, 20, 30, 40, 50] tiah a chuah
lst1[0] = 100 # lst1 lawng a thleng
print(lst1[0], lst2[0]) # 100, 10 tiah a chuah (lst2 a thleng lo)
in membership operator hman in kan kawl khawh. A tanglei bantuk in:
lst = ['a', 'e', 'i', 'o', 'u']
# 'a' cu list chungah a um caah True a chuah (return)
res = 'a' in lst
# 'z' cu list chungah a um LO caah True a chuah (return)
res = 'z' not in lst
Identity - Variable pahnih nih list khat kha an sawh (refer) maw sawh lo ti kha is identity operator hman in chek khawh a si. A tanglei bantuk in:
lst1 = [10, 20, 30, 40, 50]
lst2 = [10, 20, 30, 40, 50]
lst3 = lst1
# lst1 le lst2 cu value aa lo nain, memory ah hmun dang an si
print(lst1 is lst2) # False tiah a chuah
# lst3 cu lst1 nih a sawhmi kha a sawh ve (Aliasing)
print(lst1 is lst3) # True tiah a chuah
print(lst1 is not lst2) # True tiah a chuah
int asiloah str tibantuk basic types hna sinah cun a sining a dang deuh, mah hi cinchiah a hau:
num1 = 10
num2 = 10
s1 = 'Hi'
s2 = 'Hi'
# Nambat (int) le String (str) ah cun, value aa lo ahcun
# object khat (memory hmun khat) an sawh tawn.
print( num1 is num2) # True tiah a chuah
print( s1 is s2) # True tiah a chuah
Comparison (Tahchunh) - List pahnih chung thil pawl kha tahchunh (compare) khawh a si. Tahchunhnak cu item pakhat hnu pakhat (item by item) in tuah a si i, an i loh lonak (mismatch) a um hlan lo tuah a si.
A tanglei code ah hin, 3 le 5 an i tahchunh tikah a cu b nakin a niam deuh (less than) tiah bia a khiah lai.
Emptiness (A Lawng Sining) - List pakhat a lawng (empty) maw a lawng lo ti cu not operator hman in kan check khawh.
lst = [ ]
# List a lawngmi cu Python ah 'False' a si.
# Cucaah 'not lst' cu 'True' a si lai.
if not lst :
print('Empty list')
Alternately (Lam dang in) - List kha boolean ah thlen in a phi (result) kan check khawh.
Note: A tanglei value pawl hi False an si tiah ruah an si:
None
# Zero he aa lukmi nambat pawl:
0, 0.0, 0j
# String, List le Tuple a lawngmi (Empty):
'', "", [], ()
# Set le Dictionary a lawngmi (Empty):
{}
8.5 Using Built-in Functions on Lists (List Cungah Built-in Function Pawl Hman)¶
List he hman khawhmi built-in function tam pi a um.
len(lst) # List chung i item zat a chuah
max(lst) # List chung i a ngan bik (maximum) element a chuah
min(lst) # List chung i a niam bik (minimum) element a chuah
sum(lst) # List chung element dihlak a fonh (sum) a chuah
any(lst) # List chung i element *pakhat khat* True a si ahcun True a chuah
all(lst) # List chung i element *dihlak* True an si ahcun True a chuah
del( ) # Element, slice, asiloah list dihlak hrawh nak
sorted(lst) # List a tlar (sort) ciami a chuah, a hrampi list a thleng lo
reversed(lst) # List let (reverse) nak ah hman a si
sorted( ) le reversed( ) cu hika hnu section hnihnak ah kan chim te lai. del( ) function hman ning cu a tanglei bantuk in a si:
lst = [10, 20, 30, 40, 50]
del lst[3] # List chung i item 3-nak hlonh/hrawh
del lst[2:5] # List chung i item 2 in 4 tiang hlonh/hrawh
del lst[:] # List dihlak hlonh/hrawh
lst = [ ] # List dihlak hlonh nak lam dang
Variable tam nawn nih list khat an sawh (refer) ahcun, pakhat hlonh (delete) asiloah thlen nih a dang pawl kha a hrawh ve hna lo.
lst1 = [10, 20, 30, 40, 50]
lst3 = lst2 = lst1 # An dihlak in list khat an sawh
lst1 = [ ] # lst1 cu list thar (a lawngmi) a sawh cang;
# lst2 le lst3 cu list hlun a sawh rih
print(lst2) # [10, 20, 30, 40, 50] tiah a chuah
print(lst3) # [10, 20, 30, 40, 50] tiah a chuah
Variable tam nawn nih list khat an sawh (refer) i, kha list chung thil vialte kha hrawh (delete) kan duh ahcun, a tanglei bantuk hin kan tuah khawh:
# List chung item vialte hrawh (slice hman in)
lst2[:] = [ ]
# List khat kha an sawh (refer) caah, an dihlak in a lawng cang lai
print(lst2) # [ ] tiah a chuah
print(lst3) # [ ] tiah a chuah
8.6 List Methods (List Method Pawl)¶
List paohpaoh hi list type object an si. A chung i method pawl kha lst.method( ) tiin kan hmang khawh hna. A tanglei hi hman tam bikmi method pawl an si:
lst = [12, 15, 13, 23, 22, 16, 17] # list sernak
lst.append(22) # A donghnak ah item thar (22) telh nak
lst.remove(13) # List chungin item 13 hrawh nak
lst.remove(30) # ValueError a chuah lai, 30 cu list chungah a um lo
lst.pop( ) # A dongh bik i a ummi item hrawh nak
lst.pop(3) # Index 3-nak i a ummi item hrawh nak
lst.insert(3,21) # Index 3-nak hmun ah 21 va thun (insert) nak
lst.count(23) # List chungah 23 hi voi zeizat dah a um ti relnak
idx = lst.index(22) # 22 a umnak index nambat kawlnak
idx = lst.index(50) # ValueError a chuah lai, 50 cu list chungah a um lo
8.7 Sorting and Reversing (Tlar le Let)¶
List chung i element pawl a let (reverse) ning le a tlar (sort) ning method hmannak cu a tanglei bantuk hi a si:
lst = [10, 2, 0, 50, 4]
# List chung thil pawl a hram thawk in a let (reverse) nak
lst.reverse( )
print(lst) # [4, 50, 0, 2, 10] tiah a chuah lai
# List chung thil pawl a niam in a sang (ascending) ah tlar nak
lst.sort( )
print(lst) # [0, 2, 4, 10, 50] tiah a chuah lai
# A sang in a niam (descending) ah tlar nak
lst.sort(reverse = True)
print(lst) # [50, 10, 4, 2, 0] tiah a chuah lai
- Cinchiah ding:
reverse( )lesort( )method hna nih hin list thar an chuah (return) lo. An pahnih in a hrampi list kha a hmun (in place) ah an thlen (manipulate) colh.
List let (reverse) ning le tlar (sort) ning built-in function hman ning cu a tanglei bantuk hi a si:
lst = [10, 2, 0, 50, 4]
# List a tlar (sort) ciami a chuah, nain a hrampi list 'lst' a thleng lo
print(sorted(lst)) # [0, 2, 4, 10, 50] tiah a chuah lai
# A sang in a niam ah tlar nak (Descending order)
print(sorted(lst, reverse = True)) # [50, 10, 4, 2, 0] tiah a chuah lai
# reversed() nih iterator a chuah caah list() in kan thlen a hau
print(list(reversed(lst))) # [4, 50, 0, 2, 10] tiah a chuah lai
sorted( ) function nih cun list thar (a tlar ciami) kha a chuah (return) i, a hrampi list (original list) cu a thleng lo. Cun, reversed( ) function nih hin list_reverseiterator object a chuah tawn caah, a let (reversed) ciami list kan hmuh khawh nakhnga list( ) function hman in thlen a hau.
List let (reversal) cu a tanglei bantuk in slicing hman zongin a tuah khawh:
lst = [10, 2, 0, 50, 4]
# List a hram thawk in a dongh tiang a let (reverse) in laknak
print(lst[::-1]) # [4, 50, 0, 2, 10] tiah a chuah lai
8.8 List Varieties (List Phunphun)¶
List chungah list dang a ummi (nested lists) zong kan ser khawh.
a = [1, 3, 5, 7, 9]
b = [2, 4, 6, 8, 10]
# List 'a' le 'b' kha list 'c' chungah kan thun hna
c = [a, b]
# Index hnih hman a hau (Row le Column bantuk in)
# c[0][0] -> List 0-nak i element 0-nak (1)
# c[1][2] -> List 1-nak i element 2-nak (6)
print(c[0][0], c[1][2]) # 1 6 tiah a chuah lai
List pakhat cu list dang chungah kan thun (embed) khawh.
x = [1, 2, 3, 4]
# List 'x' kha list 'y' chungah a ummi item pakhat bantuk in kan thun
y = [10, 20, x, 30]
print(y)
# A chuahmi (output): [10, 20, [1, 2, 3, 4], 30]
* operator hman in a chung thil hna kha kan unpack (phoih/thep) khawh hna.
s = 'Hello'
l = [*s]
# String kha a cafang pakhat cio in a phoih (unpack) hna
print(l) # ['H', 'e', 'l', 'l', 'o'] tiah a chuah lai
x = [1, 2, 3, 4]
# List 'x' chung i a ummi nambat hna kha a hmun cio ah a phoih hna
y = [10, 20, *x, 30]
print(y) # [10, 20, 1, 2, 3, 4, 30] tiah a chuah lai
8.9 Stack Data Structure¶
Data structure timi cu memory chungah sining pakhat (arrangement) in hnaṭuan khawh nakhnga thil tuahmi a si. Stack, queue, tree, graph le map hna hi minthang bikmi data structure an si.
Stack cu Last In First Out (LIFO) list a si. Mah cu a dongh bikah kan telhmi (last element) kha a hmasa bikah kan hlonhmi (first element) a si tinak a si.
- Stack chungah element thar telh kha Push operation tiah auh a si.
- Stack chungin element hlonh/chuah kha Pop operation tiah auh a si.
Hi hnaṭuannak pahnih hi list i a donghnak (rear end) ah tuah tawn a si. append() le pop() method hna hmang in Stack cu a tanglei bantuk in tuah khawh a si.
8.10 Queue Data Structure¶
Queue cu First In First Out (FIFO) list a si. Mah cu a hmasa bikah kan telhmi kha a hmasa bikah kan hlonhmi a si tinak a si (Minung tlar (line) kan i tlar bantuk in).
Queue caah hin List hna hi hman an tlak (efficient) tuk lo. A chanchu, List i a hram (beginning) in thil hlonh tikah, a dang element vialte kha hmun khat cio va ṭuan (shifting) a herh caah a tlawm (slow).
Cucaah, thil telh le hlonh a ran nakhnga, collections module chung i deque class kha hman deuh a si.
Deque timi cu Double Ended Queue tinak a si. Deque ah cun a hram le a dongh (both ends) hmun hnih in thil telh le hlonh khawh a si.
Problems¶
Problem 8.1¶
List Operation Tuah Ning Tahchunhnak¶
A tanglei hnaṭuannak (operations) hna hi min tlar (list of names) cungah tuah hna:
- Min 5 unnak list ser - 'Anil', 'Amol', 'Aditya', 'Avi', 'Alka'
- 'Anuj' kha 'Aditya' hlan ah thun (Insert)
- 'Zulu' kha a donghnak ah telh (Append)
- 'Avi' kha list chungin hlonh (Delete)
- 'Anil' hmun ah 'AnilKumar' in thlen (Replace)
- Min vialte kha a tlar (Sort) in chiah
- A tlar ciami kha a let (Reverse) in print tuah
Program
# 1. Min 5 unnak list sernak
names = ['Anil', 'Amol', 'Aditya', 'Avi', 'Alka']
print(names)
# 2. 'Anuj' kha 'Aditya' hlan (index 2) ah thun (insert) nak
names.insert(2, 'Anuj')
print(names)
# 3. 'Zulu' kha a donghnak ah telh (append) nak
names.append('Zulu')
print(names)
# 4. 'Avi' kha list chungin hlonh (delete) nak
names.remove('Avi')
print(names)
# 5. 'Anil' hmun ah 'AnilKumar' in thlen (replace) nak
i = names.index('Anil') # 'Anil' a umnak index kawl hmasa a hau
names[i] = 'AnilKumar'
print(names)
# 6. Min vialte kha a tlar (sort) in chiah nak
names.sort( )
print(names)
# 7. A tlar ciami kha a let (reverse) in print tuah nak
names.reverse( )
print(names)
Output
['Anil', 'Amol', 'Aditya', 'Avi', 'Alka']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Avi', 'Alka']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Avi', 'Alka', 'Zulu']
['Anil', 'Amol', 'Anuj', 'Aditya', 'Alka', 'Zulu']
['AnilKumar', 'Amol', 'Anuj', 'Aditya', 'Alka', 'Zulu']
['Aditya', 'Alka', 'Amol', 'AnilKumar', 'Anuj', 'Zulu']
['Zulu', 'Anuj', 'AnilKumar', 'Amol', 'Alka', 'Aditya']
Problem 8.2¶
List Nambat Hna Hman Ning Tahchunhnak
A tanglei hnaṭuannak (operations) hna hi nambat tlar (list of numbers) cungah tuah hna:
- Nambat unbalanced (odd numbers) 5 unnak list ser
- Nambat balanced (even numbers) 5 unnak list ser
- List pahnih kha fonh (Combine)
- A hram (beginning) ah prime number 11, 17, 29 pawl telh
- List chungah element zeizat dah a um ti langhter (Report)
- A dongh bik nambat 3 kha 100, 200, 300 in thlen
- List chung nambat vialte hlonh (Delete all numbers)
- List dihlak hrawh (Delete the list)
Program
# 1. Nambat unbalanced (odd numbers) 5 unnak list sernak
a = [1, 3, 5, 7, 9]
print(a)
# 2. Nambat balanced (even numbers) 5 unnak list sernak
b = [2, 4, 6, 8, 10]
print(b)
# 3. List pahnih kha fonh (combine) nak
a = a + b
print(a)
# 4. A hram (beginning) ah prime number 11, 17, 29 pawl telh nak
a = [11, 17, 29] + a
print(a)
# 5. List chungah element zeizat dah a um ti rel (report) nak
num = len(a)
print(num)
# 6. A dongh bik nambat 3 kha 100, 200, 300 in thlen (replace) nak
a[num-3:num] = [100, 200, 300]
print(a)
# 7. List chung nambat vialte hlonh (delete all) nak
a[:] = [ ]
print(a)
# 8. List dihlak hrawh (delete list) nak
del a
Output
Problem 8.3¶
Stack data structure pakhat tuah ning (implement) tialnak: Stack cu Last In First Out (LIFO) list a si i, thil telh (addition) le hlonh (deletion) kha a hmun khat (a donghnak lei) ah tuah a si.
Program
Hrilhfiahnak zoh nak caah hika hi hmet
- LIFO (Last In First Out): 'Avi' kha a hnu bikah kan thun (push), nain kan chuah (pop) tikah a hmasa bikah a rak chuak.
append(): Hi method hi Stack chungah thil thar Push nak caah kan hman.pop(): Hi method nih hin a dongh bik i a ummi element kha a hrawh i, a hrawhmi kha a return (a langhter) colh.
Problem 8.4¶
Queue data structure pakhat tuah ning (implement) tialnak: Queue cu First In First Out (FIFO) list a si i, thil telh (addition) kha a donghnak (rear end) ah tuah a si, thil hlonh (deletion) kha a hram (front end) ah tuah a si.
Program
import collections
# Queue pakhat ser (deque hman in)
q = collections.deque( )
# Enqueue operations (A donghnak ah thil telh nak)
q.append('Suhana')
q.append('Shabana')
q.append('Shakila')
q.append('Shakira')
q.append('Sameera')
print(q)
# Dequeue operations (A hram bik element hlonh/chuah nak)
print(q.popleft( ))
print(q.popleft( ))
print(q.popleft( ))
print(q)
Hrilhfiahnak
collections.deque( ): Queue hnaṭuannak caah a ran deuh nakhnga (efficiency) hi module hi kan hman.append( ): List a donghnak (rear) ah min thar telh nak a si.popleft( ): Queue a hram (front) i a ummi min kha a hmasa bik in hlonh nak a si.
Output
Problem 8.5¶
10 in 100 karah random nambat 20 ser i list chungah thun ding. Mah list chungin 20 le 50 kar i a ummi nambat vialte hlonh (delete) ding. A tangmi list kha print tuah ding.
Program
import random
a = [ ]
i = 1
# Nambat 20 ser ding (Na code ah 15 a si nain, 20 ah kan thlen)
while i <= 20 :
num = random.randint(10,100)
a.append(num)
i += 1
print("A hramthawk list:", a)
# 20 le 50 kar i a ummi hlonh nak
# Cinchiah: List chungin thil kan hlonh lio ah 'for loop' hman hi a hman tawn lo,
# a hnu lei ah list thar ser ning (list comprehension) kan cawng lai.
for num in a[:] :
if num > 20 and num < 50 :
a.remove(num)
print("A tangmi list:", a)
Output
Hrilhfiahnak
random.randint(10, 100): 10 le 100 karah random nambat pakhat a lak (generate) nak a si.a.remove(num): Nambat pakhat kha a hmuh hmasa biknak hmun ah a hlonh nak a si.a[:]: Loop kan hman lio ah list kan thlen (modify) duh ahcun, a hrampi list (original) kha copy ([:]) in hman a him deuh, khatah cun nambat cheukhat a hmaih (skip) khawh.
Problem 8.6¶
3 x 4 matrix pahnih fonh khawhnak program pakhat tial ding.
Program
# Matrix pahnih sernak
mat1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
mat2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
# A phi chiah nak ding matrix a lawngin ser hmasa
mat3 = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# A tlar (rows) vialte tler (iterate) nak
for i in range(len(mat1)) :
# A tler (columns) vialte tler nak
for j in range(len(mat1[0])) :
# A hmun aa khatmi element pahnih fonh i mat3 ah khumh
mat3[i][j] = mat1[i][j] + mat2[i][j]
print(mat3)
Hrilhfiahnak
range(len(mat1)): Matrix chungah tlar (row) zeizat dah a um ti kha a rel i, cu zat cu loop a kalpi.range(len(mat1[0])): Tlar khat (row) chungah tler (column) zeizat dah a um ti kha a rel.mat3[i][j]:mat1lemat2i an nambat hmun (index) aa khatmi cio kha fonh inmat3chungah a thun hna.
Exercises¶
[A] A tanglei program hna i a chuak dingmi (output) kawl nak:¶
a.
b.
c.d.
e.
f.
num1 = [10, 20, 30, 40, 50]
num2 = num1
print(id(num1))
print(type(num2))
print(isinstance(num1, list))
print(num1 is num2)
g.
h. i. j.[B] Attempt the following questions:¶
(a) A hnuai i thil pawl lakah hin a hlei (valid) mi Python List cu zeidah a si?
['List'] | {"List"} | ("List") | "List"
(b) A hnuai i code hi na run (execute) ahcun zeidah a cang lai?
© A hnuai i code hman hnuah hin, lam dang zeiti dek in 30 le 40 hi hloh khawh an si rih lai?(d) A hnuai i list pawl lakah hin a hmaan lomi (INCORRECT) cu zeidah a si?
a = [0, 1, 2, 3, [10, 20, 30]]a = [10, 'Suraj', 34555.50]a = [[10, 20, 30], [40, 50, 60]]
(e) A hnuai i list num1 hman hin, num2 list cu zeitin dek na ser lai?
num2 result: ['A', 'B', 'C', 10, 20, 30, 40, 50, 'Y', 'Z']
(f) Pekmi list: lst = [10, 25, 4, 12, 3, 8]
Hi list hi a ngan bik in a hme bik (descending order) tlar tein zeiti dek na tuah lai?
(g) Pekmi list:
lst = [10, 25, 4, 12, 3, 8]
30 hi hi list chungah a um le um lo zeiti dek na check lai?
(h) Pekmi list: lst = [10, 25, 4, 12, 3, 8]
Hi list chungah hin 25 le 4 karah 30 kha zeiti dek na telh (insert) lai?
(i) Pekmi string: s = 'Hello'
Hi biafang (string) hi list ['H', 'e', 'l', 'l', 'o'] ah zeiti dek na canter lai?
[C] Answer the following questions:¶
a. List pakhat ser le thlen ning Namba pa (odd integers) namba 5 a ummi list pakhat tial u. A voithumnak (third element) kha namba nu (even integers) namba 4 a ummi list pakhat in thlen u. Mah hnuah list vialte kha phelh (flatten) u i, a hme bik in a ngan bik (sort) tlar tein langhter u.
b. Namba umnak hmun (position) kawlning List pakhat chungah random in namba 20 a um tiah ruat u. Keyboard (input) in namba pakhat tial u i, mah namba cu list chungah a hmun (index) zeizat hna ah dah a um tiah report tial u.
c. A hlei mi (duplicates) hlohning List pakhat chungah namba 20 a um. List chung i namba aa khatmi (duplicates) vialte hlohtu program pakhat tial u.
d. Namba (+) le (-) thleidanning List pakhat chungah namba ttha (positive) le namba chia (negative) an um tti. List thar pahnih ser u—pakhat ah namba ttha (positive) vialte chiah i, a dang pakhat ah namba chia (negative) vialte chiah ding.
e. Biafang cafang ngan (uppercase) ah canterning List pakhat chungah biafang (strings) 5 a um. Mah biafang vialte kha cafang ngan (uppercase) ah a cantertu program tial u.
f. Temperature thlenninh (Fahrenheit to Celsius) Fahrenheit (F) in pekmi temperature list kha a tlukpitu Celsius (C) ah a cantertu program tial u.
g. A laifang namba (median) kawlning List chung i namba pawl an i tlar ning (order) thleng loin, mah list i a laifang namba (median value) kawlning program tial u.
h. Namba chia (negative) zat relning List chungah namba ttha le namba chia lawng an um. List chungah namba chia (negative numbers) zeizat dah a um tiah a reltu program tial u.
i. Biafang hmai bik cafang lakning List pakhat chungah biafang (words) tampi an um. List thar pakhat ser u i, mah list chungah cun a hmasa list i biafang pakhat cio i an hmai bik cafang (first character) kha khumh u.
j. Namba 10 chung i a hlei mi hlohning List pakhat chungah namba 10 a um. List chung i aa khatmi (duplicates) vialte hlohtu program tial u.
k. Mean, Median, le Mode kawlning Namba 10 a ummi list pakhat chungah a tlangpi (mean), a laifang (median), le a chuak tam bik (mode) kawltu program tial u.
Chapter 9 Tuples¶
Keynote¶
9.1 Tuples Kong Hngalhnak¶
Tuples timi cu zeidah an si?
- Data i khumhning: List nih hin thil aa khatmi (similar data) khumh nakhnga hman a si tawn nain, Tuple cu thil aa dangdang (dissimilar data) khumh nakhnga hman a si deuh tawn.
- Hmelkhunnak: Tuple tial tikah cun parentheses
( )hman a si.
Tuple Serning (Defining Tuples)¶
A tang lei bantuk hin Tuple phunphun a ser khawh:
a = ( ) # Zeihmanh a um lonak (empty tuple)
b = (10,) # Thil pakhat lawng a ummi tuple. 10 hnuah khit (,) chiah a herh.
c = ('Sunny', 25, 34555.50) # Thil i dangdang (string, int, float) a khumhmi
d = (10, 20, 30, 40) # Thil aa khatmi namba lawng a khumhmi
Tuple Serning i Ralrin Dingmi (Tuple Initialization Rules)¶
-
Tuple
bna ser tikah, 10 hnuah khit (comma) na hman lo a si ahcun, Python nihbkhaint(namba sawhsawh) tiah a rel lai. -
Tuple na thawk (initialize) tikah, a tlangpi i kan hmanmi hmelkhunnak
( )kha na hlo (drop) khawh.
c = 'Sunny', 25, 34555.50 # thil tampi a ummi tuple
print(type(c)) # c cu tuple phun a si tiah a langhter lai
Tuple Chung i Thil aa Khatmi (Duplicate Items) Kong¶
- Tuple chung i thil (items) hna cu voi tampi an i khat (repeat) khawh, cu sullam cu tuple chungah thil aa khatmi (duplicate) an um khawh.
- Asinain, list he an i dannak cu, tuple chung i thil pawl kha
*operator hman in voi tampi tial (repeat) khawh a si lo (tuple asiloah namba na ser sining a dang lai).
tpl1 = (10,) * 5 # Hi nih hin (10, 10, 10, 10, 10) tiah a khumh lai
tpl2 = (10) * 5 # Hi nih hin (50) tiah a khumh lai
9.2 Tuple Chung i Thil Pawl Zohnak (Accessing Tuple Elements)¶
Tuple min lawng hman in a chung i a ummi thil vialte (entire tuple) kha print (chuahter) khawh an si.
Tuple Index Hmanning¶
Tuple cu i tlar tein khumhmi (ordered collection) a si. Cucaah, tuple chungah thil na telh (insertion) tlar le na lak (access) tlar cu an i khat. String le list bantuk thiamthiam in, tuple chung i thil (items) hna zong kha 0 in thawkmi index hman in lak khawh an si.
Tuple Hmunhma Phelhning (Slicing)¶
String le list bantuk thiamthiam in, tuple zong kha hme deuhmi (smaller tuples) chuahter nakhnga hmunhma phelh (slice) khawh an si.
emp = ('Sunny', 23, 23000, 1760, 2040)
print(emp[1:3]) # (23, 23000) kha a chuahter lai
print(emp[3:]) # (1760, 2040) kha a chuahter lai
print(emp[:3]) # ('Sunny', 23, 23000) kha a chuahter lai
### 9.3 Tuple Chungah Loop Hmannak (Looping in Tuples)¶
Tuple chung i thil (item) pakhat cio kha tuah duhmi (process) kan ngeih a si ahcun, a chungah kan luh (iterate) khawh a herh. Hihi while loop asiloah for loop hman in tuah khawh a si.
tpl = (10, 20, 30, 40, 50)
# While loop hman in zohnak
i = 0
while i < len(tpl) :
print(tpl[i])
i += 1
# For loop hman in zohnak
for n in tpl :
print(n)
Index le Item a Rual i Zohnak (Using enumerate)¶
For loop hmangin tuple chung i thil (elements) pawl kan zoh (iterate) tikah, atu lio i kan tuah lio mi thil kha a index (a hmun namba) zeizat nak dah a si ti hngalh kan duh ahcun, Python i a tel chih saumi enumerate() function hi hman khawh a si.
9.4 Tuple Hmanung Bik i A Sining Pawl (Basic Tuple Operations)¶
Mutability (Thlen khawh sining) - List he an i dannak cu, tuple cu immutable a si, cu sullam cu thlen khawh (modify) a si lo.
msg = ('Fall', 'In', 'Line')
# Index hman in thlen na duh ahcun 'error' a chuak lai
msg[0] ='FALL' # error
# Slicing hman in thlen na duh zongah 'error' a chuak lai
msg[1:3] = ('Above', 'Mark') # error
Tuple ah Thil Chap le Hloh Khawh a Sinning¶
Tuple cu thlen khawh a si lo (immutable) caah, thil chapnak append, hlohnak remove, le a laifang i telhnak insert ti bantuk hna hi Tuple ah cun an hman khawh lo.
msg = ('Fall', 'In', 'Line')
msg.append('Like') # error (a hnu ah chap khawh a si lo)
msg.remove('Line') # error (hloh khawh a si lo)
msg.insert(1, 'Above') # error (a laifang ah telh khawh a si lo)
Tuple le Thlen Khawhmi Thil (Mutable Objects)¶
Tuple amah hrimhrim cu thlen khawh a si lo (immutable) nain, a chungah thlen khawhmi thil (mutable objects) — phuungchimnak ah lists ti bantuk — kha a khumh khawh hna.
# thlen khawhmi lists le thlen khawh lomi string—vialte hi tuple chungah an um tti kho
s = ([1, 2, 3, 4], [4, 5], 'Ocelot')
Tuple Chung i List Thlenning¶
Tuple chungah list a um a si ahcun, mah list cu thlen khawh (mutable) a si caah a chung thil pawl kha thleng khawh an si.
s = ([1, 2, 3, 4], [10, 20], 'Oynx')
# A voihnihnak list i a voihnihnak item (20) kha 45 ah kan thlen lai
s[1][1] = 45
print(s) # ([1, 2, 3, 4], [10, 45], 'Oynx') tiah a chuak lai
# List chung i thil thlenning lam dang pakhat
p = s[1] # A voihnihnak list kha variable 'p' ah kan chiah
p[1] = 100 # p chung i a voihnihnak item kha 100 ah kan thlen
print(s) # ([1, 2, 3, 4], [10, 100], 'Oynx') tiah a chuak lai
Tuple chungah tuah khawhmi a dang sining (operations) pawl hi List chung i tuah khawhmi sining hna he khan an i lo ngai. Hi sining pawl hi tlangtar (Chapter) 8 nakah hrilhfiahnak tial an si cang. Exercise (cawnnak) caah a tang lei i Tuple sining hna hi na rak hneksak kho hna:
- Concatenation (Tuple pahnih fonhning)
- Merging (Tuple i komhter/hmerhnaning)
- Conversion (Phun dang ah canterning)
- Aliasing (Min dang peknak/Copy ttha lo)
- Cloning (A laksawng thar i serning/Copy tthanning)
- Searching (A chung thil kawlning)
- Identity (A hmun aa khat maw ti check-ning)
- Comparison (I tluk le tluk lo tahchunhning)
- Emptiness (A chungah zeihmanh a um le um lo check-ning)
9.5 Tuple ah Python i a tel chih saumi Function (Built-in Functions) Hmannak¶
Python i a tel chih saumi function (built-in functions) tampi hi Tuple he hman tti khawh an si.
t = (12, 15, 13, 23, 22, 16, 17) # tuple serning
len(t) # tuple t chung i thil (items) zeizat dah a um ti a langhter
max(t) # tuple t chung i a ngan bik namba a chuak lai
min(t) # tuple t chung i a hme bik namba a chuak lai
sum(t) # tuple t chung i namba vialte a fonh (sum) lai
any(t) # tuple chung i thil pakhat hmanh a hmaan (True) ahcun True a chuak lai
all(t) # tuple chung i thil vialte an hmaan (True) dih lawngah True a chuak lai
sorted(t) # a hme bik in a ngan bik tlar tein a ser lai (asinain list phun in a chuak lai)
reversed(t) # tuple chung thil pawl a hnu lei in a let (reverse) lai
9.6 Tuple Methods (Tuple chung i Phunglam Hna)¶
Tuple pakhat paohpaoh hi tuple phun (object) an si. A chung i method (phunglam) hna kha tpl.method() tiin hman khawh an si. A tang lei i hmuhsaknak ah hin method pahnih hmannak langhter a si:
tpl = (12, 15, 13, 23, 22) # tuple serning
# count(23) nih hin tuple chungah 23 hi zeizat dah a um ti a rel lai
print(tpl.count(23))
# index(22) nih hin 22 hi index zeizatnak ah dah a um ti a langhter lai
print(tpl.index(22))
# tuple chung i a um lomi namba (50) na kawl ahcun ValueError (error) a chuak lai
print(tpl.index(50))
9.7 Tuple Phunphun (Tuple Varieties)¶
Tuple chungah tuple dang khumh (tuple of tuples) hi a ngah ko.
a = (1, 3, 5, 7, 9)
b = (2, 4, 6, 8, 10)
c = (a, b) # Tuple pahnih a khumhmi tuple thar
# c[0][0] cu tuple 'a' i a hmai bik item (1) a si
# c[1][2] cu tuple 'b' i a voithumnak item (6) a si
print(c[0][0], c[1][2])
records = (
('Priya', 24, 3455.50),
('Sunny', 25, 4555.50),
('Sunday', 25, 4505.50),
('Sonia', 27, 4455.55)
)
# Record pakhatnak (index 0) i a chung thil (Priya, 24, 3455.50) zohnak
print(records[0][0], records[0][1], records[0][2])
# Record pahnihnak (index 1) i a chung thil (Sunny, 25, 4555.50) zohnak
print(records[1][0], records[1][1], records[1][2])
# For loop hman in tuple chung thil pawl (name, age, salary) tthen i chuahterning
for n, a, s in records :
print(n, a, s)
Tuple pakhat chungah tuple dang kha thun (embed) khawh a si.
x = (1, 2, 3, 4)
y = (10, 20, x, 30)
# y kha print na tuah tikah x kha tuple pakhat angin a chungah a um lai
print(y) # (10, 20, (1, 2, 3, 4), 30) tiah a chuak lai
* operator hman in phelh (unpack) i, tuple dang chungah thun khawh a si.
x = (1, 2, 3, 4)
y = (10, 20, *x, 30)
# *x nih x chung i thil pawl kha a phelh dih hna caah,
# y cu (10, 20, 1, 2, 3, 4, 30) tiah a chuak lai.
print(y)
# Tuple hna khumhmi list (List of tuples)
lst = [('Priya', 24, 3455.50), ('Sunny', 25, 4555.50)]
# List hna khumhmi tuple (Tuple of lists)
tpl = (['Priya', 24, 3455.50], ['Sunny', 25, 4555.50])
List of Tuples asiloah Tuple of Lists kha Sort Tuahning¶
List of tuples asiloah tuple of lists kan ngeih tikah, a tang lei bantuk hin tlar tein (sort) kan chiah kho hna:
import operator
# A chung i a ummi tuple/list hna ah min (name), kum (age), le lawhman (salary) an um
lst = [('Shailesh', 24, 3455.50), ('Priyanka', 25, 4555.50)]
tpl = (['Shailesh', 24, 3455.50], ['Priyanka', 25, 4555.50])
# A hrampi (index 0) i a ummi 'min' (name) ningin sort a tuah lai
print(sorted(lst))
print(sorted(tpl))
# Index 2 (salary) ningin sort tuah kan duh ahcun itemgetter(2) kan hman lai
print(sorted(lst, key = operator.itemgetter(2)))
print(sorted(tpl, key = operator.itemgetter(2)))
Sorted() le Itemgetter() Hmannak¶
-
A hrampi (default) ahcun,
sorted()function nih hin list/tuple chung i thil hna kha a hmaitlung bik (index 0), phuungchimnak ah "min" (name) ningin, tlar tein (sort) a chiah hna. -
Lohman (salary) ningin sort tuah kan duh a si ahcun, operator module chung i
itemgetter()function hi kan hman a herh. -
sorted()ikeyparameter nih hin "function" (sort tuah dingmi thil cung i hman dingmi phunglam) a herh, "value" (namba asiloah biafang) pakhat sawhsawh a herh lo. -
operator.itemgetter(2)nih hin list/tuple chungin lohman (salary) a la (fetch) tu ding function pakhat a kan pek lai. -
A tlangpi (in general) ah cun,
operator.itemgetter(n)nih hin list/tuple kha input ah a la i, mah chung i n-th element (a n-nak hmun i a ummi) kha a la (fetch) tu ding function a ser.
Problems¶
Problem 8.1¶
divmod() function chungah tuple pakhat thun law, a phu (quotient) le a hlei (remainder) kha la (obtain) hna.
Program
Tips
divmod()chungaht(tuple) kha a hlang (as a single object) in kan thun ahcun error a chuak lai. Tuple kha a phel (unpack) in namba pahnih (distinct values) ah kan canter hmasat a herh i, mah hnu lawngahdivmod()ah khan thun ding a si.divmod()nih cun a phu (quotient) le a hlei (remainder) aa telmi tuple pakhat a kan pek tthan lai.
Problem 8.2¶
A tang lei operations (tuahsernak) hna tuah nakhnga Python program pakhat tial:
- 10 i a let (multiples) a hmasa bik 10 kha tuple pakhat chungah khumh (pack) hna.
- Mah tuple chung thil 10 kha variable 10 ah phelh (unpack) hna, variable pakhat cio nih thil pakhat cio an i tlaih lai.
- Tuple kha a tang lei bantuk hin phelh (unpack) hna: a hmasa bik thil kha variable
xah, a hnu bik thil khayah, thil dang a laifang i a ummi vialte cu hlawt (disposable) variable_pakhat cio ah chiah hna. - Tuple kha a tang lei bantuk hin phelh (unpack) hna: a hmasa bik thil kha variable
iah, a hnu bik thil khajah, thil dang a laifang i a ummi vialte cu hlawt (disposable) variable_pakhat lawng (single variable) ah i khumhter dih hna.
Program
Output
Tips
- Hlawt khawhmi (disposable) variable
_hi a tlangpi ah cun mah variable kha hmai lei ah hman na duh ti lo tikah, a hmun-hma tlaihtu (place-holder) lawngin hman a si tawn.
Problem 8.3¶
List pakhat chungah ngakchia pa le ngakchia nu hna i an min pawl kha thil (elements) angin an um. Ngakchia pa pawl i an min cu tuple phun in khumh an si. Mah list chungah ngakchia pa le ngakchia nu zeizat dah an um ti kawlnak Python program pakhat tial.
Program
Tips
isinstance()function nih hin thil (element) pakhat kha tuple phun (type) a si le si lo a chek.- Tuple chungah thil (element) pakhat lawng a um tikah, a hnuah khit (comma) a um hrimhrim a herh ti kha philh hlah.
Problem 8.4¶
List pakhat chungah siangngakchia pawl i an roll namba, an min, le an kum hna aa telmi tuple hna an um. Mah list chung i siangngakchia min vialte kha list dang pakhat chungah khumh (gather) dih nakhnga Python program pakhat tial.
Program
Tips
nlsthi a hramthawk (begin) ah cun zeihmanh a um lomi list (empty list) a si. Loop na hman lio (iteration) paohah khan,ele[1]hman in tuple chungin "min" (name) kha lak a si i, mah khanlstchungah cun chap (added) a si tawn.
Problem 8.5¶
Tuple ('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd') hi hmang law, a tang lei operations (tuahsernak) hna hi tuah nakhnga Python program pakhat tial:
- Tuple a hnu bik ah "!" pakhat chap (add) lai.
- Tuple kha biafang (string) ah na canter (convert) lai.
- Tuple chungin ('b', 'b') kha na chuah (extract) lai.
- Tuple chungah 'e' hi zeizat dah a um ti na kawl lai.
- Tuple chungah 'r' a um le um lo na chek lai.
- Tuple kha list ah na canter (convert) lai.
- Tuple chungin 'b', 'b', 'e', 'r' ti hmi biafang hna kha na hloh (delete) lai.
Program
tpl = ('F', 'l', 'a', 'b', 'b', 'e', 'r', 'g', 'a', 's', 't', 'e', 'd')
# Tuple cu thlen khawh a si lo caah '!' chap khawh a si lo
# Cucaah tuple thar kan ser lai i 'tpl' kha mah tuple thar tu kha kohnter (refer) a herh
tpl = tpl + ('!',)
print(tpl)
# Tuple kha string (biafang) ah canterning
s = ''.join(tpl)
print(s)
# Tuple chungin ('b', 'b') kha slicing hman in lakning
t = tpl[3:5]
print(t)
# Tuple chungah 'e' zeizat dah a um ti relning
count = tpl.count('e')
print('count = ', count)
# Tuple chungah 'r' a um le um lo chekning
print('r' in tpl)
# Tuple kha list ah canterning
lst = list(tpl)
print(lst)
# Tuple cu thlen khawh a si lo caah thil (elements) kan hlo kho lo
# Cucaah tuple kha kan phel (split) lai i, kan duh lomi kan hloh hnuah
# a tangmi tuple pahnih kha kan fonh (merge) tthan lai
tpl = tpl[:3] + tpl[7:]
print(tpl)
Output
Exercises¶
[A] String, List, le Tuple hna i an sining (Properties)¶
A tang lei sining hna hi String, List, le Tuple pathum caah an hmaan dih (apply):
- Iterable: Pathum in
for loopchungah hman khawh an si. - Sliceable: Pathum in
[:]hman in a tthen lak khawh an si. - Indexable: Pathum in index
[0]hman in a chung thil lak khawh a si. - Sequence: Pathum in a hmunhmaleh (order) ningin an um.
- Can be empty: Pathum in a lawng (empty) in ser khawh an si.
- Ordered collection: A chung thil hna an umnak hmun (position) hi a hlei lo.
- Access by position: Index hman in a chung thil kha a umnak hmun (position) ningin lak khawh an si.
[B] String, List, le Tuple cung i tuah khawhmi sining (Operations)¶
Hi tuahsernak (operations) pahnih lawng hi pathum cungah tuah khawh an si:
a = b + c(Concatenation): Thil pahnih fonh in a thar serning.a += b(Augmented Assignment): A um saumi ah chap/fonhning.
Hngalhnak: Appending, Deletion, Modification, le In-place reversal hna hi List lawngah tuah khawh an si. String le Tuple cu thlen khawh an si lo (Immutable) caah mah tuahsernak hna kha an hial (error a chuak lai).
[C] Biahalnak hna i a Phi (Answers)¶
a. Is this a valid tuple? tpl = ('Square')
* Phi: Si lo (No). Python nih hihi String pakhat angin a hmuh lai. Tuple thiktuk (single element tuple) a si nakhnga cun khit (comma) telh a herh: tpl = ('Square',) tiin tial ding a si.
b. Code snippet output hrilhfiahnak:
num1 = num2 = (10, 20, 30, 40, 50)
print(id(num1), type(num2)) # num1 i memory address (id) le num2 i phun <class 'tuple'> a chuak lai
print(isinstance(num1, tuple)) # True (num1 cu tuple a si)
print(num1 is num2) # True (variable pahnih nih thil/object pakhat te an i tlaih)
print(num1 is not num2) # False (an i khat ko caah 'is not' a si khawh lo)
print(20 in num1) # True (20 cu a chungah a um ko)
print(30 not in num2) # False (30 a um ko nain 'not in' kan hman caah False a si)
c. Date kha tuple (d, m, y) angin ser law, date pahnih kar i ni (days) zeizat dah a um ti kawlnak program tial.
from datetime import date
# Date pahnih kha tuple in kan ser
d1_tuple = (15, 8, 2023)
d2_tuple = (20, 1, 2024)
# Tuple chung thil hna kha date object ah kan canter (y, m, d ningin thun a herh)
date1 = date(d1_tuple[2], d1_tuple[1], d1_tuple[0])
date2 = date(d2_tuple[2], d2_tuple[1], d2_tuple[0])
# Date pahnih kan thlan (subtract) tikah ni (days) a chuak lai
delta = date2 - date1
print(f"Ni zeizat: {abs(delta.days)} days")
**d. List of tuples pakhat ser law. Tuple pakhat cio ah thil min (item) le a man (price) kha float (decimal namba) in i khumhter hna. Mah tuples hna kha a man (price) ngan bik in a hme bik (descending order) ah sort tuah nakhnga program pakhat tial.**
*Hint: `operator.itemgetter()` kha hmang.*
**e. User pakhat nih a ngeihmi share hna i an sining (data) kha a tang lei thawnghnang (information) aa telmi tuple hna hmang in khumh (store) hna:**
* Share min (Share name)
* Khawn ni (Date of purchase)
* Cawk man (Cost price)
* Share zat (Number of shares)
* Zuarnak man (Selling price)
- Portfolio i a dihlak cawkman (Total cost).
- A dihlak i hlawk/miat asiloah liam (Total amount gained or lost).
- Miat asiloah liam a za phu (Percentage profit made or loss incurred)
f. List of tuples chungin tuple a lawng (empty tuple) hloh nakhnga program pakhat tial.
g. A tang lei list pathum (3) hi ser nakhnga program pakhat tial:
- Min tlar (a list of names)
- Roll number tlar (a list of roll numbers)
- Mark tlar (a list of marks)
Hi list pathum chungin min, roll number, le marks aa telmi list of tuples pakhat chuah (generate) law print tuah. Mah list cun tuple pathum — pakhat ah min vialte, pakhat ah roll number vialte, le a voithumnak ah marks vialte — a thar in chuah (generate) tthan hna.
[D] A tang lei a thuu (pairs) hna hi i tlak tein thim (match) hna:¶
| Options A (Thim ding) | Options B (A Phi) |
|---|---|
a. tpl1 = ('A',) |
1. tuple a tlang (length) 6 |
b. tpl1 = ('A') |
2. tuple chung i list hna (tuple of lists) |
c. t = tpl[::-1] |
3. Tuple |
d. ('A', 'B', 'C', 'D') |
4. list chung i tuple hna (list of tuples) |
e. [(1, 2), (2, 3), (4, 5)] |
5. String (Biafang) |
f. tpl = tuple(range(2, 5)) |
6. Tuple kha tlar tein a chiah (Sorts tuple) |
g. ([1, 2], [3, 4], [5, 6]) |
7. (2, 3, 4) |
h. t = tuple('Ajooba') |
8. string hna aa telmi tuple (tuple of strings) |
i. [*a, *b, *c] |
9. List chungah tuple hna phelh (Unpacking of tuples in a list) |
j. (*a, *b, *c) |
10. Tuple chungah list hna phelh (Unpacking of lists in a tuple) |
Chapter 27 Numpy Library¶
A Biapi Mi (Keynote)¶
Numpy ti mi cu Num**erical **Py**thon tiah a min a chuak mi a si. Hihi **Science le Engineering lei buaibainak (problems) pawl tawlrelnak ah hman a tam ngaingai mi library pakhat a si. Numpy nih a riantuan a ṭha tuk mi multidimensional array object a ngei i, array pawl cungah rian rannak tein a tuan khawh mi methods (tuahning) zong a ngei chih.
Cu riantuannak (operations) hna cu a tang lei bantuk an si:
- Kanan lei tuahnak (Mathematical)
- A hman le hman lo khiahnak (Logical)
- A pumrua / pungsan thlennak (Shape manipulation)
- A tluang tein remhnak (Sorting)
- Thimnak (Selecting)
- Data lak le chuahnak (I/O)
- Cazin zohnak (Statistical operations)
- Le a dangdang hna an si.
Fianternak tlawmpal:
Library: Programming ah hin, rian pakhatkhat ṭuan khawhnak ding caah ready-made in tuahcia mi code pawl an umnak hmun (collection) tinak a si. (Hakha ahcattawttiah an ti khawh.)Array hmuitinh (object): Data tampi kha dot (dimension) khat asiloah tampi in hrial (store) khawhnak caah tuahmi a si. Numpy array pawl hi a rang tuk in rian a ṭuan kho.
27.1 Creation of Array (Array Sernak)¶
- Numpy Library hman na duh ah cun, download le install na tuah a hau, a tanglei bantuk in:
- Numpy Array cu Python list he an i lo ngai nain, lists nakin a rian a rang deuh.
- List he aa lo lo nak cu, Numpy array chung i element (thil) vialte kha an type (phun) aa khat dih a hau.
- Numpy array ser na duh ah cun np.array() function na hman a hau i, a chung ah number list kha na pek a hau, a tanglei bantuk in:
import numpy as np
intarr = np.array([1,2,3,4]) # integer (nambar tling) array a ser
floattarr = np.array([1.1,2.2,3.3,4.4]) # float (nambar cheu) array a ser
- 2D array (matrix) cu 1D arrays tampi fonhmi a si i, 3D array cu 2D arrays tampi fonhmi a si. A tanglei bantuk in ser khawh an si:
a1 = np.array([[1,2,3],[4,5,6]]) # rows 2 x column 3
a2 = np.array([[[1,2],[4,5]],[[6,7],[8,9]]]) # 2,2 x 2 arrays
- Complex numbers array zong ser khawh a si:
27.2 Creation of Filler Arrays (A Chung Thil Um Cia Array Sernak)¶
- Numpy Arrays cu a hramthawk ah thil (values) a um cia mi in kan ser khawh, a hnu ah thlen khawh a si.
- Tahchunhnak ah, a chung ah 0s lawng a um mi, 1s lawng a um mi, asiloah a dang value a um mi kan ser khawh. A chung ah garbage values (sullam a ngei lo mi nambar) a um mi empty arrays zong kan ser khawh.
import numpy as np
a1 = np.empty((3,4)) # 2D array garbage values he a ser
a2 = np.zeros((3,4)) # 2D array zeros he a ser
a3 = np.ones((3,4)) # 2D array ones he a ser
a4 = np.full((2,2),7) # 2D array a chung ummi 7 he a ser
- Hi functions hna sin ah tuples pek a hau. Tuples (3,4) le (2,2) nih array kan ser ding mi a shape (pungsan/size) a chim.
- Random values (nambar sawhsawh) asiloah aa khat te in a then mi values he array kan ser khawh.
import numpy as np
a1 = np.random.random((4)) # 4 random values he a ser
a2 = np.arange(5) # [0,1,2,3,4]
a3 = np.linspace(0,2,5) # [0.0 0.5 1.0 1.5 2.0]
- arange() le linspace() i a hmasa parameter pahnih cu a thawknak le a donghnak values an si. arange() i a pathumnak parameter cu step value (karh zat) a si, linspace() i a pathumnak parameter cu kan ser duh mi values zat a si.
- Numpy nih identity matrix sernak nawl a kan pek, mah cu principal diagonal ah ones a um i, a dang vialte zeros a um mi matrix a si.
- Identity matrix cu square matrix a si caah dimension 1 lawng eye() le identity() ah pek a hau.
27.3 Array Attributes (Array Sining)¶
- Numpy array nih attributes tampi a ngei i, cu nih element type, element size, array shape, array size, tbk. a langhter.
- Numpy array chung i elements type, an size, le memory ah an umnak hmun tbk. kan hmu khawh.
import numpy as np
a1 = np.array([1,2,3,4])
a2 = np.array([1.1,2.2,3.3,4.4])
print(a1.dtype) # int32 a print
print(a2.dtype) # float64 a print
print(a1.itemsize) # 4 a print
print(a2.itemsize) # 8 a print
print(a1.nbytes) # 16 a print
print(a2.nbytes) # 16 a print
print(a1.data) # <memory at 0x024BEE08> a print
print(a1.strides) # (4,) a print
print(a2.data) # <memory at 0x0291EE08> a print
print(a2.strides) # (8,) a print
- Hika ah dtype nih array chung i elements type a langhter. itemsize nih array element pakhat i bytes a lak zat a langhter i, nbytes nih array dihlak i bytes a lak zat a langhter.
- data nih memory ah array a umnak hmun (base address) a langhter i, strides nih a hnu i array element phanhnak ding ah base address ah bytes zeizat dah chap a hau ti a langhter.
- ndim, shape le size attributes nih array i dimensions zat, array shape le a chung i elements zat a langhter.
import numpy as np
a1 = np.array ([1,2,3,4])
a2 = np.array(([1,2,3,4],[5,6,7,8]))
print(a1.ndim) # 1 a print
print(a2.ndim) # 2 a print
print(a1.shape) # tuple (4,) a print
print(a2.shape) # tuple (2,4) a print
print(a1.size) # 4 a print
print(a2.size) # 8 a print
- ndim nih array dimensions zat, shape nih array shape zat, size nih array size zat a langhter.
27.4 Array Operations (Array Tuahnak Pawl)¶
- Numpy arrays cung ah operations (tuahnak) tampi tuah khawh a si. Hi operations hna cu a tawi i a rang. Library chung ah precompiled routines a um cia mi hman a si caah a rang.
- Array operations a phunphun hna cu: (a) Arithmetic Operations (Kanan Tuahnak) (b) Statistical Operations (Statistic Tuahnak) © Linear Algebra Operations (Linear Algebra Tuahnak) (d) Bitwise Operations (Bitwise Tuahnak) (e) Copying, Sorting (Copy Tuah le Remh) (f) Comparsion Operations (Tahchunhnak Tuah)
27.4.1 Arithmetic Operations (Kanan Tuahnak)¶
- Array pahnih cung ah +, -, *, /, % tbk. operations na tuah khawh. Hi operators na hman tikah, array pahnih i a zawn cio elements cung ah operations kha a tuah. Hi operators hman lo in, add(), subtract(), multiply(), divide(), le remainder() methods zong na hman khawh. Hi operations hna cu vector operations tiah auh a si tawn.
import numpy as np
a1 = np.array([[10,2,3,4],[5,6,7,8]])
a2 = np.array([[1,1,1,1],[2,2,2,2]])
a3 = a1 + a2 # a3 = np.add(a1,a2) he aa khat
a4 = a1 - a2
a5 = a1 * a2
a6 = a1 / a2
a7 = a1 % a2
a8 = a1 ** 2 # element kip kha power 2 in a kaiter
- a1 le a2 le array pahnih i a zawn cio elements cung ah operations kha a tuah.
- a3 le a4 le a5 le a6 le a7 le a8 le array pahnih i a zawn cio elements cung ah operations kha a tuah.
- a8 le array pahnih i a zawn cio elements cung ah operations kha a tuah.
- Array elements cung ah scalar arithmetic operations kan tuah khawh. Hi operations hna cu elementwise operations tiah auh a si tawn.
import numpy as np
a1 = np.array([[10,2,3,4],[5,6,7,8]])
a2 = a1 + 2 # element kip ah 2 a chap
a3 = a1 **2 # element kip kha power 2 in a kaiter
- In place operators +=, -=, /= nih array thar ser lo in a um cia mi array kha a thlen.
Array elements cung ah a dang operations tuah khawh mi hna cu exp(), sqrt(), cos(), sin(), log().
27.4.2 Statistical Operations (Statistic Tuahnak)¶
- Numpy nih a tanglei operations hna hi array elements dihlak cung ah asiloah axis (dimension) a chimh mi elements cung ah a tuah khawh. Note: Axis cu dimension tinak a si, cucaah 1D array nih axis 1 a ngei, 2D array nih axis 2 a ngei.
import numpy as np
a = np.array([[1,2,3,],[4,5,6]])
print(a.sum())
print(a.min()) # array chung i a hme bik a kawl
print(a.max(axis = 0)) # column (tung) kip i a ngan bik a kawl
print(a.max(axis = 1)) # row (phei) kip i a ngan bik a kawl
print(a.sum(axis = 1)) # axis 1 lei ah a fonh
print(a.cumsum(axis = 1)) # cumulative sum
print(np.mean(a))
print(np.median(a))
print(np.corrcoef(a))
print(np.std(a))
- sum() nih array chung i a hme bik a kawl, min() nih array chung i a hme bik a kawl, max() nih array chung i a hme bik a kawl, max() nih array chung i a hme bik a kawl, sum() nih array chung i a hme bik a kawl, cumsum() nih array chung i a hme bik a kawl, mean() nih array chung i a hme bik a kawl, median() nih array chung i a hme bik a kawl, corrcoef() nih array chung i a hme bik a kawl, std() nih array chung i a hme bik a kawl.
- max() kan hman tikah axis hman ning theih hi a biapi. Kan array cu 2D array a si i dimensions 2 x 3 a ngei. axis = 0 kan hman tikah, 'column lei max' asiloah 'row lei max' tiah ruat hlah. A sullam cu axis = 0 kan hman tikah, Numpy nih size 2 kha a thumh (condense), cu tikah result cu elements 3 [4,5,6] a ngei mi array a si. Cu bantuk in, axis = 1 kan hman tikah, Numpy nih size 3 kha a thumh, cu tikah result cu elements [3,6] a ngei mi array a si.
27.4.3 Linear Algebra Operations (Linear Algebra Tuahnak)¶
- Multiplication operations pahnih i dannak kha theih a hau:
a3 = a1 * a2 # a1 le a2 i a zawn cio elements a multiply (karh)
a3 = a1 @ a2 # matrix multiplication a tuah
a4 = a1.dot(a2) # matrix multiplication a tuah
- Matrix i transpose zong kan hmu khawh:
- Matrix i trace cu a diagonal elements i a sum a si. A tanglei bantuk in hmuh khawh a si.
- Matrix i inverse cu a matrix i a inverse a si. A tanglei bantuk in hmuh khawh a si.
- Linear simultaneous equations i phitnak (solution) zong kan hmu khawh. Tahchunhnak ah, equations system $\(3x + y = 9\)$ $\(le \\ x + 2y = 8\)$ i phitnak cu a tanglei bantuk in hmuh khawh a si.
a = np.array([[3,1],[1,2]])
b = np.array([9,8])
x = np.linalg.solve(a,b)
print(x)
- Eigenvalues and eigenvectors cu a matrix i a eigenvalues and eigenvectors a si. A tanglei bantuk in hmuh khawh a si.
a = np.array([[1,2],[3,4]])
eigvals, eigvecs = np.linalg.eig(a)
print(eigvals)
print(eigvecs)
27.4.4 Bitwise Operations (Bitwise Tuahnak)¶
- Array elements cung ah Bitwise operations zong a tanglei bantuk in tuah khawh a si:
import numpy as np
a1 = np.array([[10,2,3,4],[5,6,7,8]])
a2 = np.array([[1,1,1,1],[2,2,2,2]])
a3 = np.bitwise_and(a1,a2)
a4 = np.bitwise_or(a1,a2)
a5 = np.bitwise_xor(a1,a2)
a6 = np.invert(a1)
a7 = np.left_shift(a1,3) # element kip bits 3 in keilei ah a shift
a8 = np.right_shift(a1,2) # element kip bits 2 in orhlei ah a shift
27.4.5 Copying and Sorting (Copy Tuah le Remh)¶
- Copy operations phun 3 a um - no copy (copy lo), shallow copy (a leng copy) le deep-copy (a thuuk copy).
- No copy ah, object asiloah a data kha copy a si lo. Array umnak address lawng variable ah pek a si. Shallow copy ah array object thar a ser nain data hlun kha a hman. Deep copy ah array object thar a ser i attributes le data hlun kha a copy dih.
import numpy as np
a = np.array([[3,3,7],[1,5,2]])
b = a # no copy
print(b is a) # True a print, a le b cu array pakhat ah an i kawk
b[0][0] = 100 # a[0][0] a thleng
c = a.view()
print(c is a) # false a print, a le c cu object dangdang an si
c[0][0] = 50 # [[3 3 7][1 5 2]] a print
d = a.copy()
print(d is a) # False a print, d le a cu object dangdang an si
d[0][0] = 150 # a[0][0] a thleng lo
a = np.array([[3,7,6],[1,5,2]])
b = np.array([[3,7,6],[1,5,2]])
a.sort()
b.sort(axis = 0) # column (tung) kip i elements a sort
- Array sorting phun 2 a um - in place sorting (copy lo) le out of place sorting (copy lo).
27.4.6 Comparison (Tahchunhnak)¶
- Arrays he tahchunhnak phun 3 hman tawn a si:
- (a) Array elements dihlak kha value pakhat he tahchunh i Boolean array result chuah.
- (b) Array pahnih i a zawn cio elements tahchunh i Booleans array chuah.
- © Array pahnih i shape le elements tahchunh, aa khah ah cun TRUE, aa khah lo ah cun FALSE.
- Array elements dihlak value pakhat he tahchunhnak:
import numpy as np
a = np.array([[3,7,6],[1,5,2]])
print(a < 5) # [[True False False][True False True]] a print
- Array pahnih i a zawn cio elements tahchunhnak:
import numpy as np
a = np.array([[3,7,6],[1,5,2]])
print(a < 5) # [[True False False][True False True]] a print
- Array pahnih i a zawn cio elements tahchunhnak:
import numpy as np
a = np.array([[3,7,6],[1,5,2]])
b = np.array([[3,1,2],[1,7,2]])
print(a < b) # [[False False False][False True False]] a print
- Array pahnih i shape le elements tahchunhnak:
import numpy as np
a = np.array([[3,7,6],[1,5,2]])
b = np.array([[3,1,2],[1,7,2]])
print(a < b) # [[False False False][False True False]] a print
import numpy as np
a = np.array([[3,7,6],[1,5,2]])
b = np.array([[3,7,6],[1,5,2]])
c = np.array([[3,7],[6,1],[5,2]])
print(np.array_equal(a,b)) # True, Shape & Elements Aa Khat
print(np.array_equal(a,c)) # False, shape aa dang
27.4.7 Indexing and Slicing (Index Tuah le Hleh)¶
- Lists bantuk in, element pakhat indexing cu 0 in a thok i array a donghnak in indexing tuah duh ah negative indices (nambar) a cohlan.
- Mutli-dimensional array i element pakhat kha indices tampi hman in lak khawh a si.
- Note: a[1][2] ah, index hmasa (i.e. [1,5,9]) hnu ah temporary array thar a ser i, cun a chung i a pahnihnak element kha a lak.
- Slicing cu lists he aa lo nain dimensions tampi ah hman khawh a si.
import numpy as np
a = np.array([8,2,4,1,5,9])
b = np.array([[3,7,6,9,8],[1,5,9,2,4]])
print(a[2:5]) # [4 1 5] a print
print(a[:-4]) # [8 2] a print
print(b[1:3,2:4]) # [[9 2][3 1]] a print
print(b[1:3][2:4]) # [] a print
- Note: b[1:3][2:4] ah, hmasa ah arrays[[1,5,9,2,4][0,0,3,1,5]] a ser i, cun elements 2 in 3 tiang a lak. Hi array thar cu elements pahnih lawng a ngeih caah, [] a chuah.
27.5 Array Manipulation (Array Sersiamnak)¶
- Array ser a si hnu ah reshape() method hmang in a shape (pungsan) kan thlen khawh. Hi method nih data cu aa khat nain shape thar a ngei mi array a chuah.
import numpy as np
a = np.array([[3,7,6,9],[0,3,1,5]])
b = a.reshape(2,6)
print(b) # [[3 7 6 9 1 5][2 4 0 3 1 5]] a print
c = a.reshape(4,-1)
print(c) # [[3 7 6][9 1 5][2 4 0][3 1 5]] a print
d = np.arange(12).reshape(2,6)
print(d) # [[0 1 2 3 4 5][6 7 8 9 10 11]] a print
- Multi-dimensional array cu kan flatten (a perter) khawh.
import numpy as np
a = np.array([[3, 7, 6, 9],[1, 5, 2, 4],[0, 3, 1, 5]])
b = a.ravel()
print(b) # [3 7 6 9 1 5 2 4 0 3 1 5] a print
- A um cia mi array a donghnak ah values kan append (chap) khawh.
import numpy as np
a = np.array([[3, 7, 6, 9],[1, 5, 2, 4]])
b = np.array([[0, 3, 1, 5],[1, 1, 1, 1]])
c = np.append(a,b,axis=0)
d = np.append(a,b,axis=1)
print(c) # [[3 7 6 9][1 5 2 4][0 3 1 5][1 1 1 1]] a print
print(d) # [[3 7 6 9 0 3 1 5][1 5 2 4 1 1 1 1]] a print
-
Note: Values cu a um cia mi array i a copy ah chap a si. Chap ding mi values cu a um cia mi array he shape aa khat a hau. axis chimh a si lo ah cun, values cu shape zeipaoh a si kho i hman hlan ah flatten tuah a si lai.
-
Elements insert tuahnak, delete tuahnak, split tuahnak tbk functions an um. Nangmah te in hlathlai ding in forh na si.
Problems (Tuahding)¶
Problem 27.1¶
- Dimensions 4 x 2 x 3 a ngei mi 3D array sernak program tial. Values cheukhat in initialize (hramthawk) tuah. Axis kip i a maximum (ngan bik) kawl.
Program
Output
Problem 27.2¶
- Shape 5 x 4 a ngei mi le elements 1 in 20 tiang a ngei mi array sernak program tial. Array dihlak i sum (fonh), row le column kip i sum kawl.
Program
Output
Problem 27.3¶
A tanglei rian hna tuahnak ding ah program tial:
- Size 10 a ngei mi array a ser, a chung i element kip value 3 ah chiah.
- Hi array le a chung i element pakhat i memory size kawl.
- Size 10 a ngei mi array b ser, a chung i values cu 0 in 90 tiang aa khat te in a then mi si seh.
- Array b i elements kha a let (reverse) in tuah.
Array a le b fonh law a result kha array c ah khon.
Program
Output
Problem 27.4¶
-
A tanglei rian hna tuahnak ding ah program tial:
-
Size 5 x 5 a ngei mi 2D array ser, a border (rim) i elements kha 1 ah chiah, a chung elements vialte value 3 ah chiah.
-
4 x 3 matrix, a chung ah 2s lawng a um mi he multiply tuah.
-
1D array pakhat pek a si tikah, 2 le 8 karlak a um mi elements vialte kha negate (minus ah thlen), in place in tuah.
Program
Output
Exercises¶
[A] A tanglei statements hi True (Hmaan) maw False (Hmaan lo) ti chim:
-
Python kan install tikah Numpy library zong aa install chih.
-
Numpy arrays cu lists nakin a rian a rang deuh.
-
Numpy array elements cu types (phun) aa dang mi a si kho.
-
Array ser a si hnu ah, a size le shape cu dynamically in thlen khawh a si.
-
a le b i shape le elements an i khah ah cun np.array_equal(a,b) nih True a return lai.
[B] A tanglei biahalnak hna hi phi:
-
First 10 natural numbers i Numpy Array zeitin dah na ser lai?
-
Numpy hmang in complex numbers array kan ser kho maw?
-
Size 3 x 4 x 5 a ngei mi arrays 5 kha zeitin dah na ser lai i, a values cu 0, 1, 5, random le garbage values cio in na khahter lai?
-
50-element array zeitin dah na ser lai i, 1 in a thok mi odd numbers (nambar tial) in na khahter lai?
-
A tanglei Numpy array i elements type, elements zat, base address le bytes a lak zat zeitin dah na hmuh lai?
-
a1 = np.array([[1,2,3,4],[5,6,7,8]]) in ser mi Numpy array i dimension le shape zeitin dah na hmuh lai?
-
3 x 4 matrices pahnih pek a si tikah, hi matrices i corresponding elements kha zeitin dah add, subtract, multiply le divide na tuah hna lai?
-
A tanglei hna lakah khuazei hi dah Numpy array cung i scalar arithmetic operations an si?
a1 = np.array([[10,2,3,4],[5,6,7,8]])
a2 = np.array([[1,1,1,1],[2,2,2,2]])
a3 = a1 + a2
a4 = a1 - a2
a5 = a1 * a2
a6 = a1 / a2
a7 = a1 % a2
a8 = a1 ** 2
a9 += a1
a10 += 5
a11 = a1 + 2
a12 = a1 ** 2
[C] A tanglei pairs hna hi a match (aa tlak) mi thim:
| Code / Function | Opertion / Description |
|---|---|
a. s = np.trace(a) |
1. Statistical Operation |
b. s = a.cumsum(axis = 1) |
2. Linear Algebra Operation |
c. a2 = np.copy(a1) |
3. Deep copy operation |
d. print(a1 < 2) |
4. Corresponding ele.comparison |
e. print(a1 > a2) |
5. Comparison with one value |
f. print(a[1:3][3:6]) |
6. Bitwise Operation |
g. a2 = invert(a1) |
7. Slicing Operation |