[go: up one dir, main page]

0% found this document useful (0 votes)
19 views13 pages

py 1

Uploaded by

fortiratra
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)
19 views13 pages

py 1

Uploaded by

fortiratra
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/ 13

Chapter 1: Getting started with Python

Language

Python 3.x

Version Release Date

3.8 2020-04-29

3.7 2018-06-27

3.6 2016-12-23

3.5 2015-09-13

3.4 2014-03-17

3.3 2012-09-29

3.2 2011-02-20

3.1 2009-06-26

3.0 2008-12-03

Python 2.x

Version Release Date

2.7 2010-07-03

2.6 2008-10-02

2.5 2006-09-19

2.4 2004-11-30

2.3 2003-07-29

2.2 2001-12-21

2.1 2001-04-15

2.0 2000-10-16

Section 1.1: Getting Started

Python is a widely used high-level programming language for general-purpose programming, created
by Guido van

Rossum and first released in 1991. Python features a dynamic type system and automatic memory
management

and supports multiple programming paradigms, including object-oriented, imperative, functional


programming,

and procedural styles. It has a large and comprehensive standard library.

Two major versions of Python are currently in active use:


Python 3.x is the current version and is under active development.

Python 2.x is the legacy version and will receive only security updates until 2020. No new features
will be

implemented. Note that many projects still use Python 2, although migrating to Python 3 is getting
easier.

You can download and install either version of Python here. See Python 3 vs. Python 2 for a
comparison between

them. In addition, some third-parties offer re-packaged versions of Python that add commonly used
libraries and

other features to ease setup for common use cases, such as math, data analysis or scientific use. See
the list at the

official site.

Verify if Python is installed

To confirm that Python was installed correctly, you can verify that by running the following command
in your

favorite terminal (If you are using Windows OS, you need to add path of python to the environment
variable before

using it in command prompt):

GoalKicker.com – Python® Notes for Professionals 3

$ python --version

Python 3.x Version ≥ 3.0

If you have Python 3 installed, and it is your default version (see Troubleshooting for more details)
you should see

something like this:

$ python --version

Python 3.6.0

Python 2.x Version ≤ 2.7

If you have Python 2 installed, and it is your default version (see Troubleshooting for more details)
you should see

something like this:

$ python --version

Python 2.7.13

If you have installed Python 3, but $ python --version outputs a Python 2 version, you also have
Python 2
installed. This is often the case on MacOS, and many Linux distributions. Use $ python3 instead to
explicitly use the

Python 3 interpreter.

Hello, World in Python using IDLE

IDLE is a simple editor for Python, that comes bundled with Python.

How to create Hello, World program in IDLE

Open IDLE on your system of choice.

In older versions of Windows, it can be found at All Programs under the Windows menu.

In Windows 8+, search for IDLE or find it in the apps that are present in your system.

On Unix-based (including Mac) systems you can open it from the shell by typing $ idle

python_file.py.

It will open a shell with options along the top.

In the shell, there is a prompt of three right angle brackets:

>>>

Now write the following code in the prompt:

>>> print("Hello, World")

Hit Enter .

>>> print("Hello, World")

Hello, World

Hello World Python file

Create a new file hello.py that contains the following line:

Python 3.x Version ≥ 3.0

print('Hello, World')

Python 2.x Version ≥ 2.6

GoalKicker.com – Python® Notes for Professionals 4

You can use the Python 3 print function in Python 2 with the following import statement:

from __future__ import print_function

Python 2 has a number of functionalities that can be optionally imported from Python 3 using the
__future__

module, as discussed here.

Python 2.x Version ≤ 2.7


If using Python 2, you may also type the line below. Note that this is not valid in Python 3 and thus
not

recommended because it reduces cross-version code compatibility.

print 'Hello, World'

In your terminal, navigate to the directory containing the file hello.py.

Type python hello.py, then hit the Enter key.

$ python hello.py

Hello, World

You should see Hello, World printed to the console.

You can also substitute hello.py with the path to your file. For example, if you have the file in your
home directory

and your user is "user" on Linux, you can type python /home/user/hello.py.

Launch an interactive Python shell

By executing (running) the python command in your terminal, you are presented with an interactive
Python shell.

This is also known as the Python Interpreter or a REPL (for 'Read Evaluate Print Loop').

$ python

Python 2.7.12 (default, Jun 28 2016, 08:46:01)

[GCC 6.1.1 20160602] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> print 'Hello, World'

Hello, World

>>>

If you want to run Python 3 from your terminal, execute the command python3.

$ python3

Python 3.6.0 (default, Jan 13 2017, 00:00:00)

[GCC 6.1.1 20160602] on linux

Type "help", "copyright", "credits" or "license" for more information.

>>> print('Hello, World')

Hello, World

>>>

Alternatively, start the interactive prompt and load file with python -i <file.py>.
In command line, run:

$ python -i hello.py

"Hello World"

>>>

GoalKicker.com – Python® Notes for Professionals 5

There are multiple ways to close the Python shell:

>>> exit()

or

>>> quit()

Alternatively, CTRL + D will close the shell and put you back on your terminal's command line.

If you want to cancel a command you're in the middle of typing and get back to a clean command
prompt, while

staying inside the Interpreter shell, use CTRL + C .

Try an interactive Python shell online.

Other Online Shells

Various websites provide online access to Python shells.

Online shells may be useful for the following purposes:

Run a small code snippet from a machine which lacks python installation(smartphones, tablets etc).

Learn or teach basic Python.

Solve online judge problems.

Examples:

Disclaimer: documentation author(s) are not affiliated with any resources listed below.

https://www.python.org/shell/ - The online Python shell hosted by the official Python website.

https://ideone.com/ - Widely used on the Net to illustrate code snippet behavior.

https://repl.it/languages/python3 - Powerful and simple online compiler, IDE and interpreter. Code,
compile,

and run code in Python.

https://www.tutorialspoint.com/execute_python_online.php - Full-featured UNIX shell, and a user-


friendly

project explorer.

http://rextester.com/l/python3_online_compiler - Simple and easy to use IDE which shows execution


time
Run commands as a string

Python can be passed arbitrary code as a string in the shell:

$ python -c 'print("Hello, World")'

Hello, World

This can be useful when concatenating the results of scripts together in the shell.

Shells and Beyond

Package Management - The PyPA recommended tool for installing Python packages is PIP. To install,
on your

command line execute pip install <the package name>. For instance, pip install numpy. (Note: On
windows

you must add pip to your PATH environment variables. To avoid this, use python -m pip install <the
package

name>)

Shells - So far, we have discussed different ways to run code using Python's native interactive shell.
Shells use

GoalKicker.com – Python® Notes for Professionals 6

Python's interpretive power for experimenting with code real-time. Alternative shells include IDLE - a
pre-bundled

GUI, IPython - known for extending the interactive experience, etc.

Programs - For long-term storage you can save content to .py files and edit/execute them as scripts
or programs

with external tools e.g. shell, IDEs (such as PyCharm), Jupyter notebooks, etc. Intermediate users
may use these

tools; however, the methods discussed here are sufficient for getting started.

Python tutor allows you to step through Python code so you can visualize how the program will flow,
and helps you

to understand where your program went wrong.

PEP8 defines guidelines for formatting Python code. Formatting code well is important so you can
quickly read what

the code does.

Section 1.2: Creating variables and assigning values

To create a variable in Python, all you need to do is specify the variable name, and then assign a
value to it.

<variable name> = <value>


Python uses = to assign values to variables. There's no need to declare a variable in advance (or to
assign a data

type to it), assigning a value to a variable itself declares and initializes the variable with that value.
There's no way to

declare a variable without assigning it an initial value.

# Integer

a=2

print(a)

# Output: 2

# Integer

b = 9223372036854775807

print(b)

# Output: 9223372036854775807

# Floating point

pi = 3.14

print(pi)

# Output: 3.14

# String

c = 'A'

print(c)

# Output: A

# String

name = 'John Doe'

print(name)

# Output: John Doe

# Boolean

q = True

print(q)

# Output: True

# Empty value or null data type

x = None

print(x)
# Output: None

GoalKicker.com – Python® Notes for Professionals 7

Variable assignment works from left to right. So the following will give you an syntax error.

0=x

=> Output: SyntaxError: can't assign to literal

You can not use python's keywords as a valid variable name. You can see the list of keyword by:

import keyword

print(keyword.kwlist)

Rules for variable naming:

1. Variables names must start with a letter or an underscore.

x = True # valid

_y = True # valid

9x = False # starts with numeral

=> SyntaxError: invalid syntax

$y = False # starts with symbol

=> SyntaxError: invalid syntax

2. The remainder of your variable name may consist of letters, numbers and underscores.

has_0_in_it = "Still Valid"

3. Names are case sensitive.

x=9

y = X*5

=>NameError: name 'X' is not defined

Even though there's no need to specify a data type when declaring a variable in Python, while
allocating the

necessary area in memory for the variable, the Python interpreter automatically picks the most
suitable built-in

type for it:

a=2

print(type(a))

# Output: <type 'int'>

b = 9223372036854775807

print(type(b))
# Output: <type 'int'>

pi = 3.14

print(type(pi))

# Output: <type 'float'>

c = 'A'

print(type(c))

# Output: <type 'str'>

name = 'John Doe'

print(type(name))

# Output: <type 'str'>

q = True

print(type(q))

GoalKicker.com – Python® Notes for Professionals 8

# Output: <type 'bool'>

x = None

print(type(x))

# Output: <type 'NoneType'>

Now you know the basics of assignment, let's get this subtlety about assignment in python out of the
way.

When you use = to do an assignment operation, what's on the left of = is a name for the object on
the right. Finally,

what = does is assign the reference of the object on the right to the name on the left.

That is:

a_name = an_object # "a_name" is now a name for the reference to the object "an_object"

So, from many assignment examples above, if we pick pi = 3.14, then pi is a name (not the name,
since an object

can have multiple names) for the object 3.14. If you don't understand something below, come back
to this point

and read this again! Also, you can take a look at this for a better understanding.

