Hướng dẫn check code python

Một case đơn giản cho các bạn làm quen với lập trình Python cơ bản, đó là kiểm tra kiểu dữ liệu truyền vào hoặc biến quy định có dữ liệu format địa chỉ IP hợp lệ hay không ?

Contents

  • Các bước kiểm tra địa chỉ IP format hợp lệ trên Python
    • 1. Ý tưởng code check biến IP có hợp lệ không ?
    • 2. Ví dụ code và chạy

1. Ý tưởng code check biến IP có hợp lệ không ?

Ý tưởng sẽ gồm các bước như sau :
– Tách các giá trị số ip thành các giá trị riêng lẻ trong 1 danh sách theo kí tự phân cách ‘.’, tức format IP ‘x1.x2.x3.x4‘ sẽ thành [‘x1‘,’x2‘,’x3‘,’x4‘] – Khi phân tách ra như vậy sẽ trở thành danh sách [list] các phần tử số của các octet số.
– Kiểm tra số lượng các octet số có đủ 4 hay không -> nếu không, trả bolean False.
– Chạy vòng lặp for với danh sách số đã phân tách ra
-+ Nếu số đó không phải là số hoàn toàn -> trả boolean False.
-+ Nếu số đó nhỏ hơn 0 và lớn hơn 255 [tức khoảng giá trị số IP octet. 0-255]

2. Ví dụ code và chạy

2.1 Code mẫu, cú pháp python 2.7

#!/usr/bin/python
__author__ = "Quach Chi Cuong"
__note__ = "Demo Only"

import sys


# Function check IP type valid
def checkip_type[ip]:
	ip_tmp = ip.split['.']
	if len[ip_tmp] != 4:
		return False

	for x in ip_tmp:
		if not x.isdigit[]:
			return False
		i = int[x]
		if i < 0 or i > 255:
			return False

	return True


def main[]:
	ip_input = sys.argv[1]
	if checkip_type[ip_input]:
		print "IP %s hop le" % ip_input
	else:
		print "IP %s khong hop le" % ip_input


if __name__ == '__main__':
	main[]

 
2.2 Chạy code

# python checkip.py 192.168.1.1
IP 192.168.1.1 hop le
# python2.7 checkip.py 192.168.256.255
IP 192.168.256.255 khong hop le

 
Như vậy các bạn đã biết cách code python kiểm tra cơ bản dữ liệu truyền vào hoặc biến có được là format IP hợp lệ hay không ?

Hướng dẫn remainder python

Introduction to Python Remainder OperatorPython remainder operators are used for the computation of some operands. Operators are special symbols that are used on operands to do some operation ...

Hướng dẫn python xml has attribute

You can specify attributes for an Element or SubElement during creation with keyword arguments.import xml.etree.ElementTree as ET root = ET.Element[Summary] ET.SubElement[root, TextSummary, ...

Hướng dẫn bar plot python

Hôm nay, chúng ta sẽ xem cách chúng ta có thể tạo Biểu đồ Python và Biểu đồ thanh Python bằng cách sử dụng thư viện Matplotlib và Seaborn Python . Hơn nữa, trong ...

Hướng dẫn body trong html

1] Thẻ trong HTML- Thẻ xác định phần thân của một tài liệu HTML, nó dùng để chứa những phần tử sẽ được hiển thị lên màn hình ...

Hướng dẫn init nested dict python

I have 2 CSV files: Data and Mapping:Mapping file has 4 columns: Device_Name, GDN, Device_Type, and Device_OS. All four columns are populated.Data file has these same columns, with ...

Hướng dẫn cài python bị lỗi

Lỗi khi cài đặt python 20:58 07-04-2018 744 lượt xem 2 bình luận 23:37 12-09-2018Xin chào a/c e mới bắt đầu học python thì trong quá trình cài đặt ban đầu ...

How do you print the sum of 10 numbers in python?

In the program below, weve used an if...else statement in combination with a while loop to calculate the sum of natural numbers up to num.Source Code# Sum of natural numbers up to num num = 16 if ...

Hướng dẫn python outstream

Hướng dẫn dùng stopwatch start trong PHPanswer 195Trên các hệ thống unixoid [và trong php 7+ trên Windows], bạn có thể sử dụng getrusage , như:// Script start $rustart = ...

Can python pull data from a website?

Web Scraping with PythonImagine you have to pull a large amount of data from websites and you want to do it as quickly as possible. How would you do it without manually going to each website and ...

Hướng dẫn dùng sets def python

Hướng dẫn sử dụng def trong python. Bạn sẽ học được cách sử dụng def để khai báo hàm trong python, cũng như cách gọi hàm trong python đã được khai báo sau ...

Does python allow nested functions?

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Inner FunctionsInner functions, ...

Hướng dẫn w3schools html

Easy Learning with HTML Try it YourselfWith our Try it Yourself editor, you can edit the HTML code and view the result:Example Page ...

Convert series float to int python

I have the following data frame:In [31]: rise_p Out[31]: time magnitude 0 1379945444 156.627598 1 1379945447 1474.648726 2 1379945448 1477.448999 3 1379945449 1474.886202 4 ...

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

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

How do you accept only integers in python?

Im trying to make a multiple choice survey that allows the user to pick from options 1-x. How can I make it so that if the user enters any characters besides numbers, return something like Thats ...

Hướng dẫn list addition python

Nội dung chínhNội dung chínhThêm một phần tử vào cuối list python | phương thức append[]Thêm các phần tử của một iterable vào cuối list | list extend trong ...

Hướng dẫn python remove json level

1.I was trying to use python to delete a particular key and its value in a JSON file. Here is the JSON file structure:Nội dung chínhAnswer #1: Answer #2: How do I remove a field from a JSON ...

Hướng dẫn dùng list oe python

Mục lục Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi ...

Hướng dẫn dùng line split python

Hàm split[] trong Python chia chuỗi theo delimeter đã cho [là space nếu không được cung cấp] và trả về danh sách các chuỗi con; nếu bạn cung cấp đối số num thì ...

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

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

How do you put two numbers in python?

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we ...

Hướng dẫn manipulate xml python

What is XML?XML stands for eXtensible Markup Language. It was designed to store and transport small to medium amounts of data and is widely used for sharing structured information.Python enables you ...

What are the 4 data structures in python?

Python has been used worldwide for different fields such as making websites, artificial intelligence and much more. But to make all of this possible, data plays a very important role which means that ...

How to indent print in python

I think what youre looking for here is the textwrap module:user = Username prefix = user + : preferredWidth = 70 wrapper = textwrap.TextWrapper[initial_indent=prefix, width=preferredWidth, ...

Hướng dẫn dùng ranger definition python

Hàm split[] trong Python chia chuỗi theo delimeter đã cho [là space nếu không được cung cấp] và trả về danh sách các chuỗi con; nếu bạn cung cấp đối số num thì ...

How does python handle nested dictionary?

In Python, a dictionary is an unordered collection of items. For example:dictionary = {key : value, key_2: value_2}Here, dictionary has a key:value pair enclosed within curly brackets {}.To ...

Hướng dẫn xor set python

Nội dung chínhNội dung chínhBit trong python là gì?Khái niệm bitỨng dụng của bit trong pythonToán tử bitwise trong Python [còn gọi là toán tử Biwter trong Python]Bảng ...

Python exercises with solutions pdf

Last update on August 24 2022 05:41:39 [UTC/GMT +8 hours]What is Python language?Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy ...

Reverse order in python assignment expert

Print in Reverse Order - 2This Program name is Print in Reverse Order - 2. Write a Python program to Print in Reverse Order - 2, it has two test casesThe below link contains Print in Reverse Order - ...

Does python have getters and setters?

Whats the pythonic way to use getters and setters?The Pythonic way is not to use getters and setters, but to use plain attributes, like the question demonstrates, and del for deleting [but the ...

Cách tối ưu code python

Python là một trong những ngôn ngữ bậc cao có cú pháp đơn giản, ngắn, dễ đọc, dễ hiểu bậc nhất hiện nay. Đặc điểm này khiến python trở thành 1 ngôn ...

Can you do matrix operations in python?

We can easily perform matrix manipulation in Python using the Numpy library. NumPy is a Python package. It stands for Numerical Python. It is a library consisting of multidimensional array objects ...

How to plot probability distribution in python

Visualizing One-Dimensional Data in PythonPlotting a single variable seems like it should be easy. With only one dimension how hard can it be to effectively display the data? For a long time, I got ...

Hướng dẫn import class trong python

Xin chào các bạn. Hôm nay mình sẽ giới thiệu với các bạn về Class và việc Phân chia Module trong PythonClassKhai báo một ClassPhân chia moduleCác loại module / thư ...

How do i use python3 instead of python2?

[June 2016] The recommended place for information on the transition is official Ubuntu Python page.From the Ubuntu wiki:For both Ubuntu and Debian, we have ongoing project goals to make Python 3 the ...

How do you draw a number in a triangle in python?

Python has a simple pen drawing library called turtle. Using simple movement commands, we can draw shapes using the python turtle library. When teaching python to children, turtle is a good library ...

Chủ Đề