T H E I N T E R A C T I V E S H E L L

Similar documents
Invent Your Own Computer Games with Python

Learning the Language - V

Intro. Scheme Basics. scm> 5 5. scm>

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Text Input and Conditionals

Variables, expressions and statements

Programming with Python

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Chapter 1 Operations With Numbers

Math 25 and Maple 3 + 4;

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Implementing an Algorithm for Boomerang Fraction Sequences in Python

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

C: How to Program. Week /Mar/05

Decisions, Decisions. Testing, testing C H A P T E R 7

Unit 3. Operators. School of Science and Technology INTRODUCTION

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

Python for Non-programmers

Boolean Expressions. Is Equal and Is Not Equal

Boolean Expressions. Is Equal and Is Not Equal

This summary is located here:

Programming for Engineers Introduction to C

Section 1.1 Definitions and Properties

SAMLab Tip Sheet #1 Translating Mathematical Formulas Into Excel s Language

9. Elementary Algebraic and Transcendental Scalar Functions

Part 6b: The effect of scale on raster calculations mean local relief and slope

Divisibility Rules and Their Explanations

These are notes for the third lecture; if statements and loops.

Chapter 2 - Introduction to C Programming

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Programming Fundamentals and Python

The Dynamic Typing Interlude

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

C++ Reference NYU Digital Electronics Lab Fall 2016

Introduction. What is Max?

IT 374 C# and Applications/ IT695 C# Data Structures

Variables and. What Really Happens When You Run hello_world.py

Expressions, Statements, Variables, Assignments, Types

CSI Lab 02. Tuesday, January 21st

Introduction to TURING

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

Our Strategy for Learning Fortran 90

>>> * *(25**0.16) *10*(25**0.16)

Part II Composition of Functions

COPYRIGHTED MATERIAL. Dipping Your Toe into Python. Part I. Chapter 1: Programming Basics and Strings. Chapter 2: Numbers and Operators

Formatting & Style Examples

Formulas in Microsoft Excel

LOOPS. Repetition using the while statement

Section 0.3 The Order of Operations

Objective- Students will be able to use the Order of Operations to evaluate algebraic expressions. Evaluating Algebraic Expressions

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Lecture 3. Input, Output and Data Types

Civil Engineering Computation

Variables and Data Representation

Chapter 2, Part III Arithmetic Operators and Decision Making

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Excel Basics: Working with Spreadsheets

CMSC 201 Computer Science I for Majors

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

Intro to Python & Programming. C-START Python PD Workshop

Signed umbers. Sign/Magnitude otation

CS Summer 2013

Try typing the following in the Python shell and press return after each calculation. Write the answer the program displays next to the sums below.

Project 2: How Parentheses and the Order of Operations Impose Structure on Expressions

AN INTRODUCTION PROGRAMMING. Simon Long

Intermediate Algebra. Gregg Waterman Oregon Institute of Technology

Memory Addressing, Binary, and Hexadecimal Review

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Introduction to MATLAB

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

Algorithms and Programming I. Lecture#12 Spring 2015

Creating Custom Financial Statements Using

Python Games. Session 1 By Declan Fox

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

(I m not printing out these notes! Take your own.)

Section we will not cover section 2.11 feel free to read it on your own

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Functions and Decomposition

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

CS1 Lecture 3 Jan. 22, 2018

Add Subtract Multiply Divide

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Introduction to Python Programming

If Statements, For Loops, Functions

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

EXCEL BASICS: MICROSOFT OFFICE 2010

CCBC Math 081 Order of Operations Section 1.7. Step 2: Exponents and Roots Simplify any numbers being raised to a power and any numbers under the

(Python) Chapter 3: Repetition

Lab 6 Vectors and functions

Practical Programming, Third Edition

Introduction to Modern Fortran

Lecture 2: SML Basics

Lecture 4 CSE July 1992

CS102: Variables and Expressions

Transcription:

