Introduction To Python


I created this book as addition to my Python Playlist on YouTube.

Enjoy.

Table of Contents:

 

Introduction - Why to Learn Python

If there's one thing that I can recommend, it's to learn Python.

Python is high, general purpose programming language that will help you to get job done - in extremely short period of time.

Some people will call it easy. Programming in general is not easy - but Python syntax is almost like plain english, which will help greatly if you are starting programming career with this beautiful language.

Sure, some things need to be done in low level programming languages, where you need to invest considerable amount of time - and this is where Python shines. It's extremely useful in testing and prototyping.

We can use Python in various fields, for example:

And so on, and so on.

But the most important thing - it's fun to work in Python.

Let's learn it together.

 

Python Installation, First Script

Go to python.org and grab Python setup file for your system.

For security reasons, always use official sites to download important setup files. Do not use anonymous FTP servers and torrents. You must be security aware.

While installing Python, make sure that you check PIP and PATH options.

PIP will be used to grab additional modules from Internet with one-line commands, and "having Python in PATH" means that you can run Pythons scripts in terminal/cmd from all parts of system, which will save you a lot of time if you like to work in terminal.

When we are done with installation, we have two options. To use Python shell for short instructions, but better option is to use graphical IDLE - Integrated Development and Learning Environment.

My advice is to use IDLE all the time.

In IDLE, open new file and save it using file name, for example, "playground.py". Just make sure that file extension is ".py"

That is important because you will immediately activate syntax highlighting for python source code, and also, IDLE will pay attention to how you are indenting lines of code, because indentation is important in Python.

Ok, now type this source code in that file you created, and run it with F5This is line you need to type:


print("Something")

And this is result. Well done.


Something
>>> 

Results are in Python Shell, that's why you see arrows. Sure, you can run print("Something") in Shell, and the thing will work, too. But Shell is not practical for big scripts.

We can print more lines, one after another. Make sure that words inside parentheses are enclosed in quotes.


print("Something")
print("Some string more")
print("3.14")
print("23423423423423")

Let's do something fun. What you see is "for loop" that will print specific number, one after another, in specific range:


for x in range(5):
    print(x)

Result:


0
1
2
3
4
>>> 

Yes, you see 4 as last number, but we are starting from 0, so in total you have 5 numbers printed.

We will talk more about for loops. Don't worry about that for now.

Let's go to next tutorial.

 

Python Prompt, CMD, Terminal

Let's learn how to run Python scripts from CMD if you are using machines with Windows.

On Windows 10, click in lower left corner where we have search box. Type "cmd" there and press Enter. This is what will pop-up (in my case):


Microsoft Windows [Version 10.0.18363.959]
(c) 2019 Microsoft Corporation. All rights reserved.

C:\Users\user>

This is default directory for user. To clear screen type "cls" and press Enter.

After that, let's move to place where I have Python installed, using "cd" command. I have Python in "Python38-64" directory inside "root" of my hard drive:


C:\Users\user>cd C:\Python38-64

C:\Python38-64>

Now, what is in that directory ? We will use "dir" command to list content:


C:\Python38-64>dir
 Volume in drive C is New Volume

 Directory of C:\Python38-64

07/30/2020  11:50 AM    <DIR>          .
07/30/2020  11:50 AM    <DIR>          ..
07/30/2020  11:50 AM    <DIR>          ARCHIVE
06/22/2020  04:59 PM    <DIR>          DLLs
05/30/2020  04:27 PM    <DIR>          Doc
06/22/2020  06:04 PM    <DIR>          include
05/30/2020  04:27 PM    <DIR>          Lib
05/30/2020  04:27 PM    <DIR>          libs
05/13/2020  10:43 PM            31,453 LICENSE.txt
07/30/2020  12:00 AM                34 playground.py
05/13/2020  10:42 PM           100,424 python.exe
05/13/2020  10:42 PM            58,952 python3.dll
05/13/2020  10:42 PM         4,208,200 python38.dll
07/27/2020  02:10 PM    <DIR>          Scripts
05/30/2020  04:28 PM    <DIR>          tcl
05/30/2020  04:27 PM    <DIR>          Tools
05/13/2020  10:43 PM           100,880 vcruntime140.dll
05/13/2020  10:43 PM            44,320 vcruntime140_1.dll
               7 File(s)      4,544,263 bytes
              11 Dir(s)  74,980,769,792 bytes free

C:\Python38-64>

That is our listing. Important thing here is python.exe file, and also we see our custom playground.py file. Ok, now we can run our custom python script, with python playground.py


C:\Python38-64>python playground.py
0
1
2
3
4

C:\Python38-64>

After script is executed, you are again in cmd, which means we can continue to run other python scripts (if we have it), or we can just type classical MS-DOS command.

You don't need to use CMD if you don't like typing, working in IDLE is perfectly fine. But knowing how to navigate through system using cmd on Windows, or Terminal on Linux/BSD system is important for programmers.

Ok, in next tutorial we will talk about syntax and indentation in Python.

 

Python Syntax, Indentation

In programming, we can create "containers". Official name for some specific "container" is variable.

Variables can contain numbers, words, characters, whole sentences, and so on. Also, we can override things in variables with new things.

Let's create a variable "something", so we can put some data there, for example: "Some String Here".

After that, we will immediately use it - just simple printing, nothing special here:


something = "Some String Here"

print(something)

Result:


Some String Here
>>> 

Python doesn't care about spaces inside parentheses (when we use variables):


print(  something  )

print(      something      )

But space inside quotes is extremely important when we do direct printing. Everything inside quotes is part of usable string. Type and run this code:


print("some string")
print(" some string ")
print("      some string     ")
print(   "      some string     "    )
print(      "some string"    )

Result:


some string
 some string 
      some string     
      some string     
some string
>>> 

Try this to see what's happening:


print("string with more parts")
print("string     with     big     spaces")

In Python, indentation is extremely important. What you see is "if statement". We will use it all the time in programming.


if 5 < 10:
    print("This Will Work")

But this code will not work - because we messed up indentation rules:


if 5 < 10:
print("This Will NOT Work")

So far so good. In next tutorial we will talk about internal code explanations (comments and docstrings).

 

Python Comments, DocStrings

If we need to explain part of code a little bit more (internally) we can use comments.

In Python, single-line comments start with hash(#) character.


#This is single-line comment

"""
We can also have explanation
on multiple lines.
Start and end them with 3 quotes.
"""

print("This will be printed") #This will not, bacause it's comment.

When we run it:


This will be printed
>>> 

Python Docstrings

What we see is Python function. Functions are like dedicated workers that will do specific job and nothing else.

In function, we can have short explanation (with 3 quotes aside). They are called "docstrings" because they are very specific "internal documentation" for that one function.

Create them immediately after function name.

For example, we can use them to generate automatic PDF documentation for all functions in our script. Or even, whole site can be based on docstrings, if our script have hundreds of functions.


def first_function():
    """ Brief explanation about func here """
    print("Some Real Operations")

To access docstrings, just target that specific function, and add __doc__ to print command:


def first_function():
    """ Brief explanation about func here """
    print("Some Real Operations")
    
print(first_function.__doc__)

Result:


 Brief explanation about func here 
>>> 

To use any function, just call it with: first_function() - don't forget parentheses. We need them because some functions can grab things in parentheses and do all types of further operations with data you provide.


def first_function():
    """ Brief explanation about func here """
    print("Some Real Operations")
    
first_function()

Result:


Some Real Operations
>>> 

Ok, in next tutorial we will talk more about variables.

 

Python Variables, Contexts

Sure, while practicing you can use abstract/short variable names like, x, y, z, a, b, c, and so on:


x = "Actual Data"

print(x)

But, better option is to use variable names that describe what they contain:


name = "John"
lastname = "Snow"

print(name)
print(lastname)

We can use (print in this case) variables one after another - on single line. Make sure to have a comma to separate them:


name = "John"
lastname = "Snow"

print(name, lastname)

Underscores will work as part of variable names, but having a lot of them connected is silly.

Variables can hold numbers, too:


name = "John"
last____name = "Snow"

number = 5
pi = 3.14

print(name, last____name)
print(number, pi)

Mathematical operations can be done directly:


x = 5
y = 10

print(x + y)

We can use one variable multiple times:


x = 5
y = 10

print(x + y + x + y)

For complicated formulas enclose parts in a dedicated parenthesis:


x = 5
y = 10

print((x + x) + (y + y))

We can have numbers treated as letters - if we enclose them in quotes.

In this context, result will be a concatenation of numbers, because they are treated as characters, and not numbers:


x = "5"
y = "10"

print(x + y)

Result when numbers are used as letters:


510
>>> 

Don't worry about contexts, over time they will become intuitive.

In next tutorial we will talk about concatenation and how to detect data types in variables.

 

Python Concatenation, Types

To concatenate left side (our custom report) with right side, which is variable that hold string, we will use plus (+) symbol:


name = "John"
lastname = "Snow"
years = "39"

print("Name: " + name)
print("LastName: " + lastname)
print("Years: " + years)

We can also use a comma:


name = "John"
lastname = "Snow"
years = 39

print("Name: ", name)
print("LastName: ", lastname)
print("Years: ", years)

To see with what we are dealing with (data type detection), there's type() function:


name = "John"
lastname = "Snow"
years = 39

"""
print("Name: ", name)
print("LastName: ", lastname)
print("Years: ", years)
"""

print(type(name))
print(type(lastname))
print(type(years))

Result:


<class 'str'>
<class 'str'>
<class 'int'>
>>> 

We are working with two strings (name, lastname) and one number (integer).

Sometimes, we will put result of type() function in dedicated variable, so it can be used in further operations.

We will use that approach all the time:


name = "John"
lastname = "Snow"
years = 39

"""
print("Name: ", name)
print("LastName: ", lastname)
print("Years: ", years)
"""

result = type(name)
print(result)

This will be result in Shell:


<class 'str'>
>>> 

It's so easy to work with numbers in Python. Let's learn about that in next tutorial.

 

Python Numbers

Python is high level programming language - it will automatically recognize number type in variables:


x = 5
y = 4654655
z = -4656456

print("Value of x: ", x, type(x))
print("Value of y: ", y, type(y))
print("Value of z: ", z, type(z))

Sure, we can use floats. If we need higher precision:


x = 5.00
y = 4654655.123
z = -4656456.435345

print("Value of x: ", x, type(x))
print("Value of y: ", y, type(y))
print("Value of z: ", z, type(z))

It's extremely useful to put result of operations in dedicated variables, so we can use it further:


x = 5
y = 10
addition = x + y

print("Result: ", addition)
print("Type:", type(addition))

If one number in calculation is float, result will be float, too:


x = 5.34
y = 10
addition = x + y

print("Result: ", addition)
print("Type:", type(addition))

Result:


Result:  15.34
Type: <class 'float'>
>>> 

Scientific notation supported by default:


# 5 x 10 on 3

x = 5e3
print(x)

This will work, too:


# 5 x 10 on 12

x = 5E12
print(x)

Result:


5000000000000.0
>>> 

In next tutorial we will convert from one data type to another.

 

Python Casting, int, float, str

This is our starting point, one integer, float, and negative float:


x = 10
y = 12.25
z = -5345345.234234

print("Value of x: ", x, "Type: ", type(x))
print("Value of y: ", y, "Type: ", type(y))
print("Value of z: ", z, "Type: ", type(z))

To transfer all of them in simple integer, we will use int() function:


x = 10
y = int(12.25)
z = int(-5345345.234234)

print("Value of x: ", x, "Type: ", type(x))
print("Value of y: ", y, "Type: ", type(y))
print("Value of z: ", z, "Type: ", type(z))

Sometimes, all we need is bunch of floats:


x = float(10)
y = float(12.25)
z = float(-5345345.234234)

print("Value of x: ", x, "Type: ", type(x))
print("Value of y: ", y, "Type: ", type(y))
print("Value of z: ", z, "Type: ", type(z))

With str() function we can convert numbers to strings:


x = str(10)
y = str(12.25)
z = str(-5345345.234234)

print("Value of x: ", x, "Type: ", type(x))
print("Value of y: ", y, "Type: ", type(y))
print("Value of z: ", z, "Type: ", type(z))

When we have all strings, just concatenate them using plus (+) symbol:


x = str(10)
y = str(12.25)
z = str(-5345345.234234)

print(x + y + z)

Result:


1012.25-5345345.234234
>>> 

What a weird result. Now we can use tab as separator:


x = str(10)
y = str(12.25)
z = str(-5345345.234234)

print(x + "\t" + y + "\t" + z)

Result:


10	12.25	-5345345.234234
>>> 

In next tutorial we will learn how to extract individual characters from strings, and how to remove spaces.

 

Python Indexing, Space Strip

Two variables with strings are our starting point. To extract characters in specific positions we will use brackets [0], for example, to extract first character.

In Python, and most other programming languages we count from 0, and not from 1, when we talk about positions/indexes.


a = "Double Quotes"
b = 'Single Quotes'

print("First char from a var: ", a[0])
print("First char from b var: ", b[0])

Result:


First char from a var:  D
First char from b var:  S
>>> 

Following same principle, we can get multiple characters, at different positions:


a = "Double Quotes"
b = 'Single Quotes'

print(a[0], a[1], a[2])

print("")

print(b[0], b[1], b[2])

Result:


D o u

S i n
>>> 

We can extract characters in specific range:


print(b[0:7])

Result:


Single 
>>>

Last character in string:


print(b[-1])

Result:


s
>>>

To grab everything, use colons:


print(b[:])

Result:


Single Quotes
>>>

How to Remove Spaces in Strings

If we have a "dirty" string with a lot of unwanted spaces, we can use strip() function:


a = "      Double Quotes"
b = 'Single Quotes         '

print(a.strip())
print(b.strip())

Result:


Double Quotes
Single Quotes
>>>

After we are done, concatenation is possible. Or, some other operation:


a = "      Double Quotes"
b = 'Single Quotes         '

print(a.strip() + " " + b.strip())

Result:


Double Quotes Single Quotes
>>>

Ok, in next tutorial we will play with string length, and how to transform characters (lowercase, uppercase).

 

Python Strings, len, lower, upper

To get string length (number of characters), we will use len() function.

Note: all whitespaces are important:


a = "      Double Quotes"
b = 'Single Quotes         '

print(len(a))
print(len(b))

Result:


19
22
>>> 

a = "Double Quotes"
b = 'Single Quotes'

print(len(a))
print(len(b))

Result:


13
13
>>>

Sometimes it's useful to put length in dedicated variable, so we can use it later:


a = "Double Quotes"
b = 'Single Quotes'

how_a_is_long = len(a)

print(how_a_is_long)

Result:


13
>>>

Even better option is to explain what is happening:


a = "Double Quotes"
b = 'Single Quotes'

how_a_is_long = len(a)

print("How long var a is: ", how_a_is_long)

To transfer all chars to lowercases, we can use lower() function:


a = "Double Quotes"
b = 'Single Quotes'

print(a.lower())
print(b.lower())

Result:


double quotes
single quotes
>>>

Same for uppercases, with upper() function:


a = "Double Quotes"
b = 'Single Quotes'

print(a.upper())
print(b.upper())

Result:


DOUBLE QUOTES
SINGLE QUOTES
>>>

 

Python Replace, Split

We can replace one character with another character, in this case 'A' will be replaced with 'Z':


a = "This is A, this is B, this is group ABC"

print(a.replace("A", "Z"))

Multiple character can replace one character, too:


a = "This is A, this is B, this is group ABC"

print(a.replace("A", "RRRRRRRR"))

One word can be replaced with another word:


a = "This is A, this is B, this is group ABC"

print(a.replace("This", "555"))

How to Split String

Function split() will accept specific separator, in this case, just space:


a = "This is A, this is B, this is group ABC"

print(a.split(" "))

Result:


['This', 'is', 'A,', 'this', 'is', 'B,', 'this', 'is', 'group', 'ABC']
>>> 

In this case, we are using comma as separator:


a = "This is A, this is B, this is group ABC"

print(a.split(","))

And now, comma and space:


a = "This is A, this is B, this is group ABC"

for x in a.split(", "):
    print(x)

What you see is "for loop". In this case it is used to print all parts of string if separator is character "i":


a = "This is A, this is B, this is group ABC"

for x in a.split("i"):
    print(x)

Result: 


Th
s 
s A, th
s 
s B, th
s 
s group ABC
>>> 

In this example, we are doing split based on comma and space. After that, all results are sent to upper() function:


a = "This is A, this is B, this is group ABC"

for x in a.split(", "):
    print(x.upper())

Result: 


THIS IS A
THIS IS B
THIS IS GROUP ABC
>>> 

We will talk more about for loops.

How to get and use input from Keyboard is topic of next tutorial.

 

Python Keyboard Input

It's extremely easy to grab input from the keyboard in Python:


print("Your First App v0.00001")
print("-----------------------")

x = input("Please, enter your name: ")
print("Name: ", x)

We can do some immediate calculations:


print("Your First App v0.00001")
print("-----------------------")

x = int(input("Please, enter some number: "))
print("Result: ", x + x)

And sure, use as much inputs as you need:


print("Your First App v0.00001")
print("-----------------------")

x = (input("Please, enter your Name: "))
y = (input("Please, enter your LastName: "))

print(x, y)

In next tutorial we will work with Lists. They are just collections of elements enclosed in brackets.

 

Python Lists

In lists, we can have numbers, characters, words - you are not limited by data type:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
names = ["Samantha", "John", "Michael"]

print(numbers)
print(names)

Result: 


[1, 2, 3, 4, 5, 6, 7, 8, 9]
['Samantha', 'John', 'Michael']
>>> 

Here, just as for strings, we can use type() function:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
names = ["Samantha", "John", "Michael"]

print(type(numbers))
print(type(names))

Result: 


<class 'list'>
<class 'list'>
>>> 

Function len() will return number of elements:


numbers = [1, 2, 1, 2, 1, 2]
names = ["Samantha", "John", "Samantha", "John"]

print(len(numbers))
print(len(names))

Result: 


6
4
>>> 

Tu turn string into list, we will use list() function:


x = "something"
y = list(x)

print(y)
print(len(y))
print(type(y))

Result: 


['s', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g']
9
<class 'list'>
>>> 

In next tutorial, we will extract elements of lists using indexes.

 

Python Length, Indexes

From last tutorial we know how to get total number of elemens in list:


names =["Michael", "Samantha", "Anastasia"]

lol = len(names)
print("Number of elements: ", lol)

Result: 


Number of elements:  3
>>> 

Also, as with strings, to get specific character we can use positions/indexes enclosed in brackets. First element is at position 0:


names =["Michael", "Samantha", "Anastasia"]

print("Element 0 :", names[0])
print("Element 1 :", names[1])
print("Element 2 :", names[2])

Result: 


Element 0 : Michael
Element 1 : Samantha
Element 2 : Anastasia
>>> 

Often, it's useful to grab elements of one list and store it in another one, changing order of them:


names =["Michael", "Samantha", "Anastasia"]

mix = (names[2], names[0], names[1])

print(mix)

print("Element 0 :", mix[0])
print("Element 1 :", mix[1])
print("Element 2 :", mix[2])

Result: 


('Anastasia', 'Michael', 'Samantha')
Element 0 : Anastasia
Element 1 : Michael
Element 2 : Samantha
>>> 

In next tutorial, we will learn how to Change, Append and Insert elements in existing lists.

 

Python Change, Insert, Append

We can change element using positions:


names =["Michael", "Samantha", "Anastasia", "John"]

names[0] = "Patrick"
print(names)

Result: 


['Patrick', 'Samantha', 'Anastasia', 'John']
>>> 

New elements can be inserted using insert() function. Even duplicates:


names =["Michael", "Samantha", "Anastasia", "John"]

names[0] = "Patrick"
names.insert(1, "Madona")
names.insert(2, "Madona")

print(names)

Result: 


['Patrick', 'Madona', 'Madona', 'Samantha', 'Anastasia', 'John']
>>> 

Sure, we can append new elements at the end of list using append() function:


names =["Michael", "Samantha", "Anastasia", "John"]

names[0] = "Patrick"
names.append("Brian")
names.append("Larry")

print(names)

Result: 


['Patrick', 'Samantha', 'Anastasia', 'John', 'Brian', 'Larry']
>>> 

We can also transfer elements of one list into another one - using for loop:


names =["Michael", "Samantha", "Anastasia", "John"]
names1 = ["Patrick", "Madona", "Larry"]

for x in names1:
    names.append(x)

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John', 'Patrick', 'Madona', 'Larry']
>>> 

In next tutorial, we will learn how to Delete, Remove and Pop elements from lists.

 

Python Delete, Remove, Pop

To delete one element from list, again, indexes will be used:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

del names[0]
del names[0]
del names[0]

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['John']
>>> 

Actually, we can delete all of them using index 0 and for loop:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

for x in range(4):
    del names[0]

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
[]
>>> 

If we know what we are searching for, we can remove() by value:


names =["Michael", "Samantha", "Anastasia", "John"]

print(names)

names.remove("Michael")
names.remove("John")

print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['Samantha', 'Anastasia']
>>> 

Sometimes it's useful to target element at the end of list:


names =["Michael", "Samantha", "Anastasia", "John"]
print(names)

names.pop()
print(names)

names.pop()
print(names)

names.pop()
print(names)

Result: 


['Michael', 'Samantha', 'Anastasia', 'John']
['Michael', 'Samantha', 'Anastasia']
['Michael', 'Samantha']
['Michael']
>>> 

Function pop() is useful when we need to grab that last element we removed, so we can do something more with it:


names =["Michael", "Samantha", "Anastasia", "John"]

last_element = names.pop()

print("What we pop-ed: ", last_element)
print("Names after pop:", names)

Result: 


What we pop-ed:  John
Names after pop: ['Michael', 'Samantha', 'Anastasia']
>>> 

In next tutorial, we will learn how to search for specific element, and how to use clear() function to remove all of them.

 

Python Search, Clear

To detect do we have specific element in list we can use simple if statement - this is "yes or no" situation:


names =["Michael", "Samantha", "Anastasia", "John"]

if "Samantha" in names:
    print("Samantha is there")

Result: 


Samantha is there
>>> 

What if Samantha is not element of list:


names =["Michael", "Anastasia", "John"]

if "Samantha" in names:
    print("Samantha is there")
else:
    print("Samantha is not there")

Result: 


Samantha is not there
>>> 

If we create multiple lists based on one original list, all changes will replicate to those lists, too:


names =["Michael", "Samantha", "Anastasia", "John"]

a = names
b = names
c = names

names[0] = "New Name"
print(names)
print()
print(a)
print(b)
print(b)

Result: 


['New Name', 'Samantha', 'Anastasia', 'John']

['New Name', 'Samantha', 'Anastasia', 'John']
['New Name', 'Samantha', 'Anastasia', 'John']
['New Name', 'Samantha', 'Anastasia', 'John']
>>> 

To delete all elements, there's dedicated clear() function:


names =["Michael", "Samantha", "Anastasia", "John"]

names.clear()
print(names)

Result: 


[]
>>> 

To delete whole list, use del() function:


names =["Michael", "Samantha", "Anastasia", "John"]

#List destruction
del names

You can't print from something you destroyed:


names =["Michael", "Samantha", "Anastasia", "John"]

del names
print(names)

Result: 


Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 4, in <module>
    print(names)
NameError: name 'names' is not defined
>>> 

In next tutorial, we will learn about Tuples.

 

Python Tuples

Think about tuples as collection of elements that you can't change. They are "fixed in time".

To create them use parentheses:


tuple_names = ("Samantha", "Madonna", "Michael")

print(tuple_names)
print(type(tuple_names))

Result: 


('Samantha', 'Madonna', 'Michael')
<class 'tuple'>
>>> 

Positions work here too:


tuple_names = ("Samantha", "Madonna", "Michael")

print(tuple_names[0])
print(tuple_names[1])
print(tuple_names[2])

Result: 


Samantha
Madonna
Michael
>>> 

And we can do very simple checks with if statement:


tuple_names = ("Samantha", "Madonna", "Michael")

if "Samantha" in tuple_names:
    print("Samantha is there")

Result: 


Samantha is there
>>> 

Ok, in next tutorial we will talk about tuple operations.

 

Python Tuples, Operations

To get number of specific elements (by value), we can use count() function:


tuple_names = ("Samantha", "Madonna", "Michael")

result = tuple_names.count("Samantha")

print("Number of Samantha's: ", result)

Result: 


Number of Samantha's:  1
>>> 

We can locate position of specific element (by value) using index() function:


tuple_names = ("Samantha", "Madonna", "Michael")

pos = tuple_names.index("Madonna")

print(pos)

Result: 


1
>>> 

If we grab value from keyboard, it's easy to find first location, and total number of elements:


tuple_names = ("Samantha", "Madonna", "Michael")

x = input("Enter name to check: ")

print("Number of them: ", tuple_names.count(x))
print("First occurence at position: ", tuple_names.index(x))

Result: 


Enter name to check: Madonna
Number of them:  1
First occurence at position:  1
>>> 

Tuples are easy to work with.

Next tutorial will be dedicated to Sets.

 

Python Sets

Sets are collections of unique elements. We don't care about positions here. That's why we will have different result every time sets are printed.

To create set, use curly bracket:


colors = {"Green", "Yellow", "Red", "Black"}

print(colors)
print(type(colors))

Result: 


{'Black', 'Yellow', 'Green', 'Red'}
<class 'set'>
>>> 

Or dedicated set() function. Don't forget to use double parentheses:


colors_2 = set(("White", "Blue"))

print(colors_2)
print(type(colors_2))

Result: 


{'Blue', 'White'}
<class 'set'>
>>> 

Try to print set multiple times - positions will be different every time:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print(colors)

Results: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Red', 'Black', 'Yellow', 'Green'}
>>> 
============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Green', 'Yellow', 'Red', 'Black'}
>>> 
============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Black', 'Yellow', 'Red', 'Green'}
>>> 

In next tutorial, we will learn how to Add or Update Sets with new elements.

 

Python Sets, Add, Update

We can create sets with multiple same elements, but duplicates are disregarded in usage.

This is how to add new element to set - function add() will get the job done:


colors = {"Green", "Yellow", "Red", "Black", "Black"}
print(colors)

colors.add("Orange")
print(colors)

Result: 


{'Black', 'Red', 'Green', 'Yellow'}
{'Black', 'Yellow', 'Red', 'Orange', 'Green'}
>>> 

We can't use indexes here - you will get Traceback (Error):


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print(colors[0])

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 3, in <module>
    print(colors[0])
TypeError: 'set' object is not subscriptable
>>> 

We can't replace one element with another one using "string replace" approach. This will result in mess:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

colors.update("Green", "OrangeRed")

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'e', 'd', 'Black', 'n', 'R', 'Yellow', 'Green', 'Red', 'r', 'g', 'a', 'O', 'G'}
>>> 

But we can add new things to sets with update() function with brackets inside parentheses:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

colors.update(["OrangeRed"])

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Green', 'OrangeRed', 'Red', 'Black', 'Yellow'}
>>> 

Sure, we can grab new elements using keyboard:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

x = input("New Color for x: ")
y = input("New Color for y: ")

colors.update([x, y])

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
New Color for x: Magenta
New Color for y: Navy
{'Yellow', 'Black', 'Red', 'Green', 'Magenta', 'Navy'}
>>> 

Function len() will work here, just as with strings or tuples:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
Colors are:  {'Red', 'Black', 'Green', 'Yellow'}
Number of colors:  4
>>> 

In next tutorial, we will learn how Remove and Discard elements of sets.

 

Python Sets, Remove, Discard

To remove element from set use remove() function:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.remove("Yellow")
print("After: ", colors)
print("Number of colors: ", len(colors))

Result:

Colors are:  {'Green', 'Black', 'Yellow', 'Red'}
Number of colors:  4
--------------------------------------------------
After:  {'Green', 'Black', 'Red'}
Number of colors:  3
>>> 

Error on multiple Remove Operations:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.remove("Yellow")
colors.remove("Yellow")
colors.remove("Yellow")

print("After: ", colors)
print("Number of colors: ", len(colors))

Result: 


Colors are:  {'Yellow', 'Green', 'Black', 'Red'}
Number of colors:  4
--------------------------------------------------
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 8, in <module>
    colors.remove("Yellow")
KeyError: 'Yellow'
>>> 

But we can use discard() function to evade errors:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.discard("Yellow")
colors.discard("Yellow")
colors.discard("Yellow")

print("After: ", colors)
print("Number of colors: ", len(colors))

Result:

Colors are:  {'Green', 'Red', 'Yellow', 'Black'}
Number of colors:  4
--------------------------------------------------
After:  {'Green', 'Red', 'Black'}
Number of colors:  3
>>> 

Function clear() will remove all elements:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.clear()

print("After: ", colors)
print("Number of colors: ", len(colors))

Result: 


Colors are:  {'Black', 'Red', 'Green', 'Yellow'}
Number of colors:  4
--------------------------------------------------
After:  set()
Number of colors:  0
>>> 

To destroy set, use del() function:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)

del colors

print(colors)

We can't use something we destroyed:


Colors are:  {'Green', 'Red', 'Black', 'Yellow'}
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 7, in <module>
    print(colors)
NameError: name 'colors' is not defined
>>> 

Next tutorial will be about Dictionaries.

 

Python Dictionaries

Dictionaries are collections with "left and right side", or, "key and value pairs".

Basically keys, (left) describe data on right (value) side.

Dictionaries are created with curly brackets:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print(dba)

Result: 


{'Name': 'Anastasia', 'SSN': 123456}
>>> 

We will get values using keys:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print(dba["Name"])
print(dba["SSN"])

Result: 


Anastasia
123456
>>> 

Small reports/explanations are easy:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print("Name: ", dba["Name"])
print("SSN: ", dba["SSN"])

Result: 


Name:  Anastasia
SSN:  123456
>>> 

Simple one-line extraction:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print(dba["Name"], " -> ", dba["SSN"])

Result: 


Anastasia  ->  123456
>>> 

Dictionaries are not "fixed in time", to change values - target keys first:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba["Name"] = "Michael"
dba["SSN"] = 555444

print(dba)

Result: 


{'Name': 'Michael', 'SSN': 555444}
>>> 

If you like parentheses more than brackets, use get() function:


dba = {"Name" : "Anastasia", "SSN" : 123456}

print(dba.get("Name"))

Result: 


Anastasia
>>> 

We will talk about Dictionary Operations more in next tutorial.

 

Python Dictionary Operations

We can easily add new key-value pairs:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba["Address"] = "No Name 123"
dba["Tel"] = 555888

print(dba)

Result: 


{'Name': 'Anastasia', 'SSN': 123456, 'Address': 'No Name 123', 'Tel': 555888}
>>> 

Use pop() function to remove specific key-value pair:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.pop("SSN")

print(dba)

Result:  


{'Name': 'Anastasia'}
>>> 

To remove k-v pair from dictionary end, use popitem() function. Here, we will use it two times:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.popitem()
dba.popitem()

print(dba)

Result:  


{}
>>> 

To remove all pairs, use clear() function:


dba = {"Name" : "Anastasia", "SSN" : 123456}

dba.clear()

print(dba)

Result:  


{}
>>> 

Well known del() function to destroy everything:


dba = {"Name" : "Anastasia", "SSN" : 123456}

del dba

We can take keys and values from keyboard:


dba = {"Name" : "Anastasia", "SSN" : 123456}

k = input("New Key: ")
v = input("New Value: ")

dba[k] = v

print(dba)

Result:  


New Key: Telephone
New Value: 555888
{'Name': 'Anastasia', 'SSN': 123456, 'Telephone': '555888'}
>>> 

Now we know a lot about Python.

It's time to talk about if-else statements - they are just simple checks that we will use all the time in programming.

 

Python If, elif, else

With if statements we will do all kind of checks. For example, if x is smaller than y, we will just print: "x is smaller than y", and so on:


x = 20
y = 20

if x < y:
    print("x is smaller than y")
if x > y:
    print("x is bigger than y")
if x == y:
    print("They are Equal")

Result: 


They are Equal
>>> 

We can add "else" at the end of check, as the last possible case. In the middle of check you can use "elif", which is short for "else if":


x = 20
y = 20

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


They are Equal
>>> 

It's fun to take input from keyboard:


x = input("Please enter x: ")
y = input("Please enter y: ")

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


Please enter x: 555
Please enter y: 10
x is bigger than y
>>> 

When you know that you will need numbers, and not strings, convert what you take from keyboard into integers/floats with int() or float() function.


x = input("Please enter x: ")
y = input("Please enter y: ")

print("Before x and y are strings: ")
print(type(x))
print(type(y))

print("After we convert them, they are integers: ")
x = int(x)
y = int(y)

print(type(x))
print(type(y))

Result: 


Please enter x: 10
Please enter y: 50
Before x and y are strings: 
<class 'str'>
<class 'str'>
After we convert them, they are integers: 
<class 'int'>
<class 'int'>
>>> 

Now, we are absolutely sure that things from keyboard will be used as numbers, and not as strings (words):


x = int(input("Please enter x: "))
y = int(input("Please enter y: "))

if x < y:
    print("x is smaller than y")
elif x > y:
    print("x is bigger than y")
else:
    print("They are Equal")

Result: 


Please enter x: 50
Please enter y: 100
x is smaller than y
>>> 

In next tutorial, we will learn about While Loops.

 

Python While Loops

While loops are extremely useful when we need specific lines of code to run constantly.

Basically, we need to define a starting point, ending point, and how to jump from one point to another.

Of course, in between those points, some useful part of code need to be executed:


x = 0

while x < 10:
    print("Value of x atm: ", x)
    x = x + 1

Result: 


Value of x atm:  0
Value of x atm:  1
Value of x atm:  2
Value of x atm:  3
Value of x atm:  4
Value of x atm:  5
Value of x atm:  6
Value of x atm:  7
Value of x atm:  8
Value of x atm:  9
>>> 

We will import os module, so we can run application inside our operating system - using Python script.

"x = x + 1" is used to gradually jump from 0 until 3 is reached - it's like a very simple algorithm.

If you run this code, calculator will pop-up 3 times on Desktop. Sure, we can run other apps, not just calc:


import os

x = 0

while x <= 3:
    os.system("calc")
    x = x + 1

In next tutorial, we will learn about Break and Continue options when looping with While Loops.

 

Python Break, Continue

If you need to stop While Loop at specific point, use break when you reach that point.

In this case we are stopping when x reaches number 5. After that point everything stops:


x = 0

while x < 10:
    print(x)
    if x == 5:
        break
    x = x + 1

Result: 


0
1
2
3
4
5
>>> 

What if we need to skip specific things. In that case use continue. Please note - While Loop will run just fine, just specific numbers will be skipped.

In this example, we are skipping over numbers: 3, 5 and 7.


x = 0

while x < 10:
    x = x + 1
    if x == 3:
        continue
    if x == 5:
        continue
    if x == 7:
        continue

    print(x)

Result:  


1
2
4
6
8
9
10
>>> 

For Loops are also fun to work with. We will learn about them in next tutorial.

 

Python For Loops

For loops are awesome when we need to repeat same operation - they are great for custom reports, for example:


colors = ("red", "blue", "yellow", "green")

for x in colors:
    print(x)

Result: 


red
blue
yellow
green
>>> 

Even better, explain what you are doing:


colors = ("red", "blue", "yellow", "green")

for x in colors:
    print("Elements is: ", x)

Result:  


Elements is:  red
Elements is:  blue
Elements is:  yellow
Elements is:  green
>>> 

For example, we can check if sites are available, with a little bit of pause between checks.

To pause operations, we will import "time" modul to aktivate sleep() function for 2 seconds.

With system() function from "os" module we can run terminal apps just as we use them in terminal or command prompt on machines with Windows.


import os, time

ip = ["127.0.0.1", "google.com"]

for x in ip:
    os.system("ping " + x)
    time.sleep(2)

Now when we know about For Loops, understanding Dictionary Iterations will be easy.

 

Python Dictionary Iteration

To grab only keys from dictionary use key() function:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

for x in colors.keys():
    print("Key: ", x)

Result: 


Key:  Color 1
Key:  Color 2
>>> 

Same approach for values, using value() function:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

for x in colors.values():
    print("Value: ", x)

Result:  


Value:  Red
Value:  Yellow
>>> 

Or use items() function to grab key-value pairs:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

print("Key -> Value")
print("-" * 49)

for x, y in colors.items():
    print(x, " -> ", y)

Result:  


Key -> Value
-------------------------------
Color 1  ->  Red
Color 2  ->  Yellow
>>> 

This is how to extract keys and values into dedicated lists:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

key_parts = []
value_parts = []

for x in colors.keys():
    key_parts.append(x)

for y in colors.values():
    value_parts.append(y)

print(key_parts)
print("-" * 59)
print(value_parts)

Result:  


['Color 1', 'Color 2']
-------------------------------
['Red', 'Yellow']
>>> 

Same as above, using only one for loop:


colors = {"Color 1" : "Red", "Color 2" : "Yellow"}

key_parts = []
value_parts = []

for x, y in colors.items():
    key_parts.append(x)
    value_parts.append(y)

print(key_parts)
print("-" * 59)
print(value_parts)

Result:  


['Color 1', 'Color 2']
-------------------------------
['Red', 'Yellow']
>>> 

Excellent. In next tutorial we will learn about functions.

 

Python Functions

A function is just specific peace of code that will do one thing, and do it well. Think about them as workers that will do only one task.

We can write our own functions, or we can grab them from Internet because they are distributed in dedicated files - modules.

When we install Python, we have at our disposal dedicated modules, with many functions.

Don't forget parentheses and def keyword when creating functions:


def my_function():
    print("Line 1")
    print("Line 2")
    print("Line 3")

my_function()

Result: 


Line 1
Line 2
Line 3
>>> 

Our custom triple() function can call multiple times other functions, in this case we are calling function my_function() three times:


def my_function():
    print("Line 1")
    print("Line 2")
    print("Line 3")

def triple():
    my_function()
    my_function()
    my_function()

triple()

Result:  


Line 1
Line 2
Line 3
Line 1
Line 2
Line 3
Line 1
Line 2
Line 3
>>> 

This is how to create function that will ask for IP so we can Ping it with other function that is in os module:


import os

def ping_something():
    x = input("Enter IP: ")

    os.system("ping " + x)

ping_something()

We can have loops inside functions, too:


def while_in_function():
    x = 0
    while x < 3:
        print(x)
        x = x + 1

while_in_function()

Result:  


0
1
2
>>> 

This is how to have while loop inside function that will have option to stop if you enter "QUIT":


def get_out():
    while True:
        x = input("Enter something: ")
        print(x)

        if x == "QUIT":
            break

get_out() 

Result:  


Enter something: Something
Something
Enter something: Again
Again
Enter something: QUIT
QUIT
>>> 

So far so good. In next tutorial we will learn how to provide some data to functions, so functions can grab it and do something with data we provided.

 

Python Function Arguments

Arguments are data that we pass to functions so that other operations can be done further using what we provided as input.

We will type arguments between parentheses.

This function will just add same number we provided to itself:


def addition(num_1):
    print("Addition:", num_1 + num_1)

addition(5)

Result: 


Addition: 10
>>> 

Sure, you can use multiple arguments, delimited by comma:


def print_them(x, y, z):
    print(x)
    print(y)
    print(z)

print_them(43, 24, "Something")

Result:  


43
24
Something
>>> 

And here, we see very simple calculator:


def calculator(x, y):
    print("Add: ", x + y)
    print("Sub: ", x - y)
    print("Mul: ", x * y)
    print("Div: ", x / y)

calculator(10, 5) 

Result:  


Add:  15
Sub:  5
Mul:  50
Div:  2.0
>>> 

Easy. In next tutorial we will learn how to take arguments from keyboard.

 

Python Keyboard Arguments

This function will ping some IP/domain with 5 packets. With "-n" number of packets will be part of "ping" instruction.

Pay attention about spaces, they are important while constructing command.

If you are on Linux use "-c", "-n" is for Windows machines.


import os

def custom_ping(ip, packets):
    os.system("ping -n " + str(packets) + " " + ip)

custom_ping("127.0.0.1", 5)

But this is more usable, because we can grab domain and packet number from keyboard without messing around directly with function every time:


import os

def custom_ping(ip, packets):
    os.system("ping -n " + str(packets) + " " + ip)

real_ip = input("Please Enter IP: ")
real_packets = input("Number of packets: ")
    
custom_ping(real_ip, real_packets)

 

Python Return Multiple Values

Function can return results to the rest of the script, where other function can take them for further operations.

This simple function will run, but because no further operations will be done, nothing will be printed in shell.


def external(num_1):
    add = num_1 + num_1
    return add

external(10)

But now, results are placed into variable "container" so we can print it on dedicated line, with a little bit of custom report:


def external(num_1):

    add = num_1 + num_1

    return add

container = external(10)

print("Result: ", container)

Result: 


Result:  20
>>> 

Or, you can use function with different arguments on individual lines:


def external(num_1):

    add = num_1 + num_1

    return add

print("Result: ", external(20))
print("Result: ", external(40))
print("Result: ", external(60))

Result: 


Result:  40
Result:  80
Result:  120
>>> 

It's awesome that in Python we can have multiple returns, in this case, "add", and "mul".

Multiple returns are packet into tuple:


def external(num_1):

    add = num_1 + num_1
    mul = num_1 * num_1

    return add, mul

print("Result: ", external(20))
print("Return Type: ", type(external(20)))

Result: 


Result:  (40, 400)
Return Type:  <class 'tuple'>
>>> 

And now we are using individual parts of tuple:


def external(num_1):

    add = num_1 + num_1
    mul = num_1 * num_1

    return add, mul

x, y = external(20)
print("Result of Add: ", x)
print("Result of Mul: ", y)

Result: 


Result of Add:  40
Result of Mul:  400
>>> 

Sometimes we care only about one index from tuple:


def external(num_1):

    add = num_1 + num_1
    mul = num_1 * num_1

    return add, mul

print("Result of Add: ", external(10)[0])
print("Result of Mul: ", external(10)[1])

Result: 


Result of Add:  20
Result of Mul:  100
>>> 

Ok, in next tutorial we will learn about Iterations.

 

Python Iteration, Iter, Next

With iter() function we will target specific list, and individual next() functions will be used to print elements of list:


colors = ["red", "blue", "yellow"]

target = iter(colors)

print(next(target))
print(next(target))
print(next(target))

Result: 


red
blue
yellow
>>> 

But for loops are more practical, especially if lists are big:


colors = ["red", "blue", "yellow"]

target = iter(colors)

for x in range(3):
    print(next(target))

Result: 


red
blue
yellow
>>> 

Can we use iteration on dictionaries ? Sure:


diction = {"name" : "Anastasia", "SSN" : 246546}

target = iter(diction)

print(next(target))
print(next(target))

Result: 


name
SSN
>>> 

This is how to extract only keys, so we can put them in dedicated list:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

target = iter(diction)

for x in range(2):
    k_keys.append(next(target))

print(k_keys)

Result: 


['name', 'SSN']
>>> 

Better option is to not think about number of elements, just use len() function:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

target = iter(diction)
print("Len of diction: ", len(diction))

for x in range(len(diction)):
    k_keys.append(next(target))

print(k_keys)

Result: 


Len of diction:  2
['name', 'SSN']
>>> 

Of course, we can do that without iter() and next() functions:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

for x in diction.keys():
    print(x)

Result: 


name
SSN
>>> 

Next tutorial will be dedicated to modules.

 

Python Modules

Modules are external files that hold additional source (functions) that we can use - if we need them.

Create file "external.py" - that will be our module with one function my_func(), for now:


def my_func():
    print("I am from external world...")

This is our main file where we are practicing: "playground.py". First we need to "import" external module (without extension ".py").

Then, just call our function from module, with dot in the middle:


import external

external.my_func()

Result: 


I am from external world...
>>> 

Functions in main file are also fine:


import external

external.my_func()

def localone():
    print("Local Stuff...")

localone()

Result: 


I am from external world...
Local Stuff...
>>> 

Create new module "anotherone.py" with this source:


print("AUTOMATIC print on module import")

Import "anotherone.py" into our main script:


import external, anotherone

external.my_func()

def localone():
    print("Local Stuff...")

localone()

Stuff from "anotherone.py" will be immediately executed when we run our mains script.

This can be security problem if you just like to grab things from Internet, without checking:


AUTOMATIC print on module import
I am from external world...
Local Stuff...
>>> 

We can use short names for modules:


import external as ex

ex.my_func()

Or we can grab everything from module in such a way that there's no need to type module name every time when we need specific function from that module:


from external import *

my_func()

Result: 


I am from external world...
>>> 

Next tutorial will be dedicated to practical example how to use modules from Standard Library.

 

Python Standard Library Examples

We will use "ftplib" module to establish connection to public remote FTP server.

Task will be to grab debian directory listing.

After we connect to host, login() function will be used to log in as "anon" user.

Then, we will relocate to "debian" directory with cwd() function.

Function retrlines() with argument "LIST" will be used to grab listing.

It's polite to close connection with close() function.


from ftplib import *

host = FTP("ftp.fi.debian.org")
host.login()
host.cwd("debian")
host.retrlines("LIST")

Result: 


-rw-r--r--    1 ftp      ftp          1185 Jul 18 11:48 README
-rw-r--r--    1 ftp      ftp          1290 Jun 26  2010 README.CD-manufacture
-rw-r--r--    1 ftp      ftp          2895 Jul 18 11:48 README.html
-rw-r--r--    1 ftp      ftp           291 Mar 04  2017 README.mirrors.html
-rw-r--r--    1 ftp      ftp            86 Mar 04  2017 README.mirrors.txt
drwxr-xr-x   19 ftp      ftp            41 Jul 18 11:50 dists
drwxr-xr-x    4 ftp      ftp            16 Jul 19 15:52 doc
-rw-r--r--    1 ftp      ftp        210880 Jul 19 16:22 extrafiles
drwxr-xr-x    3 ftp      ftp            58 Jul 19 16:17 indices
-rw-r--r--    1 ftp      ftp      12803150 Jul 19 16:17 ls-lR.gz
drwxr-xr-x    5 ftp      ftp             5 Dec 19  2000 pool
drwxr-xr-x    4 ftp      ftp             5 Nov 18  2008 project
drwxr-xr-x    3 ftp      ftp             5 Oct 10  2012 tools
drwxr-xr-x   20 ftp      ftp            20 Jul 07  2019 zzz-dists
>>> 

It's so easy to do this in Python.

Now it's time to learn how to read from file.

 

Python Files, Reading

Our "source.txt" is simple, just three lines.

Use "f" as handle for operation. We will just read() all lines, so "r" is second argument:


f = open("source.txt", "r")

result = f.read()

print(result)

Result: 


first line
second line
third line

>>> 

If you need to read just specific number of bytes, you can pass that as argument:


f = open("source.txt", "r")

print(f.read(5))
print(f.read(5))
print(f.read(5))

Result:  


first
 line

seco
>>> 

For loops are also great here:


f = open("source.txt", "r")

for x in range(3):
    print(f.read(6))

Result:  


first 
line
s
econd 
>>> 

With function readline() we can read line by line:


f = open("source.txt", "r")

print(f.readline())
print(f.readline())
print(f.readline())

Result:  


first line

second line

third line

>>> 

If you need to extract all lines to list, use readlines() function:


f = open("source.txt", "r")

all_lines = f.readlines()

print(all_lines)
print(type(all_lines))

Result:  


['first line\n', 'second line\n', 'third line\n']
<class 'list'>
>>> 

Then we can target individual lines as elements:


f = open("source.txt", "r")

all_lines = f.readlines()

print(all_lines[0])
print(all_lines[1])
print(all_lines[2])

Result:  


first line

second line

third line

>>> 

Easy.

It't time to learn how to write and append to files.

 

Python Files, Write, Append

To create a new file, or to overwrite existing one, use "w" as second argument:


f = open("external.txt", "w")

f.write("Line One")
f.write("Second One")
f.write("Third One")

f.close()

Result: 


Line OneSecond OneThird One

To evade concatenation, add "\n" at the end of every new line:


f = open("external.txt", "w")

f.write("Line One \n")
f.write("Second One \n")
f.write("Third One \n")

f.close()

Result: 


Line One 
Second One 
Third One 

If you need to add new content, without destruction of previous lines, use "a" as second argument:


f = open("external_2.txt", "a")

f.write("One More Time \n")
f.write("One More Time \n")
f.write("One More Time \n")

f.close()

Content of external_2.txt after we run code from above two times:


One More Time 
One More Time 
One More Time 
One More Time 
One More Time 
One More Time 

Sometimes we will need to delete files and folders. About that, in next tutorial.

 

Python Delete Files, Folders

To delete files we will use os module, and remove() function:


import os

print("WARNING, files will be deleted")
print("-" * 50)

os.remove("external.txt")
os.remove("external_2.txt")

If we try to delete directory with content using rmdir(), operation will fail:


import os

print("Trying to delete Full Folder Will Fail")
print("-" * 50)

os.rmdir("FULL_FOLDER")

Result: 


Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 6, in <module>
    os.rmdir("FULL_FOLDER")
OSError: [WinError 145] The directory is not empty: 'FULL_FOLDER'
>>> 

That function can be used only on empty folders:


import os

print("With rmdir You Can delete only Empty Folder")
print("-" * 50)

os.rmdir("EMPTY_FOLDER")

Result: 


With rmdir You Can delete only Empty Folder
--------------------------------------------------
>>> 

What if you must delete folder and everything in it ? In that case, use "shutil" module and rmtree() function:


import shutil

print("With shutil.rmtree() You Can delete Full Folder")
print("-" * 50)

shutil.rmtree("FULL_FOLDER")

Result:


With shutil.rmtree() You Can delete Full Folder
--------------------------------------------------
>>> 

Well done.

It's time to learn about Try, Except and Finally blocks.

 

Python Try, Except, Finally

Simple if-else blocks will work just fine:


import os

print("Script to check removal of files")
print("-" * 50)

if os.path.exists("deleteme.txt"):
    print("File Detected")
    os.remove("deleteme.txt")
    print("File Removed")
else:
    print("No File There - Nothing To Delete")

Result: 


Script to check removal of files
--------------------------------------------------
File Detected
File Removed
>>> 

If you run script one more time - when there's no file there:


Script to check removal of files
--------------------------------------------------
No File There - Nothing To Delete
>>> 

But more elegant approach is to Try to do something, and if that fails, than we will activate code in Except section.

The best thing here is that code in Finally section will always run.

So, no metter what happens with code in Try/Except, we can always be sure that whatever we put in Finally will get some job done.

It's like backup operation that will always work.


import os

print("Script to check removal of files")
print("-" * 50)

try:
    os.remove("deleteme.txt")
    print("File Removed")
except:
    print("No file - Nothing to Delete")
finally:
    print("This will work - always")

Result: 


Script to check removal of files
--------------------------------------------------
File Removed
This will work - always
>>> 

After second run:


Script to check removal of files
--------------------------------------------------
No file - Nothing to Delete
This will work - always
>>> 

Congratulations - You just finished "Introduction to Python".

Thank You.