Cộng đồng chia sẻ tri thức Lib24.vn

Chạy chương trình Python

Gửi bởi: Phạm Thọ Thái Dương 20 tháng 11 2020 lúc 10:44:31


Mục lục
* * * * *

Dẫn nhập

Trong các bài trước chúng ta đã cùng nhau tìm hiểu TỔNG QUAN NGÔN NGỮ PYTHON cũng như MÔI TRƯỜNG PHÁT TRIỂN của nó.

Ở bài này, Kteam sẽ hướng dẫn các bạn CÁCH CHẠY MỘT CHƯƠNG TRÌNH PYTHON cơ bản nhé!

Nội dung chính

Để theo dõi bài này, bạn nên xem qua bài:

Trong bài này, chúng ta sẽ tìm hiểu:

  • Thao tác trực tiếp với Interactive Prompt
  • Chạy chương trình bằng command line

Thao tác trực tiếp với Interactive Prompt

Như ở bài trước, các bạn sử dụng Command Prompt để kiểm tra cài đặt thành công hay chưa bằng cách gõ python lên Command Prompt.

Như các bạn thấy ở hình trên đó chính là một Interactive Prompt để thao tác với Python.

Và chúng ta sẽ chạy chương trình huyền thoại “Hello HowKTeam”.

Tạm thời các bạn không cần quan tâm đến cách mà hàm print(“Hello HowKTeam”) hoạt động. Mình sẽ giới thiệu hàm này ở bài NHẬP XUẤT TRONG PYTHON.

Như các bạn có thể thấy mình vừa thao tác trực tiếp với interactive prompt.

Ưu điểm:

  • Thao tác đơn giản, dễ dàng.
  • Cho kết quả ngay lặp tức khi kết thúc câu lệnh

Nhược điểm:

  • Không thích hợp cho việc một dãy lệnh dài, có cấu trúc
  • Khi code sai chính tả, sai logic không thể sửa

Chạy chương trình bằng command line

Muốn chạy một chương trình Python bằng Command line thì chúng ta phải tạo ra được một file Python. Một file Python là một file mà có phần đuổi (mở rộng) là .py

Như đã giới thiệu ở bài CÀI ĐẶT MÔI TRƯỜNG PHÁT TRIỂN PYTHON. Editor để soạn code sẽ là SUBLIME TEXT. Và mình sẽ dùng Sublime Text tạo một file Python.

Khởi tạo file Python

Bước 1: Đầu tiên, chúng ta mở Sublime Text lên và chọn File > New File

  • Hoặc bạn cũng có thể dùng phím tắt Ctrl + N

Bước 2: Tiếp tục chọn File > Save

  • Hoặc sử dụng phím tắt Ctrl + S để lưu lại file
  • Sau khi chọn Save thì sẽ có một hộp thoại yêu cầu tại Save as Type > chọn Python trong danh sách chọn.
  • Tiếp đến, các bạn tìm nơi để lưu lại file. Ở đây mình sẽ lưu ở ngoài Desktop
  • Và cuối cùng, các bạn điền tên file vào ô File name. Các bạn nhớ là phải thêm .py vào cuối tên file nữa. Ở đây mình chọn tên file là HelloHowKTeam > Save

Sau cùng, đây chính là file Python mình vừa tạo ở ngoài Desktop

Thao tác trên file vừa khởi tạo

Công đoạn tiếp theo là mình nhập code vào trong file HelloHowKTeam.py vừa mới tạo ở phần trên, sau đó lưu lại bằng Ctrl + S

print (“Hello HowKTeam”)

Kế đến mình ra ngoài Desktop – vị trí lưu file khởi tạo để bắt đầu thực hiện chạy chương trình. Các bạn giữ nút Shift  và nhấn chuột phải vào một khoảng trống nào gần đấy và chọn Open command window here để mở Command Prompt

Và rồi sau đó, bạn gõ command line với cấu trúc sau > Enter

python <tên file.py>

Và như các bạn đã thấy chúng ta đã in ra thành công dòng chữ “Hello HowKTeam”

Kết Luận

Qua bài học này chúng ta đã hiểu được CÁCH CHẠY CHƯƠNG TRÌNH PYTHON qua interactive mode và bằng command line.

Bài sau chúng ta sẽ tìm hiểu CÁCH GHI CHÚ TRONG PYTHON.

Cảm ơn các bạn đã theo dõi bài viết. Hãy để lại bình luận hoặc góp ý của mình để phát triển bài viết tốt hơn nữa. Đừng quyên “Luyện tập – Thử thách – Không ngại khó”.

Python Test

import React from 'react';

import { View, Image } from 'react-native';
import Text from '/components/Text';
import { SvgUri } from 'react-native-svg';
const cheerio = require('cheerio');

/**
 * This is a TypeScript React function that converts HTML to React Native components.
 * @property {string} html - A string containing HTML code that needs to be converted to React Native
 * components.
 */
type Props = {
    html: string;
};

/* This is a function that takes in an object with a string property called `html` and returns an array
of React Native components (`JSX.Element[]`). The function uses the `cheerio` library to parse the
HTML string and then iterates through each HTML element using the `each` method. For each element,
the function checks the element's tag name and creates a corresponding React Native component. For
example, if the tag name is `p`, the function creates a `Text` component with the element's text
content. If the tag name is `img`, the function creates an `Image` component with the element's
`src`, `width`, and `height` attributes. The function recursively calls itself for any `div`
elements to handle nested HTML. Finally, the function returns an array of all the created React
Native components. */
const convertHtmlToReactNative = ({ html }: Props): JSX.Element[] => {
    const $ = cheerio.load(html);
    // console.log(html, "\n")
    const reactNativeComponents: JSX.Element[] = [];

    $('*').each((index: number, element: any) => {
        const tagName = $(element).prop('tagName').toLowerCase();
        switch (tagName) {
            case 'p':
                reactNativeComponents.push(<Text key={index} textAlign={"justify"} fontSize={16}>{$(element).text()}</Text>);
                break;
            case 'div':
                reactNativeComponents.push(<View key={index}>{convertHtmlToReactNative({ html: $(element).html() })}</View>);
                break;
            case 'img':
                // const src = $(element).attr('src');
                // reactNativeComponents.push(<Image key={index} source={{ uri: $(element).attr('src') ?? "" }} style={{ resizeMode: "cover", width: "100%", height: "auto" }} />);
                const src = $(element).attr('src');
                // const isBase64 = src && src.startsWith('data:image');
                // const uri = isBase64 ? src : undefined;
                // const resolvedSource = Image.resolveAssetSource({ uri });
                // "https://cdn3.olm.vn/upload/img_teacher/0405/img_teacher_2023-04-05_642d95b7284bb.jpg"
                reactNativeComponents.push(<Image
                    key={index}
                    source={{ uri: src }}
                    style={{ width: "100%", resizeMode: "stretch", maxHeight: "100%", minHeight: 200}}
                />);
                break;
            case 'ul':
                reactNativeComponents.push(<View key={index}>{convertHtmlToReactNative({html: $(element).html()})}</View>);
                break;
            case 'li':
                reactNativeComponents.push(<Text key={index}>&bull; {$(element).text()}</Text>);
                break;
            case 'ol':
                let count = 0;
                reactNativeComponents.push(<View key={index}>{convertHtmlToReactNative({html: $(element).html()}).map((component) => {
                    if (component.type === Text) {
                        count += 1;
                        return <Text key={count}>{count}. {component.props.children}</Text>;
                    }
                    return component;
                })}</View>);
                break;
            case 'svg':
                const svgXml = $(element).html();
                reactNativeComponents.push(<SvgUri key={index} uri={`data:image/svg+xml;utf8,${svgXml}`} />);
                break;
            // Add more cases for other HTML elements
            default:
                reactNativeComponents.push(<Text key={index} textAlign={"justify"} fontSize={16}>{$(element).text()}</Text>);
                break;
        }
    });
    // console.log(reactNativeComponents)
    return reactNativeComponents;
};

export default convertHtmlToReactNative;

Được cập nhật: 27 tháng 3 lúc 0:53:53 | Lượt xem: 774

Các bài học liên quan