What is Python? #1 - Hacettepeyunus.hacettepe.edu.tr/~saritan/bco601/hafta_01.pdf · What is...

Preview:

Citation preview

1

Biomechanics Research Group,

Faculty of Sports Sciences, and

Department of Computer Graphics

Hacettepe University, Ankara, Turkey

Serdar ARITAN

What is Python?

#1

2

Monty Python (sometimes known as The Pythons) was a British surreal comedy group that created

Monty Python's Flying Circus, a British television comedy sketch show that first aired on the BBC on

5 October 1969.

Snake logos and mascot not

with standing, it’s named after

Monty Python’s Flying Circus

• Invented in the Netherlands, early 90s by Guido van Rossum

• Named after Monty Python

• Open sourced from the beginning, man-aged by Python Software Foundation

• Considered a scripting language, but is much more

• Scalable, object oriented and functional from the beginning

• Used by Google from the beginning

Brief History of Python

3

4

Python’s Benevolent Dictator For Life

“Python is an experiment in how

much freedom program-mers

need. Too much freedom and

nobody can read another's code;

too little and expressive-ness is

endangered.”

- Guido van Rossum

5

• TIOBE has been collecting

data on programming language

“popularity” for many years

6

Python’s place in the Market

7

Python’s place in the Market

8

Python’s place in the Market

9

• Extensible (packages)

• Embeddable into applications

• Functional programming

• Object-Oriented programming

• Rapid Prototyping

• Great for readability and presentation

• White space is significant

• Low maintenance costs

• Exception handling

• Free (open source)

Distinct Features of Python

10

The core philosophy of the language is summarized by

the document "PEP 20 (The Zen of Python)",

• Beautiful is better than ugly.

• Explicit is better than implicit.

• Simple is better than complex.

• Complex is better than complicated.

• Readability counts.

Try;

>>>import this

11

http://www.python.org/

12

https://docs.python.org/3/

13

• code or source code: The sequence of instructions in a program.

• syntax: The set of legal structures and commands that can be used in a particular

programming language.

Programming Basics

• output: The messages printed to

the user by a program.

• console: The text box onto which

output is printed.

– Some source code editors pop

up the console as an external

window, and others contain

their own console window.

14

Compiling and Interpreting

Both types of languages have their strengths and weaknesses. Usually, the

decision to use an interpreted language is based on time restrictions on

development or for ease of future changes to the program.

Compiled languages are all translated by running the source code through a

compiler. This results in very efficient code that can be executed any number of

times. The overhead for the translation is incurred just once, when the source is

compiled; thereafter, it need only be loaded and executed. Interpreted

languages, in contrast, must be parsed, interpreted, and executed each time the

program is run, thereby greatly adding to the cost of running the program. For

this reason, interpreted programs are usually less efficient than compiled

programs.

15

Compiling and Interpreting

Python is an interpreted language, as opposed to a compiled one, though the

distinction can be blurry because of the presence of the bytecode compiler. This

means that source files can be run directly without explicitly creating an

executable which is then run.

Python is not interpreted. The standard implementation compiles to bytecode,

and then executes in a virtual machine.

This is the approach taken by languages like Java and C#. The code is

transformed into instructions for a "virtual machine". These instructions are then

interpreted.

Bytecode, also known as p-code (portable code), is a form of instruction set

designed for efficient execution by a software interpreter.

16

Compiling and Interpreting

• Many languages require you to compile (translate) your program

into a form that the machine understands.

17

Compiling and Interpreting

18

Compiling and Interpreting

• Python is instead directly interpreted into machine instructions.

interpret

output source code Hello.py

19

Compiling and Interpreting

Your source code doesn’t contain all the information that the virtual

machine needs. For example, it does not contain the implementation of

the print function. The virtual machine locates functions such as print in

library modules. Generally, you need not be concerned with library

modules.

20

Compiling and Interpreting

An interpreter is a translating program that translates and executes the

statements in sequence. Unlike an assembler or compiler that produces

machine code as output, which is then executed in a separate step, an

interpreter translates a statement and then immediately executes the

statement.

By definition, machine code differs from machine to machine. That is,

each type of CPU has its own machine language that it understands. So

how can we give each of you the experience of using machine language

when you may be working on different machines? We solve that problem

by using a virtual computer. A virtual computer is a hypothetical machine,

in this case one that is designed to contain the important features of real

computers that we want to illustrate.

21

Hello World

22

Hello World

Hello World

23

Hello World

24

Hello World

25

Hello World

26

27

• variable: A named piece of memory that can store a value.

– Usage:

• Compute an expression's result,

• store that result into a variable,

• and use that variable later in the program.

• assignment statement: Stores a value into a variable.

– Syntax:

variable = expression

– Examples: x = 5

gpa = 3.14

x 5 gpa 3.14

Variables

left-hand side = right-hand side

LHS = RHS >>> width = 10 <enter>

>>> length = 5 <enter>

>>>

>>> print(width) <enter>

10

>>> print(length) <enter>

5

>>> print('width') <enter>

width

>>> print(width) <enter>

10

>>> 25 = age <enter>

SyntaxError: can't assign to literal

28

Variables

29

Variables are chunks of data stored in the computers memory.

There are generally three types of data stored in variables. Variables can be

in the form of integers or in a string. The second type of data, called a float,

refers to the non-whole numbers like decimals.

integers 1, 2, 3, 4, .....

float 0.3, 1.1, 1.8, 2.5, 3.14, ....

string “what is your name ? “, “your age is 18”, ...

How about 5j ? What is it?

Variables

30

• Integer objects

• Floating-point objects

• Complex number objects

• Decimal: fixed-precision objects

• Fraction: rational number objects

• Sets: collections with numeric operations

• Booleans: true and false

• Built-in functions and modules: round, math, random, etc.

• Expressions; unlimited integer precision; bitwise operations; hex,

octal, and binary formats

• Third-party extensions: vectors, libraries, visualization, plotting, etc.

Variables

31

Literal Interpretation

1234, −24, 0, 99999999999999 Integers (unlimited size)

1.23, 1., 3.14e-10, 4E210, 4.0e+210 Floating-point numbers

0o177, 0x9ff, 0b101010 Octal, hex, and binary literals

3+4j, 3.0+4.0j, 3J Complex number literals

set('spam'), {1, 2, 3, 4} Sets: construction forms

Decimal('1.0'), Fraction(1, 3) Decimal and fraction extension types

bool(X) True, False Boolean type and constants

Variables

32

Numbers in Python

Python offers three different kinds of numbers with which you can work:

integers , floating - point numbers (or floats ), and imaginary numbers .

>>> type(1)

<class 'int'>

>>> type(200000)

<class 'int'>

>>> type(99999999999999)

<class 'int'>

>>> type(1.0)

<class 'float'>

>>> type(5j)

<class 'complex'>

Variables

33

Data type Cat <class 'cat'>

Variables

34

>>> 399 + 3020 + 1 + 3456

6876

>>> 300 - 59994 + 20

-59674

>>> 4023 - 22.46

4000.54

>>> 2000403030 * 392381727

784921595607432810

>>> 2000403030 * 3923817273929

7849215963933911604870

>>> 2e304 * 3923817273929

inf

>>> 2e34 * 3923817273929

7.847634547858e+46

Numbers in Python

Variables

35

>>> import sys

>>> sys.float_info

sys.float_info(max=1.7976931348623157e+308, max_exp=1024,

max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021,

min_10_exp=-307, dig=15, mant_dig=53,

epsilon=2.220446049250313e-16, radix=2, rounds=1)

>>> sys.int_info

sys.int_info(bits_per_digit=30, sizeof_digit=4)

>>> # Guess what is the answer?

>>> 0.1 + 0.1 + 0.1 - 0.3 # it must be ZERO !!

Numbers in Python

Variables

36

>>> 0.1 + 0.1 + 0.1 - 0.3

5.551115123125783e-17 # be careful !!

>>> # However, with decimals, the result can be exact:

>>> from decimal import Decimal

>>> Decimal('0.1')+Decimal('0.1')+Decimal('0.1')-Decimal('0.3')

Decimal('0.0')

# When decimals of different precision are mixed in expressions,

# Python converts up to the largest number of decimal digits

>>> Decimal('0.1')+Decimal('0.10')+Decimal('0.10')-

Decimal('0.30')

Decimal('0.00')

Numbers in Python

Variables

37

Setting Decimal Precision Globally

>>> import decimal

>>> decimal.Decimal(1) / decimal.Decimal(7)

Decimal('0.1428571428571428571428571429')

# Default: 28 digits

>>> decimal.getcontext().prec = 4

# Fixed precision

>>> decimal.Decimal(1) / decimal.Decimal(7)

Decimal('0.1429')

The decimal module provides support for fast correctly-rounded decimal

floating point arithmetic. It offers several advantages over the float

datatype

Fixed Point and Floating Point Arithmetic

Variables

38

Mixed Types Are Converted Up

integers are simpler than floating point numbers, which are simpler than

complex numbers. So, when an integer is mixed with a floating point, as in

the preceding example, the integer is converted up to a floating-point value

first, and floating-point math yields the floating-point result

>>> 40 + 3.14 # Integer to float, float math/result

43.14

You can force the issue by calling built-in functions to convert types

manually >>> int(3.1415) # Truncates float to integer

3

>>> float(3) # Converts integer to float

3.0

Variables

Variables and Basic Expressions

Variables are created when they are first assigned values.

Variables are replaced with their values when used in expressions.

Variables must be assigned before they can be used in expressions.

Variables refer to objects and are never declared ahead of time.

>>> a = 3 # Name created: not declared ahead of time

>>> b = 4

>>> a + 1, a − 1 # Addition (3+1), subtraction (3−1)

(4, 2)

>>> b * 3, b / 2 # Multiplication (4*3), division (4/2)

(12, 2.0)

>>> a % 2, b ** 2 # Modulus (remainder), power (4**2)

(1, 16)

>>> 2 + 4.0, 2.0 ** b # Mixed-type conversions

(6.0, 16.0)

Variables

39

Unpacking a Sequence into Separate Variables >>> p = (4, 5)

>>> x, y = p

>>> x

4

>>> y

5

If there is a mismatch in the number of elements, you’ll get an error. For

example:

>>> p = (4, 5)

>>> x, y, z = p

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: need more than 2 values to unpack

Variables

40

You can name a variable almost anything and use symbols like the _

underscore. But there are some rules. You can’t use special key words that

Python understands as having special meanings. Don’t use these words:

Key Words in Python

Variables

41

Key Words in Python

“SyntaxError: invalid syntax...” is Python’s ways of saying, “Hey, you

don’t know what you are talking about and neither do I! Speak Python!”

Variables

42

Variables Naming Rules

• You cannot use one of Python’s key words as a variable name.

• A variable name cannot contain spaces.

• The first character must be one of the letters a through z, A through Z,

or an underscore character (_).

• After the first character you may use the letters a through z or A

through Z, the digits 0 through 9, or underscores.

• Uppercase and lowercase characters are distinct. This means the

variable name ItemsOrdered is not the same as itemsordered.

Variables

43

Variables

Legal or Illegal?

Variable names may only use letters, digits, or underscores.

Variable Name Legal or Illegal?

units_per_day Legal

dayOfWeek Legal

3dGraph Illegal. Variable names cannot begin with a digit.

June1997 Legal

Mixture#3 Illegal

Please give 5 Legal and 5 Illegal Variable Names

44

Lecture Notes

45

46

Lecture Notes

47

Lecture Notes

48

Lecture Notes

Recommended