You can assign multiple values to multiple variables in one line. Note that there must be the same
number of

arguments on the right and left sides of the = operator:

a, b, c = 1, 2, 3
print(a, b, c)

# Output: 1 2 3

a, b, c = 1, 2

=> Traceback (most recent call last):

=> File "name.py", line N, in <module>

=> a, b, c = 1, 2

=> ValueError: need more than 2 values to unpack

a, b = 1, 2, 3

=> Traceback (most recent call last):

=> File "name.py", line N, in <module>

=> a, b = 1, 2, 3

=> ValueError: too many values to unpack

The error in last example can be obviated by assigning remaining values to equal number of arbitrary
variables.

This dummy variable can have any name, but it is conventional to use the underscore (_) for
assigning unwanted

values:

a, b, _ = 1, 2, 3

print(a, b)

# Output: 1, 2

Note that the number of _ and number of remaining values must be equal. Otherwise 'too many
values to unpack

error' is thrown as above:

a, b, _ = 1,2,3,4

=>Traceback (most recent call last):

=>File "name.py", line N, in <module>

=>a, b, _ = 1,2,3,4

=>ValueError: too many values to unpack (expected 3)

You can also assign a single value to several variables simultaneously.

GoalKicker.com – Python® Notes for Professionals 9

a=b=c=1

print(a, b, c)
# Output: 1 1 1

When using such cascading assignment, it is important to note that all three variables a, b and c refer
to the same

object in memory, an int object with the value of 1. In other words, a, b and c are three different
names given to the

same int object. Assigning a different object to one of them afterwards doesn't change the others,
just as expected:

a = b = c = 1 # all three names a, b and c refer to same int object with value 1

print(a, b, c)

# Output: 1 1 1

b = 2 # b now refers to another int object, one with a value of 2

print(a, b, c)

# Output: 1 2 1 # so output is as expected.

The above is also true for mutable types (like list, dict, etc.) just as it is true for immutable types (like
int, string,

tuple, etc.):

x = y = [7, 8, 9] # x and y refer to the same list object just created, [7, 8, 9]

x = [13, 8, 9] # x now refers to a different list object just created, [13, 8, 9]

print(y) # y still refers to the list it was first assigned

# Output: [7, 8, 9]

So far so good. Things are a bit different when it comes to modifying the object (in contrast to
assigning the name to

a different object, which we did above) when the cascading assignment is used for mutable types.
Take a look

below, and you will see it first hand:

x = y = [7, 8, 9] # x and y are two different names for the same list object just created, [7,

8, 9]

x[0] = 13 # we are updating the value of the list [7, 8, 9] through one of its names, x

in this case

print(y) # printing the value of the list using its other name

# Output: [13, 8, 9] # hence, naturally the change is reflected

Nested lists are also valid in python. This means that a list can contain another list as an element.

x = [1, 2, [3, 4, 5], 6, 7] # this is nested list


print x[2]

# Output: [3, 4, 5]

print x[2][1]

# Output: 4

Lastly, variables in Python do not have to stay the same type as which they were first defined -- you
can simply use

= to assign a new value to a variable, even if that value is of a different type.

a=2

print(a)

# Output: 2

a = "New value"

print(a)

# Output: New value

If this bothers you, think about the fact that what's on the left of = is just a name for an object. First
you call the int

object with value 2 a, then you change your mind and decide to give the name a to a string object,
having value

'New value'. Simple, right?

GoalKicker.com – Python® Notes for Professionals 10

Section 1.3: Block Indentation

Python uses indentation to define control and loop constructs. This contributes to Python's
readability, however, it

requires the programmer to pay close attention to the use of whitespace. Thus, editor miscalibration
could result in

code that behaves in unexpected ways.

Python uses the colon symbol (:) and indentation for showing where blocks of code begin and end (If
you come

from another language, do not confuse this with somehow being related to the ternary operator).
That is, blocks in

Python, such as functions, loops, if clauses and other constructs, have no ending identifiers. All
blocks start with a

colon and then contain the indented lines below it.

For example:

def my_function(): # This is a function definition. Note the colon (:)


a = 2 # This line belongs to the function because it's indented

return a # This line also belongs to the same function

print(my_function()) # This line is OUTSIDE the function block

or

if a > b: # If block starts here

print(a) # This is part of the if block

else: # else must be at the same level as if

print(b) # This line is part of the else block

Blocks that contain exactly one single-line statement may be put on the same line, though this form
is generally not

considered good style:

if a > b: print(a)

else: print(b)

Attempting to do this with more than a single statement will not work:

if x > y: y = x

print(y) # IndentationError: unexpected indent

if x > y: while y != z: y -= 1 # SyntaxError: invalid syntax

An empty block causes an IndentationError. Use pass (a command that does nothing) when you have
a block with

no content:

def will_be_implemented_later():

pass

Spaces vs. Tabs

In short: always use 4 spaces for indentation.

Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are
preferred.

Python 3.x Version ≥ 3.0

Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time
error is

generated: Inconsistent use of tabs and spaces in indentation and the program will not run.

Python 2.x Version ≤ 2.7

You might also like