[go: up one dir, main page]

0% found this document useful (0 votes)
25 views11 pages

Interactive Media

This document discusses integers, floating-point numbers, expressions, evaluating expressions, syntax errors, assignment statements, string values, string concatenation, operators, functions, and flow control statements in Python. It provides examples of integer and float values, expressions, evaluating expressions, syntax errors, assignment statements, string values, operators like + and *, functions like print() and input(), and flow control statements like if, for, and break. It also discusses topics like variable naming conventions, commenting code, the boolean data type, comparison operators, escape characters, and multiline strings.
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)
25 views11 pages

Interactive Media

This document discusses integers, floating-point numbers, expressions, evaluating expressions, syntax errors, assignment statements, string values, string concatenation, operators, functions, and flow control statements in Python. It provides examples of integer and float values, expressions, evaluating expressions, syntax errors, assignment statements, string values, operators like + and *, functions like print() and input(), and flow control statements like if, for, and break. It also discusses topics like variable naming conventions, commenting code, the boolean data type, comparison operators, escape characters, and multiline strings.
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/ 11

Integers and Floating-Point Numbers

Integers (or ints for short) are whole numbers such as 4, 99, and 0. Floating-point numbers (or floats for


short) are fractions or numbers with decimal points like 3.5, 42.1, and 5.0. In Python, 5 is an integer,
but 5.0 is a float. These numbers are called values. (Later we will learn about other kinds of values
besides numbers.) In the math problem you entered in the shell, 2 and 2 are integer values.

Expressions
The math problem 2 + 2 is an example of an expression. As Figure 1-2 shows, expressions are made up of
values (the numbers) connected by operators (the math signs) that produce a new value the code can use.
Computers can solve millions of expressions in seconds.

Evaluating Expressions

When a computer solves the expression 10 + 5 and returns the value 15, 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. For example, the expressions 10 + 5 and 10 + 3 +
2 both evaluate to 15.
When Python evaluates an expression, it follows an order of operations just like you do when you do
math. There are just a few rules:

• Parts of the expression inside parentheses are evaluated first.


• Multiplication and division are done before addition and subtraction.
• The evaluation is performed left to right.
Syntax Error
- Means Python doesn’t understand the instruction because you typed it incorrectly
Assignment Statement
- Will store a value inside a variable. Type a name for the variable, followed by the equal sign (=)
which is called the assignment operator, and then the value to store in the variable.
- Expressions evaluate to a single value
- Any other kind of instruction is a statement
String Values
- In Python, text values are called strings. String values can be used just like integer or float values.
You can store strings in variables. In code, string values start and end with a single quote, '.
String Concatenation
- You can combine string values with operators to make expressions, just as you did with integer
and float values. When you combine two strings with the + operator, it’s called string
concatenation.
+, -, *, / are called operators
// integer division
/ division
% modulus
PYTHON- high level, dynamic type, general purpose and interpreted programming language.
- Created by Guido Van Rossum and was first released to the public in 1991.
- Currently maintained by the Python Software Foundation (PSF).
TOP 15 POPULAR WEBSITES BUILT WITH PYTHON
Netflix Spotify
Google Reddit
Youtube Yahoo
Instagram Instacart
Uber Disqus
Pinterest Survey Monkey
Dropbox Bitly
Quora

FUNCTIONS
- Random integer/ randint
- Print
- Input
- String/ str
- Integer/ int
- Float

The step where Python is currently working in the program is called the execution. When the program
starts, the execution is at the first instruction. After executing the instruction, Python moves down to the
next instruction.

