0% found this document useful (0 votes)
8 views28 pages

L3a- basic

This document provides an overview of Python basics, including the structure of Python programs, advantages of the language, variable handling, data types, and operators. It also covers memory organization, constants, comments, function calls, input/output operations, and error handling. Key concepts such as expressions, operator precedence, and string manipulation are explained to facilitate understanding of Python programming.

Uploaded by

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

L3a- basic

This document provides an overview of Python basics, including the structure of Python programs, advantages of the language, variable handling, data types, and operators. It also covers memory organization, constants, comments, function calls, input/output operations, and error handling. Key concepts such as expressions, operator precedence, and string manipulation are explained to facilitate understanding of Python programming.

Uploaded by

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

Lesson 3a: Python Basics

1
Basic elements in Python
• A program in Python is a sequence of definitions and
statements:
– Definitions are evaluated
– Statements are executed by Python Interpreter (Shell)

• Statements are instructions to do something.

Definitions

Statements

Indentation
2
Synth elements of a program in Python

Reserved words: These are the basic instructions of Python

... and the instructions for printing on the screen and reading from the keyboard ?

3
Advantages of Python
• It is a very portable language, that is, it is independent of
the architecture of the machine. Python programs run on a
virtual machine.
• Its grammar is elegant. It allows writing clear, concise and
simple code, and develop a lot of use cases in an elegant
and natural way.
• Large set of functions in the standard library and lots of
external projects with specific functionalities.
• Its interface with C, C++ and Java facilitates the
connection between heterogeneous programs.

4
Synth elements of a program in Python

They are not part of the kernel, but they are a fundamental part of language:

instructions for writing and reading... and some more

5
Modules

matplotlib
__buildins__ Default Modules Data View
pillow

csv
pandas
xml Kernel Data analysis numpy
Read Write
json Language scipy
zipfile

time
urlib
random
Other Web interaction
BeautifulSoup
math

sys

6
Variables

All values are stored in the computer memory.

We can imagine the memory as a shelf where boxes


contain data.

A variable is the name to refer to and to access a


value/object.

In Python, unlike in other languages, variables must NOT be declared


previously to be used.

When we make an assignment ( = ), we are


creating a variable (the one to the left of the =)
and giving it a value (the one to the right of the =)

7
Memory organization
Variable
name Address Storage space (1 byte) 1 byte = 8 bits
pi 1
2 3.14
3
n 4
5 2
6
7
pi = 3.14
n = 2 8 3.141592653
pi = 3.141592653 9

So many positions
as memory has
65535 the computer 8
Types
• Each variable has a type depending on the data it stores.

• Basic types of data in Python:


– int is used to represent integers (e.g. -1 , 4 , 2300)
– float is used to represent real numbers (e.g. -1.1 , 4.3 , 2.3E3)
– bool is used to represent Boolean values (True and False)
– str is used to represent a set of characters (e.g. "Hello" , "A23")

9
Names of variables
• In Python, a variable is just a name.
• An assignment statement associates the name on the left of = with the
object denoted by the expression on the right of =.
• A value can have one, more than one or no names associated with it:

• But names are important:


a = 3.14159 pi = 3.14159
b = 11.2 radius = 11.2
c = a*(b**2) area = pi*(radius**2)

Both programs are exactly the same for


Python, but not for us...

10
Names of variables
Rules:
• Valid characters: letters (a.. z and A.. Z), digits (0-9) and underscore ( _ ).
• Any other character is not allowed.
• First character: a letter or underscore. Cannot be a digit.
• Python's reserved words must not be used.
• Case sensitive:
area ≠ Area ≠ AREA

Examples:

Valid identifiers Invalid identifiers


circle_area 1x

_circle_area Circle Area

CircleArea_1 Circle#Area

x1 X:

ThisIdentifierIsValid ThisIsNotV@lid

11
Constants
Constants: In many languages, values that do not change during
execution are defined as constants.

In Phyton there is no difference between constants and variables.

It is a good programming practice to differentiate them. Usually,


variables that do not change value in the program will be defined in
uppercase:

PI = 3.141592

12
Comments
• A good practice to facilitate understanding the code is to add
comments.
• Text after character # is not interpreted by Phyton:

#Computes the area of a circle


PI = 3.14159
radius = 11.2
area = PI*radius**2

• To comment on more than one line, we use 3 double quotes in a row to


indicate the beginning and the end of a comment:

"""
Computes the area of a circle
Version 27-12-2020
"""
PI = 3.14159
radius = 11.2
area = PI*radius**2 13
Function calls

• We have already seen some examples of a call to a function:

• The function name is type, and it displays the type of a value or


variable.

• The value or variable, which is called the function argument or


parameter, must be included in parentheses.

• It is common to say that a function "takes" an argument and


"returns" a result.

• The result is called return value.

14
Data output
The standard output is usually the screen.

print ("Hello, World")

print() within the parenthesis we put what we want to print on the screen.

To print more than one item, we separate items with commas (,):

print() leaves a space between the elements

Advanced parameters print(value, ..., sep=' ', end='\n’)

15
Data input
The standard input is usually the keyboard.

input() is a function that returns a value (the one read from the keyboard).
Therefore, we must assign it to a variable:

num=input("Enter a number: ")

input() always returns a string. Therefore, input is of type str despite


entering a number:

We will see later how we solve this.


16
Type conversion
• Function int takes any value and converts it to an integer if possible
or gives an error.
• int can also convert floating point values to integers, but it truncates
the fractional part:

• Function float converts integers and strings to float numbers


• Function str converts a value or variable into a string

17
Expressions
An expression is essentially a formula that allows calculating a value.

An expression is a combination of values, variables, and operators. If we type


an expression on the command line, the interpreter evaluates it and displays
the result.

We do not need to have all the elements to have an expression; a single value
is also considered an expression

Any expression has a type. For example, the expression:

3.0 + 1.5
has type float.

The result of an expression can be assigned to a variable:

res = 3.0 + 1.5

18
Operators and operands

• Operators are special symbols that represent calculations such as


addition, multiplication, etc.
• The values used by the operator are called operands

Arithmetic operators

Type of
Operation Symbol Examples
operands*
Addition + int, float 5+3à8
Subtraction - int, float 5–3à2
Product * int, float 5 * 3 à 15
Division / int, float 10.0 / 3.0 à 3.333
Integer division // int, float 10 / /3 à 3
Modulus % int, float 10 % 3 à 1
Power ** int, float 10**2 à100

* If the two operands are int, the result is int (except for division, which returns float).
If any of them is a float, the result is float.

19
Assignment operators

• Assignment operators are used to link a value to a name (variable).


• They allow compacting the instructions and writing less.

Assignment operators

Operation Symbol Example


Addition += x += y is equivalent to x = x + y
Subtraction -= x -= y is equivalent to x = x - y
Product *= x *= y is equivalent to x = x * y
Division /= x /= y is equivalent to x = x / y
Integer division //= x //= y is equivalent to x = x // y
Modulus %= x %= y is equivalent to x = x % y
Power **= x **= y is equivalent to x = x ** y

20
Precedence of operators

• When there is more than one operator in the expression, the


evaluation order depends on the rules of precedence.

• Python follows the same rules of precedence for its mathematical


operators as those used in mathematics:
– Parentheses have the highest priority and can be used to force one's evaluation
in the order we want.

– The exponent is next in precedence.

– Multiplication and division have the same priority

– Next in precedence, we have addition and subtraction, with the same priority.

– Operators with the same priority are evaluated from left to right.

21
String Type (str)
• A string is a sequence of characters.

• How is it stored?
characters
H e l l o w o r l d
indices 0 1 2 3 4 5 6 7 8 9 10 11

• Operator [ ] : access to a position


e.g. 5th character (index 4)

• Operator [n:m] returns the part of the string from the n-th character
(included) to the m-th (not included):

22
ASCII Code
The ASCII code is a Latin-based character code. It was created in 1963 by the
American Committee on Standards (source: Wikipedia).

Essentially, it establishes a correspondence between the 256 integers that fit in


a byte (8 bits of information = 28 possible combinations) and the alphabet.

The most interesting values for us are the letters "a" and "A", and the digit "0".
These characters have codes 97, 65 and 48 respectively.

The interest in choosing these comes from the fact that the entire lowercase
alphabet comes after letter "a", so "b" has code 98, "c" has code 99, and so on
until "z", which has code 122.

The same happens for capital letters: "B" is 66, "C" on 67, and so on until "Z",
which is 90.

Numbers from "0" to "9" have codes from 48 to 57.

23
ASCII Code

Each character corresponds to a


number between 0 and 255.

On the keyboard:
ALT + Num ® character from table
Example: ALT + 169 ® ©

Python

print(chr(65)) ® ‘A’
print(ord(“A”)) ® 65

24
Operators and strings
• In mathematics it makes no sense to operate with strings, although
sometimes the strings look like numbers (e.g. "17"):
”17” + 1
• If we open our minds:
– what could it mean to add two strings? à Concatenate them
– what could it mean to multiply a string by an int? à Repeat it

Which mathematical property does not have the sum of strings? 25


Commutative Property ( a+b ≠ b+a )
Interpreter

Editor

NO
Done?

YES
Py
Execution Py YES

Error?

NO

26
Understanding Error Messages
• When Python finds syntax mistakes or other errors in your code, it
gives you error messages to help you figure out what the problem is
• Usually include these types of information:
– The filename
– The line of code where Python first figured out there was an error
– The kind of error

27
Errors related to language
In programming there are two type of errors:

1. Syntactic Errors (interpreting) :


• We did not follow the exact rules of the writing language.
• As the interpret is a program that automatically scans the code it will warn
us that it is not correct.
• Sometimes it helps us with the type of error, but sometimes when the code
is written so badly, help messages do not allow us to detect it quickly.

2. Semantic Errors (execution):


• The source code is syntactically correct but our program does not do what
we wanted.
• The Integrated Development Environment (IDE) has a debugger tool that
allows us to run the program step by step to detect where the error is.

28

You might also like