• Skip to main content
  • Skip to primary sidebar
…

...

cuộc sống là phải luôn khám phá.

  • Home
  • Music Box
  • Các trang web hay
  • Giới thiệu
  • Liên kết website
Bạn đang ở đây:Trang chủ / IT / Python Basic: Getting to Python (part 2)

Python Basic: Getting to Python (part 2)

20/10/2021 tác giả: Mạnh Hùng 2 Bình luận

python

Please check part 1 first and then come back to read this article later.

How to write Comments in Python

Comments are an integral part of any program. They can come in the form of module-level docstrings, or even inline explanations that help throw light on a complex function.

When your project grows from a single line to thousand lines of code, that’s when comments play its part. You may think that you surely understand and remember your code now, however, as time goes by, you need something to recall.

Python uses # (hash mark) for single-line comment.

# This is a single comment

To write multiple comment lines, instead of putting hash mark before each line, you can put the paragraph inside a triple-double quotes:

"""
Instead of pressing "enter" many times and
typing all those annoying hash marks, I could
do like this.
"""

However, be careful where you place these multi-line “comments.” Depending on where they sit in your program, they could turn into docstrings, which are pieces of documentation that are associated with a function or method. If you slip a triple quotes comment right after a function definition, then what you intended to be a comment will become associated with that object. It’s not really a concern now, but we should learn this anyway.

Operators

Operators are used to perform operations on variables and values, and it should be mostly the same with other programing language. I’ll dig into this more when I have more time, but for now just check these links:

https://www.w3schools.com/python/python_operators.asp
https://docs.python.org/3.9/library/stdtypes.html

Keyboard Input

In Python to enter data from the keyboard, we use the input() function. The input value of the default input() function is usually of type string, so we need to convert if we want to store the input value is not of string type.

For example, to return a integer or float type of value:

print("Type an int value:")
x = int(input()) # or float(input())
print("You type:", x)
print("Data type:", type(x))

To return a boolean type:

#True of False
def StrToBool(s):
    return s.lower() in ("yes", "true", "t", "1")

print("Enter bool: ")
x = StrToBool(input())
print("You typed:", x)
print("Data type:", type(x))
#def: is user's defined function. I'll look into this later.

We can also put a label directly in input()

# Expect a int value returns:
x = int(input("Enter an int value:"))
print(type(x))
# Expect a str value returns:
y = input("Enter an int value:")
print(type(y))

The output

In order to print a loop-style of data, we can do thing like this:

print("*"*15)
# print "*" out 15 times.

Using format() function:

print("{0}x^2+{1}x+{2}=0".format(4,2,3))
# 4x^2+2x+3=0
print("{1}x^2+{1}x+{2}=0".format(4,2,3)) # Note that output string only passes last two arguments to format()
# 2x^2+2x+3=0
print("{0:>5}".format("Apple"))
print("{0:>10}".format("Orange"))  # This will insert 4 blank character before the string

There is other way to do this, is that you put letter f before string and it stands for “format”, such as f”string {variable}”. You embed variables inside a string by using { } to wrap variables.

apple = 5
print(f"He has {apple} apples.")

Unpacking and Argument

We can use input() to get something from user by using keyboard to type while the script is running. But there is a way to get that directly on the command line at the start of the script, by using argument variable (argv). In other words, this variable holds the arguments you pass to your Python script when you run it. (A script, is just another name of .py file)

Let’s try an example and see how it will happen:

from sys import argv
script_name, one_more_thing = argv
print("The script is called:", script_name)
print("Your first variable is:", one_more_thing)

# file name of this file is saved as Hello.py

From line 2, the two variables unpack argv, and get assigned by arguments held in it, in order.

When you run above code in your command line by typing:

python Hello.py Apple

This is how it’s printed: (note that ‘Apple’ is just some random word, you could type anything you like)

The script is called: Hello.py
Your first variable is: Apple

There is another thing you need to know, if you’re using PyCharm (or similar IDE), instead of pressing Run, you need to type those command above on Windows Command Prompt, or switch to Terminal tab in PyCharm which works as the same. Or else, you will get an error like this : ValueError: not enough values to unpack (expected 2, got 1). Because when you press Run button you don’t have chance to provide arguments to the script. (only default agrv)

The first item in argv is the name of the Python script you’re running. Any additional arguments (one_more_thing, in this case) are arguments pass to this script. argv is a list that is expected to contain many values.

Because it is a list, we could also do this:

from sys import argv
script_name = argv
print("The script is called:", script_name)

Now script_name is the argument list. We can pass as many arguments into it.

python Hello.py Apple Orange

and the result is:

The script is called: ['Hello.py', 'Apple', 'Orange']

(okay, this blog is long enough, let me continue it in another part … )

Reader Interactions

Trackbacks

  1. Python Basic: Getting to Python (part 1) - ... viết:
    20/10/2021 lúc 9:11 chiều

    […] Continue to part 2. […]

    Trả lời
  2. Python Basic: Getting to Python (part 3) - ... viết:
    21/10/2021 lúc 9:36 sáng

    […] Continue from part 2. […]

    Trả lời

Để lại bình luận: Hủy

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Primary Sidebar

Chuyên mục

  • fun
  • IT
  • News
  • testing

python

Python Basic: Getting to Python (part 4)

In short, Lists are used to store multiple items in a single variable, they are convenient data structures for representing a sequence of data. In that regard, a list is similar to a string, except a string can hold only characters, however, a list can hold any Python object.

python

Python Basic: Getting to Python (part 3)

Python Functions: (user-defined or from libraries) function is a block of code which only runs when it is called, to do a complete job (module), is named, and can be called to execute multiple times at many places in the program. What happens if you don’t use function? What I can think about is repetitive works, hard to debug, hard to expand the whole code, so usually when working on a large project you need to split your code into many small modules.

Tạo một website dễ dàng với Hugo

Hôm nay chúng ta cùng thử generate 1 website với Hugo, theo như lời giới thiệu ở trang chủ “The world’s fastest framework for building websites.”

Steam_logo

DMCA.com Protection Status

Copyright ©2022 · pquan.info - All Rights Reserved ·