Hướng dẫn dùng programiz python python

  • Free and open-source - You can freely use and distribute Python, even for commercial use.
  • Easy to learn - Python has a very simple and elegant syntax. It's much easier to read and write Python programs compared to other languages like C++, Java, C#.
  • Portable - You can move Python programs from one platform to another, and run it without any changes.

Why Learn Python?

  • Python is easy to learn. Its syntax is easy and code is very readable.
  • Python has a lot of applications. It's used for developing web applications, data science, rapid application development, and so on.
  • Python allows you to write programs in fewer lines of code than most of the programming languages.
  • The popularity of Python is growing rapidly. Now it's one of the most popular programming languages.

How to learn Python?

  • Interactive Python Course - Want to learn Python by solving quizzes and challenges after learning each concept? Enroll in our Python Interactive Course for FREE.
  • Python tutorial from Programiz - We provide step by step Python tutorials, examples, and references. Get started with Python.
  • Official Python tutorial - Might be hard to follow and understand for beginners. Visit the official Python tutorial.
  • Get Learn Python App - The beginner-friendly app contains byte-size lessons and an integrated Python interpreter. To learn more, visit: Learn Python app
  • Write a lot of Python code- The only way you can learn programming is by writing a lot of code.

Video: Python Full Course

Python Resources

  • Python Examples
  • Python References
  • Python Online Compiler

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 Beginners

If you are a programming newbie, we suggest you visit:

  1. Python Interactive Course - Learn to code through bite-size lessons, quizzes and 100+ challenges
  2. Python Programming - A comprehensive guide on what's Python, how to get started in Python, why you should learn it, and how you can learn it.
  3. Python Examples - Simple examples for beginners to follow.

What's covered in this tutorial?

  • Run Python on your computer
  • Introduction [Variables, Operators, I/O, ...]
  • Data Structures [List, Dictionary, Set, ...]
  • Control Flow [if, loop, break, ...]
  • File [File Handling, Directory, ...]
  • Exceptions [Handling, User-defined Exception, ...]
  • OOP [Object & Class, Inheritance, Overloading, ...]
  • Standard Library [Built-in Function, List Methods, ...]
  • Misc [Generators, decorators, ...]

Run Python on Your computer

If you want to install Python on your computer, follow these resources.

  • Run Python on Windows
  • Run Python on MacOS

You can also use our online Python editor to get started in Python without installing anything on your computer.

Python Introduction

Let'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

print["Hello, World!"]

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 Literals

A variable is a named location used to store data in the memory. Here's an example:

a = 5  

Here, a is a variable. We have assigned 5 to variable a

We do not need to define the type of variables in Python. You can do something like this:

a = 5
print["a =", 5]
a = "High five"
print["a =", a]

Initially, integer value 5 is assigned to the variable a. Then, the string High five is assigned to the same variable.

By the way, 5 is a numeric literal and "High five" is a string literal.

When you run the program, the output will be:

a = 5
a = High five

Visit Python Variables, Constants and Literals to learn more.

Operators

Operators 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.

x = 14
y = 4

# Add two operands
print['x + y =', x+y] # Output: x + y = 18

# Subtract right operand from the left
print['x - y =', x-y] # Output: x - y = 10

# Multiply two operands
print['x * y =', x*y] # Output: x * y = 56

# Divide left operand by the right one 
print['x / y =', x/y] # Output: x / y = 3.5

