- Beginning Python Programming for Aspiring Web Developers »
- 2. Values, expressions, and statements

2. Values, expressions, and statements ¶
2.1. programs and data ¶.
We can restate our previous definition of a computer program colloquially:
A computer program is a step-by-step set of instructions to tell a computer to do things to stuff .
We will be spending the rest of this book deepening and refining our understanding of exactly what kinds of things a computer can do . Your ability to program a computer effectively will depend in large part on your ability to understand these things well, so that you can express what you want to accomplish in a language the computer can execute .
Before we get to that, however, we need to talk about the stuff on which computers operate.
Computer programs operate on data . A single piece of data can be called a datum, but we will use the related term, value .
A value is one of the fundamental things — like a letter or a number — that a program manipulates. The values we have seen so far are 4 (the result when we added 2 + 2 ), and "Hello, World!" .
Values are grouped into different data types or classes .
At the level of the hardware of the machine, all values are stored as a sequence of bits , usually represented by the digits 0 and 1 . All computer data types, whether they be numbers, text, images, sounds, or anything else, ultimately reduce to an interpretation of these bit patterns by the computer.
Thankfully, high-level languages like Python give us flexible, high-level data types which abstract away the tedious details of all these bits and better fit our human brains.
4 is an integer , and "Hello, World!" is a string , so-called because it contains a string of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.
If you are not sure what class a value falls into, Python has a function called type which can tell you.
Not surprisingly, strings belong to the class str and integers belong to the class int . Less obviously, numbers with a point between their whole number and fractional parts belong to a class called float , because these numbers are represented in a format called floating-point . At this stage, you can treat the words class and type interchangeably. We’ll come back to a deeper understanding of what a class is in later chapters.
What about values like "17" and "3.2" ? They look like numbers, but they are in quotation marks like strings.
They are strings!
Don’t use commas in int s
When you type a large integer, you might be tempted to use commas between groups of three digits, as in 42,000 . This is not a legal integer in Python, but it does mean something else, which is legal:
Well, that’s not what we expected at all! Because of the comma, Python treats this as a pair of values in a tuple . So, remember not to put commas or spaces in your integers. Also revisit what we said in the previous chapter: formal languages are strict, the notation is concise, and even the smallest change might mean something quite different from what you intended.
2.2. Three ways to write strings ¶
Strings in Python can be enclosed in either single quotes ( ' ) or double quotes ( " ), or three of each ( ''' or """ )
Double quoted strings can contain single quotes inside them, as in "Bruce's beard" , and single quoted strings can have double quotes inside them, as in 'The knights who say "Ni!"' .
Strings enclosed with three occurrences of either quote symbol are called triple quoted strings. They can contain either single or double quotes:
Triple quoted strings can even span multiple lines:
Python doesn’t care whether you use single or double quotes or the three-of-a-kind quotes to surround your strings: once it has parsed the text of your program or command, the way it stores the value is identical in all cases, and the surrounding quotes are not part of the value. But when the interpreter wants to display a string, it has to decide which quotes to use to make it look like a string.
So the Python language designers chose to usually surround their strings by single quotes. What do think would happen if the string already contained single quotes? Try it for yourself and see.
2.3. String literals and escape sequences ¶
A literal is a notation for representing a constant value of a built-in data type.
In string literals , most characters represent themselves, so if we want the literal with letters s-t-r-i-n-g , we simply write 'string' .
But what if we want to represent the literal for a linefeed (what you get when you press the <Enter> key on the keyboard), or a tab? These string literals are not printable the way an s or a t is. To solve this problem Python uses an escape sequence to represent these string literals.
There are several of these escape sequences that are helpful to know.
\n is the most frequently used of these. The following example will hopefully make what it does clear.
2.4. Names and assignment statements ¶
In order to write programs that do things to the stuff we now call values , we need a way to store our values in the memory of the computer and to name them for later retrieval.
We use Python’s assignment statement for just this purpose:
The example above makes three assignments. The first assigns the string value "What's up, Doc?" to the name message . The second gives the integer 17 the name n , and the third assigns the floating-point number 3.14159 the name pi .
Assignment statements create names and associate these names with values. The values can then be retrieved from the computer’s memory by refering to the name associated with them.
Names are also called variables , since the values to which they refer can change during the execution of the program. Variables also have types. Again, we can ask the interpreter what they are.
The type of a variable is the type of the value it currently refers to.
A common way to represent variables on paper is to write the name of the variable with a line connecting it with its current value. This kind of figure is called an object diagram . It shows the state of the variables at a particular instant in time.
This diagram shows the result of executing the previous assignment statements:

2.5. Variables are variable ¶
We use variables in a program to “remember” things, like the current score at the football game. But variables are variable . This means they can change over time, just like the scoreboard at a football game. You can assign a value to a variable, and later assign a different value to the same variable.
This is different from math. In math, if you give x the value 3, it cannot change to link to a different value half-way through your calculations!
You’ll notice we changed the value of day three times, and on the third assignment we even gave it a value that was of a different type.
A great deal of programming is about having the computer remember things, like assigning a variable to the number of missed calls on your phone, and then arranging to update the variable when you miss another call.
In the Python shell, entering a name at the prompt causes the interpreter to look up the value associated with the name (or return an error message if the name is not defined), and to display it. In a script, a defined name not in a print function call does not display at all.
2.6. The assignment operator is not an equal sign! ¶
The semantics of the assignment statement can be confusing to beginning programmers, especially since the assignment token , = can be easily confused with the with equals (Python uses the token == for equals, as we will see soon). It is not!
The middle statement above would be impossible if = meant equals, since n could never be equal to n + 1 . This statement is perfectly legal Python, however. The assignment statement links a name , on the left hand side of the operator, with a value , on the right hand side.
The two n s in n = n + 1 have different meanings: the n on the right is a memory look-up that is replaced by a value when the right hand side is evaluated by the Python interpreter. It has to already exist or a name error will result. The right hand side of the assignment statement is evaluated first.
The n on the left is the name given to the new value computed on the right hand side as it is stored in the computer’s memory. It does not have to exist previously, since it will be added to the running program’s available names if it isn’t there already.
Names in Python exist within a context, called a namespace , which we will discuss later in the book.
The left hand side of the assignment statement does have to be a valid Python variable name. This is why you will get an error if you enter:
When reading or writing code, say to yourself “n is assigned 17” or “n gets the value 17”. Don’t say “n equals 17”.
In case you are wondering, a token is a character or string of characters that has syntactic meaning in a language. In Python operators , keywords , literals , and white space all form tokens in the language.
2.7. Variable names and keywords ¶
Valid variable names in Python must conform to the following three simple rules:
They are an arbitrarily long sequence of letters and digits.
The sequence must begin with a letter.
In addtion to a..z, and A..Z, the underscore ( _ ) is a letter.
Although it is legal to use uppercase letters, by convention we don’t. If you do, remember that case matters. day and Day would be different variables.
The underscore character ( _ ) can appear in a name. It is often used in names with multiple words, such as my_name or price_of_tea_in_china .
There are some situations in which names beginning with an underscore have special meaning, so a safe rule for beginners is to start all names with a letter other than the underscore.
If you give a variable an illegal name, you get a syntax error:
76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains an illegal character, the dollar sign. But what’s wrong with class ?
It turns out that class is one of the Python keywords . Keywords define the language’s syntax rules and structure, and they cannot be used as variable names.
Python 3 has thirty-three keywords (and every now and again improvements to Python introduce or eliminate one or two):
You might want to keep this list handy. Actually, as will often be the case when learning to program with Python, when you aren’t sure about something, you can ask Python :
The list of keywords, keyword.kwlist , comes to us, appropriately, in a Python list.
If the interpreter complains about one of your variable names and you don’t know why, see if it is on this list.
Programmers generally choose names for their variables that are meaningful to the human readers of the program — they help the programmer document, or remember, what the variable is used for.
Beginners sometimes confuse meaningful to the human readers with meaningful to the computer . So they’ll wrongly think that because they’ve called some variable average or pi , it will somehow automatically calculate an average, or automatically associate the variable pi with the value 3.14159. No! The computer doesn’t attach semantic meaning to your variable names. It is up to you to do that.
2.8. Statements and expressions ¶
A statement is an instruction that the Python interpreter can execute. We have seen two so far, the assignment statement and the import statement. Some other kinds of statements that we’ll see shortly are if statements, while statements, and for statements. (There are other kinds too!)
When you type a statement on the command line, Python executes it. The interpreter does not display any results.
An expression is a combination of values, variables, operators, and calls to functions. If you type an expression at the Python prompt, the interpreter evaluates it and displays the result, which is always a value :
In this example len is a built-in Python function that returns the number of characters in a string. We’ve previously seen the print and the type functions, so this is our third example of a function.
The evaluation of an expression produces a value, which is why expressions can appear on the right hand side of assignment statements. A value all by itself is a simple expression, and so is a variable.
2.9. Operators and operands ¶
Operators are special tokens that represent computations like addition, multiplication and division. The values the operator uses are called operands .
The following are all legal Python expressions whose meaning is more or less clear:
The tokens + and - , and the use of parenthesis for grouping, mean in Python what they mean in mathematics. The asterisk ( * ) is the token for multiplication, and ** is the token for exponentiation (raising a number to a power).
When a variable name appears in the place of an operand, it is replaced with its value before the operation is performed.
Addition, subtraction, multiplication, and exponentiation all do what you expect.
Example: so let us convert 645 minutes into hours:
Oops! In Python 3, the division operator / always yields a floating point result. What we might have wanted to know was how many whole hours there are, and how many minutes remain. Python gives us two different flavors of the division operator. The second, called integer division uses the token // . It always truncates its result down to the next smallest integer (to the left on the number line).
Take care that you choose the correct division operator. If you’re working with expressions where you need floating point values, use the division operator that does the division appropriately.
2.10. The modulus operator ¶
The modulus operator works on integers (and integer expressions) and gives the remainder when the first number is divided by the second. In Python, the modulus operator is a percent sign ( % ). The syntax is the same as for other operators:
So 7 divided by 3 is 2 with a remainder of 1.
The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another – if x % y is zero, then x is divisible by y .
Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.
It is also extremely useful for doing conversions, say from seconds, to hours, minutes and seconds. So let’s write a program to ask the user to enter some seconds, and we’ll convert them into hours, minutes, and remaining seconds.
2.11. Order of operations ¶
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence . Python follows the same precedence rules for its mathematical operators that mathematics does. The acronym PEMDAS is a useful way to remember the order of operations:
P arentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60 , even though it doesn’t change the result.
E xponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.
M ultiplication and both D ivision operators have the same precedence, which is higher than A ddition and S ubtraction, which also have the same precedence. So 2*3-1 yields 5 rather than 4, and 5-2*2 is 1, not 6. #. Operators with the same precedence are evaluated from left-to-right. In algebra we say they are left-associative . So in the expression 6-3+2 , the subtraction happens first, yielding 3. We then add 2 to get the result 5. If the operations had been evaluated from right to left, the result would have been 6-(3+2) , which is 1. (The acronym PEDMAS could mislead you to thinking that division has higher precedence than multiplication, and addition is done ahead of subtraction - don’t be misled. Subtraction and addition are at the same precedence, and the left-to-right rule applies.)
Due to some historical quirk, an exception to the left-to-right left-associative rule is the exponentiation operator ** , so a useful hint is to always use parentheses to force exactly the order you want when exponentiation is involved:
The immediate mode command prompt of Python is great for exploring and experimenting with expressions like this.
2.12. Operations on strings ¶
In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. The following are illegal (assuming that message has type string):
Interestingly, the + operator does work with strings, but for strings, the + operator represents concatenation , not addition. Concatenation means joining the two operands by linking them end-to-end. For example:
The output of this program is banana nut bread . The space before the word nut is part of the string, and is necessary to produce the space between the concatenated strings.
The * operator also works on strings; it performs repetition. For example, 'Fun' * 3 is 'FunFunFun' . One of the operands has to be a string; the other has to be an integer.
On one hand, this interpretation of + and * makes sense by analogy with addition and multiplication. Just as 4 * 3 is equivalent to 4 + 4 + 4 , we expect "Fun" * 3 to be the same as "Fun" + "Fun" + "Fun" , and it is. On the other hand, there is a significant way in which string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition and multiplication have that string concatenation and repetition do not?
2.13. Type converter functions ¶
Here we’ll look at three more Python functions, int , float and str , which will (attempt to) convert their arguments into types int , float and str respectively. We call these type converter functions.
The int function can take a floating point number or a string, and turn it into an int. For floating point numbers, it discards the fractional portion of the number - a process we call truncation towards zero on the number line. Let us see this in action:
The last case shows that a string has to be a syntactically legal number, otherwise you’ll get one of those pesky runtime errors.
The type converter float can turn an integer, a float, or a syntactically legal string into a float.
The type converter str turns its argument into a string:
2.14. Input ¶
There is a built-in function in Python for getting input from the user:
The user of the program can enter the name and press return . When this happens the text that has been entered is returned from the input function, and in this case assigned to the variable name .
The string value inside the parentheses is called a prompt and contains a message which will be displayed to the user when the statement is executed to prompt their response.
When a key is pressed on a keyboard a single character is sent to a keyboard buffer inside the computer. When the enter key is pressed, the sequence of characters inside the keyboard buffer in the order in which they were received are returned by the input function as a single string value.
Even if you asked the user to enter their age, you would get back a string like "17" . It would be your job, as the programmer, to convert that string into a int or a float, using the int or float converter functions we saw in the previous section, which leads us to …
2.15. Composition ¶
So far, we have looked at the elements of a program — variables, expressions, statements, and function calls — in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them into larger chunks.
For example, we know how to get the user to enter some input, we know how to convert the string we get into a float, we know how to write a complex expression, and we know how to print values. Let’s put these together in a small four-step program that asks the user to input a value for the radius of a circle, and then computes the area of the circle from the formula

Firstly, we’ll do the four steps one at a time:
Now let’s compose the first two lines into a single line of code, and compose the second two lines into another line of code.
If we really wanted to be tricky, we could write it all in one statement:
Such compact code may not be most understandable for humans, but it does illustrate how we can compose bigger chunks from our building blocks.
If you’re ever in doubt about whether to compose code or fragment it into smaller steps, try to make it as simple as you can for the human reader to follow.
2.16. More about the print function ¶
At the end of the previous chapter, you learned that the print function can take a series of arguments, seperated by commas, and that it prints a string with each argument in order seperated by a space.
In the example in the previous section of this chapter, you may have noticed that the arguments don’t have to be strings.
By default, print uses a single space as a seperator and a \n as a terminator (at the end of the string). Both of these defaults can be overridden.
You will explore these new features of the print function in the exercises.
2.17. Glossary ¶
A statement that assigns a value to a name (variable). To the left of the assignment operator, = , is a name. To the right of the assignment token is an expression which is evaluated by the Python interpreter and then assigned to the name. The difference between the left and right hand sides of the assignment statement is often confusing to new programmers. In the following assignment:
n plays a very different role on each side of the = . On the right it is a value and makes up part of the expression which will be evaluated by the Python interpreter before assigning it to the name on the left.
= is Python’s assignment token, which should not be confused with the mathematical comparison operator using the same symbol.
The ability to combine simple expressions and statements into compound statements and expressions in order to represent complex computations concisely.
To join two strings end-to-end.
A set of values. The type of a value determines how it can be used in expressions. So far, the types you have seen are integers ( int ), floating-point numbers ( float ), and strings ( str ).
A sequence of characters starting with the escape character ( \ ) used to represent string literals such as linefeeds and tabs.
To simplify an expression by performing the operations in order to yield a single value.
A combination of variables, operators, and values that represents a single result value.
A Python data type which stores floating-point numbers. Floating-point numbers are stored internally in two parts: a base and an exponent . When printed in the standard format, they look like decimal numbers. Beware of rounding errors when you use float s, and remember that they are only approximate values.
A Python data type that holds positive and negative whole numbers.
An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder.
A reserved word that is used by the compiler to parse program; you cannot use keywords like if , def , and while as variable names.
A notation for representing for representing a constant value of one of Python’s built-in types. \n , for example, is a literal representing the newline character.
An operator, denoted with a percent sign ( % ), that works on integers and yields the remainder when one number is divided by another.
A graphical representation of a set of variables (objects) and the values to which they refer, taken at a particular instant during the program’s execution.
One of the values on which an operator operates.
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.
An instruction that the Python interpreter can execute. So far we have only seen the assignment statement, but we will soon meet the import statement and the for statement.
A Python data type that holds a string of characters.
A string enclosed by either """ or ''' . Tripple quoted strings can span several lines.
A number, string, or any of the other things that can be stored in a variable or computed in an expression.
A name that refers to a value.
A name given to a variable. Variable names in Python consist of a sequence of letters (a..z, A..Z, and _) and digits (0..9) that begins with a letter. In best programming practice, variable names should be chosen so that they describe their use in the program, making the program self documenting .
2.18. Exercises ¶
Chapter 2 exercise set 0: Chapter Review
Chapter 2 exercise set 1
Chapter 2 exercise set 2
Computer Science final

Terms in this set (71)
Students also viewed, 2.1-2.10 ap-style mc practices & quizzes.

ap computer science test 1
Ap computer science principles unit 2 review….

Computer Science
Recent flashcard sets, a&p i final, polyatomic ions, effects of the autonomic nervous system on or….
Sets found in the same folder
Module 1.1-1.4, other sets by this creator, geomatics midterm 1, ce 203 geomatics, exam 2 prado, verified questions.
In a single-celled organism, mitosis is used for _______.
Are there any probability calculations that would be appropriate for rating an investment service? Why or why not?
(Conversion from kilograms to pounds and pounds to kilograms) Write a program that displays the following two tables side by side (note that 1 kilogram is 2.2 pounds and that 1 pound is .453 kilograms):
The amount of ozone in a mixture of gases can be determined by passing the mixture through an acidic aqueous solution of potassium iodide, where the ozone reacts according to
O 3 ( g ) + 3 I − ( a q ) + H 2 O ( l ) → O 2 ( g ) + I − 3 ( a q ) + 2 O H − ( a q ) O3(g) + 3 I^- (aq) + H2O(l)→O2(g) + I^-3(a q) + 2 OH^-(aq) O 3 ( g ) + 3 I − ( a q ) + H 2 O ( l ) → O 2 ( g ) + I − 3 ( a q ) + 2 O H − ( a q )
to form the triiodide ion I^- 3. The amount of triiodide produced is then determined by titrating with thiosulfate solution:
l − 3 ( a q ) + 2 S 2 O 2 − 3 ( a q ) → 3 I − ( a q ) + S 4 O 2 − 6 ( a q ) l^-3(aq) + 2 S2O^2-3 (aq) →3I^- (aq) + S4O^2-6 (aq) l − 3 ( a q ) + 2 S 2 O 2 − 3 ( a q ) → 3 I − ( a q ) + S 4 O 2 − 6 ( a q )
A small amount of starch solution is added as an indicator because it forms a deep-blue complex with the triiodide solution. Disappearance of the blue color thus signals the completion of the titration . Suppose 53.2 L of a gas mixture at a temperature of 18°C and a total pressure of 0.993 atm is passed through a solution of potassium iodide until the ozone in the mixture has reacted completely. The solution requires 26.2 mL of a 0.1359-M solution of thiosulfate ion to titrate to the endpoint. Calculate the mole fraction of ozone in the original gas sample.
Recommended textbook solutions

Information Technology Project Management: Providing Measurable Organizational Value

Introduction to Algorithms

Fundamentals of Database Systems
Other quizlet sets, mgsc exam2 pt2, p1 & p2 quiz 10.4.19.

A directory of Objective Type Questions covering all the Computer Science subjects. Here you can access and discuss Multiple choice questions and answers for various competitive exams and interviews.

Online Test
Take a quick online test
UGC NET MCQs
GATE CSE MCQs
Discussion Forum
Confused about the answer ask for details here, know explanation add it here, similar questions:, gate cse resources.
Questions from Previous year GATE question papers
UGC NET Computer science Resources
UGC NET Previous year questions and practice sets
NET General Paper 1
Gate cse online test.
Attempt a small test to analyze your preparation level. This GATE exam includes questions from previous year GATE papers.
UGC NET practice Test
Practice test for UGC NET Computer Science Paper. The questions asked in this NET practice paper are from various previous year papers.
- TOS and Privacy policy

- Python »
- 3.11.2 Documentation »
- The Python Tutorial »
- 3. An Informal Introduction to Python
3. An Informal Introduction to Python ¶
In the following examples, input and output are distinguished by the presence or absence of prompts ( >>> and … ): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.
You can toggle the display of prompts and output by clicking on >>> in the upper-right corner of an example box. If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter.
Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, # , and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.
Some examples:
3.1. Using Python as a Calculator ¶
Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>> . (It shouldn’t take long.)
3.1.1. Numbers ¶
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators + , - , * and / work just like in most other languages (for example, Pascal or C); parentheses ( () ) can be used for grouping. For example:
The integer numbers (e.g. 2 , 4 , 20 ) have type int , the ones with a fractional part (e.g. 5.0 , 1.6 ) have type float . We will see more about numeric types later in the tutorial.
Division ( / ) always returns a float. To do floor division and get an integer result you can use the // operator; to calculate the remainder you can use % :
With Python, it is possible to use the ** operator to calculate powers 1 :
The equal sign ( = ) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
In interactive mode, the last printed expression is assigned to the variable _ . This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.
In addition to int and float , Python supports other types of numbers, such as Decimal and Fraction . Python also has built-in support for complex numbers , and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j ).
3.1.2. Strings ¶
Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ( '...' ) or double quotes ( "..." ) with the same result 2 . \ can be used to escape quotes:
In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:
If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:
There is one subtle aspect to raw strings: a raw string may not end in an odd number of \ characters; see the FAQ entry for more information and workarounds.
String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...''' . End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:
produces the following output (note that the initial newline is not included):
Strings can be concatenated (glued together) with the + operator, and repeated with * :
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.
This feature is particularly useful when you want to break long strings:
This only works with two literals though, not with variables or expressions:
If you want to concatenate variables or a variable and a literal, use + :
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
Indices may also be negative numbers, to start counting from the right:
Note that since -0 is the same as 0, negative indices start from -1.
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s :
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n , for example:
The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j , respectively.
For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.
Attempting to use an index that is too large will result in an error:
However, out of range slice indexes are handled gracefully when used for slicing:
Python strings cannot be changed — they are immutable . Therefore, assigning to an indexed position in the string results in an error:
If you need a different string, you should create a new one:
The built-in function len() returns the length of a string:
Strings are examples of sequence types , and support the common operations supported by such types.
Strings support a large number of methods for basic transformations and searching.
String literals that have embedded expressions.
Information about string formatting with str.format() .
The old formatting operations invoked when strings are the left operand of the % operator are described in more detail here.
3.1.3. Lists ¶
Python knows a number of compound data types, used to group together other values. The most versatile is the list , which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
Like strings (and all other built-in sequence types), lists can be indexed and sliced:
All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:
Lists also support operations like concatenation:
Unlike strings, which are immutable , lists are a mutable type, i.e. it is possible to change their content:
You can also add new items at the end of the list, by using the append() method (we will see more about methods later):
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
The built-in function len() also applies to lists:
It is possible to nest lists (create lists containing other lists), for example:
3.2. First Steps Towards Programming ¶
Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:
This example introduces several new features.
The first line contains a multiple assignment : the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.
The while loop executes as long as the condition (here: a < 10 ) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).
The body of the loop is indented : indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.
The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:
The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:
Since ** has higher precedence than - , -3**2 will be interpreted as -(3**2) and thus result in -9 . To avoid this and get 9 , you can use (-3)**2 .
Unlike other languages, special characters such as \n have the same meaning with both single ( '...' ) and double ( "..." ) quotes. The only difference between the two is that within single quotes you don’t need to escape " (but you have to escape \' ) and vice versa.
Table of Contents
- 3.1.1. Numbers
- 3.1.2. Strings
- 3.1.3. Lists
- 3.2. First Steps Towards Programming
Previous topic
2. Using the Python Interpreter
4. More Control Flow Tools
- Report a Bug
- Show Source
- FR Français
- ID Indonesia
- IT Italiano
- UK Українська
We want to make this open-source project available for people all around the world.
Help to translate the content of this tutorial to your language!
- The JavaScript language
- JavaScript Fundamentals
Logical operators
There are four logical operators in JavaScript: || (OR), && (AND), ! (NOT), ?? (Nullish Coalescing). Here we cover the first three, the ?? operator is in the next article.
Although they are called “logical”, they can be applied to values of any type, not only boolean. Their result can also be of any type.
Let’s see the details.
The “OR” operator is represented with two vertical line symbols:
In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true , it returns true , otherwise it returns false .
In JavaScript, the operator is a little bit trickier and more powerful. But first, let’s see what happens with boolean values.
There are four possible logical combinations:
As we can see, the result is always true except for the case when both operands are false .
If an operand is not a boolean, it’s converted to a boolean for the evaluation.
For instance, the number 1 is treated as true , the number 0 as false :
Most of the time, OR || is used in an if statement to test if any of the given conditions is true .
For example:
We can pass more conditions:
OR "||" finds the first truthy value
The logic described above is somewhat classical. Now, let’s bring in the “extra” features of JavaScript.
The extended algorithm works as follows.
Given multiple OR’ed values:
The OR || operator does the following:
- Evaluates operands from left to right.
- For each operand, converts it to boolean. If the result is true , stops and returns the original value of that operand.
- If all operands have been evaluated (i.e. all were false ), returns the last operand.
A value is returned in its original form, without the conversion.
In other words, a chain of OR || returns the first truthy value or the last one if no truthy value is found.
For instance:
This leads to some interesting usage compared to a “pure, classical, boolean-only OR”.
Getting the first truthy value from a list of variables or expressions.
For instance, we have firstName , lastName and nickName variables, all optional (i.e. can be undefined or have falsy values).
Let’s use OR || to choose the one that has the data and show it (or "Anonymous" if nothing set):
If all variables were falsy, "Anonymous" would show up.
Short-circuit evaluation.
Another feature of OR || operator is the so-called “short-circuit” evaluation.
It means that || processes its arguments until the first truthy value is reached, and then the value is returned immediately, without even touching the other argument.
The importance of this feature becomes obvious if an operand isn’t just a value, but an expression with a side effect, such as a variable assignment or a function call.
In the example below, only the second message is printed:
In the first line, the OR || operator stops the evaluation immediately upon seeing true , so the alert isn’t run.
Sometimes, people use this feature to execute commands only if the condition on the left part is falsy.
&& (AND)
The AND operator is represented with two ampersands && :
In classical programming, AND returns true if both operands are truthy and false otherwise:
An example with if :
Just as with OR, any value is allowed as an operand of AND:
AND “&&” finds the first falsy value
Given multiple AND’ed values:
The AND && operator does the following:
- For each operand, converts it to a boolean. If the result is false , stops and returns the original value of that operand.
- If all operands have been evaluated (i.e. all were truthy), returns the last operand.
In other words, AND returns the first falsy value or the last value if none were found.
The rules above are similar to OR. The difference is that AND returns the first falsy value while OR returns the first truthy one.
We can also pass several values in a row. See how the first falsy one is returned:
When all values are truthy, the last value is returned:
The precedence of AND && operator is higher than OR || .
So the code a && b || c && d is essentially the same as if the && expressions were in parentheses: (a && b) || (c && d) .
Sometimes, people use the AND && operator as a "shorter way to write if ".
The action in the right part of && would execute only if the evaluation reaches it. That is, only if (x > 0) is true.
So we basically have an analogue for:
Although, the variant with && appears shorter, if is more obvious and tends to be a little bit more readable. So we recommend using every construct for its purpose: use if if we want if and use && if we want AND.
The boolean NOT operator is represented with an exclamation sign ! .
The syntax is pretty simple:
The operator accepts a single argument and does the following:
- Converts the operand to boolean type: true/false .
- Returns the inverse value.
A double NOT !! is sometimes used for converting a value to boolean type:
That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In the end, we have a plain value-to-boolean conversion.
There’s a little more verbose way to do the same thing – a built-in Boolean function:
The precedence of NOT ! is the highest of all logical operators, so it always executes first, before && or || .
What's the result of OR?
What is the code below going to output?
The answer is 2 , that’s the first truthy value.
What's the result of OR'ed alerts?
What will the code below output?
The answer: first 1 , then 2 .
The call to alert does not return a value. Or, in other words, it returns undefined .
- The first OR || evaluates its left operand alert(1) . That shows the first message with 1 .
- The alert returns undefined , so OR goes on to the second operand searching for a truthy value.
- The second operand 2 is truthy, so the execution is halted, 2 is returned and then shown by the outer alert.
There will be no 3 , because the evaluation does not reach alert(3) .
What is the result of AND?
What is this code going to show?
The answer: null , because it’s the first falsy value from the list.
What is the result of AND'ed alerts?
What will this code show?
The answer: 1 , and then undefined .
The call to alert returns undefined (it just shows a message, so there’s no meaningful return).
Because of that, && evaluates the left operand (outputs 1 ), and immediately stops, because undefined is a falsy value. And && looks for a falsy value and returns it, so it’s done.
The result of OR AND OR
What will the result be?
The answer: 3 .
The precedence of AND && is higher than || , so it executes first.
The result of 2 && 3 = 3 , so the expression becomes:
Now the result is the first truthy value: 3 .
Check the range between
Write an if condition to check that age is between 14 and 90 inclusively.
“Inclusively” means that age can reach the edges 14 or 90 .
Check the range outside
Write an if condition to check that age is NOT between 14 and 90 inclusively.
Create two variants: the first one using NOT ! , the second one – without it.
The first variant:
The second variant:
A question about "if"
Which of these alert s are going to execute?
What will the results of the expressions be inside if(...) ?
The answer: the first and the third will execute.
Check the login
Write the code which asks for a login with prompt .
If the visitor enters "Admin" , then prompt for a password, if the input is an empty line or Esc – show “Canceled”, if it’s another string – then show “I don’t know you”.
The password is checked as follows:
- If it equals “TheMaster”, then show “Welcome!”,
- Another string – show “Wrong password”,
- For an empty string or cancelled input, show “Canceled”
The schema:
Please use nested if blocks. Mind the overall readability of the code.
Hint: passing an empty input to a prompt returns an empty string '' . Pressing ESC during a prompt returns null .
Run the demo
Note the vertical indents inside the if blocks. They are technically not required, but make the code more readable.
- If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
- If you can't understand something in the article – please elaborate.
- To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)
Lesson navigation
- © 2007—2023 Ilya Kantor
- about the project
- terms of usage
- privacy policy