3 T H E I N T E R A C T I V E S H E L L The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform. Ada Lovelace, October 1842 Before you can write encryption programs, you need to learn some basic programming concepts. These concepts include values, operators, expressions, and variables. TOPICS COV E R E D IN T HIS CH A P T E R Operators Values Integers and floating-point numbers Expressions Evaluating expressions Storing values in variables Overwriting variables

Let s start by exploring how to use Python s interactive shell. Be sure to read this book next to your computer so you can enter the short code examples and see what they do. Developing muscle memory from typing programs will help you remember how Python code is constructed. Some Simple Math Start by opening IDLE (see Starting IDLE on page XX). You ll see the interactive shell and the cursor blinking next to the >>> prompt. The interactive shell can work just like a calculator. Type 2 + 2 into the shell and press ENTER on your keyboard. (On some keyboards, this is the RETURN key.) The computer should respond by displaying the number 4, as shown in Figure 3-1. Figure 3-1: Type 2 + 2 into the shell. By itself, 2 + 2 isn t a program; it s just a single instruction. Programs are made of many of these instructions. We ll start out by using the math instructions Python understands, which are summarized in Table 3-1. Table 3-1: Math Operators in Python Operator Operation + Addition - Subtraction * Multiplication / Division In the example in Figure 3-1, the + sign tells the computer to add the numbers 2 and 2, but Python can do other calculations as well, such as subtract numbers using the minus sign ( ), multiply numbers with an asterisk (*), or divide numbers with a forward slash (/). When used in this 2 Chapter 3

way, +, -, *, and / are called operators because they tell the computer to perform an operation on the numbers surrounding them. The 2s (or other numbers) are called values. Integers and Floating-Point Values In programming, whole numbers, such as 4, 0, and 99, are called integers. Numbers with decimal points (3.5, 42.1, and 5.0) are called floating-point numbers. In Python, the number 5 is an integer, but if you wrote it as 5.0, it would be a floating-point number. Every Value Has a Data Type Integers and floating points are data types. Every value has a data type. The value 42 is a value of the integer, or int, data type. The value 7.5 is a value of the floating point, or float, data type. You ll learn about a few other data types (such as strings in Chapter 4), but for now just remember that any time we talk about a value, that value is of a certain data type. It s usually easy to identify the data type just by looking at how the value is written. Ints are numbers without decimal points. Floats are numbers with decimal points. So 42 is an int, but 42.0 is a float. Expressions You ve already seen Python solve one math problem, but Python can do a lot more. Try typing the following math problems into the shell, pressing the ENTER key after each one: >>> 2+2+2+2+2 10 >>> 8*6 48 >>> 10-5+6 11 >>> 2 + 2 4 These math problems are called expressions. Computers can solve millions of these problems in seconds. Expressions are made up of values (the numbers) connected by operators (the math signs), as shown in Figure 3-2. You can have as many numbers in an expression as you want, as long as they re connected by operators; you can even use multiple types of operators in a single expression. You can also enter any number of spaces in between the integers and these operators. But be sure to always start an expression at the beginning of the line, with no spaces in Operator Value 2 + 2 Expression Value Figure 3-2: An expression is made up of values (like 2) and operators (like +). The Interactive Shell 3

front, because spaces at the beginning of a line change how Python interprets instructions. You ll learn more about spaces at the beginning of a line in Chapter 5. Order of Operations You might remember the phrase order of operations from your math class. For example, multiplication is done before addition. The expression 2 + 4 * 3 evaluates to 14 because multiplication is done first to evaluate 4 * 3, and then 2 is added. Parentheses can make different operators go first. In the expression (2 + 4) * 3, the addition is done first to evaluate (2 + 4), and then that sum is multiplied by 3. The parentheses make the expression evaluate to 18 instead of 14. The order of operations (also called precedence) of Python math operators is similar to that of mathematics. Operations inside parentheses are evaluated first; next the * and / operators are evaluated from left to right; then the + and - operators are evaluated from left to right. Evaluating Expressions When a computer solves the expression 10 + 5 and gets the value, we say it has evaluated the expression. Evaluating an expression reduces the expression to a single value, just like solving a math problem reduces the problem to a single number: the answer. An expression always evaluates (that is, reduces down to) a single value. The expressions 10 + 5 and 10 + 3 + 2 have the same value, because they both evaluate to. Even single values are considered expressions: the expression evaluates to the value. Python continues to evaluate an expression until it becomes a single value, as in the following: (5-1) * ((7 + 1) / (3-1)) 4 * ((7 + 1) / (3-1)) 4 * (( 8 ) / (3-1)) 4 * (( 8 ) / ( 2 )) 4 * 4.0 16.0 Python evaluates an expression starting with the innermost, leftmost parentheses. Even when parentheses are nested in each other, the parts of expressions inside them are evaluated with the same rules as any other expression. So when Python encounters ((7 + 1) / (3-1)), it first solves the expression in the leftmost inner parentheses, (7 + 1), and then solves the expression on the right, (3-1). When each expression in the inner parentheses is reduced to a single value, the expressions in the 4 Chapter 3

outer parentheses are then evaluated. Finally, when there are no more expressions in parentheses, Python performs any remaining calculations in the order of operations. In an expression, you can have two or more values connected by operators, or you can have just one value, but if you enter one value and an operator into the interactive shell, you ll get an error message: >>> 5 + SyntaxError: invalid syntax This error happens because 5 + is not an expression. Expressions with multiple values need operators to connect those values, and in the Python language the + operator expects to connect two values. A syntax error means that the computer doesn t understand the instruction you gave it because you typed it incorrectly. This may not seem important, but computer programming isn t just about telling the computer what to do it s also about knowing the correct way to give the computer instructions that it can follow. E R RORS A R E OK AY! It s perfectly fine to make errors! You won t break your computer by entering code that causes errors. Python will simply tell you an error has occurred and then display the >>> prompt again. You can continue entering new code into the interactive shell. Until you gain more programming experience, error messages might not make a lot of sense to you. However, you can always Google the error message text to find web pages that explain that specific error. You can also go to https://www.nostarch.com/crackingcodes/ to see a list of common Python error messages and their meanings. Storing Values with Variables Programs often need to save values to use later in the program. You can store values in variables. Think of a variable as a box that holds a value. You can store values inside variables using the = sign (called the assignment operator). For example, to store the value in a variable named spam, enter spam = into the shell: When you press ENTER, you won t see anything except a blank line in response. Unless you see an error message, you can assume that the instruction executed successfully. The next >>> prompt appears so you can enter the next instruction. The Interactive Shell 5

You can think of the variable like a box with the value inside it (as shown in Figure 3-3). The variable name spam is the label on the box (so we can tell one variable from another), and the value stored in it is like a note inside the box. This instruction with the = assignment operator (called an assignment statement) creates the variable spam and stores the value in it. Unlike expressions, statements are instructions that don t evaluate to any value; instead, they just perform an action. This is why no value is displayed on the next line in the shell. It might be confusing to know which instructions are expressions and which are statements. Just remember that if a Python instruction evaluates to a single value, it s an expression. If it doesn t, it s a statement. An assignment statement is written as a variable, followed by the = operator, followed by an expression, as shown in Figure 3-4. The value that the expression evaluates to is stored inside the variable. Equal sign Expression Variable name spam = 10 + 5 Assignment statement Figure 3-4: The parts of an assignment statement Keep in mind that variables store single values, not the expressions they are assigned. For example, if you enter the statement spam = 10 + 5, the expression 10 + 5 is first evaluated to and then the value is stored in the variable spam: >>> spam = 10 + 5 >>> spam To find out what the current value is inside a variable, enter the variable name into the shell: >>> spam spam Figure 3-3: Variables are like boxes with names that can hold values in them. 6 Chapter 3

The value is returned because a variable by itself is an expression that evaluates to the value stored in the variable. A value by itself is also an expression that evaluates to itself: >>> And here s an interesting twist. If you now enter spam + 5 into the shell, you ll get the integer 20: >>> spam + 5 20 This result may seem unexpected, but it makes sense because we set the value of spam to. Because the value of spam is, the expression spam + 5 evaluates to the expression + 5, which then evaluates to 20. Overwriting Variables You can change the value stored in a variable by entering another assignment statement. For example, enter the following: >>> spam + 5 20 >>> spam = 3 >>> spam + 5 8 The first time you enter spam + 5, the expression evaluates to 20 because you stored the value inside the variable spam. But when you enter spam = 3, the value is overwritten (that is, replaced) with the value 3, as shown in Figure 3-5. Now when you enter spam + 5, the expression evaluates to 8 because spam + 5 evaluates to 3 + 5. The old value in spam is forgotten. 3 spam Figure 3-5: The value in spam is overwritten by the value 3. The Interactive Shell 7

You can even use the value in the spam variable to assign spam a new value: >>> spam = spam + 5 >>> spam 20 The assignment statement spam = spam + 5 is like telling the computer that the new value of the spam variable is the current value of spam plus five. The variable on the left side of the = sign is assigned the value of the expression on the right side. You can keep increasing the value in spam by 5 several times: >>> spam = spam + 5 >>> spam = spam + 5 >>> spam = spam + 5 >>> spam 30 Variable Names Although the computer doesn t care what you name your variables, you should. Giving variables names that reflect what type of data they contain makes it easier to understand what a program does. You could give your variables names like abrahamlincoln or monkey even if your program had nothing to do with Abraham Lincoln or monkeys the computer would still run the program (as long as you consistently used abrahamlincoln or monkey). But when you return to a program after not seeing it for a long time, you might not remember what each variable does. Variable names (as well as everything else in Python) are case-sensitive. Case-sensitive means the same variable name in a different case is considered an entirely different variable. For example, spam, SPAM, Spam, and spam are considered four different variables in Python. They each can contain their own separate values and can t be used interchangeably. A good variable name describes the data it contains. Imagine that you moved to a new house and labeled all of your moving boxes as Stuff. You d never find anything! The variable names spam, eggs, bacon, and so on (inspired by the Monty Python Spam sketch) are used as generic names for the examples in this book and in much of Python s documentation, but in your programs, a descriptive name helps make your code more readable. 8 Chapter 3

Summary So when are we going to start hacking? Soon. But before you can hack ciphers, you need to learn a few more basic programming concepts. You won t need to learn a lot before you start writing encryption programs, but there s one more programming chapter you need to read. In this chapter, you learned the basics about writing Python instructions in the interactive shell. Python needs you to tell it exactly what to do in a strict way, because computers only understand very simple instructions. You learned that Python can evaluate expressions (that is, reduce the expression to a single value), and that expressions are values (such as 2 or 5) combined with operators (such as + or -). You also learned that you can store values inside variables so your program can remember them to use later on. The interactive shell is a useful tool for learning what Python instructions do because it lets you enter them one at a time and see the results. In the next chapter, you ll create programs that contain many instructions that are executed in sequence rather than one at a time. We ll discuss some more basic concepts, and you ll write your first program! Practice Questions Answers to the practice questions can be found on the book s website at https://www.nostarch.com/crackingcodes/. 1. Which is the operator for division, / or \? 2. Which of the following is an integer value, and which is a floating-point value? 42 3.1492 3. Which of the following lines are not expressions? 4 x 10 + 2 3 * 7 + 1 2 + 42 2 + 2 spam = 42 4. If you enter the following lines of code into the interactive shell, what do lines and print out? spam = 20 spam + 20 SPAM = 30 spam The Interactive Shell 9