Any text following a hash mark (#) is a comment. Comments are the programmer’s notes about what the
code does; they are not written for Python but for you, the programmer. Python ignores comments when it
runs a program. Programmers usually put a comment at the top of their code to give their program a title.

Functions: Mini-Programs Inside Programs


- A function is kind of like a mini-program inside your program that contains several instructions
for Python to execute.
- A function call is an instruction that tells Python to run the code inside a function
A value between the parentheses in a function call is an argument.
When input() is called, the program waits for the user to enter text. The text string that the user enters
becomes the value that the function call evaluates to.
Comment- are the programmers notes about what the code does.
The End of the Program
Once the program executes the last line, it terminates or exits. This means the program stops running.
Python forgets all of the values stored in variables, including the string stored in myName.

Naming Variables
Variable names are case sensitive, which means the same variable name in a different case is considered a
different variable.
Capitalizing your variables this way is called camel case (because it resembles the humps on a camel’s
back), and it makes your code more readable.
Flow Control Statement
- For, if, else, break
- Changes the flow of the program execution as it moves around your program.
- Always has a colon (:) after the condition. Statements that end with a colon expect a new block
on the next line.
- The if, for, and break statements are flow control statements that can make the execution skip
instructions, loop over instructions, or break out of loops. Function calls also change the flow of
execution by jumping to the instructions inside of a function.
Boolean Data type
- Has two values; true or false
- Boolean values must be entered with an uppercase T or F and the rest of the values name in
lowercase.
Comparison Operators
< less than
>greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to

Equal sign (=) used in assignment statements to store a value to a variable.


Double equal sign (==) used in expression to see whether two values are equal.

Checking for True or False with Conditions


A condition is an expression that combines two values with a comparison operator (such as < or >) and
evaluates to a Boolean value. A condition is just another name for an expression that evaluates
to True or False.
Default data type is string.
Backlash/ skip character
Lines indentation- additional spaces
Randint function- this function will come up with a random number for the player to guess.
Int() function- takes one argument and returns the arguments value as an integer.
Variable name- spam, egg, bacon
\'. (Note that \ is a backslash, and / is a forward slash.) This backslash tells you that the letter right
after it is an escape character. An escape character lets you print special characters that are difficult or
impossible to enter into the source code, such as the single quote in a string value that begins and ends
with single quotes.

Escape Characters
Escape character What is actually printed
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\n Newline
\t Tab

DRAGON REALM

In this game, the player is in a land full of dragons. The dragons all live in caves with their large piles of
collected treasure. Some dragons are friendly and share their treasure. Other dragons are hungry and eat
anyone who enters their cave. The player approaches two caves, one with a friendly dragon and the other
with a hungry dragon, but doesn’t know which dragon is in which cave. The player must choose between
the two.
The def statement defines a new function (in this case, the displayIntro() function), which you can
call later in the program.

Where to Put Function Definitions


A function’s def statement and def block must come before you call the function, just as you must assign
a value to a variable before you use that variable. If you put the function call before the function
definition, you’ll get an error.

Multiline Strings

So far, all of the strings in our print() function calls have been on one line and have had one quote
character at the start and end. However, if you use three quotes at the start and end of a string, then it can
go across several lines. These are multiline strings.

The and Operator


The and operator in Python also requires the whole Boolean expression to be True or False. If the
Boolean values on both sides of the and keyword are True, then the expression evaluates to True. If either
or both of the Boolean values are False, then the expression evaluates to False.
The and Operator’s Truth Table
A and B Evaluates to
True and True True
True and False False
False and True False
False and False False

The or Operator
The or operator is similar to the and operator, except it evaluates to True if either of the two Boolean
values is True. The only time the or operator evaluates to False is if both of the Boolean values are False.

The or Operator’s Truth Table


A or B Evaluates to
True or True True
True or False True
False or True True
False or False False

The not Operator


Instead of combining two values, the not operator works on only one value. The not operator evaluates to
the opposite Boolean value: True expressions evaluate to False, and False expressions evaluate to True.

The not Operator’s Truth Table


not A Evaluates to
not True False
not False True

Function Parameters
Notice the text chosenCave between the parentheses. This is a parameter: a local variable that is used
by the function’s code. When the function is called, the call’s arguments are the values assigned to the
parameters.
The len() function returns an integer indicating how many characters are in the string passed to it. In this
case, it tells us that the string 'Hello' has 5 characters.
The time module has a function called sleep() that pauses the program.
These short pauses add suspense to the game instead of displaying the text all at once.

Types of Bugs
Syntax errors This type of bug comes from typos. When the Python interpreter sees a syntax error,
it’s because your code isn’t written in proper Python language. A Python program with even a single
syntax error won’t run.
Runtime errors These are bugs that happen while the program is running. The program will work
up until it reaches the line of code with the error, and then the program will terminate with an error
message (this is called crashing). The Python interpreter will display a traceback: an error message
showing the line containing the problem.
Semantic errors These bugs—which are the trickiest to fix—don’t crash the program, but they
prevent the program from doing what the programmer intended it to do. For example, if the
programmer wants the variable total to be the sum of the values in variables a, b, and c but
writes total = a * b * c, then the value in total will be wrong. This could crash the program later on,
but it won’t be immediately obvious where the semantic bug happened.

The Debugger

It can be hard to figure out the source of a bug because the lines of code are executed quickly and the
values in variables change so often. A debugger is a program that lets you step through your code one line
at a time in the same order that Python executes each instruction. The debugger also shows you what
values are stored in variables at each step.

Globals Area

The Globals area in the Debug Control window is where all the global variables are displayed.
Remember, global variables are variables created outside of any functions (that is, in the global scope).

Locals Area

In addition to the Globals area, there is a Locals area, which shows you the local scope variables and their
values. The Locals area will contain variables only when the program execution is inside of a function.
When the execution is in the global scope, this area is blank.

The Go and Quit Buttons

If you get tired of clicking the Step button repeatedly and just want the program to run normally, click the
Go button at the top of the Debug Control window. This will tell the program to run normally instead of
stepping.
Go Executes the rest of the code as normal, or until it reaches a breakpoint (see “Setting
Breakpoints” on page 73).
Step Executes one instruction or one step. If the line is a function call, the debugger will step into
the function.
Over Executes one instruction or one step. If the line is a function call, the debugger won’t step
into the function but instead will step over the call.
Out Keeps stepping over lines of code until the debugger leaves the function it was in when Out was
clicked. This steps out of the function.
Quit Immediately terminates the program.
HANGMAN
Hangman is a game for two people in which one player thinks of a word and then draws a blank line on
the page for each letter in the word. The second player then tries to guess letters that might be in the word.
If the second player guesses the letter correctly, the first player writes the letter in the proper blank.
But if the second player guesses incorrectly, the first player draws a single body part of a hanging man.
The second player has to guess all the letters in the word before the hanging man is completely drawn to
win the game.

Accessing Items with Indexes


You can access an item inside a list by adding square brackets to the end of the list variable with a
number between them. The number between the square brackets is the index. In Python, the index of the
first item in a list is 0. The second item is at index 1, the third item is at index 2, and so on. Because the
indexes begin at 0 and not 1, we say that Python lists are zero indexed.

List Concatenation
You can join several lists into one list using the + operator, just as you can with strings. Doing so is
called list concatenation.

The in Operator
The in operator can tell you whether a value is in a list or not. Expressions that use the in operator
return a Boolean value: True if the value is in the list and False if it isn’t.

Calling Methods

A method is a function attached to a value. To call a method, you must attach it to a specific value using a
period. Python has many useful methods, and we’ll use some of them in the Hangman program.

The reverse() and append() List Methods


The list data type has a couple of methods you’ll probably use a lot: reverse() and append().
The reverse() method will reverse the order of the items in the list. Try entering spam = [1, 2, 3, 4, 5, 6,
'meow', 'woof'], and then spam.reverse() to reverse the list. Then enter spam to view the contents of the
variable.
The most common list method you’ll use is append(). This method will add the value you pass as an
argument to the end of the list.

The split() String Method


The string data type has a split() method, which returns a list of strings made from a string that has
been split.

Displaying the Board to the Player


This code defines a new function named displayBoard(). This function has three parameters:

missedLetters A string of the letters the player has guessed that are not in the secret word
correctLetters A string of the letters the player has guessed that are in the secret word
secretWord A string of the secret word that the player is trying to guess

The list() and range() Functions


When called with one argument, range() will return a range object of integers from 0 up to (but not
including) the argument. This range object is used in for loops but can also be converted to the more
familiar list data type with the list() function.
The list() function is similar to the str() or int() functions. It takes the value it’s passed and returns a list.
It’s easy to generate huge lists with the range() function.

List and String Slicing


List slicing creates a new list value using a subset of another list’s items. To slice a list, specify two
indexes (the beginning and end) with a colon in the square brackets after the list name. For example, enter
the following into the interactive shell:

>>> spam = ['apples', 'bananas', 'carrots', 'dates']


>>> spam[1:3]
['bananas', 'carrots']

Getting the Player’s Guess

The getGuess() function will be called so that the player can enter a letter to guess. The function returns
the letter the player guessed as a string. Further, getGuess() will make sure that the player types a valid
letter before it returns from the function.

elif Statements
The next part of the Hangman program uses elif statements. You can think of elif or “else-if” statements
as saying, “If this is true, do this. Or else if this next condition is true, do that. Or else if none of them is
true, do this last thing.”

Review of the Hangman Functions


getRandomWord(wordList) Takes a list of strings passed to it and returns one string from it. That
is how a word is chosen for the player to guess.
displayBoard(missedLetters, correctLetters, secretWord) Shows the current state of the board,
including how much of the secret word the player has guessed so far and the wrong letters the player
has guessed. This function needs three parameters passed to it to work
correctly. correctLetters and missedLetters are strings made up of the letters that the player has
guessed that are in and not in the secret word, respectively. And secretWord is the secret word the
player is trying to guess. This function has no return value.
getGuess(alreadyGuessed) Takes a string of letters the player has already guessed and will keep
asking the player for a letter that isn’t in alreadyGuessed. This function returns the string of the valid
letter the player guessed.
playAgain() Asks if the player wants to play another round of Hangman. This function
returns True if the player does, False if they don’t.

The values between the curly brackets are key-value pairs. The keys are on the left of the colon and
the key’s values are on the right. You can access the values like items in lists by using the key. To see an
example, enter the following into the interactive shell:
>>> spam = {'hello':'Hello there, how are you?', 4:'bacon', 'eggs':9999}
>>> spam['hello']
'Hello there, how are you?'
>>> spam[4]
'bacon'
>>> spam['eggs']
9999

The Difference Between Dictionaries and Lists


One difference between dictionaries and lists is that dictionaries can have keys of any data type, as you’ve
seen. But remember, because 0 and '0' are different values, they will be different keys.

>>> spam = {'0':'a string', 0:'an integer'}


>>> spam[0]
'an integer'
>>> spam['0']
'a string'

The keys() and values() Dictionary Methods


Dictionaries have two useful methods, keys() and values(). These will return values of a type
called dict_keys and dict_values, respectively. Much like range objects, list forms of those data types are
returned by list().

>>> favorites = {'fruit':'apples', 'animal':'cats', 'number':42}


>>> list(favorites.keys())
['fruit', 'number', 'animal']
>>> list(favorites.values())
['apples', 42, 'cats']

Randomly Choosing from a List

The choice() function in the random module takes a list argument and returns a random value from it.
This is similar to what the previous getRandomWord() function did. You’ll use choice() in the new
version of the getRandomWord() function.

>>> import random
>>> random.choice(['cat', 'dog', 'mouse'])
'mouse'
>>> random.choice(['cat', 'dog', 'mouse'])
'cat'

Deleting Items from Lists

A del statement will delete an item at a certain index from a list. Because del is a statement, not a function
or an operator, it doesn’t have parentheses or evaluate to a return value.

>>> animals = ['aardvark', 'anteater', 'antelope', 'albert']


>>> del animals[1]
>>> animals
['aardvark', 'antelope', 'albert']

Multiple Assignment

Multiple assignment is a shortcut to assign multiple variables in one line of code. To use multiple
assignment, separate your variables with commas and assign them to a list of values.

>>> spam, eggs, ham = ['apples', 'cats', 42]


>>> spam
'apples'
>>> eggs
'cats'
>>> ham
42

TICTACTOE

This chapter features a Tic-Tac-Toe game. Tic-Tac-Toe is normally played with two people. One player
is X and the other player is O. Players take turns placing their X or O. If a player gets three of their marks
on the board in a row, column, or diagonal, they win. When the board fills up with neither player
winning, the game ends in a draw.

The None Value

The None value represents the lack of a value. None is the only value of the data type NoneType. You
might use the None value when you need a value that means “does not exist” or “none of the above.”
THE BAGELS DEDUCTION GAME

Bagels is a deduction game in which the player tries to guess a random three-digit number (with no
repeating digits) generated by the computer. After each guess, the computer gives the player three types
of clues:

Bagels None of the three digits guessed is in the secret number.


Pico One of the digits is in the secret number, but the guess has the digit in the wrong place.
Fermi The guess has a correct digit in the correct place.

Changing List Item Order with the random.shuffle() Function


The random.shuffle() function randomly changes the order of a list’s items (in this case, the list of digits).
This function doesn’t return a value but rather modifies the list you pass it in place.

String Interpolation

String interpolation, also known as string formatting, is a coding shortcut. Normally, if you want to use
the string values inside variables in another string, you have to use the + concatenation operator:

>>> name = 'Alice'
>>> event = 'party'
>>> location = 'the pool'
>>> day = 'Saturday'
>>> time = '6:00pm'
>>> print('Hello, ' + name + '. Will you go to the ' + event + ' at ' +
location + ' this ' + day + ' at ' + time + '?')
Hello, Alice. Will you go to the party at the pool this Saturday at 6:00pm?

SONAR TREASURE HUNT


In this chapter’s game, the player drops sonar devices at various places in the ocean to locate sunken
treasure chests. Sonar is a technology that ships use to locate objects under the sea. The sonar devices in
this game tell the player how far away the closest treasure chest is, but not in what direction. But by
placing multiple sonar devices, the player can figure out the location of the treasure chest.
CAESAR CIPHER

Because this program manipulates text to convert it into secret messages, you’ll learn several new
functions and methods for manipulating strings. You’ll also learn how programs can do math with text
strings just as they can with numbers.

Cryptography and Encryption

The science of writing secret codes is called cryptography. For thousands of years, cryptography has
made it possible to send secret messages that only the sender and recipient could read, even if someone
captured the messenger and read the coded message. A secret code system is called a cipher. The cipher
used by the program in this chapter is called the Caesar cipher.

Encrypting or Decrypting the Message


mode This sets the function to encryption mode or decryption mode.
message This is the plaintext (or ciphertext) to be encrypted (or decrypted).
key This is the key that is used in this cipher.

You might also like