0% found this document useful (0 votes)
2 views41 pages

Python Basics

The document is a comprehensive tutorial on Python programming, covering its syntax, data types, control structures, and functions. It includes practical examples for executing Python scripts, using variables, and manipulating strings and lists. The tutorial is designed for beginners and provides exercises to reinforce learning.

Uploaded by

sharmila.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views41 pages

Python Basics

The document is a comprehensive tutorial on Python programming, covering its syntax, data types, control structures, and functions. It includes practical examples for executing Python scripts, using variables, and manipulating strings and lists. The tutorial is designed for beginners and provides exercises to reinforce learning.

Uploaded by

sharmila.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Learn Python Programming - Python Tutorial (pythonbasics.

org)

Python is a programming language with a clean syntax that is easy to


learn. Python programs can be run under all desktop computers.

It used in many application domains including: Web and Internet


Development, Scientific apps, Desktop apps, education and general
software applications.

Python interpreter
To run Python programs, you will need the Python interpreter and possibly
a graphical editor.
A Python interpreter executes Python code (sometimes called programs).

A program can be one or more Python files. Code files can include other
files or modules. To run a program, you need to specify a parameter when
executing Python.

To run the code, open a terminal and launch:

python file.py

This site contains exercises for the Python programming language. If you
are new to programming, start with running Python code.

Execute Python scripts


Execute Python scripts in the terminal or an IDE. Python files have the .py extension.
Whenever you make a Python script, save it as name.py

A simple program (hello.py) is shown below. The first line indicates that we want to use the
Python interpreter. The 3rd line outputs a line of text “hello wlrd” to the screen.
The text below can be copied into a text editor and save as hello.py. Python works with files
that end in .py.

#!/usr/bin/env python3

print('hello world')

You can use any text editor to create a Python program. I recommend using a text editor that
supports syntax highlighting (text colouring) and line numbers.

Variables and Types


Python supports different types of variables (datatypes) such as whole numbers, floating point
numbers and text.

You do not need to specify the datatype of a variable, you can simply assign any value to a
variable. Type the program below and start it.

Related course: Complete Python Programming Course & Exercises

Datatypes
Variables can be of several data types. Python supports integers (numbers), floating point
numbers, booleans (true or false) and strings (text).

Python will determine the datatype based on the value you assign to the variable. If you
create a variable x, x = 3, then Python assumes its an integer. But if you assign x = 1.5 then
Python knows its not an integer but floating point number.

Example
The example below shows you several variables. These can be assigned as you wish. Once
defined you can print them or use arithmetics.

#!/usr/bin/python

x = 3 # a whole number

f = 3.1415926 # a floating point number


name = "Python" # a string

print(x)
print(f)
print(name)

combination = name + " " + name


print(combination)

sum = f + f
print(sum)

Run the program from terminal or with an IDE.

python example.py

In the example we have several variables (x,f,name) which are of different data types. Later
in the program we create more variables (combination, sum).

Variables can be defined anywhere in the program. Variable names can be one to n letters.

You should see several lines containing numbers and text:

Naming

A variable name must begin with a letter (upper or lower case) or an underscore. Variables
cannot start with a number and are case sensitive.
If you create two variables x and X, they are different variables.

Python 3.5.3 (default, Jan 19 2017, 14:11:04)


[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more
information.
>>> x = 3
>>> X = 4
>>> print(x)
3
>>> print(X)
4
>>>

Camel casing

By convention variables are often camel cased, meaning the first letter is small and the next
words are all capital.

Some example variables that use camel casing

daysInYear = 365
daysInMonth = 30
numberFiles = 5

Python Strings (With Examples)


Any time you want to use text in Python, you are using strings. Python understands you want
to use a string if you use the double-quotes symbol.

Once a string is created, you can simply print the string variable directly. You can access
characters using block quotes.

Strings
Define string

Variables can be of the string data type. They can hold characters or text.
If you create string variable x. You can show it on the screen using the print() function.

x = "Hello"
print(x)
String indexing

Individual characters can be accessed using blockquotes, counting starts from zero.

print(x[0])
print(x[1])

The first character starts at zero. This may be a bit counter intuitive, but has historic reasons.

Sub string

By using a colon you can create a substring. If no start or end number is written, Python
assumes you mean the first character or last character.

Try the example below:

x = "hello world"
s = x[0:3]
print(s)
s = x[:3]
print(s)

Complete example

This example does a lot of string operations like printing text, numbers, combining strings,
slicing and accessing elements.

Try the program below:

x = "Nancy"
print(x)

# Combine numbers and text


s = "My lucky number is %d, what is yours?" % 7
print(s)

# alternative method of combining numbers and text


s = "My lucky number is " + str(7) + ", what is yours?"
print(s)

# print character by index


print(x[0])

# print piece of string


print(x[0:3])

You should see this output:


Python String replace() Method
Python has builtin support for string replacement. A string is a variable that contains text
data. If you don’t know about strings, you can read more about strings in this article.

Can call the string.replace(old, new) method using the string object. This article demonstrates
the replace method.

Not all programming languages have a standard string replace function. Python has a lot of
functionality that comes out of the box.

Related course: Complete Python Programming Course & Exercises

Example
Replace method

Define a string and call the replace() method. The first parameter is the word to search, the
second parameter specifies the new value.

The output needs to be saved in the string. If you don’t save the output, the string variable
will contain the same contents. Saving output is done using: s = function()

Try the program below:

s = "Hello World"
s = s.replace("World","Universe")
print(s)

Save the program as app.py, then run in terminal (or IDE)

python app.py

This will output the new output of string variable s:


Number of words to replace

An optional parameter is the number of items that will be replaced. By default its all.
The program below replaces only the first item:

s = "Hello World World World"


s = s.replace("World","Universe",1)
print(s)

The parameter (1) indicates that the string should be replaced only once.

join() function in Python


The join(sequence) method joins elements and returns the combined string. The join methods
combines every element of the sequence.

Combine list of words?

Combine them into a sentence with the join(sequence) method. The method is called on a
seperator string, which can be anything from a space to a dash.

This is easier than using the plus operator for every word, which would quickly become
tedious with a long list of words.

Related course: Complete Python Programming Course & Exercises

Example
The join method takes a sequence as argument. The sequence is written as single argument:
you need to add brackets around the sequence.

If you’d like, you can pass a variable holding the sequence as argument. This makes it easier
to read. We’ll use a space a seperator string in the example below.

Try the program below:

# define strings

firstname = "Bugs"
lastname = "Bunny"

# define our sequence

sequence = (firstname,lastname)

# join into new string


name = " ".join(sequence)
print(name)

You should see this output:

It can also join a list of words:

words = ["How","are","you","doing","?"]
sentence = ' '.join(words)
print(sentence)

String find() in Python


The find(query) method is built-in to standard python. Just call the method on the string
object to search for a string, like so: obj.find(“search”).

The find() method searches for a query string and returns the character position if found. If
the string is not found, it returns -1.
In simple English: find out if a string contains another string.

Related course: Complete Python Programming Course & Exercises

Example
Find method

The find method returns the index if a word is found. If not found, it returns -1. You can add
a starting index and end index: find(query, start, end), but these parameters are optional.

Try the program below:

s = "That I ever did see. Dusty as the handle on the door"

index = s.find("Dusty")
print(index)

Save the program as search.py, run from terminal or IDE.


You should see this output:

The in keyword

You can also use the keyword _in_. The example below shows you how to use the Python in
keyword.

s = "That I ever did see. Dusty as the handle on the door"

if "Dusty" in s:
print("query found")

The difference is the in keyword returns if the string contains a word, but find returns the
character position.

Control Structures
If Statements Explained
A program sometimes may have to make choices. These choices can execute different code
depending on certain condition.

In Python the if statement is used for conditional execution or branching. An if statement is


one of the control structures. (A control structure controls the flow of the program.)

The if statement may be combined with certain operator such as equality (==), greater than
(>=), smaller than (<=) and not equal (!=). Conditions may be combined using the
keywords or and and.

Related course: Complete Python Programming Course & Exercises

Introduction
In the example below we show the use if statement, a control structure. An if statement
evaluates data (a condition) and makes a choice.

Lets have al look at a basic if statement. In its basic form it looks like this:

#!/usr/bin/env python3
if <condition>:
<statement>

In this form

 is the condition evaluated as a Boolean, it can either be True or False.


 is one more lines of code. Each of those lines must indented with four spaces.

Several examples of the if statements are shown below, you can run them in the Python
interpreter:

#!/usr/bin/env python3
>>> x = 3
>>> if x < 10:
... print('x below ten')
...
x below ten
>>> if x > 10:
... print('x is greater than ten')
...
>>> if x > 1 and x < 4:
... print('x is in range')
...
x is in range
>>>
It’s very important to have four spaces for the statements. Every if statement needs a colon.
More than one condition can be combined using the and keyword.

Indentation and Blocks


An if statement doesn’t need to have a single statement, it can have a block. A block is more
than one statement.

The example below shows a code block with 3 statements (print). A block is seen by Python
as a single entity, that means that if the condition is true, the whole block is executed (every
statement).

#!/usr/bin/env python3
x = 4
if x < 5:
print("x is smaller than five")
print("this means it's not equal to five either")
print("x is an integer")

All programming languages can create blocks, but Python has a unique way of doing it. A
block is defined only by its indention.

Python "for" Loops (Iteration


Introduction)
Programs sometimes need to repeat actions. To repeat actions we can use a for loop.
A for loop is written inside the code. A for loop can have 1 or more instructions.

A for loop will repeat a code block. Repeation is continued until the stop condition is met. If
the stop condition is not met it will loop infintely.

These instructions (loop) is repeated until a condition is met.

Related course: Complete Python Programming Course & Exercises

Example
In the exercise below we will repeat actions on every item of a list.

The first loop will repeat the print functionfor every item of the list.
The second loop will do a calculation on every element of the list num and print the result.

Type the code below and run the program.

#!/usr/bin/env python3
city = ['Tokyo','New York','Toronto','Hong Kong']
print('Cities loop:')
for x in city:
print('City: ' + x)

print('\n') # newline

num = [1,2,3,4,5,6,7,8,9]
print('x^2 loop:')
for x in num:
y = x * x
print(str(x) + '*' + str(x) + '=' + str(y))

Save the file as loopexample.py


Then run the code with the command:

python loopexample.py

Schematically a for loop does this:


Python "while" Loops (Indefinite
Iteration)
A while loop repeats code until the condition is met. Unlike for loops, the number of
iterations in it may be unknown. A while loop always consists of a condition and a block of
code.

A while loop ends if and only if the condition is true, in contrast to a for loop that always has
a finite countable number of steps.

Related course: Complete Python Programming Course & Exercises

Example
While loop example

The while loop below defines the condition (x < 10) and repeats the instructions until that
condition is true. Type this code:

#!/usr/bin/python

x = 3

while x < 10:


print(x)
x = x + 1

Executes the code below until the condition x < 10 is met. Unlike a for loop, the iterator i is increased
in the loop.

Functions in Python (With Examples)


To group sets of code you can use functions. Functions are small parts of repeatable code.
A function accepts parameters.

Without functions we only have a long list of instructions. Functions can help you organize
code. Functions can also be reused, often they are included in modules.

Related course: Complete Python Programming Course & Exercises

Example
Functions

Functions can be seen as executable code blocks. A function can be used once or more.

A simple example of a function is:

def currentYear():
print('2018')

currentYear()

The function is immediately called in this example. Function definitions always start with the
def keyword.

Functions can be reusable, once created a function can be used in multiple programs. The
print function is an example of that.

Functions with parameters

In the example below we have parameter x and y. Type this program and save it as
summation.py

#!/usr/bin/env python3

def f(x,y):
return x*y

print(f(3,4))

In this example we have two functions: f(x,y) and print(). The function f(x,y) passed its
output to the print function using the return keyword.

Return variables

Functions can return variables. Sometimes a function makes a calculation or has some output,
this can be given to the program with a return varaible.

In many cases that output is stored in a variable:

result = f(3,4)
print(result)
In this case the program will call the function f with parameters 3 and 4, then save the output
to the variable result.

Python Lists (With Examples)


List can be seen as a collection: they can hold many variables. List resemble physical lists,
they can contain a number of items.

A list can have any number of elements. They are similar to arrays in other programming
languages. Lists can hold all kinds of variables: integers (whole numbers), floats, characters,
texts and many more.

Related course: Complete Python Programming Course & Exercises

Example
Empty list

Lets create an empty list. To define an empty list you should use brackets.
Brackets is what tells Python that the object is a list.

list = []

Lists can hold both numbers and text. Regardless of contents, they are accessed in the same
fashion.

To access a list add the id between the brackets, such as list[0], list[1] and so on.

Define list

An empty list was defined above. Lists can contain all kinds of data.
You can create numeric lists like this:

ratings = [ 3,4,6,3,4,6,5 ]

Lists can contain strings or characters:

ratings = [ 'A','A','B','A','C','A' ]

To output simple print them

print(ratings)

You can interact item by item using a for loop.


Access list items

You can access a list item by using brackets and its index. Python starts counting at zero, that
means the first element is zero.

Why count from zero?

Computer languages used to count from zero. At the time when programming languages were
first created, it made sense to count from zero. These days it would just be strange to change
that tradition.

To get the first item, simply add the brackets and a zero after the list name.

print(rating[0])

Every other element can be accessed by the incremental numbers, to print the second item
you’d use (1), to print the thrid item you’d use (2).

print(rating[1])

List example

Type the code below and run it:

#!/usr/bin/python

list = [ "New York", "Los Angles", "Boston", "Denver" ]

print(list) # prints all elements


print(list[0]) # print first element

list2 = [1,3,4,6,4,7,8,2,3]

print(sum(list2))
print(min(list2))
print(max(list2))
print(list2[0])
print(list2[-1])

This should output:


If you are a beginner, then I highly recommend this book.

List operations
Lists can be changed with several methods. What are these methods?

To add items to a list, you can use the append() method. Call the method on the list, the
parameter contains the item to add. Calling append(3) would add 3 to the list. To remove an
item from the end of the list, you can use the pop() method.

Lists can be accessed like traditional arrays, use the block quotes and index to get an item.

Related course: Complete Python Programming Course & Exercises

Example
Lists can be modified using their methods.
In the example below we create a list and use methods to change the list contents.

Append and pop

Type the program shown below and run it:

x = [3,4,5]
x.append(6)
print(x)
x.append(7)
print(x)
x.pop()
print(x)

Access items

To access items, simply use the block quotes:


x = [3,4,5]

print(x[0])
print(x[1])

print(x[-1])

List operations
Lists can be changed with several methods. What are these methods?

To add items to a list, you can use the append() method. Call the method on the list, the
parameter contains the item to add. Calling append(3) would add 3 to the list. To remove an
item from the end of the list, you can use the pop() method.

Lists can be accessed like traditional arrays, use the block quotes and index to get an item.

Related course: Complete Python Programming Course & Exercises

Example
Lists can be modified using their methods.
In the example below we create a list and use methods to change the list contents.

Append and pop

Type the program shown below and run it:

x = [3,4,5]
x.append(6)
print(x)
x.append(7)
print(x)
x.pop()
print(x)

Access items

To access items, simply use the block quotes:

x = [3,4,5]

print(x[0])
print(x[1])

print(x[-1])
How to Sort a List in Python
Sorting a list is pretty easy: Python has built-in support for sorting lists.

Start with some data: Create a list of numbers and then call the sort() method. This method is
directly called on the list object. This will work with any list, including list of pairs.

Related course: Complete Python Programming Course & Exercises

Sort example
Sort list

We define a list (x) with a bunch of numbers. Then call the sort method on the list object. We
do not need to save the return variable, simply calling the method is enough.

x = [3,6,21,1,5,98,4,23,1,6]
x.sort()
print(x)

Save the program (sort1.py) and run it. This will output all numbers in low to high order.

Do you have a list of strings? Strings can also be sorted.

words = ["Be","Car","Always","Door","Eat" ]
words.sort()
print(words)

By simply calling the .sort() method, you can sort a list with a number of items.

You do not need to use a return variable when doing this, because lists are objects (more on
this later in the OOP section). For now just remember that you can call .sort() on lists.

Reverse order

To sort in reverse order, combine it with the method reverse()

x = [3,6,21,1,5,98,4,23,1,6]
x.sort()
x = list(reversed(x))
print(x)

All of the numbers will be shown in reverse order.

So what’s happening here?

First the list is sorted with x.sort().


Then it’s given to the function reversed() which takes a list as parameter. But, the function
does not return a list object but an iterator. The method list() converts the output of reversed()
and converts it to a list object.

Best way to sort in reverse order

You can sort the list in a more elegant way:

words = words[::-1]

What’s this trickery?

The technique of slicing is used on the list. It means slice the list, starting at the first
character, ending at the last character and with step size of -1 (reverse).

Python Range() function explained


The range() function generates a list of numbers. This is very useful when creating new lists
or when using for loops: it can be used for both.

In practice you rarely define lists yourself, you either get them from a database, the web or
generate them using range().

Related course: Complete Python Programming Course & Exercises

Python range() parameters


The range() function takes parameter, which must be integers. They can be both positive and
negative.
By default, it creates a list of numbers starting from zero, as parameter the stop value is
defined

range(stop)

But you can define the starting number of the sequence and then step size.

range(start, stop, step)


Python’s range() example
Lets say you want to create a list of 100 numbers. To do that, you can use the range()
function. By calling list(range(100)) it returns a list of 100 numbers. Writing them out by
hand would be very time consuming, so instead use the range function:
x = list(range(100))
print(x)

Python starts counting from zero. Now what if you want to count from 1 to 100?

x = list(range(1,101))
print(x)

A third parameter defines the step size, by default its one. Range can be used in a for loop:

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

Some other examples which have a step size parameter:

>>> for i in range(0,25,5):


... print(i)
...
0
5
10
15
20
>>> for i in range(0,100,10):
... print(i)
...
0
10
20
30
40
50
60
70
80
90

Dictionaries in Python
Python dictionaries are another collection. Real word dictionaries are a good analogy to
understand them: they contain a list of items, each item has a key and a value.

In the traditional dictionary, the key is the word and the value is the explanation or
description of it. In Python you can do something similar.

Related course: Complete Python Programming Course & Exercises

Example
Introduction

In a more strict way of speaking (mathematical), a dictionary is a one-to-one mapping. For


every key in the dictionary there is a value. This value is assigned to the key.

dictionary: a set which contains (key, value) pairs

For every key in a dictionary, there is a value. Unlike lists, dictionaries do not have an
specific order.

That means if you were to define a dictionary and loop over it, each time the output could be
different because Python neglects the order.
Defintion

Lets type some code! You can create a dictionary with a one liner. A dictionary is defined
with these brackets {}.

words = {}

Beware: This is just two characters different from a list. Making a typo here, would mix it up
with a list.

Then you can create a mapping. A mapping is defined as a key,value pair. First define the key
then the value:

words[key] = value

You can use strings as keys. A key defintion could be : words[“PRONTO”]

Dictionary example

In the example below we define some key,value pairs and then print them using their unique
keys.
Type the code below, save it and run it:

#!/usr/bin/python

words = {}
words["BMP"] = "Bitmap"
words["BTW"] = "By The Way"
words["BRB"] = "Be Right Back"

print words["BMP"]
print words["BRB"]

Read File in Python


Reading files is part of the Python standard library. This means you do not have to include
any module.

There are two ways to read files:

 line by line
 read block
Write file in Python
Write file functionality is part of the standard module, you don’t need to include any
modules.

Writing files and appending to a file are different in the Python language.
You can open a file for writing using the line

Nested loops
A loop can contain one or more other loops: you can create a loop inside a loop.
This principle is known as nested loops. Nested loops go over two or more loops.

Programmers typically nest 2 or 3 levels deep. Anything higher than that is just confusing.

Related course: Complete Python Programming Course & Exercises

Example
Lets do a simple example. We create two lists:

persons = [ "John", "Marissa", "Pete", "Dayton" ]


restaurants = [ "Japanese", "American", "Mexican", "French" ]

If we have a list of persons who like to eat at restaurants, can we make every one of them eat
a certain restaurant?

#!/usr/bin/python

persons = [ "John", "Marissa", "Pete", "Dayton" ]


restaurants = [ "Japanese", "American", "Mexican", "French" ]

for person in persons:


for restaurant in restaurants:
print(person + " eats " + restaurant)

This goes over both loops:


How to Slice Lists/Arrays in Python
A slice can be taken from a string or list, just as you can take a slice from a pizza.
If you have a variable, be it a list or a string, that you want a part of, you don’t have to define
it all over again.

You can get a copy of the variable, which is the whole or a subset of the original variable.
This concept is known as slicing.

Related course: Complete Python Programming Course & Exercises

Example
Slicing

To take the first two slices, you’d use:

slice = pizza[0:2]

The variable slice will now contain a copy of pizza, but only part of it. This is expressed
using the brackets, the first number is the start and the number after the colon is the end.

Why does it start with zero?

Python starts numbering of string and list elements from zero, not one.
In this case we took a slice from the list pizza, the output is stored into a new variable.
If you want you can pass it directly to the print function.

List slice

Create a list of persons. We’ll use the slicing technique to get the first two persons in the list.

#!/usr/bin/python
persons = [ "John", "Marissa", "Pete", "Dayton" ]

slice = persons[0:2]
print(slice)

This outputs the slice:

String slicing

A string can be sliced too. This is done in exactly the same way, but the main differnece is
that it won’t return a number of items, but simply a new string.

destination = "summer holiday at beach"


mySlice = destination[0:6]
print(mySlice)

Multiple return
Python functions can return multiple variables. These variables can be stored in variables
directly. A function is not required to return a variable, it can return zero, one, two or more
variables.

This is a unique property of Python, other programming languages such as C++ or Java do
not support this by default.

Related course: Complete Python Programming Course & Exercises


Example
Introduction

Variables defined in a function are only known in the function. That’s because of the scope of
the variable. In general that’s not a problem, unless you want to use the function output in
your program.

In that case you can return variables from a function. In the most simple case you can return a
single variable:

def complexfunction(a,b):
sum = a +b
return sum

Call the function with complexfunction(2,3) and its output can be used or saved.

But what if you have multiple variables in a function that you want access to?

Multiple return

Create a function getPerson(). As you already know a function can return a single variable,
but it can also return multiple variables.

We’ll store all of these variables directly from the function call.

#!/usr/bin/env python3

def getPerson():
name = "Leona"
age = 35
country = "UK"
return name,age,country

name,age,country = getPerson()
print(name)
print(age)
print(country)

This will output:


Python Scope of Variables
Variables have a certain reach within a program. A global variable can be used anywhere in a
program, but a local variable is known only in a certain area (function, loop)

Sometimes the word scope is used in projects: “its outside the scope of the project”, meaning
not included. Likewise, a variable can be outside the scope of a function.

Related course: Complete Python Programming Course & Exercises

Example:
Introduction

Scope has to do with where a variable can be used. If you define a variable, it’s not
necessarily usable everywhere in the code. A variable defined in a function is only known in
a function, unless you return it.

def something():
localVar = 1

# this will crash because localVar is a local variable


print(localVar)

That means unless you return the variables from a function, they can only be used there. This
is in stark constrast with global variables: global variables can be used anywhere including in
multiple functions and the main code. Global variables are often defined at the top of the
program.

Global and local variables

In the program below, balance is a global variable. It can be used anywhere in the code. But
the variable x can only be used inside addAmount.

#!/usr/bin/env python3
balance = 0

def addAmount(x):
global balance
balance = balance + x

addAmount(5)
print(balance)

Date and Time in Python


Python can get the system time using the module time. TIme is not part of the standard
library. You can load this module by typing import time.

The time module has all kinds of time related functions. Not all functions exist on all
operating systems.

The time module starts counting from epoch time, which is 1st January 1970.

Related course: Complete Python Programming Course & Exercises

Example
Current time

In the example below we output the day,month and year followed by the current time.

The first line returns all variables required (year,month,day,hour,minute).

timenow = time.localtime(time.time())

The function time.time() returns ticks. Ticks are system ticks every computer holds.

timenow = time.localtime(time.time())

As humans we don’t read system ticks, this needs to be converted to actual human time.
The function localtime() converts these ticks into the actual human readable values.

year,month,day,hour,minute = timenow[0:5]

Convert with:

timenow = time.localtime(time.time())
Type the program shown below and run it:

import time

timenow = time.localtime(time.time())
year,month,day,hour,minute = timenow[0:5]

print(str(day) + "/" + str(month) + "/" + str(year))


print(str(hour) + ":" + str(minute))

Epoch time

How do you get the number of seconds since epoch time?


The time() method will give you that:

>>> import time


>>> time.time()
1563018526.7016013
>>> time.time()
1563018527.5820937
>>>
To get the time sequence call time.gmtime().
>>> time.gmtime()
time.struct_time(tm_year=2019, tm_mon=7, tm_mday=13,
tm_hour=11, tm_min=49, tm_sec=39, tm_wday=5, tm_yday=194,
tm_isdst=0)

Time in string

The methods asctime() and ctime() return a 24 character string. Without arguments it gets the
current time.

>>> time.asctime()
'Sat Jul 13 13:53:00 2019'
>>> time.ctime()
'Sat Jul 13 13:53:01 2019'
>>>

Sleep

You can make the program hault execution. The program won’t do anything but wait. The
sleep module lets you do that.

import time

print("Hello")
time.sleep(1)
print("World")
time.sleep(1)

Try and Except in Python


The try except statement can handle exceptions. Exceptions may happen when you run a
program.

Exceptions are errors that happen during execution of the program. Python won’t tell you
about errors like syntax errors (grammar faults), instead it will abruptly stop.

An abrupt exit is bad for both the end user and developer.

Instead of an emergency halt, you can use a try except statement to properly deal with the
problem. An emergency halt will happen if you do not properly handle exceptions.

Related course: Complete Python Programming Course & Exercises

What are exceptions in Python?


Python has built-in exceptions which can output an error. If an error occurs while running the
program, it’s called an exception.

If an exception occurs, the type of exception is shown. Exceptions needs to be dealt with or
the program will crash. To handle exceptions, the try-catch block is used.
Some exceptions you may have seen before
are FileNotFoundError, ZeroDivisionError or ImportError but there are many more.

All exceptions in Python inherit from the class BaseException. If you open the Python
interactive shell and type the following statement it will list all built-in exceptions:

>>> dir(builtins)

The idea of the try-except clause is to handle exceptions (errors at runtime). The syntax of the
try-except block is:

try:
<do something>
except Exception:
<handle the error>

The idea of the try-except block is this:

 try: the code with the exception(s) to catch. If an exception is raised, it jumps straight
into the except block.
 except: this code is only executed if an exception occured in the try block. The except
block is required with a try block, even if it contains only the pass statement.

It may be combined with the else and finally keywords.

 else: Code in the else block is only executed if no exceptions were raised in the try
block.
 finally: The code in the finally block is always executed, regardless of if a an
exception was raised or not.

Catching Exceptions in Python


The try-except block can handle exceptions. This prevents abrupt exits of the program on
error. In the example below we purposely raise an exception.

try:
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')

After the except block, the program continues. Without a try-except block, the last line
wouldn’t be reached as the program would crash.

$ python3 example.py

Divided by zero
Should reach here

In the above example we catch the specific exception ZeroDivisionError. You can handle any
exception like this:

try:
open("fantasy.txt")
except:
print('Something went wrong')

print('Should reach here')

You can write different logic for each type of exception that happens:

try:
# your code here
except FileNotFoundError:
# handle exception
except IsADirectoryError:
# handle exception
except:
# all other types of exceptions

print('Should reach here')

Related course: Complete Python Programming Course & Exercises

try-except
Lets take do a real world example of the try-except block.

The program asks for numeric user input. Instead the user types characters in the input box.
The program normally would crash. But with a try-except block it can be handled properly.

The try except statement prevents the program from crashing and properly deals with it.

try:
x = input("Enter number: ")
x = x + 1
print(x)
except:
print("Invalid input")

Entering invalid input, makes the program continue normally:

The try except statement can be extended with the finally keyword, this will be executed if no
exception is thrown:

finally:
print("Valid input.")

The program continues execution if no exception has been thrown.

There are different kinds of exceptions: ZeroDivisionError, NameError, TypeError and so on.
Sometimes modules define their own exceptions.

The try-except block works for function calls too:

def fail():
1 / 0

try:
fail()
except:
print('Exception occured')

print('Program continues')

This outputs:

$ python3 example.py

Exception occured
Program continues

If you are a beginner, then I highly recommend this book.

try finally
A try-except block can have the finally clause (optionally). The finally clause is always
executed.
So the general idea is:

try:
<do something>
except Exception:
<handle the error>
finally:
<cleanup>

For instance: if you open a file you’ll want to close it, you can do so in the finally clause.
try:
f = open("test.txt")
except:
print('Could not open file')
finally:
f.close()

print('Program continue')

try else
The else clause is executed if and only if no exception is raised. This is different from the
finally clause that’s always executed.

try:
x = 1
except:
print('Failed to set x')
else:
print('No exception occured')
finally:
print('We always do this')

Output:

No exception occured
We always do this

You can catch many types of exceptions this way, where the else clause is executed only if
no exception happens.

try:
lunch()
except SyntaxError:
print('Fix your syntax')
except TypeError:
print('Oh no! A TypeError has occured')
except ValueError:
print('A ValueError occured!')
except ZeroDivisionError:
print('Did by zero?')
else:
print('No exception')
finally:
print('Ok then')
Raise Exception
Exceptions are raised when an error occurs. But in Python you can also force an exception to
occur with the keyword raise.

Any type of exception can be raised:

>>> raise MemoryError("Out of memory")


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError: Out of memory

>>> raise ValueError("Wrong value")


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Wrong value
>>>

Related course: Complete Python Programming Course & Exercises

Built-in exceptions
A list of Python's Built-in Exceptions is shown below. This list shows the Exception and why it is
thrown (raised).

Exception Cause of Error

AssertionError if assert statement fails.

AttributeError if attribute assignment or reference fails.

EOFError if the input() functions hits end-of-file condition.

FloatingPointError if a floating point operation fails.

GeneratorExit Raise if a generator's close() method is called.

ImportError if the imported module is not found.


IndexError if index of a sequence is out of range.

KeyError if a key is not found in a dictionary.

KeyboardInterrupt if the user hits interrupt key (Ctrl+c or delete).

MemoryError if an operation runs out of memory.

NameError if a variable is not found in local or global scope.

NotImplementedError by abstract methods.

OSError if system operation causes system related error.

if result of an arithmetic operation is too large to be


OverflowError
represented.

if a weak reference proxy is used to access a garbage


ReferenceError
collected referent.

RuntimeError if an error does not fall under any other category.

by next() function to indicate that there is no further


StopIteration
item to be returned by iterator.

SyntaxError by parser if syntax error is encountered.

IndentationError if there is incorrect indentation.

TabError if indentation consists of inconsistent tabs and spaces.

SystemError if interpreter detects internal error.

SystemExit by sys.exit() function.


if a function or operation is applied to an object of
TypeError
incorrect type.

if a reference is made to a local variable in a function or


UnboundLocalError
method, but no value has been bound to that variable.

UnicodeError if a Unicode-related encoding or decoding error occurs.

UnicodeEncodeError if a Unicode-related error occurs during encoding.

UnicodeDecodeError if a Unicode-related error occurs during decoding.

UnicodeTranslateError if a Unicode-related error occurs during translating.

if a function gets argument of correct type but improper


ValueError
value.

ZeroDivisionError if second operand of division or modulo operation is zero.

User-defined Exceptions
Python has many standard types of exceptions, but they may not always serve your purpose.
Your program can have your own type of exceptions.

To create a user-defined exception, you have to create a class that inherits from Exception.

class LunchError(Exception):
pass

raise LunchError("Programmer went to lunch")

You made a user-defined exception named LunchError in the above code. You can raise this
new exception if an error occurs.

Outputs your custom error:

$ python3 example.py
Traceback (most recent call last):
File “example.py”, line 5, in
raise LunchError(“Programmer went to lunch”)
main.LunchError: Programmer went to lunch

Your program can have many user-defined exceptions. The program below throws exceptions
based on a new projects money:

class NoMoneyException(Exception):
pass

class OutOfBudget(Exception):
pass

balance = int(input("Enter a balance: "))


if balance < 1000:
raise NoMoneyException
elif balance > 10000:
raise OutOfBudget

Here are some sample runs:

$ python3 example.py
Enter a balance: 500
Traceback (most recent call last):
File “example.py”, line 10, in
raise NoMoneyException
main.NoMoneyException
$ python3 example.py
$ python3 example.py
Enter a balance: 100000
Traceback (most recent call last):
File “example.py”, line 12, in
raise OutOfBudget
main.OutOfBudget

It is a good practice to put all user-defined exceptions in a separate file (exceptions.py or


errors.py). This is common practice in standard modules too.

How to use pip and pypi


Pip is a package manager for Python. You can use it to install modules. Sometimes systems
have two versions of pip in the store, you need version 3 (the newest).

A module is code: in the form of functions or objects. You can include this in your program
and build upon it. You could see this as premade parts that you use build your project with.
PyPI is the Python package index, where all the official modules for Python are stored.

Related course: Complete Python Programming Course & Exercises

Pip
Install pip

Installation of pip is easy. You can install it with the system package manager. If you use
Linux it’s often already installed.

On Linux you can install it with:

# debian and ubuntu linux


sudo apt-get install python3-pip

# fedora linux
sudo yum install python3-pip

On Mac OS X, install it with easy_install.

sudo easy install pip

Install module

Is pip installed? It can install packages from the PyPi repository. It’s the official repository
for python modules.

Software you install with pip is downloaded from the PyPi repo and installed.

To install a module, simply type:

pip install modulename

This could be any module from the PiPy index, lets take playsound:

pip install playsound

Virtualenv

You’d always want to install inside a virtual environment and not globally on your system.

Virtualenv creates an isolated environment, so packages you install won’t affect other python
projects. You can do that in this way:

virtualenv name
cd name
source bin/activate
Then your environment is active and you can install modules with pip,

pip install package

If you want to end working with the project type deactivate.

If you are a beginner, then I highly recommend this book.

Search

You can find packages in the PyPi index either online or in the command line.
To search in the command line type the command below, where topic is the word you want to
search for.

pip search topic

This will show a list of available software modules.

You might also like