0% found this document useful (0 votes)
3 views

55284A - Introduction to Python _ Chapter1

The document provides an introduction to Python basics, covering topics such as Python's functionality, syntax, and how to navigate the terminal. It explains how to run Python commands, manage directories, and execute Python scripts, including a simple 'Hello, world!' example. Additionally, it offers guidance on ensuring Python is installed correctly on different operating systems and using the Python interactive shell.

Uploaded by

mhetre2017
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)
3 views

55284A - Introduction to Python _ Chapter1

The document provides an introduction to Python basics, covering topics such as Python's functionality, syntax, and how to navigate the terminal. It explains how to run Python commands, manage directories, and execute Python scripts, including a simple 'Hello, world!' example. Additionally, it offers guidance on ensuring Python is installed correctly on different operating systems and using the Python interactive shell.

Uploaded by

mhetre2017
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/ 23

LESSON 1: Python Basics

Topics Covered

How Python works.

Python’s
Th place in the world of programming languages.
is
do
c
Python literals.ume
nt
be
lon
Python comments.No ja gta gs to
un p NI
au nilka LK
t
Variables and Python data h o n t
riz types.@ ANT
ed re ES
co diff.c HW
pie o AR
Simple modules. sa m JA
llo GT
we AP
d! .
Outputting data with print().

Collecting user input.

Th
The pythons
is had entered into Mankind. No man knew at what moment he might be Possessed!
do
c
– Plague of uPythons, Frederik Pohl
me
nt
be
lon
No jagta gs to
u p
Introduction nautho nilkant NILKAN
riz @ TE
ed re SH
co diff.c
pie om WAR
Python, which first appeared in 1991, sisaone JA popular programming languages used today. 1 Python
llo of the most GT
we AP a syntax that is relatively human readable, which gets
is a high-level programming language, meaning d! that it uses.
translated by a Python Interpreter into a language your computer can understand. Examples of other popular high-
level programming languages are C#, Objective-C, Java, PHP, and JavaScript. Interestingly, all of these other
languages, unlike Python, share a C-like syntax. If you use one or more of those languages, you may find Python’s
syntax a little strange. But give it a little time. You’ll find it’s quite programmer friendly.
Th
is
do
Getting Familiar
cu
m
with the Terminal
en
tb
elo
N jag ngs
o u totabe
Python developers need to
comfortable navigating around and running commands at the terminal. 2 We’ll walk
na pnilk NIL
you through some basics:utho ant KAN
riz @ TE
ed re SH
co diff.c
pie om WAR
1. Open a terminal. In Visual Studios Code, all you can
JA open a terminal by selecting Terminal from the View menu:
ow GT
ed AP
! .

Th
is
do
cu
men
tb
elo
jag ng
N s
Th
is
do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .

You canThalso open a terminal by pressing Ctrl+`. The ` key is on the upper left of most keyboards. It looks like
is
do
this: cu
me
nt
be
lon
No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
l
The terminal will open at the root ofloyour GT
we Visual Studio
AP Code workspace. If you’re working in the workspace
d! .
we had you set up, that should be in a Webucator\Python directory (the words folder and directory are
used interchangeably). The prompt on Windows will read something like:

PS C:\Webucator\Python>
Th
is
do
cu
On a Mac, it willmshow
en
tb
some combination of your computer name, the directory you are in, and your
username, followed byeloa $ or % sign. For example:
n
No jagta gs to
un pn NI
au il LK
tho kant
r i z @ ANT
NatsMac:Python natdunn$ ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
natdunn@NatsMac:Python % we AP
d! .

2. Use cd to change directories. From the Webucator\Python directory, run:

PS C:\Webucator\Python>
T cd python-basics
his
do
PS …\Python\python-basics>
c um
en
tb
elo
ja ng
N g s
Your prompt now shows that your are in the python-basics directory.
3. Move up to the parent directory by running:

cd ..

You will now be back in your Python directory.


Th
is
4. Run: do
cu
me
nt
be
lon
No j
cd python-basics/Demosa gta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c WA
Your prompt will show that youpiare m Demos
es inothe R directory. Depending on your environment, it may also show
all JA
one or more directories above the Demos ow GT To get the full path to your current location, run pwd for
directory.
ed AP
present working directory: ! .

pwd

Th
is
On Windows, do that will look something like this:
cu
me
nt
be
lon
No agta gs to
j
PS …\python-basics\Demos> pwd
un pn N ILK
au il
tho kant AN
r ize @ T
d c rediff ESH
Path
op . WA
---- ies com R
all JA
C:\Webucator\Python\python-basics\Demos ow GT
ed AP
! .

On a Mac, it will look something like this:

natdunn@NatsMac Demos % pwd


Th
sd i
/Users/natdunn/Documents/Webucator/Python/python-basics/Demos
o cu
men
tb
elo
n
No agta gs to
j
5. Run cd .. to back
un uppto the Npython-basics directory.
au nilka IL
tho nt@ KAN
riz TE
6. Type cd De and then press ed thereTab key.
SH On Windows, you should see something like this:
co diff.c
pie om WAR
sa JA
llo GT
we AP
PS …\Python\python-basics> cd .\Demos\ d! .

The “.” at the beginning of the path represents the current (or present) directory. So, .\Demos refers to the
Demos directory within the current directory. A Mac won’t include the current directory in the path. When you
press Tab,
Th it will just fill out the rest of the folder name.
is
do
cu
cd Demos me
nt
be
lon
N ja g gs
Press Enter to run the command. Then run cd .. to move back up to the python-basics directory.

7. Each of our lesson folders will contain Demos, Exercises, and Solutions folders. Some may contain
additional folders. To see the contents of the current directory, run dir on Windows or ls on Mac/Linux: 3

Windows PowerShell
PS …\Python\python-basics> dir
Th
is
do
cu
me C:\Webucator\Python\python-basics
Directory:n tb
elo
n
No jagta gs to
Mode un p LastWriteTime
NI Length Name
au nilka L
---- nt@ KAN
tho ------------- ------ ----
riz red TES
ed H
co 6:13 if
d----- 2/18/2020 pie f.comAMWAR data
d----- 2/18/2020
s all AM
6:13 JA Demos
ow GT
ed AP
d----- 2/18/2020 5:09 AM ! . Exercises
d----- 2/18/2020 6:13 AM Solutions

Mac Terminal
NatsMac:python-basics natdunn$ ls
T
Demos his Exercises Solutions data
do
cu
m en
tb
elo
n
j gta gs to directories using the cd command until you feel comfortable navigating the
No abetween
8. Play with switching
un pn NI
terminal. au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
Visual Studio Shortcut l lo GT
we AP
d! .
Visual Studio provides a shortcut for opening a specific directory at the terminal. Simply right-click on the directory
in the Explorer panel and select Open in Terminal:

Th
is
do
cu
m en
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

Running Python

Python runs on Microsoft Windows, Mac OS X, Linux, and other Unix-like systems. The first thing to do is to make
Th a recent version of Python installed:
sure you have is
do
cu
me
nt
1. Open the terminal in beVisual Studio Code.
lon
N ja g gs
2. Run python -V:

PS C:\Webucator\Python> python -V
Python 3.8.1

Th
is
do
If you have Python c3.6
um or later, you are all set.
en
tb
elo
ng
If you do not have Python No jagt3.6 ors later installed, download it for free at https://www.python.org/downloads.
un a pn to NI
After running through the ilka run
auinstaller, LKpython -V at the terminal again to make sure Python installed correctly.
tho n A
riz t@re NTE
ed d SH
co if
pie f.com WAR
Python Versions on Macs sa JA
llo GT
we AP
d!
Your Mac will likely have a version of Python 2 already installed. After you .install Python 3, you may find that running python -V still shows the
Python 2 version. In that case, try running python3 -V. That should output the version of Python 3 that you have. If it does, then you should use
the python3 command instead of the python command to run Python 3.
If you would prefer to be able to use the python command for Python 3 (and who wouldn’t), visit
https://www.webucator.com/blog/2020/02/mapping-python-to-python-3-on-your-mac/ to see how you can map python to
python3.

Th
is
oc d
Python Interactive
um Shell
en
tb
elo
You can run Python in Interactive Mode by running python at the terminal:
n
No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .

Th
is
This will open updothe
cu Python shell, at which you can run Python commands. For example, to print out “Hello,
m
world!”, you would run:ent b
elo
n
No jagta gs to
un pn NI
au il LK
tho kant
print('Hello, world!') riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

Th
is
do
cu
men
tb
elo
jag ng
N s
You can tell that you are at the Python prompt by the three right-angle brackets:

To exit the Python shell, run:

Th
is
exit() do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .

T
Now, you are hback
is
do at the regular prompt.
cu
me
nt
be
Running a Python lonFile
No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
riz TE
re be useful
While working at the Python shell ed can SH in some scenarios, you will often be writing Python files, so you can
co diff.c WA
save, re-run, and share your code. Let’s pie get omstarted R with a simple “Hello, world!” demo using your editor. We will
sa JA
open a script, which is simply a file with a .py l lo GT that contains Python code. After the demonstration, you
we extension AP
d!
will add another line of code to the script in an exercise. .

Here is the script we are going to run:

Demo 1: python-basics/Demos/hello_world.py
Th
is
do
cu
me
1. # Say Hello to nt the World
be
2. print("Hello, jaworld!") lon
No gta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
Code Explanation co diff.c
pie om WAR
sa JA
llo GT
we AP
The print() function simply outputs contentd! either to standard . output (e.g., the terminal) or to a file if specified.

To run this code:

1. Open the terminal at python-basics/Demos.


Th
is
Run python
2. do hello_world.py
cu
me
n
3. The “Hello, world!” tmessage
be
lon will be displayed.
N ja g g s
Here it is in the terminal:

Th
is
do
Right-click and Run cu
m
en
tb
elo within Visual Studio Code is to right-click on the open file and select Run Python
Another way to run a file from
N jag ngs
File at Terminal: o u ta to
na pnilk NIL
uth an KA
ori t N
ze @red TES
dc
op iff.co HWA
ies m R
all JA
ow GT
ed AP
! .

Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

If you don’t see this option, then you don’t have the Python extension installed.
Th
is
do
cu
me
nt
Exercise 1: Hello, be
lon
world!
j
No agta g s
un pn to NI
au i l LK
tho kant
riz @ ANT
r ES
5 to 10 minutes ed c ediff
op .co HWA
ies m R
all JA
ow GT
ed AP
! .
1. Open python-basics/Demos/hello_world.py in your editor.

2. Add the following line after the “Hello, world!” line:

print("Hello
T again, world!")
his
do
cu
en m
tb
3. Save your changes. elon
N jag gs
4. Run the Python file just as you did earlier for the demonstration.

5. The output should look like this:

Hello, world!
Hello again, world!

Th
is
do
cu
men
tb
elo
Solution: python-basics/Solutions/hello_again_world.py
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
1. r
# Say Hello to theizWorld TE
re(twice!)
ed SH
co diff.c
2. print("Hello, world!") pie om WAR
sa JA
llo GT
3. print("Hello again, world!") we AP
d! .

Code Explanation

The extra line of code will cause a second message to be printed to the standard output.
Th
is
do
cu
Literals me
nt
be
lon
When a value is hard No agta into
coded
j gs an instruction, as "Hello" is in print("Hello"), that value is called a literal
p to
u
because the Python interpreter
na n shouldN not try to interpret it but should take it literally. If we left out the quotation
uth ilkan ILKA
t
ori Python NT output an error because it would not know how to interpret the name
marks (i.e., print(Hello)), ze @rewoulddif ESH
dc f
Hello. op . WA
ies com R
all JA
ow GT
ed AP
Either single quotes or double quotes can be used ! . string literals. Just make sure that the open and close
to create
quotation marks match.

Literals representing numbers (e.g., 42 and 3.14) are note enclosed in quotation marks.

Th
Python Comments
is
d oc
um
In the previous demo, eyou
nt may have noticed this line of code:
be
lon
No jagta gs to
un p NI
au nilka LK
t h ori n t AN
ze @red TES
# Say Hello to the World
dc
op iff.co HWA
ies m R
all JA
ow GT
That number sign (or hash or pound sign) indicates ed AP
a comment. Everything that trails it on the same line will be
! .
ignored.

Multi-line Comments
There is no official syntax for creating multi-line comments; however, Guido van Rossum, the creator of Python,
T 4
tweeted this htip
is as a workaround:
do
cu
me
nt
be
lon
N ja g gs
Th
is
do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
Multi-line strings are created with triples quotes,
all JA
like this:
ow GT
ed AP
! .

"""This is a
very very helpful and informative
comment about my code!"""
Th
is
do
cu
me generate no code, they can be used as pseudo-comments. In certain situations, these
Because multi-line strings
nt
b
pseudo-comments can geteconfused
lo with docstrings, which are used to auto-generate Python documentation, so
jag ngs
we recommend youNoavoidun
tusing
a p t o
themNI until you become familiar with docstrings. Instead, use:
au nilka LK
tho n A
riz t@re NTE
ed d SH
co if
pie f.com WAR
# This is a sa JA
llo GT
w AP
# very very helpful and informativeed! .
# comment about my code!

Data Types
T his
do
In Python programming,cu
me objects have different data types. The data type determines both what an object can do
and what can be done to nt it. For example, an object of the data type integer can be subtracted from another integer,
be
lon
but it cannot be subtracted
No jagtafrom gs a string of characters.
un pn to NI
au il LK
tho kant AN
In the following list, we showrthe @ data
ize basic TEtypes used in Python. Abbreviations are in parentheses.
dc re d S
op iff.co HWA
ies m R
all JA
1. boolean (bool) – A True or False value. ow GT
ed AP
! .

2. integer (int) – A whole number.

3. float (float) – A decimal.

4. string (str) – A sequence of Unicode 5 characters.


Th
is
do
5. list (list) – An cordered
um sequence of objects, similar to an array in other languages.
en
tb
elo
6. jag ngs of fixed length, in which an element’s position is meaningful.
tuple (tuple) –NA sequence
7. dictionary (dict) – An unordered grouping of key-value pairs.

8. set (set) – An unordered grouping of values.

We will cover all of these data types in detail.

Th
sd i
Exercise oc2: Exploring Types
um
en
tb
elo
n
No jagta gs to
un p NI
au nilka
10 to 15 minutes L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
s JA
In this exercise, you will use the built-in atype()
llo
we GT to explore different data types.
function
d! AP
.

1. Open the terminal.

2. Start the Python shell by typing python and then pressing Enter:

Th
is
PS …\python-basics\Demos> python
d oc
u
Python 3.8.1me(tags/v3.8.1:1b293b6,
nt Dec 18 2019, 23:11:46) [MSC v.1916 64 bit
be
(AMD64)] on win32 lon
jag
N gs
tap to
o u"copyright",
Type "help",
na n N "credits" or "license" for more information.
uth ilkan ILKA
>>> ori t N
ze @red TES
dc iff HW
op .
ies com AR
all JA
ow GT
You are now in the Python shell. ed AP
! .

3. To check the type of an object, use the type() function. For example, type(3) will return

<class 'int'>:

T
his
>>> type(3)
do
um c
<class 'int'> e nt
be
lon
No jagta gs to
un pn NI
auof the il L
4. Find the types of all tho kafollowing:
nt@ KAN
riz r e TE
ed SH
co diff.c
A. 3 pie om WAR
sa JA
llo GT
B. 3.1 we AP
d! .

C. '3'

D. 'pizza'

E. True
Th
is
do
F. ('1', c'2',
um
en '3')
tb
elo
G. ['1', N'2',jag'3'] ng
s
H. {'1', '2', '3'}

Solution

When you’re done, the output should appear as follows:

Th
s i
>>> type(3) doc
um
<class 'int'> en
t
be
lon
j gta gs to
>>> type(3.1) a
No
<class 'float'> una pnilk NIL
uth a K
>>> type('3') ori nt@ ANT
ze re d ES
dc
<class 'str'> op iff.co HWA
ies m R
all JA
>>> type('pizza') ow GT
ed AP
<class 'str'> ! .

>>> type(True)
<class 'bool'>
>>> type(('1', '2', '3'))
<class 'tuple'>
Th
is
>>> type(['1',d '2', '3'])
oc
um
<class 'list'> en
be t
lon
>>> type({'1', '2', '3'})
No agta gs to
j
<class 'set'> un pn N ILK
au il
tho kant
riz @ ANT
ed re ES
co diff.c H
p om WAR
Don’t worry if you’re not familiar withieall
s aof the preceding
JA data types. We will cover them all.
llo GT
we AP
d! .
Class and Type

You may wonder at Python’s use of the word "class" when outputting a data type. In Python, “class” and “type” mean the same thing.

VariablesT
his
do
Variables are used cto
umhold data in memory. In Python, variables are untyped, meaning you do not need to specify
en
the data type when creating t b the variable. You simply assign a value to a variable. Python determines the type by
elo
the value assigned.N jag ngs
ou ta to
na pnilk NIL
uth a K
ori nt@ ANT
Variable Names z ed re ES
co diff.c HW
pie o AR
sa m JA is different from Age. By convention, variable names are
Variable names are case sensitive, meaning llo that age GT
we AP
written in all lowercase letters and words in variable d! names . are separated by underscores (e.g., home_address).
Variable names must begin with a letter or an underscore and may contain only letters, digits, and underscores.

Keywords

The followingThlist
is of keywords have special meaning in Python and may not be used as variable names:
do
cu
me
Python Keywords nt bel
o
N jag ngs
and del if pass

as elif import raise

assert Th else in return


is
do
cu
men
tb
elo
n
async No jagta gs toexcept is True
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
await Falses al JA lambda try
low GT
ed AP
! .

break finally None while

Th
is
class do for nonlocal with
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il from LK
tho kant
continue not yield
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
def global d! .
or

Variable Assignment
There are three
Th parts to variable assignment:
is
do
cu
m
1. Variable name. ent b
elo
N jag ngs
ou
2. Assignment operator. ta to
na pnilk NIL
uth a K
ori nt@ ANT
3. Value assigned. This could z r
ed be any
e data ES type.
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

Th
is
do
cu
men
tb
elo
jag ng
N s
Here is the “Hello, world!” script again, but this time, instead of outputting a literal, we assign a string to a variable
and then output the variable:

Demo 2: python-basics/Demos/hello_variables.py

1. greeting = "Hello, world!"


2. print(greeting)
T his
do
cu
men
tb
Code Explanation elo
n
No jagta gs to
un pn
a ilk NILK
Run this Python file at theutterminal.
ho ant@The AN output will be the same as it was in the previous demo (see page 7):
riz red TES
ed H
co if
pie f.com WAR
sa JA
llo GT
Hello, world! wed AP
! .

Simultaneous Assignment
A very cool feature
Th of Python is that it allows for simultaneous assignment. The syntax is as follows:
is
do
cu
me
nt
be
lon
var_name1, var_name2 j
No agta= value1,gs value2
un pn to NI
au il LK
tho kant
riz @ ANT
e red E
This can be useful as a shortcutdfor iff. SHseveral
co assigning WA values at once, like this:
pie c o
sa m R
JA
llo GT
we AP
d! .
>>> first_name, last_name, company = "Nat", "Dunn", "Webucator"
>>> first_name
'Nat'
>>> last_name
'Dunn' Th
is
do
>>> company cu
men
'Webucator' tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c H
pie om WAR
Exercise 3: A Simple sPython
all Script
JA
GT
ow
ed AP
! .

5 to 10 minutes

Th you will write a simple Python script from scratch. The script will create a variable called today
In this exercise,
is
that stores the daydo of the week.
cu
me
nt
be
1. In your editor create ja alonew
ng file and save it as today.py in the python-basics/Exercises folder.
s
N g
2. Create a variable called today that holds the current day of the week as literal text (i.e., in quotes).

3. Use the print() function to output the variable value.

4. Save your changes.

5. Test your solution.

Th
is
do
cu
Solution: python-basics/Solutions/today.py
me
nt
be
lon
No ja gta gs to
1. today = "Monday"un p NI
au nilka L
2. print(today) tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
Constants
In programming, a constant is like a variable in that it is an identifier that holds a value, but, unlike variables,
constants are not variable, they are constant. Good name choices, right?

Th really have constants, but as a convention, variables that are meant to act like constants (i.e., their
Python doesn’tis
do
values are not meantcu to be changed) are written in all capital letters. For example:
me
nt
be
lon
No agta gs to
j
un p NI
PI = 3.141592653589793 au nilka L
tho nt@ KAN
r ize code Tfor red
d c rediff ESH
RED = "FF0000" # hexadecimal
op . WA
ies com R
all JA
ow GT
ed AP
! .
Deleting Variables
Although it’s rarely necessary to do so, variables can be deleted using the del statement, like this:

T
>>> a = 1 his d
oc
>>> print(a) um
e nt
be
1 lon
No jagta gs to
>>> del a un p NI
au nilka L
>>> print(a) tho nt@ KAN
riz red TES
ed H
co last):if
pie f.com WAR
Traceback (most recent call
File "<stdin>", line 1, in <module> s all JA
ow GT
NameError: name 'a' is not defined d! e AP
.

Notice that trying to print a results in an error, because after del a, the a variable no longer exists.

Writing aThPython
is
Module
do
cu
me
A Python module is simplynt a file that contains code that can be reused. The today.py file is really a module, albeit
a very simple one. A module be can be run by itself or as part of a larger program. It is too early to get into all the
lon
N ja g gs
aspects of code reuse and modular programming, but you want to start with good habits, one of which is to use a
main() function in your programs.

The main() Function


Let’s look at the basic syntax of a function. A function is created using the def keyword like this:

Th
Demo 3: python-basics/Demos/indent_demo.py
is
do
cu
me
nt
1. def main(): be
lon
N ja g gs
2. print("I o u am tapart
p tof
o the function.")
na
u
n ilka NILK
3. print("I am halso t ori npart t A
of N the function.")
ze @red TES
4. print("Hey, me too!") d co if H
pie f.com WAR
5. print("Sad not to be parts of all the JA
function. I've been outdented.")
ow GT
6. ed AP.
!
7. main()

Code Explanation
Th
is
do file will render the following:
Running this Python cu
me
nt
be
lon
No agta gs to
j
Sad not to be part un of pthe NI
function. I’ve been outdented.
au nilka LK
t h ori n t A N
ze @red TES
I am part of the function.
dc iff HW
I am also part of the function. op .
ies com AR
Hey, me too! all JA
ow GT
ed AP
! .

Notice that the first line of output is the line that is not part of the function. That is because the function does not run
until it is called, and it is called after the print() function that outputs “Sad not to be part of the function. I’ve been
outdented.”
Th
is
The code is readdoby
cuthe Python interpreter from top to bottom, but the function definition just defines the function; it
me
does not invoke the function
nt (programmer speak for “call the function to execute”).
be
lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .

Th
is
do
cu
men
tb
elo
jag ng
N s
pythontutor.com

Visit http://bit.ly/pythontutor-indentdemo to see this demo in pythontutor.com6, a web application for visualizing how Python
executes code.

Th
is
do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .

Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

Th
is
do
cu
en m
tb
A few things to note about efunctions:
lon
No agta gs to
j
un p NI
au nilka LK
t h n AN keyword. The content that follows the def keyword on the same line is
1. Functions are created ousing riz tthe@ def
r ed TES
ed
called the function signature.cop iff.c HW
ies om AR
all JA
o GT
2. The convention for naming functions wisedthe same as APthat for variables: use all lowercase letters and separate
! .
words with underscores.

3. In the function definition, the function name is followed by a pair of parentheses, which may contain
parameters (more on that soon), and a colon.

4. The contents
Th of the function starts on the next line and must be indented. Either spaces or tabs can be used
is
d
for indenting,ocbut
um spaces are preferred.
en
tb
5. The first line of code eafter
lo the function definition that is not indented is not part of the function and effectively
N jag ngs
marks the end of the function definition.
6. Functions are invoked using the function name followed by the parentheses (e.g., indent_demo()).

There is nothing magic about the name “main”. It is simply the name used by convention for the function that starts
the program or module running. 7

Grouping of Th Statements
is
do
cu
me
A programming statement is nat unit of code that does something. The following code shows two statements:
be
lon
greeting = "Hello!" No ja gta gs to
un p NI
print(greeting) au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
In Python, statements are grouped using indenting. pie omwe W
As ARsaw with the main() function, lines that are indented below the function signature
just
sa
are part of the function. It is important to understand llothis: changesJAinGindentation level denote code groups. You must be careful with your
we TA
indenting. d! P.

print() Function
You have already seen how to output data using the built-in print() function. Now, let’s see how to output a
variable and a literal string together. The print() function can take multiple arguments. By default, it will output
Th
them all separated
is by single spaces. For example, the following code will output "H e l l o !"
do
cu
me
nt
be
lon
jag 'l', g
print('H', 'e',No'l', tap s t'o',
o N '!')
un
au nilka ILK
tho n A
riz t@re NTE
ed d SH
co if
This functionality allows for the combinationpie f.comof W literal
AR strings and variables as shown in the following demo:
sa JA
llo GT
we AP
d! .
Demo 4: python-basics/Demos/variable_and_string_output.py

1. def main():
2. today = "Monday"
3. print("Today
T is", today, ".")
his
4. do
cu
men
5. main() tb
elo
n
No agta gs to
j
un pn
au ilka NILK
Code Explanation t h ori nt@ ANT
ze
d c rediff ESH
op . WA
ies com R
Run the Python file. It should render the alfollowing: JA
low GT
ed AP
! .

Today is Monday .

Notice the extra space before the period in the output of the last demo:
Th
is
do
cu
me
nt
be
lon
N ja g gs
We'll get rid of that soon.

Named Arguments
As we have seen with print(), functions can take multiple arguments. These arguments can be named or
unnamed. To illustrate, let’s look at some more arguments the print() function can take:

Th
is
d
oc 'l', 'l', 'o', '!', sep=' ', end='\n')
print('H', 'e', u me
nt
be
lon
No ja gta gs to
un are
Those last two arguments p NI arguments.
au nilnamed LK
tho kant
riz @ ANT
ed red E
iff. Sthe
sep is short for “separator.” cItopspecifies
HW
ies om c Acharacter
R
that separates the list of objects to output. The default
value is a single space, so specifying all sep=" " JAdoesn’t change the default behavior at all.
ow GT
ed AP
! .
end specifies the character to print at the very end (i.e., after the last printed object). The default is a newline
character (denoted with \n). You can use an empty string (e.g., '') to specify that nothing should be printed
at the end.

Th
is
The following demodo shows how the sep argument can be used to get rid of the extra space we saw in the previous
cu
me
example: nt
be
lon
No agta gs to
j
un p
Demo 5: python-basics/Demos/variable_and_string_output_fixed_spacing.py
NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
1. def main(): pie om WAR
sa JA
llo GT
2. today = "Monday" we AP
d! .
3. print("Today is ", today, ".", sep="")
4.
5. main()

Th
Code Explanation
is
do
cu
m en
tb
Run the Python file. It shouldelo render the following:
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c
Today is Monday. HW
pie o AR
sa m JA
llo GT
we AP
d! .
Collecting User Input
Functions may or may not return values. The print() function, for example, does not return a value.

Th a built-in input() function, which takes a single argument: the prompt for the user’s input. Unlike
Python provides
is
do
print(), the input() function does return a value: the input from the user as a string. The following demo shows
cu
m
how to use it to promptenthe user for the day of the week.
tb
elo
N jag ngs
Demo 6: python-basics/Demos/input.py
1. def main():
2. today = input("What day is it? ")
3. print("Wow! Today is ", today, "? Awesome!", sep="")
4.
5. main()

Th
is
Code Explanationdo
cu
en m
tb
Run the Python file. It shouldelo immediately prompt the user:
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
What day is it? co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
Enter the day and press Enter. It will output something like:

Wow! Today is Monday? Awesome!

Th
is
do
The full output will clook
um like this:
en
tb
elo
n
No agta gs to
j
un pn NI
au il LK
What day is it? Monday tho kant
riz @ ANT
ed re ES
co diff.c
Wow! Today is Monday? Awesome! HW
pie o AR
sa m JA
llo GT
we AP
d! .

Exercise 4: Hello, You!

T5hto 10 minutes
is
do
cu
me
nt
be
lon
In this exercise, you Nowilljagreet
gta gthe s user by name.
un pn to NI
au il LK
tho kant AN
1. Open a new script. Save riz it as@hello_you.py
red TES in python-basics/Exercises.
ed HW
co iff.
pie c om AR
2. Write code to prompt for the user’s s a name. JA
llo GT
we AP
d! .
3. After the user has entered their name, output a greeting.

4. Save your changes.

5. Test your solution.


Th
is
do
cu
me
nt
Solution: python-basics/Solutions/hello_you.py
be
lon
N ja g gs
1. def main():
2. your_name = input("What is your name? ")
3. print("Hello, ", your_name, "!", sep="")
4.
5. main()

Th
is
Code Explanationdo
cu
en m
tb
The code should work like ethis:
lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed
PS …\python-basics\Solutions> iff. SHWhello_you.py
co dpython
pie com AR
What is your name? Nat sa JA
llo GT
we AP
Hello, Nat! d! .

Reading from and Writing to Files


Th
To built-in open()
is method is used to open a file from the file system. We will cover this in the File Processing
d
lesson (see page o261).
cu For now, you just need to know how to read from a file and how to write to a file.
me
nt
be
lo
Reading from jag ngs
No a Filetap to
un NI
au nilka LK
tho n t@ to:ANT
The following code shows therizsteps re ES
ed
co diff.c HW
pie o AR
sa m
1. Open a file and assign the file to a file llo handler.JAG
we TA
d! P.
2. Read the content of the file into a variable.

3. Print that variable.

4. Close the file.


Th
is
do
cu
men
tb
elo
n
No agta g#s tOpen
j
f = open("my-file.txt")
oN
my-file.txt and assign result to f.
u p nil contents
content = f.read()na#u Read I LK of file into content variable.
tho kant AN
print(content) # Print ricontent.
ze @ T
d c rediff ESH
o . c WA
f.close() # Close the file. pie o
sa m R
JA
llo GT
we AP
d! .
Because we referenced the file name directly, Python will look in the current directory for the file. If the file is located
in a different directory, you must provide the path, either as an absolute or relative path. 8

with Blocks
Th
is close the file to free up the memory space the handler is taking up. It’s also easy to forget to do so.
It is important to do
c
Fortunately, Pythonuprovides
me a structure that makes explicitly closing the file unnecessary:
nt
be
lo
N jag ngs
with open("my-file.txt") as f:
content = f.read()
print(content)

When Python reaches the end of the with block, it understands that the file is no longer necessary and
automatically closes it.
Th
is
do
cu
Writing to a File me
nt
be
lon
In addition to the path ja
No to the gs the open() function takes a second parameter: mode, which indicates whether
gta file,
un pn to NI
the file is being opened afor ilka ("r"),
uthreading LK writing ("w"), or appending ("a"). The default value for mode is "r",
ori nt@ ANT
which is why we didn’t need tozepass rae valueESin when opening the file for reading. If we want to write to a file, we do
dc d
have to pass in a value: "w". op iff.co HWA
ies m R
all JA
ow GT
ed AP
! .
with open("my-file2.txt", "w") as f:
f.write("Hello, world!!!!!")

When you run Th the code above, it will open my-file2.txt if it exists and overwrite the file with the text you write to
is
it. If it doesn’t finddoa file named my-file2.txt, it will create it.
cu
me
nt
be
lon
No agta gs to
j
Exercise 5: un Working
p
au nilka
tho
NI with Files
L
nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
10 to 15 minutes we AP
d! .

In this exercise, you will open two files that contain lists of popular boys and girls names from 1880, 9 read their
contents into two variables, and then write the combined content of the two files into a new file.

T
1. Open a hnew
is script. Save it as files.py in python-basics/Exercises.
do
cu
me
2. Write code to open nt python-basics/data/1880-boys.txt and read its contents into a variable called
be
lon
boys. No jagta gs to
un p NI
au nilka LK
3. t h n AN
Write code to open python-basics/data/1880-girls.txt
ori t and read its contents into a variable called
ze @red TES
girls. dc iff. H
op WA
ies com R
all JA
4. Write code to open a new file namedow1880-all.txt GT in the python-basics/data folder and write the
ed AP
! .
combined contents of the boys and girls variables into the file. Note that you can combine the two strings
like this:

boys + "\n" + girls


Th
is
do
cu
me
That will place one ntnewline between the content in boys and the content in girls.
be
lon
ja g gs
5. Save your file.N
6. Test your solution. When you run it, it should create the new file. Look in the data folder for the 1880-
all.txt file. Does it exist? If so, open it up. Does it have a list of all the boys and girls names?

Run Python File in Terminal

You may have discovered that you can run Python files in the terminal using the green triangle in the upper-right of Visual Studio Code:
Th
is
do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz red TES
ed HW folder and search for any files being referenced with relative paths from that folder.
By default, VS Code will run the file from the iff.
co Workspace co root
pie errors. AR fix this by changing a setting:
As a result, you may get FileNotFoundError s a mYou can JA
llo GT
1. From the File menu, select Preferences > Settings. we AP
d! .
2. Search for “execute in file dir”.

3. Check the Python > Terminal: Execute in File Dir setting.

Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie
Solution: python-basics/Solutions/files.py o AR
sa m JA
llo GT
we AP
d! .
1. with open("../data/1880-boys.txt") as f_boys:
2. boys = f_boys.read()
3.
4. with open("../data/1880-girls.txt") as f_girls:
5. Th
girls = f_girls.read()
is
do
6. cu
me
7. nt
with open("../data/1880-all.txt", "w") as f:
b elo
8. N jag +ng"\n"
f.write(boys s + girls)
tap ou to
n na N
uth ilkan ILKA
ori t N
ze @red TES
dc iff. HW
op
ies com AR
Conclusion all
ow
JA
GT
ed AP
! .
In this lesson, you have begun to work with Python. Among other things, you have learned to use variables, to
output data, to collect user input, and to write simple Python functions and modules.

Th
1. is
https://pypl.github.io/PYPL.html
do
cu
me
nt
be
lon
N ja g gs
2. The generic term for the various terminals is command line shell
(https://en.wikipedia.org/wiki/Shell_(computing)). Visual Studio Code will select an
appropriate terminal for you. On Windows, that will most likely be Command Prompt or PowerShell. On a
Mac, it will most likely be bash or Zsh. The names “prompt,” “command prompt,” “shell,” and “terminal” are
used interchangeably.

3. The ls command works in Windows PowerShell as well.


Th
is
do
cu
me
nt
be
4. https://twitter.com/gvanrossum/status/112670605505077248?lang=en
lon
No ja gta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH handle text from most of the world’s languages.
5. Unicode is a 16-bit character coset dthat
iff. can
pie com WAR
sa JA
llo GT
we AP
d! .
6. http://www.pythontutor.com/visualize.html

7. Although only a convention, the name “main()” was not chosen arbitrarily. It is used because modules refer to
Th as “__main__”, so it seems fitting to get them started with a corresponding “main()” function.
themselvesis
do
cu
me
nt
be
lon
jagfrom g
8. Absolute paths Nostart tap sthe to top of the file system and work their way downwards towards the referenced file.
un nil NI
a
Relative paths startufrom L
ka current
tho the nt@ KAN location (the location of the file containing the path) and work their way to
the referenced file from ithatr ze location. T
d c rediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
! .
9. The lists of names come from https://www.ssa.gov/oact/babynames/.

Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .

Th
is
do
cu
men
tb
elo
jag ng
N s

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy