Python

Tag: beginner

REPL

What is REPL?

REPL is the language shell.

Its short for Read, Eval, Print and Loop.
To start the language shell, type ‘python’ and press enter.


$ python
Python 3.6.1 (default, Mar 27 2017, 01:39:26)
[GCC 6.3.1 20170306] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>> 700713 + 700713 # read, eval
1401426 # print
>>> # loop

Then it starts this process:

  1. Read: take user input.
  2. Eval: evaluate the input.
  3. Print: shows the output to the user.
  4. Loop: repeat.

Related Courses: Complete Python Bootcamp: Go from zero to hero in Python

REPL

We can type all kinds of input in the interactive shell:

>>> 128 / 8
16.0
>>> 8 (8 8)
512
>>> 256 * 4
1024
>>>
Note: We’ll teach you how to start python programs in the next article.

If you get an error when typing Python, install Python or set your environment variables. The method for setting this varies per operating system.

How to run

Learn how to run Python code?

You can execute Python code from the terminal or from a Python IDE. An IDE is a graphical environment that assitsts in software development.

If you are new to Python, I recommend this course:
Complete Python Bootcamp: Go from zero to hero in Python

How to run Python

All Python programs are written in code, text files with lots of instructions. These are saved with the extension .py.

Note: Often a Python program is not just one file, but many files.
python program

To run a Python program, you need to have Python installed.

Python installed?

Open a terminal and type:



where file.py is the name of your program. If you have more than one file, the main program is often the name of the program itself;

Use an IDE

Sometimes an easier way to execute Python programs is using a Python IDE. In a Python IDE, you simply press the ‘play’ button.

pycharm toolbar

The image above shows the header of the program PyCharm, a Python IDE. The green play button can be used to start a program.

Python IDE

Python IDE compared. What’s an IDE and where to find them?

An IDE is a program for software development. Its like the user interface for development: where you write code.

What’s the best IDE? It depends on your preferences. You can choose an IDE based on feaures.

Related courses:
Complete Python Bootcamp: Go from zero to hero in Python

Python IDEs

An IDE is a software program. Its stands for Integrated Development Environment.
The sole purpose of an IDE is software development. They often include:

  • a code editor
  • code completion features
  • running the program
  • file management

Some IDEs are designed for one programming language, but others allow many languages to be used.

PyCharm

Category: IDE
Website: https://www.jetbrains.com/pycharm/

PyCharm is one of the best Python IDEs. Its a graphical app that has powerful features like code navigation, code completion, syntax highlighting, code analysis, debugger and much more.

pycharm

Spyder

Category: IDE
Website: https://github.com/spyder-ide/spyder

Spyder is a Python IDE from the open source community. Its often used by data scientists. Spyder works well with modules often used in data science like numpy, scipy and matplotlib.

It supports a lot of the common feautures like syntax highlighting, code completion and file browsing.

Wing IDE

Category: IDE
Website: https://wingware.com/

Wing IDE is a full featured IDE. It’s an IDE thats been around for almost two decades. It has many advanced features.

Sublime Text

Category: Editor
Website: http://www.sublimetext.com/

Sublime Text is a popular IDE for developers. It has a very mininalistic look, but it’s a powerful editor.

It has a package manager, addons, plugins, styles, tab windows, syntax highlighting and lots more features.

In comparison to IDE its much more lightweight, but feature wise its much more than a simple text pad.

Eric IDE

Category: IDE
Website: https://eric-ide.python-projects.org/

Fully features IDE made in Python. Its based on Qt and cross platform (windows, mac, linux).

Eric has professional features like source code folding, syntax highlighting, windowing, error highlighting and many more features.

Vim

Category: Editor
Website: http://www.vim.org/

Vim is an advanced text editor. Its one of the oldest code editors around and it’s quite challenging to learn it.

Many expert programmers use this editor as it’s powerful and works on any system, even remotely.

Emacs

Category: Editor
Website: https://www.gnu.org/software/emacs/

Emacs is not only a code editor, it can do many more things like file browsing, web browsing and others. Like Vim it takes time to learn and master this editor. It has syntax highlighting, code completion, keyboard macros and many advanced features.

Compare IDE

To get a full overview of Python IDEs compared, see the image below (click to enlarge):

Python IDE comparison

Python IDE

Python IDE : a software development tool. Compare Python IDEs.

An integrated software developent (IDE) makes software development much better!

Code with tabs, syntax highlighting, code completion and many awesome features!

Related courses:
Complete Python Bootcamp: Go from zero to hero in Python

Python IDEs

An IDE is a program for software development.

pycharm

List of popular Python IDEs. These are some of the most popular.
If you are a total beginer, I recommend PyCharm or Spyder.

Some popular IDEs:

For power users:

In the next article we’ll compare features and IDEs.

Text output

Text output is one of the basics in Python programming. Not all Programs have graphical user interfaces, text screens often suffice.

You can output to the terminal with print function. This function displays text on your screen, it won’t print.

Related Courses: Complete Python Bootcamp: Go from zero to hero in Python

The terminal is a very simple interface for Python programs. While not as shiny as a GUI or web app, it’s good enough to cover the basics in.

Create a new program (text file) in your IDE or code editor.
Name the file hello.py. It only needs one line of code.

To output text to the screen you will need this line::

print("Hello World")

Run the program (from terminal: python hello.py)
If you run the program:

Hello World

The program above prints everything on a single line. At some point you’ll want to write multiple lines.

To write multiple lines, add the ‘\n’ character:

print("Hello World\nThis is a message")

Results in:

Hello World
This is a message
Note: the characters \n create a new line

To print variables:

x = 3
print(x)

This will show:

3

To print multiple variables on one line:

x = 2
y = 3
print("x = {}, y = {}".format(x,y))

Will give you:

x = 2, y = 3

Text Input

Want to get keyboard input?

To get keyboard input, use the input function. Inside the terminal you’ll be able to type text.

In Python 3 you can use the input() function, older versions of Python have the raw_input() function.

Related Courses: Complete Python Bootcamp: Go from zero to hero in Python

User Input

The input function has a return variable. In this case the keyboard input. If we do not store the return variable into a programs variable, we lose it. That’s why we write a variable to store the result in.

To get a text value:

name = input("Enter a name: ")
print(name)

This will show you:

Enter a name:

You can now give keyboard input, it will be stored in the variable name.

Note: don’t forget to store the return variable. variable = input(“..”)

Numeric input

To get a whole number:

x = int(input("What is x? "))

To get a decimal number:
x = float(input("Write a number"))

Strings

Strings in Python can be defined using quote symbols. An example of a string definition and output below:

s = "Hello World"
print(s)

This will output to the terminal:

Hello World

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Accesing array elements

You may access character elements of a string using the brackets symbol, which are [ and ]. We do so by specifying the string name and the index.

Note: Computers start counting from zero, thus s[0] is the first character.

 
The example below prints the first element of a string.

print(s[0])

To print the second character you would write:

print(s[1])

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

String Slicing

You can slice the string into smaller strings. To do so you need to specify either a starting, ending index or both. Let us illustrate that in the Python shell:

>>> s = “Hello World”
>>> s[:3]
‘Hel’
>>> s[3:]
‘lo World’
>>> s[1:3]
‘el’
>>>

If no number is given, such as in s[:3] it will simply take the beginning or end of teh string. We have accessed the string as if it was an array.

If you want to output them from your program, you have to wrap them in the print command. You can store the sliced string as a new string:
slice = s[0:5]

There you have it! String slicing is pretty easy.
 

Split string

Want to split a string?

To split a string, we use the method .split().

This method will return one or more new strings. All substrings are returned in the list datatype.

Note: Split with the method str.split(sep, maxsplit). The 2nd parameter is optional. If maxsplit is set, it returns no more than maxsplit elements.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

String split

We can split a string based on a character.

s = "To convert the result to"
parts = s.split(" ")
print(parts)


Result:

[‘To’, ‘convert’, ‘the’, ‘result’, ‘to’]

Any character can be used. If you want to get sentences you could use:
 
s = "Python string example. We split it using the dot character."
parts = s.split(".")
print(parts)


This will result in:
[‘Python string example’, ‘ We split it using the dot character’, ‘’]

If statements

If statements are all about choices.

A block of code is executed based on one or more conditions. The block of code will only be executed if the condition is true.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

If statements

Computer programs do not only execute instructions. Occasionally, a choice needs to be made. Such as a choice is based on a condition.

Python has several conditional operators:

> greater than
< smaller than
== equals
!= is not

Conditions are always combined with variables. A program can make a choice using the if keyword. For example:
x = int(input("Tell X"))

if x == 4:
print('You guessed correctly!')

print('End of program.')

The condition is shown on line 3.

When you execute this program it will always print ‘End of program’, but the text ‘You guessed correctly!’ will only be printed if the variable x equals to four (see table above).

Note: Code is executed based on the variable x. Try different numbers: 2,3,4

If else

Python can also execute a block of code if x does not equal to 4. The else keyword is used for that.

x = int(input("Tell X"))

if x == 4:
print('You guessed correctly!')
else:
print('Wrong guess')

print('End of program.')

If x is set to 2, the second code block is executed. If x equals (==) four, the first code block is executed.

Take a look at the execution below:

if statement

if elif and else

We can chain if statements.

How?

Using the keywords elif and else. That way, we can walk through all options for the condition. Imagine a weather app: if snow, elif rain, elif thunder, else sunny. We can execute different code for each condition.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

If elif and else

We can execute blocks of code using if-statements. We can also do that if we have multiple conditions.
Lets start with an if statement, like so:

 
x = 3

if x < 5:
print('x smaller than 5')
else:
print('x is too big')


It will make the decision based on the value of x, also known as the condition.

x smaller than 5

What if you want to have multiple cases?
In that case you can use elif

 
x = 8

if x < 5:
print('x smaller than 5')
elif x >= 5 and x <= 10:
print('great choice')
else:
print('x is too big')

Variables

Variables in Python can hold text and numbers. For example:

x = 2
price = 2.5
word = 'Hello'

The variable names are on the left and the values on the right. Once a variable is assigned, it can be used in other places of the program.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

In the example above, we have three variables: _x_, price and word.

Note: Variables may not contain spaces or special characters.

Text in variables

Text variables may be defined in 3 ways:

word = 'Hello'
word = "Hello"
word = '''Hello'''

The type depends on what you prefer.

Operators

Once defined variables can be replaced or modified:

  x = 2

# increase x by one
x = x + 1

# replace x
x = 5

Python supports the operators +, -, / and * as well as brackets. Variables may be shown on the screen using the print statement.

  
x = 5
print(x)

y = 3 * x
print(y)

# more detailed output
print("x = " + str(x))
print("y = " + str(y))


The first output of the program above is simply the raw value of the variables. If you want to print a more detailed message like “x = 5”, use the line ‘print(“x = “ + str(x))’. This str() function converts the numeric variable to text.
 

Booleans

What is a boolean?

A boolean is a variable that is either True or False. We say the datatype of a variable can be booelan.

You can think of it like a light switch, its either on or off.

Note: A bit is the smallest unit in a computer. Its either 0 or 1, True or False. Also called a boolean

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Boolean

To define a boolean in Python we simply type:

light = FALSE

If you want to set it to on, you would type:

light = TRUE

You can also type:

light = 0

which is equivalent to FALSE. Likewise you can write
light = 1

which is the same as TRUE.

Global variables

What is the difference between global and local variables?

A global variable can be accessed anywhere in code. A local variable can only be used in a specific code block.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

global variable example

We say the scope is global, it can be used in any function or location throughout the code.
In the example below we define a global variable, y amount lines of code later we can still use that variable.

 
x = 3
...
200 lines of code
...
print(x)

Note: In Python a global variable is always limited to the module. Thus, there is no global variable as there is in other programming languages. It’s always within a module.

local variables

This is contrary to a local variable, which can only be accessed in the local scope.
In the example below, x is a local variable..

 
def f(x):
.. x can only be used here

If a variable is declared inside a function or loop, it’s a local variable. Global variables are usually defined at the top of the code.

best practice

Global variables are considered a bad practice because functions can have non-obvious behavior. Usually you want to keep functions small, staying within the size of the screen. If variables are declared everywhere throughout the code, it becomes less obvious to what the function does.

Tuples

A tuple is a collection that cannot be modified.

Variables can be of the datatype tuple. A tuple is defined using parenthesis.

If you want to change the data during program execution, use a list instead of a tuple.

Related Courses Complete Python Bootcamp: Go from zero to hero in Python

Example

A tuple with one item ( a comma is needed in the end ):

x = (1,) 

A tuple with multiple items:

x = (1,2,3,4) 
Note: Even with one element, the comma is needed.

Accessing tuples

To access individual elements, we use square brackets. To print the first element (Python starts counting from zero):

print(x[0]) 

To print the second element:

print(x[1]) 

To print the last element, you can count from the back using the minus sign.

print(x[-1]) 

Dictionary

A dictionary in Python is a one to one mapping.

Every key points to a value, separated by a colon (:).

A dictionary is defined using curly brackets. The value left of the colon is called the key, the value right of the colon is called the value. Every (key,value) pair is separated by a comma.

Related Courses Complete Python Bootcamp: Go from zero to hero in Python

Example

The example below creates a dictionary. Keys must be unique values, you can not use the same key twice. Values may or may not be unique.

k = { 'EN':'English', 'FR':'French' }
print(k['EN'])

We defined a dictionary named k and access elements using the square brackets you’ve seen before. We use the key [‘EN’] to print the value ‘English’.

English
Note: A dictionary has no specific order.

Add and remove

To add a new value to a dictionary you can simply assign a key value pair:

k['DE'] = 'German'

To remove a key/value pair use the del keyword:
k = { 'EN':'English', 'FR':'French' }

del k['FR']
print(k)

Lists

A list is a collection of objects

Everything in Python is an object. These objects in a list are numbers in most cases. Lists can also contain text (strings) or both.

Note: Lists can have zero or more elements (empty lists are possible).

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Lists Example

A list is defined using square brackets. Let us define as simple list:

c = [5,2,10,48,32,16,49,10,11,32,64,55,34,45,41,23,26,27,72,18]

In this case we have a list defined by the variable c. We defined a purely random set of numbers above.

Accessing elements

To access individual elements, we use the same brackets. To print the first element (Python starts counting from zero):

print(c[0])

This shows

5

To print the second element:

print(c[1])

Results in:

2

To print the last element, you can count from the back using the minus sign.

print(c[-1])

Result

18

Size of the list

You can get the length of the list using the len function. Example code:

c = [5,2,10,48,32,16,49,10,11,32,64,55,34,45,41,23,26,27,72,18]
print(len(c))

Datatypes

List may contain various types of variables in the same list including text, whole numbers, floating point numbers and so on. For example, we may define a list with text variables:

fears = ["Spiders","Ghosts","Dracula"]

List comprehensions

What is list comprehension?

List comprehensions are an easy way to create lists.

Its much easier to write a one liner than it is to write a for loop, just for creating a list. This _ one liner_ is called a list comprehension.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Example

Assume we want to create a list containing 100 numbers. Manually that would be a lot of typing work. So we would use a for loop, right?

We can define a for loop to fill the list.

numbers = []

for i in range(0,100):
numbers.append(i)

print(numbers)

We can replace it with a one liners, which is how we obtain the same result:

numbers = [ x for x in range(100) ]

This is also useful if you want to create large lists.

Note: List comprehensions can include function calls and expressions.

Assume we want the square roots to 100:

import math

numbers = [ math.sqrt(x) for x in range(100) ]
print(numbers)

While loop

Unsure how many times to repeat code?

Python has the while keyword. Unlike the for loop which tests the condition first, the while loop execute the code first. Sometimes we don’t know how long sometimes will take.

A theoretical program could be (pseudocode):

while sun_not_shining:
use jacket
use gloves

which keeps executing the code block until the condition is true.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

while loop example

Lets build an extended ‘guess the number game’:

 x = 0
while x != 5:
x = int(input("Guess a number:"))

if x != 5:
print("Incorrect choice")

print("Correct")

This will keep asking a number until the number is guessed. This is defined in the line: while x != 5, or in English, “while x is not equal to five, execute”.

Illustrated:
while loop

The program keeps repeating the code block while the condition (x!=5) is True. Once x equals 5, the program continues.

Infinite loops

If a condition in a while loop is never met, it could cause the program to run forever or to freeze/crash.
 

For loops

Do you want to repeat code blocks?

To repeat code, the for keyword can be used.

Sometimes you need to execute a block of code more than once, for loops solve that problem. We specify the start and end of the loop using the function range(min,max).

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Example

To execute a line of code 10 times we can do:

for i in range(1,11):
print(i)

The last number (11) is not included. This will output the numbers 1 to 10. Python itself starts counting from 0, so this code will also work:
for i in range(0,10):
print(i)

but will output 0 to 9.

Illustrated in this graphic:

for loop

The code is repeated while the condition is True. In this case the condition is: i < 10. Every iteration (round), the variable i is updated.

Nested loops

Loops can be combined:

for i in range(0,10):
for j in range(0,10):
print(i,' ',j)

In this case we have a multidimensional loops. It will iterate over the entire coordinate range (0,0) to (9,9)

 

Functions

If you want to reuse code, you can use a function.

This prevents you from writing the same thing over and over again.

A function has a unique distinct name in the program. Once you call a function it will execute one or more lines of codes, which we will call a code block.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Function example

For example, we could have the Pythagoras function.

In case your math is a little rusty, a^2 + b^2 = c^2. Thus, c = sqrt( a^2 + b^2). In code we could write that as:

import math

def pythagoras(a,b):
value = math.sqrt(a *a + b*b)
print(value)

pythagoras(3,3)

We call the function with parameters a=3 and b =3 on the last line. A function can be called several times with varying parameters. There is no limit to the number of function calls.

Note: The def keyword tells Python we define a function. Always use four spaces to indent the code block, using another number of spaces will throw a syntax error.

Return value

It is also possible to store the output of a function in a variable. To do so, we use the keyword return.

import math

def pythagoras(a,b):
value = math.sqrt(a*a + b*b)
return value

result = pythagoras(3,3)
print(result)

The function pythagoras is called with a=3 and b=3. The program execution continues in the function pythagoras.

The output of math.sqrt(aa + bb) is stored in the function variable value. This is returned and the output is stored in the variable result. Finally, we print variable result to the screen.
 

Try except

Sometimes code throws an exception.

You can catch that exception using the try-except block.

The try-except statement starts with a block of code, and a response is specified in case an exception is thrown.

Note: In other programming languages this is often called try-catch.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Try-except example

Lets say we want to get numeric input from the keyboard and calculate the number squared.
The straight forward method would be:

# get keyboard input (string)
rawInput = input('Enter number:')

# convert string to integer
x = int(rawInput)

# calculate number squared
print(x*x)

This works as long as we give numeric input. If we would type “two”, the program crashes - an exception is thrown. That’s where try-catch comes in:

rawInput = input('Enter number:')

try:
x = int(rawInput)
print(x*x)
except:
print('Invalid input specified')

We can also be specific about the type of exception we want to catch:

except ValueError:
print('Invalid input specified')

Expanded For Loop

What is an expanded for loop?

We’ve seen simple numerical for loops before. For numerical lists these type of for loops well. What if we use a dictionary? a dictionary can also be used in a loop too!

Related Courses Complete Python Bootcamp: Go from zero to hero in Python

Expanded For Loop

Given a dictionary with a one to one mapping we simply iterate over each item and print the key and value. We use the dictionaries method .items() which contains all items.

states = {
'NY': 'New York',
'ME': 'Maine',
'VT': 'Vermont',
'TX': 'Taxas',
'LA': 'Los Angeles'
}

for key, value in states.items():
print('Acronym: %s. State = %s ' % (key,value))

This will output:

Acronym: NY. State = New York
Acronym: ME. State = Maine
Acronym: VT. State = Vermont
Acronym: TX. State = Taxas
Acronym: LA. State = Los Angeles

What is going on? we used an expanded for loop. We use both key and value through the dictionary states.

Read File

Reading files is straightforward: Python has built in support for reading and writing files. The function readlines() can be used to read the entire files contents.

Related Courses Complete Python Bootcamp: Go from zero to hero in Python

Read file into list

We call the function method open to read the file, then we call the method readlines() to read all of the file contents into a variable. Finally we print out all file data.

Example read file:

 #!/usr/bin/env python

filename = "readme.txt"

with open(filename) as fn:
content = fn.readlines()

print(content)

Content will contain a list of all strings in the file.
If you print the variable content:

print(content)

you would see a list. Every item of the list contains one line. However, every line of the list contains the newline character (\n).
To remove the newline characters from the list use:

content = [x.strip() for x in content]

Read file into string

If you want to read a file into a string variable, you can use a different method.
The code below reads the entire file data into a single string.

#!/usr/bin/env python

filename = "x.py"
contents = open(filename,'r').read()
print(contents)

Command line arguments

What are command line arguments in python?

In the command line, we can start a program with additional arguments.
These arguments are passed into the program.

Python programs can start with command line arguments. For example:

$ python program.py image.bmp

where program.py and image.bmp is are arguments. (the program is Python)

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python

How to use command line arguments in python?

We can use modules to get arguments.

Which modules can get command line arguments?

ModuleUsePython version
sysAll arguments in sys.argv (basic)All
argparseBuild a command line interface>= 2.3
docoptCreate command line interfaces>= 2.5
fireAutomatically generating command line interfaces (CLIs)All
optparseDeprecated< 2.7

Sys argv

You can get access to the command line parameters using the sys module. len(sys.argv) contains the number of arguments. To print all of the arguments simply execute str(sys.argv)

  #!/usr/bin/python

import sys

print('Arguments:', len(sys.argv))
print('List:', str(sys.argv))


Example:

$ python3 example.py image.bmp color
Arguments: 3
List: [‘example.py’, ‘image.bmp’, ‘color’]

Storing command line arguments
You can store the arguments given at the start of the program in variables.
For example, an image loader program may start like this:

  #!/usr/bin/python
#!/usr/bin/python

import sys

print('Arguments:', len(sys.argv))
print('List:', str(sys.argv))

if sys.argv < 2:
print('To few arguments, please specify a filename')

filename = sys.argv[1]
print('Filename:', filename)

Another example:

(‘Arguments:’, 2)
(‘List:’, “[‘example.py’, ‘world.png’]”)
(‘Filename:’, ‘world.png’)

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Argparse

If you need more advanced parsing, you can use argparse.
You can define arguments like (-o, -s).

The example below parses parameters:

  
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-o','--open-file', help='Description', required=False)
parser.add_argument('-s','--save-file', help='Description', required=False)

args = parser.parse_args()

print(args.open_file)
print(args.save_file)

Docopt

Docopt can be used to create command line interfaces.

  
from docopt import docopt

if __name__ == '__main__':
arguments = docopt(__doc__, version='Example 1.0')
print(arguments)

Note: docopt is not tested with Python 3.6

Fire

Python Fire automatically generates a command line interface, you only need one line of code. Unlike the other modules, this works instantly.

You don’t need to define any arguments, all methods are linked by default.

To install it type:

pip install fire

Then define or use a class:
  
import fire

class Program(object):
def hello(self):
print("Hello World")

def openfile(self, filename):
print("Opening file '" + filename + "'")

if __name__ == '__main__':
fire.Fire(Program)


You then have the options matching the class methods:
python example.py hello
python example.py openfile filename.txt

 

argparse

The argsparse module can be used to parse command line arguments.

This article is written for argsparse with Python 3. Sure you could write your own parser to get command line arguments from sys.argv, but argparse makes it easier.

By default it will add a help option, even if you don’t specify it. Let’s show the sort of thing you can do with argsparse.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Arguments

The code below is a Python program that takes opitional arguments. We create an ArgumentParser instance and create new arguments by callig nt he method add_argument().

Then when the method parse_args() is called, it uses all that information and interprets sys.argv automatically!

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-o','--open-file', help='Description', required=False)
parser.add_argument('-s','--save-file', help='Description', required=False)

args = parser.parse_args()

print(args.open_file)
print(args.save_file)

If we save the code above as example.py, it can be run like this:

$ python example.py -o open.txt -s save.txt
open.txt
save.txt

We have set the parameter required=False, they are optional.

$ python example.py -o open.txt
open.txt

If we set the last parameter to required=True, it has to be specified or it will throw an error.

Write file

Writing files is easy: Python has built in support for writing files. In this article we’ll show you how to write data to a file.

To write a file, we must first open it. We can open the file with method open(filename, flag). The flag needs to be ‘w’, short for write.

Related Courses Complete Python Bootcamp: Go from zero to hero in Python

Example code

We call the method open, then we write strings using the method write(). This is similar to how you would write files in other programming languages. Then we close the file.

To write files, you can use this code:

#!/usr/bin/env python

f = open("output.txt","w")
f.write("Pythonprogramminglanguage.com, \n")
f.write("Example program.")
f.close()

On the first line we open the file for writing. The parameter “w” tells Python we want to open the file for writing. The write() calls write data into the file. Finally we close the file.

Write list to file

A list can be written directly into a file.
We do that by:

  • Define list
  • Open file
  • Write list elements using for loop
    In code that’s:
#!/usr/bin/env python

europe = [ 'Netherlands','Belgium','France','Germany','Danmark' ]

mfile = open('europe.txt', 'w')
for country in europe:
mfile.write("%s\n" % country)

Date and Time

Introduction
Computers handle time using ticks. To get the date or time in Python we need to use the standard time module.

Note: All computers keep track of time since 12:00am, January 1, 1970, known as epoch time.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

Epoch time

To get the number of ticks, use this program:

import time 

ticks = time.time()
print("Ticks since epoch:", ticks)

The output will be similar to this:

Ticks since epoch: 1450535867.84

Local time

To get the current time on the machine, you can use the function localtime:

import time

timenow = time.localtime(time.time())
print("Current time :", timenow)

The output will not be formatted:

Current time : time.struct_time(tm_year=2015, tm_mon=12, tm_mday=19, tm_hour=15, tm_min=42, tm_sec=0, tm_wday=5, tm_yday=353, tm_isdst=0)

You can access each of the elements of the array:

import time

timenow = time.localtime(time.time())
print("Year:", timenow[0])
print("Month:", timenow[1])
print("Day:", timenow[2])

and use a combination for your own formatting. One alternative is to use the asctime function:

import time

timenow = time.asctime(time.localtime(time.time()))
print(timenow)

This will show output as:
Sat Dec 19 15:44:40 2015

Comments

Comments are little texts that can be added in code. They are created for programmers to read, not computers. A comment is simply one or more lines of text that is not executed by the computer.

There are two ways to comment in Python:
single-line comments and multi-line comments.

Related Courses Complete Python Bootcamp: Go from zero to hero in Python

Single line comment

A single line comment starts with the number sign (#) character:

  # This is a comment
print('Hello')

For each line you want to comment, put the number sign (#) in front.

# print('This is not run')
print('Hello')

Comments should help other software developers, not be obvious like:

typical code comments

Multiline comment

Multiple lines can be created by repeating the number sign several times:

# This is a comment
# second line
x = 4

but this quickly becomes impractical. A common way to use comments for multiple lines is to use the (‘’’) symbol:
  ''' This is a multiline 
Python comment example.'''
x = 5

How to install modules

Python modules allow you to use code of others in your code. This saves you a lot of development time, you don’t have to reinvent the wheel each time.

There are two ways to install Python modules: system wide and using a virtual environment.

You may like: Complete Python Bootcamp: Go from zero to hero in Python

Virtualenv

We can create a virtual environemnt, that is seperate from the operating system. This allows you to use the same Python modules as other developers in your team.

Create a virtual environment with the line:

virtualenv foo

Then open /foo/

cd /foo/

You now have 3 directories: bin, include and lib.
Move up a directory.
To activate the virtual environment type:

source foo/bin/activate

we can then install any module, any version we want - without affecting the operating system. This way we can have the same version of modules as other developers.

Note: Pip will now install for this environment only.

To exit the virtual environment write:

deactivate

System wide

To install a module system wide, use pip and type

sudo pip install module-name

That will install a Python module automatically. Generally you do not install modules system wide.

Modules

What is a module? why?

A module is a Python file with one or more functions and variables. These functions and variables can be called from your program by importing a module.

Modules can be used to organize your code.

You may like Complete Python Bootcamp: Go from zero to hero in Python

In this example we use the math module. This module has many functions such as sine, cosine as well as variables:

import math

print(math.pi)
x = math.sin(1)
print(x)

Find available functions and variables in a Python module

To find the available functions in a module, you can use this code:

import math

content = dir(math)
print(content)

A list will be returned with all functions and variables:

$ python example.py
[‘doc‘, ‘name‘, ‘package‘, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’,
‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’,
‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘hypot’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’,
‘log1p’, ‘modf’, ‘pi’, ‘pow’, ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘trunc’]

Create your own module

First create a Python file with a function. We call this file hello.py and we have one function:

def hello():
print("Hello World")

Now that we have create a module named hello we can use it in our program test.py
 # Import your module
import hello

# Call of function defined in module
hello.hello()

Random Numbers

The random module can be used to make random numbers in Python. The function random() generates a number between 0 and 1.

Online Courses Complete Python Bootcamp: Go from zero to hero in Python

Generate random nubers

Generate a real number between 0 and 1
Simply call the random() method to generate a real (float) number between 0 and 1.

import random
x = random.random()
print(x)

Generate a number between 0 and 50
We use the randint() method to generate a whole number.

import random
x = random.randint(0,50)
print(x)

Generate a random number between 1 and 10
Change the parameters of randint() to generate a number between 1 and 10.

import random
x = random.randint(1,10)
print(x)

List of random numbers

To generate a list of 100 random numbers:

import random

list = []

for i in range(0,100):
x = random.randint(1,10)
list.append(x)

print(list)

Choosing random items from a list

To get 3 random items from a list:

import random

list = [1,2,3,4,5,6,7,8,9,10]
x = random.sample(list,3)
print(x)