- Information
- AI Chat
Python module 1
Information Technology (37304)
Don Bosco Institute of Technology
Preview text
>>> 2+
4
>>> 2+
4
>>> 2
2
PYTHON BASICS
- Entering expressions into the interactive shell
- The integer, floating-point and String Data Types
- String concatenation and replication
- Storing values in variables
- Your first program
- Dissecting your program
1. Entering expressions into the interactive shell
Run the interactive shell by launching IDLE, which is installed with Python. On Windows, open the Start menu, select All Programs ▸ Python 3, and then select IDLE (Python GUI). On OS X, select Applications ▸ MacPython 3 ▸ IDLE. On Ubuntu, open a new Terminal window and enter idle3. A window with the >>> prompt should appear; that’s the interactive shell. The IDLE window should now show some text like this: Python 3.3 (v3.3:d047928ae3f6, May 16 2013, 00:06:53) [MSC v 64 bit (AMD64)] on win Type "copyright", "credits" or "license()" for more information. In Python, 2 + 2 is called an expression, which is the most basic kind of programming instruction in the language. Expressions consist of values (such as 2) and operators (such as +), and they can always evaluate (that is, reduce) down to a single value. That means you can use expressions anywhere in Python code that you could also use a value. In the previous example, 2 + 2 is evaluated down to a single value, 4. A single value with no operators is also considered an expression, though it evaluates only to itself, as shown here: The other operators which can be used are:
The order of operations (also called precedence) of Python math operators is similar to that of mathematics. The ** operator is evaluated first; the *, /, //, and % operators are evaluated next, from left to right; and the + and - operators are evaluated last (also from left to right). We can use parentheses to override the usual precedence if you need to. Due to wrong instructions errors occurs as shown below:
The integer, floating-point and String Data Types
The expressions are just values combined with operators, and they always evaluate down to a single value. A data type is a category for values, and every value belongs to exactly one data type. The integer (or int) data type indicates values that are whole numbers. Numbers with a decimal point, such as 3, are called floating-point numbers (or floats). Note that even though the value 42 is an integer, the value 42 would be a floating-point number. Python programs can also have text values called strings, or strs and surrounded in single quote. The string with no characters, '', called a blank string. If the error message SyntaxError: EOL while scanning string literal, then probably the final single quote character at the end of the string is missing.
Overwriting the variable
A variable is initialized (or created) the first time a value is stored in it ❶. After that, you can use it in expressions with other variables and values ❷. When a variable is assigned a new value ③, the old value is forgotten, which is why spam evaluated to 42 instead of 40 at the end of the example.
One more example
Variable names
We can name a variable anything as long as it obeys the following three rules:
- It can be only one word.
- It can use only letters, numbers, and the underscore (_) character.
- It can’t begin with a number.
Variable names are case-sensitive, meaning that spam, SPAM, Spam, and sPaM are four different variables. This book uses camelcase for variable names instead of underscores; that is, variables lookLikeThis instead of looking_like_this. A good variable name describes the data it contains.
Your First Program
The file editor is similar to text editors such as Notepad or TextMate, but it has some specific features for typing in source code. The interactive shell window will always be the one with the >>> prompt. The file editor window will not have the >>> prompt. The extension for python program is .py Example program: The output looks like:
Dissecting Your Program
Comments
The following line is called a comment.
The len() Function
We can pass the len() function a string value (or a variable containing a string), and the function evaluates to the integer value of the number of characters in that string. In the interactive shell: len(myName) evaluates to an integer. It is then passed to print() to be displayed on the screen. Possible errors: The print() function isn’t causing that error, but rather it’s the expression you tried to pass to print(). Python gives an error because we can use the + operator only to add two integers together or concatenate two strings. We can’t add an integer to a string because this is ungrammatical in Python.
The str(), int() and float() Functions
If we want to concatenate an integer such as 29 with a string to pass to print(), we’ll need to get the value '29', which is the string form of 29. The str() function can be passed an integer value and will evaluate to a string value version of it, as follows:
Because str(29) evaluates to '29', the expression 'I am ' + str(29) + ' years old.' evaluates to 'I am ' + '29' + ' years old.', which in turn evaluates to 'I am 29 years old.'. This is the value that is passed to the print() function. The str(), int(), and float() functions will evaluate to the string, integer, and floating-point forms of the value you pass, respectively. Converting some values in the interactive shell with these functions: The previous examples call the str(), int(), and float() functions and pass them values of the other data types to obtain a string, integer, or floating-point form of those values. The str() function is handy when you have an integer or float that you want to concatenate to a string. The int() function is also helpful if we have a number as a string value that you want to use in some mathematics. For example, the input() function always returns a string, even if the user enters a number. Enter spam = input() into the interactive shell and enter 101 when it waits for your text. The value stored inside spam isn’t the integer 101 but the string '101'. If we want to do math using the value in spam, use the int() function to get the integer form of spam and then store this as the new value in spam. Now we should be able to treat the spam variable as an integer instead of a string. Note that if we pass a value to int() that it cannot evaluate as an integer, Python will display an error message.
Text and Number Equivalence
Although the string value of a number is considered a completely different value from the integer or floating-point version, an integer can be equal to a floating point.
FLOW CONTROL
- Boolean Values
- Comparison Operators
- Boolean Operators
- Mixing Boolean and Comparison Operators
- Elements of Flow Control
- Program Execution
- Flow Control Statements
- Importing Modules
- Ending a Program Early with sys()
Introduction
Flow control statements can decide which Python instructions to execute under which conditions. These flow control statements directly correspond to the symbols in a flowchart In a flowchart, there is usually more than one way to go from the start to the end. Flowcharts represent these branching points with diamonds, while the other steps are represented with rectangles.
The starting and ending steps are represented with rounded rectangles.
Boolean Values
The Boolean data type has only two values: True and False. When typed as Python code, the Boolean values True and False lack the quotes you place around strings, and they always start with a capital T or F, with the rest of the word in lowercase. Examples: Like any other value, Boolean values are used in expressions and can be stored in variables ❶. If we don’t use the proper case ❷ or we try to use True and False for variable names ❸, Python will give you an error message.
Comparison Operators
Comparison operators compare two values and evaluate down to a single Boolean value. Table 2 - 1 lists the comparison operators.
Binary Boolean Operators The and and or operators always take two Boolean values (or expressions), so they’re considered binary Operators. and operator: The and operator evaluates an expression to True if both Boolean values are True; otherwise, it evaluates to False. or operator: The or operator valuates an expression to True if either of the two Boolean values is True. If both are False, it evaluates to False. not operator: The not operator operates on only one Boolean value (or expression). The not operator simply evaluates to the opposite Boolean value. Much like using double negatives in speech and writing, you can nest not operators ❶, though there’s never not no reason to do this in real programs.
Mixing Boolean and Comparison Operators
Since the comparison operators evaluate to Boolean values, we can use them in expressions with the Boolean operators. Ex: The computer will evaluate the left expression first, and then it will evaluate the right expression. When it knows the Boolean value for each, it will then evaluate the whole expression down to one Boolean value. You can think of the computer’s evaluation process for (4 < 5) and (5 < 6) as shown in Figure below:
We can also use multiple Boolean operators in an expression, along with the comparison operators. The Boolean operators have an order of operations just like the math operators do. After any math and comparison operators evaluate, Python evaluates the not operators first, then the and operators, and then the or operators.
Elements of Flow Control
Flow control statements often start with a part called the condition, and all are followed by a block of code called the clause. Conditions: The Boolean expressions you’ve seen so far could all be considered conditions, which are the same thing as expressions; condition is just a more specific name in the context of flow control statements. Conditions always evaluate down to a Boolean value, True or False. A flow control statement decides what to do based on whether its condition is True or False, and almost every flow control statement uses a condition. Blocks of Code: Lines of Python code can be grouped together in blocks. There are three rules for blocks.
- Blocks begin when the indentation increases.
- Blocks can contain other blocks.
- Blocks end when the indentation decreases to zero or to a containing block’s indentation. The first block of code ❶ starts at the line print('Hello Mary') and contains all the lines after it. Inside this block is another block ❷, which has only a single line in it: print('Access Granted.'). The third block ❸ is also one line long: print('Wrong password.').
Example: Flowchart: 3. elif Statements: While only one of the if or else clauses will execute, we may have a case where we want one of many possible clauses to execute. The elif statement is an “else if” statement that always follows an if or another elif statement. It provides another condition that is checked only if all of the previous conditions were False. In code, an elif statement always consists of the following: 1. The elif keyword 2. A condition (that is, an expression that evaluates to True or False) 3. A colon 4. Starting on the next line, an indented block of code (called the elif clause) Example: Flowchart:
When there is a chain of elif statements, only one or none of the clauses will be executed. Example: Flowchart:
- while loop Statements: We can make a block of code execute over and over again with a while statement. The code in a while clause will be executed as long as the while statement’s condition is True. In code, a while statement always consists of the following:
- The while keyword
- A condition (that is, an expression that evaluates to True or False.
- A colon
- Starting on the next line, an indented block of code (called the while clause) We can see that a while statement looks similar to an if statement. The difference is in how they behave. At the end of an if clause, the program execution continues after the if statement. But, at the end of a while clause, the program execution jumps back to the start of the while statement. The while clause is often called the while loop or just the loop. Example: Using if statement Using while statement These statements are similar—both if and while check the value of spam, and if it’s less than five, they print a message. But when we run these two code snippets, for the if statement, the output is simply "Hello, world." But for the while statement, it’s "Hello, world." repeated five times! Flowchart: Using if statement Using while statement In the while loop, the condition is always checked at the start of each iteration (that is, each time the loop is executed). If the condition is True, then the clause is executed, and afterward, the condition is checked again. The first time the condition is found to be False, the while clause is skipped.
An annoying while loop: Here’s a small example program that will keep asking to type, literally, your name. Example Program Output First, the program sets the name variable ❶ to an empty string. This is so that the name != 'your name' condition will evaluate to True and the program execution will enter the while loop’s clause ❷. The code inside this clause asks the user to type their name, which is assigned to the name variable ❸. Since this is the last line of the block, the execution moves back to the start of the while loop and reevaluates the condition. If the value in name is not equal to the string 'your name', then the condition is True, and the execution enters the while clause again. But once the user types your name, the condition of the while loop will be 'your name' != 'your name', which evaluates to False. The condition is now False, and instead of the program execution reentering the while loop’s clause, it skips past it and continues running the rest of the program ❹. Flowchart: 5. break Statements: There is a shortcut to getting the program execution to break out of a while loop’s clause early. If the execution reaches a break statement, it immediately exits the while loop’s clause.
Python module 1
Course: Information Technology (37304)
University: Don Bosco Institute of Technology
- Discover more from: