Hướng dẫn dùng programiz python python
Why Learn Python?
How to learn Python?
Video: Python Full Course
Show
Python Resources
Python is a powerful programming language ideal for scripting and rapid application development. It is used in web development (like: Django and Bottle), scientific and mathematical computing (Orange, SymPy, NumPy) to desktop graphical user Interfaces (Pygame, Panda3D). This tutorial introduces all the core concepts and features of Python 3. After reading the tutorial, you will be able to read and write basic Python programs, and explore Python in-depth on your own. This tutorial is intended for people who have knowledge of other programming languages and want to get started with Python quickly. Python for BeginnersIf you are a programming newbie, we suggest you visit:
What's covered in this tutorial?
Run Python on Your computerIf you want to install Python on your computer, follow these resources.
You can also use our online Python editor to get started in Python without installing anything on your computer. Python IntroductionLet's write our first Python program, "Hello, World!". It's a simple program that prints Hello World! on the standard output device (screen). "Hello, World!" Program
When you run the program, the output will be: Hello, World! In this program, we have used the built-in print() function to print Hello, world! string. Variables and LiteralsA variable is a named location used to store data in the memory. Here's an example:
Here, a is a variable. We have assigned We do not need to define the type of variables in Python. You can do something like this:
Initially, integer value By the way, When you run the program, the output will be: a = 5 a = High five Visit Python Variables, Constants and Literals to learn more. OperatorsOperators are special symbols that carry out operations on operands (variables and values). Let's talk about arithmetic and assignment operators in this part. Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assignment operators are used to assign values to variables. You have already seen the use of
Other commonly used assignment operators: Visit Python Operators to learn about all operators in detail. Get Input from UserIn Python, you can use input() function to take input from user. For example:
When you run the program, the output will be: Enter a sentence: Hello there. The inputted string is: Hello there. Python CommentsThere are 3 ways of creating comments in Python. # This is a comment """This is a multiline comment.""" '''This is also a multiline comment.''' To learn more about comments and docstring, visit: Python Comments. Type ConversionThe process of converting the value of one data type (integer, string, float, etc.) to another is called type conversion. Python has two types of type conversion. Implicit Type Conversion Implicit conversion doesn't need any user involvement. For example:
When you run the program, the output will be: Value of num_new: 124.23 datatype of num_new: datatype of num_new: Here, num_new has float data type because Python always converts smaller data type to larger data type to avoid the loss of data. Here is an example where the Python interpreter cannot implicitly type convert.
When you run the program, you will get TypeError: unsupported operand type(s) for +: 'int' and 'str' However, Python has a solution for this type of situation which is known as explicit conversion. Explicit Conversion In case of explicit conversion, you convert the datatype of an object to the required data type. We use predefined functions like int(), float(), str() etc. to perform explicit type conversion. For example:
To lean more, visit Python type conversion. Python Numeric TypesPython supports integers, floating point numbers and complex numbers. They are defined as
To learn more, visit Python Number Types. Python Data StructuresPython offers a range of compound datatypes often referred to as sequences. You will learn about those built-in types in this section. ListsA list is created by placing all the items (elements) inside a
square bracket It can have any number of items and they may be of different types (integer, float, string etc.)
You can also use list() function to create lists. Here's how you can access elements of a list.
You use the index operator Python also allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item, and so on. Check these resources for more information about Python lists:
TuplesTuple is similar to a list except you cannot change elements of a tuple once it is defined. Whereas in a list, items can be modified. Basically, lists are mutable whereas tuples are immutable.
You can also use tuple() function to create tuples. You can access elements of a tuple in a similar way to a list.
You cannot delete elements of a tuple, however, you can entirely delete a tuple itself using
To learn more, visit Python Tuples. StringA string is a sequence of characters. Here are different ways to create a string.
You can access individual characters of a string using indexing (in a similar manner to lists and tuples).
Strings are immutable. You cannot change elements of a string once it is assigned. However, you can assign one string to another. Also, you can delete the string using Concatenation is probably the most common string operation. To concatenate strings,
you use
Check these resources for more information about Python strings:
SetsA set is an unordered collection of items where every element is unique (no duplicates). Here is how you create sets in Python.
You can also use set() function to create sets. Sets are mutable. You can add, remove and delete elements of a set. However, you cannot replace one item of a set with another as they are unordered and indexing has no meaning. Let's try commonly used set methods: add(), update() and remove().
Let's tryout some commonly used set operations:
More Resources:
DictionariesDictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a
You can also use dict() function to create dictionaries. To access value from a dictionary, we use keys. For example:
Here's how you can change, add or delete dictionary elements.
More resources:
Python range()
The output is an iterable and you can convert it to lists, tuples, set and so on. For example:
We have omitted optional
Python Control Flowif...else StatementThe
There can be zero or more Most programming languages use A code block starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block. Generally, four whitespaces are used for indentation and is preferred over tabs. Let's try another example:
Before you move on to next section, we recommend you to check comparison operator and logical operator. Also, check out Python if...else in detail. while LoopLike most programming languages,
In Python, while loop can have optional To learn more, visit Python while Loop for LoopIn Python, Here's an example to find the sum of all numbers stored in a list.
Notice the use of In Python, To learn more, visit Python for Loop break StatementThe break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. For example:
When you run the program, the output will be: s t The end continue StatementThe continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. For example:
When you run the program, the output will be: s t i n g The end To learn more on pass StatementSuppose, you have a loop or a function that is not implemented yet but want to implement it in the future. They cannot have an empty body. The interpreter would complain. So, you use the
Python FunctionA function is a group of related statements that perform a
specific task. You use
You have to call the function to run the codes inside it. Here's how:
A function can accept arguments.
You can also return value from a function using
Here are few resources to check:
Recursion (Recursive function)A function that calls itself is known as recursive function and this process is called recursion. Every recursive function must have a base condition that stops the recursion or else the function calls itself infinitely.
Visit Python recursion to learn more. Lambda FunctionIn Python, you can define functions without a name. These functions are called lambda or anonymous function. To create a lambda function,
We use lambda functions when we require a nameless function for a short period of time. Lambda functions are used along with built-in
functions like To learn more, visit:
ModulesModules refer to a file containing Python statements and definitions. A file containing Python code, for e.g.: Let us create it and save it as
To use this module, we use
Python has a ton of standard modules readily available for use. For example:
You can import specific names from a module without importing the module as a whole. Here is an example.
More Resources:
Python File I/OA file operation takes place in the following order.
How to open a file?You can use open() function to open a file.
We can specify the mode while opening a file.
How to close a file?To close a file, you use
How to write to a file?In order to write into a file in Python, we need to open it in write
Here, we have used How to read files?To read a file in Python, you must open the file in reading mode. There are various methods available for this purpose. We can use the
Visit Python File I/O to learn more. Python DirectoryA directory or folder is a collection of files and subdirectories. Python has the os module, which provides many useful methods to work with directories and files.
Visit Python Directory to learn more. Python Exception HandlingErrors that occur at runtime are called exceptions. They occur, for example, when a file we try to open does not exist Visit this page to learn about all built-in exceptions in Python. If exceptions are not handled, an error message is spit out and our program comes to a sudden, unexpected halt. In Python, exceptions can be handled using
When you run the program, the output will be: The entry is a Oops! To learn about catching specific exceptions and
Also, you can create user-defined exceptions in Python. For that, visit Python Custom Exceptions Python OOPEverything in Python is an object including integers, floats, functions, classes,
and Class and ObjectsObject is simply a collection of data (variables) and methods (functions) that act on data. And, class is a blueprint for the object. How to define a class?
As soon as you define a class, a new class object is created with the same name. This class object allows us to access the different attributes as well as to instantiate new objects of that class.
You may have noticed the This is because, whenever an object calls its method, the object itself is passed as the first argument. So,
Creating ObjectsYou can also create objects of the class yourself.
Python ConstructorsIn Python, a method with name
Visit Python Class and Object to learn more. Python InheritanceInheritance refers to defining a new class with little or no modification to an existing class. Let's take an example:
Let's derive a new class Dog from this
Notice that we are able to call method of base class To learn more about inheritance and method overriding, visit Python Inheritance. We also suggest you to check multiple inheritance and operator overloading if you are interested. Miscellaneous and Advance TopicsIteratorsIterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time. Technically
speaking, Python iterator object must implement two special methods, An object is called iterable if we can get an iterator from it. Most of the built-in containers in Python like: list, tuple, string etc. are iterables. The
To learn more about infinite iterators and how to create custom iterators, visit: Python Iterators. GeneratorsThere is a lot of overhead in building an iterator in Python; we have to implement a class with This is both lengthy and counterintuitive. Generators come to rescue in such situations. Python generators are a simple way of creating iterators. Learn more about Python Generators. ClosuresThis technique by which some data gets attached to the code is called closure in Python.
Here, the The criteria that must be met to create closure in Python are summarized in the following points.
Visit Python closures to learn more about closures and when to use them. DecoratorsPython has an interesting feature called decorators to add functionality to an existing code. This is also called metaprogramming as a part of the program tries to modify another part of the program at compile time. To learn about decorators in detail, visit Python Decorators. Did we miss anything in this Python tutorial? |