IMAGES
VIDEO
COMMENTS
Thinking about starting your own small business, but you’re intimidated by the thought of managing all your records and handling your own accounting? The good news is you don’t have to be a genius or a financial wizard to understand and pre...
A good thesis statement is a single sentence contained in the introduction of a paper that provides the reader with some idea of what the writer is trying to convey in the body of the paper. The thesis statement is a condensed summary of th...
A credibility statement is a rhetorical device that establishes the validity of the rhetor’s position as articulated in a given speech or artifact. Credibility statements are often associated with Aristotelian models of argumentation.
34. The statement 5%2 will evaluate toand 5/2 will evaluate to Get the answers you need, now!
The statement 5%2 will evaluate to _____and 5/2 will evaluate to_____. - 35549981.
A computer program is a step-by-step set of instructions to tell a computer to do things to stuff. We will be spending the rest of this book deepening and
You just think, "I know what a number is, and I know what it means to add up any expressions." So, for example, to understand the expression. (+ (+ 2 3) (+ 4 5)).
parts of a statement that evaluate to true or false
What outputs would be the best choice to substitute in for "missing output 1" and "missing output 2", based on the condition? missing output 1: value does not
The expression 5 - 2 - 3 * 5 - 2 will evaluate to 18, if - is left associative and * has precedence over * * has precedence over - - has precedence over
5 ** 2 # 5 squared 25 >>> 2 ** 7 # 2 to the power of 7 128.
else {. // code to execute if boolean expression is false. } For example, I could say the following, with the output shown in Figure 5-2. FIGURE 5-2.
Less likely to make a semantic error. Indent the body of the if statement 3 to 5 spaces -- be consistent! CMSC 104, Version 8/06. 12.
The AND && operator does the following: Evaluates operands from left to right. For each operand, converts it to a boolean. If the result is