Comments and Printing
Python uses comments to provide information to the programmer. The # symbol is used to provide a comment. Every text after the # sign is omitted for the Python interpreter, in other words, it is not considered to be part of code.
# this is a comment
# the name of the Script is helloMsg.py
# the following line uses the print() function to print the string "Hello Hackers" into the screen
print("Hello Hackers")
by executing the program:
servin@linux-csit-club:~/pythonscripts$ python3 helloMsg.py
Hello Hackers
We can use a different way to print:
# Name of program printingLines.py
print("hello", end='')
print("Hackers")
An executable Script.
The Built-in Functions
Python provides functionalities that are quite useful whenever a script is written. The functions can be found at https://docs.python.org/3/library/functions.html. However, here is a list of the most popular functions that we will use towards this course:
ascii() | chr() | dir() | exec() | float() |
---|---|---|---|---|
format() | hash() | hex() | id() | input() |
int() | isisntance() | len() | list() | max() |
min() | open() | pow() | print() | range() |
set() | () | hex() | id() | float() |
In fact, we will start with a couple of them this chapter, to specify the data type of a number (i.e., int()
and float()
), to manipulate a sequence of strings (i.e., str()
and format()
) and to interact with the user through functions such as print()
and input()
.
Python Strings
A string is a collection of characters, that are enumerated starting at position 0
. For example:
>>> s = "hello"
>>> s
'hello'
The variable s contains the string “hello”
. We can extract the size of the string, also called the length, by using the function len()
, as follows:
>>> len(s)
5
and we can extract each character by specifying the position, also called index inside the [].
>>> s[0]
'h'
>>> s[1]
'e'
>>> s[2]
'l'
>>> s[3]
'l'
>>> s[4]
'o'
In addition, python has the flexibility to “wrap around” the string by providing a round of negative indexing. For example:
>>> s[-1]
'o'
>>> s[-2]
'l'
>>> s[-3]
'l'
>>> s[-4]
'e'
>>> s[-5]
'h'
However, Python recognizes the length of the string, so when an attempt to extract an index that does not belong to the possible bounds of the string we obtain the following:
>>> s[-6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Cutting Strings (slicing)
Python provides the ability to “cut” strings into segments, creating substrings. This process is called slicing. The “:” is used as the operator to cut the String. For example, let us trace the following sequence of cuts in the string s containing the string “hello”
>>> s[:-1]
'hell'
>>> s[:]
'hello'
>>> s[-1:]
'o'
>>> s[:1]
'h'
>>> s[2:5]
'llo'
>>> s[2:4]
'll'
>>> s[::-1]
'olleh'
Concatenation and Data Types Transformation Operations
Strings own a number of functionalities and built-in operations that help to manipulate the strings by specifying patterns and operations.
For example, we can concatenate or “glue” two strings together by using the + operator as following
>>> "5" + "2"
'52'
However, if you require to extract the numeric value of the string and then perform operations, then you can cast the string by using int() or float() functions, as follows:
>>> int("5") + int("2")
7
It is often requiring to glue different data types to a string (e.g., an int, or a float) and we need to be careful how to perform such operations. E.g., suppose we have the following variables
>>> x = 5
>>> y = “apples”
And we would like to have a message “5 apples” by using variables x and y. If we attempt to do:
>>> x+y
x+y
TypeError: must be str, not int
Reproduction of Strings
The multiplication operator (*) can be applied as well to the string to produce multiple strings based on the base. For example:
>>> s*2
'hellohello'
>>> s*10
'hellohellohellohellohellohellohellohellohellohello'
Having fun with strings
Although Python is flexible with string operations, Python will require to perform operations with similar data types.
Suppose that x
is 5
and y
is "apples"
.
There are several ways to obtain the string “5 apples
”
1. Change all variables to strings: one way (and the simplest one) is to transform x into a string by using the casting function str()and simply concatenate it with y (also a string).
>>> str(x)+y
5apples
We can fix the spacing by concatenating an extra white space between x and y ad follows:
>>> str(x)+” ”+y
5 apples
2. Use the format functionality to construct a string: The function “format
” allows to incorporate values within strings. It is useful when building scripts that would like to report certain values in a print()
. The format requires a string in the left hand side and the curly brackets ‘{}’
, where the {}
represent the space where the value will be “inserted” into the string. For example:
>>> ‘{} apples’.format(x)
5 apples
Notice that there is no need to concatenate an additional white space (” ”) between the string and the number. The format function allows you to customize a resulting string output.
In Ch. 5, we will discuss more in detail functions. Although in programming often are called methods if we deal with object-oriented, functions are defined in old scripting techniques, including the functions in Linux as we described in previous chapters. The String is a complex creature, and therefore, there are functions that belong to this structure. Here is a demonstration of the functions for the string.
Counting Occurences
>>> s = "hello"
>>> s.count('h')
1
>>> s.count('e')
1
>>> s.count('l')
2
>>> s.count('o')
1
Changing the case
Another feature of strings is the capability to format the cases in the string by using the built-in functions.
>>> s.capitalize()
'Hello'
>>> s.lower()
'hello'
>>> s.title()
'Hello'
>>> s.upper()
'HELLO'
>>> s = "hElLo"
>>> s
'hElLo'
>>> s.swapcase()
'HeLlO'
User Interaction Through Arguments
In Python, we can access the arguments provided to the script by using the library sys
. In the library sys
, there is the argv
a field that allows us to extract the argument vector from the program.
Let us remember that Python uses iterable objects VERY often, as we described in previous sections. The argument vector is considered an iterable object (in fact is an iterable list, we will discuss this item in Ch. 4 with more detail), which means that we can access that information from the argv
by specifying the position (i.e., the index). For example, if we attempt to extract the first element in the argument vector, we specify as follows:
firstArg = sys.argv[0]
Python will assign to the first argument to be the name of the script/program that is running the script itself. The second argument, i.e., sys.argv[1]
, will be considered the first actual value provided as an argument, sys.argv[2],
the second actual value provided, and so on.
Similarly, as we did with string, we have the ability to extract the length of the argument vector by using the function len()
. In case we are interested to know the number of arguments provided in the argument vector we simply specify
size = len(sys.argv)
Check Point
Task 1: Write a script called ch2Task1.py that will print the contents of the first and second arguments.
Task 2: Write a script called ch2Task2.py. The script will print the following:
– (1) the total number of arguments provided to argumentsList.py, and
– (2) the list of the arguments (without the name of the script)
Remember the notion of iterable in Python. The arguments provided to the program is an iterable object (i.e., a list of values). We can use the power of Python to process the list or extracting the values of the list by specifying the index.
Task 3: Modify the program from Task 2 by creating a script called ch2Task3.py. This time print the list of arguments in reverse order.
Task 4: Write a script called addition.py. The script will take two arguments, i.e., x and y. The script will perform the addition of x and y and report a message as follows:
the sum of <number> and <number> is: <addition>