
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 … )
Để lại bình luận: