Lab 1 - Introduction to Python

What we need

Python is a widely used high-level interpreted programming language for general-purpose programming. Python 3.x will be used which presents some changes in terms of syntax and lots of improvements from Python 2.x, while the two major versions are not backward compatible.

Anaconda is a distribution of Python with other packages needed for Data Mining.

Visual Studio Code (VS Code) is a code editor with support for most programming languages. Alternative: you can use any text editor e.g. Notepad++ (not recommended) or a specialized python IDE e.g. PyCharm.

Libraries are commonly installed using the pip package manager if they are not already included in the Anaconda distribution:

  • NumPy is the fundamental package for scientific computing with Python.
  • Scipy is a Python-based ecosystem of open-source software for mathematics, science, and engineering
  • Scikit-learn is a simple and efficient tool for data mining and data analysis
  • Pandas is an open source library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
  • Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

Installing a library (e.g. numpy) in Python is as simple as running the following command in the terminal:

pip install numpy

Setup

  • Install Python 3.6.8 (download)
  • Create a new file and save it as e.g. lab1.py
  • Open with e.g. Notepad++
  • Write a simple Python program e.g.
    print("hello world")
  • Open the terminal in the current folder (Shift+Right click>Open command window here) and run the program from the command line e.g.
    python lab1.py

The Python version should be specified if there are multiple distributions installed (e.g. 2.7, 3.6, 3.7), according to the installed environment (Windows/Linux) and distribution:

# on linux
python3 lab1.py
python3.7 lab1.py

# on windows
py -3 lab1.py

The same applies for installing packages using pip:

# on linux
pip install numpy
pip3 install numpy
pip3.7 install numpy

# on windows
py -3 -m pip install numpy

Data types in Python

Python is an interpreted dynamically-typed language. Data type specification is not required when creating a variable (but can be specified in modern Python). Creating a variable is as simple as:

a = 10
a: int = 10

*Why would types be useful in Python?

Numbers

Numbers in Python can be integers or floating point (real) and also Decimal and Fraction.

Operations:

  • addition:
    4+5=9, 4.3+4.2=8.5
  • subtraction:
    4-5=-1, 4.3-8.2=-3.9
  • division:
    5/2=2.5
  • division discards the fractional part:
    5//2=2
  • remainder of the division:
    5%2=1
  • power:
    3**4=81

# create a numeric variable
a = 10
b = 20
 
# print the value
print(a)
 
# addition
s = a + b
print(s)
 
# fractions
from fractions import Fraction
 
print(Fraction(16, -10))
 
# decimal
from decimal import *
 
print(Decimal(1) / Decimal(7))
print(1/7)

Strings

Strings are used to represent text or a sequence of characters. Python can operate with strings which can be expressed in several ways

# declaring strings
s1 = 'Python'
s2 = "Programing"
 
# declaring unicode strings:
us1 = u"Ciprian Truică"
us2 = u'Ciprian Truică'

T1 (1p) Using s1 and s2, print the following string: “Python Programming”

T2 (1p) Print the length of the string

T3 (1p) Replace “Python” with “Fun” using replace function

T4 (1p) Split the string in two words using split function

Operations:

  • Concatenation
    s3 = s1 + " " + s2
  • Multiplication with a scalar
    s4 = "alibec" * 3
  • Getting a character from a specific index
    s3[5]
  • Getting the length of a string
    len(s3)
  • Getting sub-strings
    • characters between 2 indexes
      s3[2:4]
    • first n elements
      s3[:n]
    • last n elements
      s3[len(s3)-n:]
      s3[-n:]

Functions:

  • len returns the length of the string
    len(s3)
  • replace is used for replacing a substring by another substring
    s3.replace("Python", "Fun")
  • split is used for splitting a string into substrings based on a given token/delimiter
    s3.split(" ")

Index numbers start with 0. Strings are immutable, meaning that the content of a string cannot be changed. This does not work for a string:

s3[2] = "a"

Lists

Python knows several compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets.

list1 = [1, 4, 9, 25]
list2 = [36, 49, 65, 81, 100]

Operations:

  • Concatenation
    list3 = list1 + list2
  • Multiplication with a scalar
    list4 = list1 * 3
  • Getting an element from a specific index
    list3[5]
  • Getting the length of a list
    len(list3)
  • Getting sub-lists
    • characters between 2 indexes
      list3[2:4]
    • first n elements
      list3[:n]
    • last n elements
      list3[len(list3)-n:]
      list3[-n:]

Index numbers start with 0. List operations are similar with string operations. Lists are a mutable type, it is possible to change their content:

list2[2] = 65

Functions:

  • len returns the length of the list
    len(list1)
  • append is used for adding an element at the end of a list
    list1.append(64)
  • reverse is used for reversing the elements of the list
    list1.reverse()
  • sort is used for ordering the list
    list1.sort()
  • List comprehension is used to create a new list based on existing list elements
    newlist = [x*10 for x in list1]
  • range can be used to create a list of numbers
    # create a list from given start/end values
    list(range(1,10))
    
    # create a list from given number of elements
    list(range(10))
  • other methods can be found here

Matrices

Matrices are lists of lists:

m = [ [1, 2], [3, 4] ]

Basic control statements

In computer programming, a statement is a syntactic unit of a programming language that expresses some action to be carried out. Examples of statements in Python include if else, for in, while

Decision structures. if else

If else statements are used to allow programmers to ask questions and then, based on the result, perform different actions.

if exp1:
   # do something
elif exp2:
   # do something else
else:
   # do something else

T5 (1p) Write a simple program that asks for a number and prints if the number is even or odd

Hint: use the input function to get the user input:

n=int(input("Enter a number"))

Use the % operator to check if the number is divisible by 2

Repetitive structures. for in

For loops are used to iterate though a list of values, useful when performing repeated actions with a defined number of iterations.

for elem in list1:
   # do something
   # print the element in the list
   print(elem)

T6 (1p) Having a list of numbers, use a for loop to print the numbers one by one

T7 (1p) Having a list of numbers, write a Python program to print only even numbers one by one

Hint: Using lists, for loop, if else, % operator

Repetitive structures. while

While loops are used to iterate until a condition that is true becomes false. The condition is evaluated before the execution of the block.

while exp:
   # code block
   # do something

Here is an example:

counter = 1
while counter < 10:
   print(counter)
   counter = counter + 1

You can force exit a repetitive loop (for, while) at any iteration by using break

while exp:
   # do something
   if condition:
      break

Here is an example:

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

T8 (1p) Using a while loop, print the number of digits in an integer number, e.g. 12345 has 5 digits

T9 (1p) Using a while loop, print the digits of a number one by one, e.g. 12345 has the following digits: 1,2,3,4,5

Hint: Use the % operator to get the last digit of a number divided by 10

12345 % 10 = 5

Then perform integer division by 10 until there are no more digits

12345 // 10 = 1234

T10 (1p) In T9, you (most probably) printed the digits in reverse order. Using a list and a for loop, print the digits in the correct order. You may use the following method to reverse a list

list.reverse()

Resources

ewis/laboratoare/01.txt · Last modified: 2021/03/17 17:07 by alexandru.predescu
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0