# Floor division [quotient]
print['x // y =', x//y] # Output: x // y = 3

# Remainder of the division of left operand by the right
print['x % y =', x%y] # Output: x % y = 2

# Left operand raised to the power of right [x^y]
print['x ** y =', x**y] # Output: x ** y = 38416

Assignment operators are used to assign values to variables. You have already seen the use of = operator. Let's try some more assignment operators.

x = 5

# x += 5 ----> x = x + 5
x +=5
print[x] # Output: 10

# x /= 5 ----> x = x / 5
x /= 5
print[x] # Output: 2.0

Other commonly used assignment operators: -=, *=, %=, //= and **=.

Visit Python Operators to learn about all operators in detail.

Get Input from User

In Python, you can use input[] function to take input from user. For example:

inputString = input['Enter a sentence:']
print['The inputted string is:', inputString]

When you run the program, the output will be:

Enter a sentence: Hello there.
The inputted string is: Hello there. 

Python Comments

There 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 Conversion

The 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:

num_int = 123  # integer type
num_flo = 1.23 # float type

num_new = num_int + num_flo

print["Value of num_new:",num_new]
print["datatype of num_new:",type[num_new]]

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.

num_int = 123     # int type
num_str = "456"   # str type

print[num_int+num_str]

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:

num_int = 123  # int type
num_str = "456" # str type

# explicitly converted to int type
num_str = int[num_str] 

print[num_int+num_str]

To lean more, visit Python type conversion.

Python Numeric Types

Python supports integers, floating point numbers and complex numbers. They are defined as int, float and complex class in Python. In addition to that, booleans: True and False are a subtype of integers.

# Output: 
print[type[5]]

# Output: 
print[type[5.0]]

c = 5 + 3j

# Output: 
print[type[c]]

To learn more, visit Python Number Types.

Python Data Structures

Python offers a range of compound datatypes often referred to as sequences. You will learn about those built-in types in this section.

Lists

A list is created by placing all the items [elements] inside a square bracket [] separated by commas.

It can have any number of items and they may be of different types [integer, float, string etc.]

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed data types
my_list = [1, "Hello", 3.4]

You can also use list[] function to create lists.

Here's how you can access elements of a list.

language = ["French", "German", "English", "Polish"]

# Accessing first element
print[language[0]]


# Accessing fourth element
print[language[3]]

You use the index operator [] to access an item in a list. Index starts from 0. So, a list having 10 elements will have index from 0 to 9.

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:

  • Python lists [slice, add and remove item etc.]
  • Python list methods
  • Python list comprehension

Tuples

Tuple 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.

language = ["French", "German", "English", "Polish"]
print[language]

You can also use tuple[] function to create tuples.

You can access elements of a tuple in a similar way to a list.

language = ["French", "German", "English", "Polish"]

print[language[1]] #Output: German
print[language[3]] #Output: Polish
print[language[-1]] # Output: Polish

You cannot delete elements of a tuple, however, you can entirely delete a tuple itself using del operator.

language = ["French", "German", "English", "Polish"]
del language

# NameError: name 'language' is not defined
print[language]

To learn more, visit Python Tuples.

String

A string is a sequence of characters. Here are different ways to create a string.

# all of the following are equivalent
my_string = 'Hello'
print[my_string]

my_string = "Hello"
print[my_string]

my_string = '''Hello'''
print[my_string]

# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
           the world of Python"""
print[my_string]

You can access individual characters of a string using indexing [in a similar manner to lists and tuples].

str = 'programiz'
print['str = ', str]

print['str[0] = ', str[0]] # Output: p

print['str[-1] = ', str[-1]] # Output: z

#slicing 2nd to 5th character
print['str[1:5] = ', str[1:5]] # Output: rogr

#slicing 6th to 2nd last character
print['str[5:-2] = ', str[5:-2]] # Output: am

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 del operator.

Concatenation is probably the most common string operation. To concatenate strings, you use + operator. Similarly, the * operator can be used to repeat the string for a given number of times.

str1 = 'Hello '
str2 ='World!'

# Output: Hello World!
print[str1 + str2]

# Hello Hello Hello
print[str1 * 3]

Check these resources for more information about Python strings:

  • Python Strings
  • Python String Methods
  • Python String Formatting

Sets

A set is an unordered collection of items where every element is unique [no duplicates].

Here is how you create sets in Python.

# set of integers
my_set = {1, 2, 3}
print[my_set]

# set of mixed datatypes
my_set = {1.0, "Hello", [1, 2, 3]}
print[my_set]

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[].

# set of integers
my_set = {1, 2, 3}

my_set.add[4]
print[my_set] # Output: {1, 2, 3, 4}

my_set.add[2]
print[my_set] # Output: {1, 2, 3, 4}

my_set.update[[3, 4, 5]]
print[my_set] # Output: {1, 2, 3, 4, 5}

my_set.remove[4]
print[my_set] # Output: {1, 2, 3, 5}

Let's tryout some commonly used set operations:

A = {1, 2, 3}
B = {2, 3, 4, 5}

# Equivalent to A.union[B] 
# Also equivalent to B.union[A]
print[A | B] # Output: {1, 2, 3, 4, 5}

# Equivalent to A.intersection[B]
# Also equivalent to B.intersection[A]
print [A & B] # Output: {2, 3}

# Set Difference
print [A - B] # Output: {1}

# Set Symmetric Difference
print[A ^ B]  # Output: {1, 4, 5}

More Resources:

  • Python Sets
  • Python Set Methods
  • Python Frozen Set

Dictionaries

Dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. For example:

# empty dictionary
my_dict = {}

# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}

You can also use dict[] function to create dictionaries.

To access value from a dictionary, we use keys. For example:

person = {'name':'Jack', 'age': 26, 'salary': 4534.2}
print[person['age']] # Output: 26

Here's how you can change, add or delete dictionary elements.

person = {'name':'Jack', 'age': 26}

# Changing age to 36
person['age'] = 36 
print[person] # Output: {'name': 'Jack', 'age': 36}

# Adding salary key, value pair
person['salary'] = 4342.4
print[person] # Output: {'name': 'Jack', 'age': 36, 'salary': 4342.4}


# Deleting age
del person['age']
print[person] # Output: {'name': 'Jack', 'salary': 4342.4}

# Deleting entire dictionary
del person

More resources:

  • Python Dictionary
  • Python Dictionary Methods
  • Python Dictionary Comprehension

Python range[]

range[] returns an immutable sequence of numbers between the given start integer to the stop integer.


print[range[1, 10]] # Output: range[1, 10]

The output is an iterable and you can convert it to lists, tuples, set and so on. For example:

numbers = range[1, 6]

print[list[numbers]] # Output: [1, 2, 3, 4, 5]
print[tuple[numbers]] # Output: [1, 2, 3, 4, 5]
print[set[numbers]] # Output: {1, 2, 3, 4, 5}

# Output: {1: 99, 2: 99, 3: 99, 4: 99, 5: 99} 
print[dict.fromkeys[numbers, 99]]

We have omitted optional step parameter for range[] in above examples. When omitted, step defaults to 1. Let's try few examples with step parameter.

# Equivalent to: numbers = range[1, 6]
numbers1 = range[1, 6 , 1]
print[list[numbers1]] # Output: [1, 2, 3, 4, 5]

numbers2 = range[1, 6, 2]
print[list[numbers2]] # Output: [1, 3, 5]

numbers3 = range[5, 0, -1]
print[list[numbers3]] # Output: [5, 4, 3, 2, 1]

Python Control Flow

if...else Statement

The if...else statement is used if you want perform different action [run different code] on different condition. For example:

num = -1

if num > 0:
    print["Positive number"]
elif num == 0:
    print["Zero"]
else:
    print["Negative number"]
    
# Output: Negative number

There can be zero or more elif parts, and the else part is optional.

Most programming languages use {} to specify the block of code. Python uses indentation.

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:

if False:
  print["I am inside the body of if."]
  print["I am also inside the body of if."]
print["I am outside the body of if"]

# Output: I am outside the body of if.

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 Loop

Like most programming languages, while loop is used to iterate over a block of code as long as the test expression [condition] is true. Here is an example to find the sum of natural numbers:

n = 100

# initialize sum and counter
sum = 0
i = 1

while i 

Chủ Đề