Leseprobe
Contents
Chapter 1 About Python
1.1 Python Features
1.2 Python Environment
1.3 Installing Python on Windows
1.4 Running Python Code
1.5 Sample Runs
1.6 Parts of a Python Program
Exercise
Chapter 2 Python Basics.
2.1 Identifiers
2.2 Keywords
2.3 Variables
2.4 Comments
2.5 Quotes
2.6 Blank Lines and Indentation
2.7 Multiline Statements
2.8 Operators
2.9 Expressions
2.10 Assignment Statements
2.11 Multiple Assignments in Single Statements
2.12 Multiple Statements on Single Lines
2.13 Code Blocks
2.14 Data Types
2.15 Input-Output Statements
2.16 Importing Modules
Exercise
Chapter 3 Control Structures.....
3.1 Sequence
3.2 Decision Making
3.3 Loops
3.4 Other Control Flows
3.5 Sample Programs
Exercise
Chapter 4 Advanced Data Types
4.1 Lists
4.2 Tuples
4.3 Dictionaries
4.4 Sets
4.5 Arrays
Exercise
Chapter 5 Advanced Input/Output.....
5.1 Reading Data from Keyboard
5.2 Sending Output to Monitor
5.3 Formatting Output
5.4 Reading Input from Text File
5.5 Writing Output to Text File
5.6 Reading from and Writing to Text Files
5.7 Sending Output to Printer
Exercise
Chapter 6 Built-in Functions
6.1 What are Functions?
6.2 Built-in Functions
6.3 Math Functions
6.4 String Functions
6.5 Data Conversion Functions
6.6 Input/Output Functions
6.7 Date Functions
6.8 List Functions
6.9 Tuple Functions
6.10 Dictionary Functions
6.11 Set Functions
6.12 Sample Programs
Exercise
Chapter 7 User-defined Functions..
7.1 Why User-defined Functions
7.2 Defining Functions
7.3 Calling Functions
7.4 Call by Reference vs. Value
7.5 Function Overloading
7.6 Scope of Variables
7.7 Recursive Functions
7.8 Anonymous Functions
7.9 Sample Programs
Exercise
Chapter 8 Classes..
8.1 Object-oriented Concepts
8.2 Defining Classes
8.3 Class Inheritance
8.4 Abstract Classes
8.5 Overloading and Overriding Methods
8.6 Operator Overloading
8.7 Object Interaction
8.8 Sample programs
Exercise
Chapter 9 Threading....
9.1 What are Threads?
9.2 Importing Thread Modules
9.3 Thread Methods
9.4 Creating Threads With Functions
9.5 Creating Threads With Classes
9.6 Synchronizing Threads
9.7 Accessing Shared Resources
9.8 Daemon vs. Non-Daemon Threads
9.9 Enumerating Threads
9.10 Sample Programs
Exercise
Chapter 10 Database.
10.1 What is a Database?
10.2 Database Concepts
10.3 SQL Commands
10.4 Creating Database
10.5 Inserting Records
10.6 Fetching Records
10.7 Displaying Records in Different Formats
10.8 Inserting Records from Lists
10.9 Deleting Records
10.10 Updating Records
10.11 Aggregate Functions
10.12 Multiple Databases
10.13 MySQL Database
Exercise
References
Preface
Python, developed by Guido van Rossum of Netherlands in the late 80s, and named after the BBC TV show Monty Python's Flying Circus, is one of the most user-friendly and powerful general-purpose computer programming languages available today.
Its English-like syntax makes it a great language for teaching and learning computer programming. Python’s powerful data structures/types such as lists, tuples, dictionaries, sets, and arrays make coding simple. It also comes with an extensive collection of built-in/library functions that allows users to develop software applications with relative ease. Besides, users can freely import external modules to help them develop all sorts of applications.
Python’s interactive and interpreted mode makes coding and testing software easy. Python also doubles us as a powerful and sophisticated calculator.
You can use Python to develop all sorts of applications ranging from simple Mathematical and Text processing to Database, Web, Graphical User Interface, Network, Games, Data Mining, Artificial Intelligence, Machine Learning and Deep Learning.
This book is intended for beginners who have little or no knowledge of programming. It is also suitable for intermediate programmers who already have some knowledge of programming.
This text is suitable for secondary school, college and university students irrespective of their field of study – be it Arts, Business, Science, Engineering, Life Sciences or Medicine. It starts with the basics, but progresses rapidly to the advanced topics such as lists, tuples, dictionaries, arrays, functions, classes, files and databases. So whether you are a beginner or an intermediate programmer, this book will help you master the essentials of Python programming very quickly.
The book is written in a simple, easy-to-read style and contains numerous examples to illustrate the programming concepts presented. It also contains exercises to test the reader’s grasp of the material presented in each chapter.
Acknowledgements
I would like to gratefully acknowledge the contributions of several people who have in one or another assisted me in the preparation of this book. I would like to thank all my IT students and colleagues for their valuable input and feedback in the preparation of this manuscript.
My grateful thanks also go to Professor Dr. Premkumar Rajagopal, President of the Malaysia University of Science and Technology for giving me the opportunity, freedom, encouragement and support that I needed in the preparation of this manuscript. I would like to especially thank him for creating and nurturing an environment that actively promotes learning, research, teamwork and personal development. His dynamic leadership is greatly appreciated.
Last but first I would like to thank God for giving me the desire, motivation, interest, passion, strength and guidance to successfully complete this manuscript.
Dr. P. Sellappan
Professor of Information Technology
Dean of School of Science and Engineering
Provost of Malaysia University of Science and Technology
About the Author
Dr. P. Sellappan is currently Professor of Information Technology, Dean of School of Science and Engineering, and Provost of the Malaysia University of Science and Technology. Prior to joining Malaysia University of Science and Technology, he held a similar academic position in the Faculty of Computer Science and Information Technology, University of Malaya, Malaysia.
He holds a Bachelor in Economics degree with a Statistics major from the University of Malaya, a Master in Computer Science from the University of London (UK), and a PhD in Interdisciplinary Information Science from the University of Pittsburgh (USA).
Working in the academia for more than 30 years, he has taught a wide range of courses both at undergraduate and postgraduate levels: Principles of Programming, Advanced Programming, Programming Languages, Data Structures and Algorithms, System Analysis and Design, Software Engineering, Human Computer Interaction, Database Systems, Data Mining, Health Informatics, Web Applications, E-Commerce, Operating Systems, Management Information Systems, Research Methods, Mathematics and Statistics.
Professor Sellappan is an active researcher. He has received several national research grants from the Ministry of Science and Technology and Innovation under E-Science and FRGS to undertake IT-related research projects. Arising from these projects, he has published numerous research papers in reputable international journals and conference proceedings. Besides, he has also authored over a dozen college- and university-level IT text books.
As a thesis supervisor, he has supervised more than 70 Master and PhD theses. He also serves in editorial/review boards of several international journals and conferences. He is also chief editor of the Journal of Advanced Applied Sciences and the Plain Truth magazine. He is a certified trainer, external examiner, moderator and program assessor for IT programs for several local and international universities.
Together with other international experts, he has also served as an IT Consultant for several local and international agencies such as the Asian Development Bank, the United Nations Development Program, the World Bank, and the Government of Malaysia. His professional affiliation includes membership in the Chartered Engineering Council (UK), the British Computer Society (UK), the Institute of Statisticians (UK), and the Malaysian National Computer Confederation (MNCC).
Chapter 1 About Python
Learning Outcomes:
After completing this chapter, the student will be able to
- Describe the main features of Python.
- Explain the Python environment.
- Run Python in calculator, interpreted, and script mode.
- Describe the different parts of a Python program.
1.1 Python Features
Python was developed by Guido van Rossum of Netherlands in the late 80s. It was named after the BBC TV show Monty Python's Flying Circus.
Python is one of the popular general-purpose programming languages available today. Its English-like syntax makes it easier to learn. It is a great language for learning and teaching computer programming.
With Python you can develop all kinds of applications ranging from simple Business, Mathematical and Text processing to Database, Web, GUI (Graphical User Interface), Network, Games, Data Mining and Machine Learning applications.
Python has rich features which includes the following:
- Python can be used as a powerful and sophisticated calculator.
- Python is interactive – you can type your code at the Command prompt and view the results immediately.
- Python has an interpreter that lets you execute code as you type. You don’t have to compile the whole program to run it. This is very useful for testing and debugging code.
- Python is object-oriented – you can define classes by bundling data attributes (variables) and functionality (methods) and create objects and work with them.
1) It has extensive libraries with built-in functions/methods that greatly simplify programming.
2) It is portable – you can run Python code on several hardware and software platforms (Linux and Windows).
3) It provides interfaces to major database software like MS Access, SQL Server, SQL Lite, MySQL and Oracle.
4) It supports Graphical User Interface (GUI).
5) It provides advanced data structures/types like lists, tuples, dictionaries and sets that make programming easy.
6) It supports automatic garbage collection to reclaim and reuse unused memory previously allocated to objects that no longer exist.
7) It can be used as a scripting language – you can write programs and store them in files for later use or embedding them in other programs.
1.2 Python Environment
You can run Python on several platforms like Windows and Linux. You can also incorporate Python code in programming languages like C, C++, Java and R.
You can execute Python code in three modes:
- Calculator mode – execute one statement or line of code at a time. It will automatically remember the previous results stored in the memory (provided they are not overwritten).
- Interpreted mode - you can execute statements and view the results immediately. You don’t have to have the full program to execute it. This feature is very useful for testing and debugging code.
- Script mode – after you have debugged a program, you can store it in a file and later execute it as a script. This will improve performance, especially if it is a large or computationally-intensive program.
Thus Python provides a user-friendly environment for both novice, intermediate, and expert programmers.
1.3 Installing Python on Windows
This text is based on Python 3.6.x. for Windows. You can download and install Python as follows:
- Open a Web browser and go tohttps://www.anaconda.com/download/.
- Click on Download Python 3.6.x. for Windows.
- Run the downloaded file by accepting all the default settings.
- Run Python and you will see the Command window like the one shown below.
illustration not visible in this excerpt
1.4 Running Python Code
You can run Python in three modes as follows:
§ Interactive Interpreter
Enter python at the command line as follows:
illustration not visible in this excerpt
You can include options at the Command prompt such as
-d provides debug output
file runs script from file
§ Script at Command-line
You can execute a Python script at the Command line as follows:
C:> python script.py
§ Integrated Development Environment
You can also run Python in the Integrated Development Environment (IDE) that looks like the one shown below:
illustration not visible in this excerpt
The IDE provides several windows to help you code, see output/results and consult related documentation if you need them. It also provides several menus and menu icons (Save, Run, Debug, Stop Debugging, etc.) at the top to help you write, test and debug code.
1.5 Sample Runs
Let’s now run some simple code in the different modes.
Calculator Mode
At the >>> prompt, type the code below and press Enter.
illustration not visible in this excerpt
You will get the following output:
illustration not visible in this excerpt
Here are more examples with their output.
illustration not visible in this excerpt
Interpreted Mode
Type the following code and run by clicking the arrow button on the menu bar (Abbildung in dieser Leseprobe nicht enthalten).
illustration not visible in this excerpt
Script Mode
Write a Python script (like the above) and store it in the default directory as test.py. (Python files have extension .py ).
You can now run the stored script by typing
illustration not visible in this excerpt
The script will produce the same output as above.
1.6 Parts of a Python Program
A Python program has many parts/sections (see the below sample program): comments, expressions, statements, input, output, functions, import, etc. We will explain the different parts of a Python program using a simple sample program given below.
Note: The line numberings on the left, generated by the system, is for reference purpose only – they are not part of the code. Also, for easy reading, Python uses different colors for different parts of a program: green for comments, blue for keywords, pink for functions, etc.
Comments
Inserting comments in a program makes the code more readable. You can insert comments on a single line, on several lines, or inline after a statement.
A single line comment starts with a sharp character (#) as in lines 7, 10…. in the sample code. Everything on that after # is treated as a comment. You can create a multiline comment by starting each line with a #.
An inline comment starts with a # after a statement as in lines 12, 17…. in the sample code.
You can also insert a multiline comment by starting and ending the comment with triple apostrophes ('''). Such a comment can span several lines as in lines 2 to 6.
Line spacing
Inserting blank lines to separate code blocks makes a program more readable as in lines 9, 14….
Indentation
Code blocks in Python are indented by a fixed number of spaces (typically 4 spaces) as in lines 12 and 13. All statements in the code block must follow the same indentation.
Sample Python code
illustration not visible in this excerpt
Sample output
illustration not visible in this excerpt
Keywords
Keywords (also called reserved words) have special meaning in Python. You cannot use these keywords for any other purpose such as for naming identifiers (variables, functions or classes). For example, import (line 8), define (line 11) and return (line 13) in the code are keywords.
Case sensitivity
Python identifiers for naming variables, functions and classes are case-sensitive. It treats uppercase and lowercase letters as different characters. That means, name, Name and NAME are all different identifiers.
Parameters
Parameters (arguments) in functions (methods) are enclosed between a pair of curved brackets (). The brackets are still needed even if a function has no parameters.
Input statement
The input statement (function) is used for reading data from the Keyboard (or Console). It takes the form
variable = input ('prompt')
where variable stores the data entered, and prompt prompts the user to enter the data.
Output statement
The print function is used for sending output (results) to the monitor (Console). It takes the form
print (output list)
where output list is a list of variables or expressions that you want to print or display.
Assignment statement
An assignment statement takes the form
variable = expression
where variable stores the result of the expression, and = is an assignment operator (not an equality operator). In an assignment statement, the expression on the right-hand side of = is first evaluated and the result is assigned to the variable on the left-hand side of =. The expression can be a number, a constant, a literal, a variable, an algebraic expression, or a function or method call.
Import statement
The import statement is used to import modules (classes) stored in external files. It begins with the keyword import followed by the name of the module (e.g. math) as in line 8.
Lists, tuples and dictionaries
Python variables include grouped data: lists, tuples and dictionaries. Lists are enclosed between square brackets [] as in line 28; tuples are enclosed between curved brackets () as in line 31; and dictionaries (containing paired items) are enclosed between braces or curly brackets {} as in line 34.
Note: We will discuss all these and topics in greater detail in the rest of the chapters. So don’t worry if you haven’t fully grasped the material presented in this chapter. The sample code is meant to give you a flavor of how a Python program looks like. As you progress through the chapters, you will learn how to write Python programs.
Exercise
1. Run Python in calculator mode to evaluate the following:
a) 23 – (4 * 15) / 3 + 73
b) Concatenate (join) the strings “Good” and “day”
c) Concatenate the strings “time”, “and”, “chance”
2. Run Python in calculator mode to evaluate the following:
a) Square of 547.25
b) Square root of 973.16
c) Square root of (973.75 + square of (45) )
3. Run Python in interpreted mode to execute the following code:
x = (55 + 25) * 2
y = 546.95 + sqrt(25)
z = x + y
print ('Sum of x and y = ', z)
4. Execute the code in question (3) in script mode.
5. Run Python in interpreted mode to execute the following code:
hours = 98
rate = 35.70
gross_pay = hours * rate
deduction = 10 * pay
net_pay = pay - deduction
print ('Take home pay = $', netpay)
6. Execute the code in question (5) in script mode.
Chapter 2 Python Basics
Learning Outcomes:
After completing this chapter, the student will be able to
- Form identifiers and variables.
- Use arithmetic, logical and relational operators.
- Form expressions.
- Write assignment statements.
- Identify different data types.
- Perform input/output.
- Write simple Python code.
2.1 Identifiers
Identifiers are used to name variables, functions, classes, objects and modules. They are simply references (pointers) to memory locations for storing objects such as numbers, strings, dates or Boolean values.
An identifier consists of one or more lower and upper letters (a-z, A-Z), digits (0-9) and the underscore (_). Identifiers must start with an underscore or a letter followed by zero or more letters, digits or underscores. Special characters such as #, &, @, $ and % are not allowed in an identifier. The blank or space character is also not allowed in an identifier.
Python identifiers are case-sensitive, meaning it treats uppercase and lowercase letters as different characters. That means, NAME, Name and name are all different identifiers.
The following naming convention is used for identifiers:
- All class names start with uppercase letters.
- All other identifiers start with lowercase letters.
- An identifier with a single leading underscore indicates that it is private.
- An identifier with two leading underscores indicates that it is strongly private.
- An identifier that ends with two trailing underscores indicates that it is a special language-defined name.
The following are examples of valid identifiers.
illustration not visible in this excerpt
The following are examples of invalid identifiers.
illustration not visible in this excerpt
2.2 Keywords
Keywords, also called reserved words, have special meaning in Python. You cannot use them for any other purpose, e.g. for naming identifiers, variables, functions, classes, objects or modules. All keywords use only lowercase letters.
Below is a list of Python keywords.
illustration not visible in this excerpt
2.3 Variables
Unlike in some other programming languages (like C# and Java), Python variables don’t need explicit declaration. Python automatically allocates memory to variables when you assign them values. The amount of memory Python allocates to variables will depend on their data type. Some data types (e.g. float) will require more bytes than others (e.g. integer).
Variables are pointers (references) to data objects such as integers, float, strings, Boolean, list, tuple and dictionary.
For example:
n = 12 would be represented internally as follows:
illustration not visible in this excerpt
Similarly,
price = 29.90 would be represented internally as follows (float type requires more bytes):
illustration not visible in this excerpt
price
illustration not visible in this excerpt
would be represented internally as follows (the number of bytes needed will depend on the length of the string):
sentence
2.4 Comments
Comments are inserted into a program to make it readable. The Python interpreter does not process comments – it just ignores them.
Comments start with a sharp sign (#). Characters following # are part of a comment. You can create a multiline comment by starting each line with #. You can also insert a comment after a statement on the same line. This is called an inline comment.
Here are some examples of valid comments.
illustration not visible in this excerpt
2.5 Quotes
Quotes are used to indicate literal strings. You can use a single ('), double (") or triple (''') quote to indicate a string literal as long as it begins and ends with the same quote type. The triple quote is used to span a long quote (a sentence or a paragraph) across multiple lines.
The following are examples of valid quotes.
illustration not visible in this excerpt
2.6 Blank Lines & Indentation
A blank line is one that contains only whitespaces. Python ignores blank lines. Blank lines are inserted to separate code blocks and thus make the code readable.
Unlike in some other programming languages such as C# and Java, Python doesn’t use braces or curly brackets ({}) to separate code blocks. Instead, it uses line indentation. The number of spaces in a line indentation can vary, but all statements within a code block must have the same indentation (typically four spaces).
The following line indentation is valid as all statements in the code blocks follow the same number of spaces.
illustration not visible in this excerpt
2.8 Operators
Python supports the following operators.
- Arithmetic operators
- Comparison/Relational operators
- Assignment operators
- Logical operators
- Bitwise operators
- Membership operators
- Identity operators
Arithmetic Operators
Arithmetic operators are similar to those used in algebra except for *, **, % and //.
The table below gives the list of arithmetic operators. The last column gives examples for the operands: x = 10 and y = 20.
illustration not visible in this excerpt
Logical Operators
Logical operators are and (&), or (|) and not.
The table below gives the list of logical operators. The last column gives examples for the operands: x = True and y = False.
illustration not visible in this excerpt
Comparison Operators
The comparison or relational operators compare the values of the two operands and yields the result of the comparison which is True or False.
The table below gives the list of comparison operators. The last column gives examples for the operands: x = 10 and y = 20.
illustration not visible in this excerpt
Assignment Operators
Assignment operators evaluate the expression on the right-hand side of = and assign the result to the variable on the left-hand side. Some assignment operators are short-hand operators that use the left-hand operand as part of the expression.
The table below gives the list of assignment operators. The last column gives examples for the operands: x = 10 and y = 20.
illustration not visible in this excerpt
Bitwise Operators
Bitwise operators perform bit-by-bit operation.
The table below gives the list of bitwise operators. The last column gives examples for the operands: x = 15 and y = 23. The binary equivalent of x and y are as follows:
x = 0b1111
y = 0b1100001
illustration not visible in this excerpt
Membership Operators
Membership operators test if an item is a member of a sequence such as string, list or tuple.
There are two membership operators: in and not in as shown below. The last column gives examples for the operands: x, y and z:
x = 'jack and jill and sam'
y = ['jack', 'jill', 'sam']
z = ('red', 'blue', 'green')
v = [1, 2, 3, 4, 5]
illustration not visible in this excerpt
Identity Operators
Identity operators compare the memory locations of two objects.
There are two identity operators: is and is not as shown below. The last column gives examples for the operands:
x = 127
y = x
z = 256
illustration not visible in this excerpt
Operator Precedence
The table below lists the operator precedence from the highest to the lowest.
illustration not visible in this excerpt
#
2.9 Expressions
Expressions in Python are similar to algebraic expressions in math except for certain operators like *, **, %, and //.
Here are some examples of valid expressions.
illustration not visible in this excerpt
2.10 Assignment Statements
The assignment operator (=) is used to assign values to variables. It takes the form
variable = expression
The variable on the left hand side of the assignment operator stores the value of the expression on the right hand side.
Here are some examples (code snippets) of assignment statements.
illustration not visible in this excerpt
2.11 Multiple Assignments in a Single Statement
Python allows you to make multiple assignments in a single statement. For example, the code below assigns the value 1 to the variables a, b and c simultaneously.
illustration not visible in this excerpt
The statement creates an integer object with value 1, and all the variables point to the same object. There is only one copy of 1.
Python also allows you to assign multiple values to multiple variables in a single statement as in the code below.
illustration not visible in this excerpt
Here, iPad is assigned to product; 1200.50 is assigned to price; and 5 is assigned to quantity. The values on the right hand side are assigned to the variables on the left hand side in the same order.
2.12 Multiple Statements in a Single Line
Python allows multiple statements on a single line (this saves space), separated by a semicolon (;) provided no statement starts a new code block. Here is an example.
illustration not visible in this excerpt
The above code has four statements – all packed compactly in one line.
2.13 Code Blocks
A code block is a collection of one or more statements all following the same line indentation. Compound statements like if, while, def or class have headers. A header begins the statement with a keyword and terminates with a colon (:). The colon marks the beginning of a new code block as shown in the code below.
illustration not visible in this excerpt
2.14 Data Types
Python has several data types: number, string, Boolean, list, tuple, dictionary and set.
The number data type stores numerical values such as integer and floating point numbers. String data type stores a sequence of characters. Boolean data type stores the value True or False. List data type stores a list of (mutable) items enclosed between []. Tuple data type stores a list of (immutable) items enclosed between (). Dictionary data type stores a list of (mutable) paired items in the form of key:value enclosed between {}. A set data has a collection of items which can be any data type.
Mutable items can be changed or updated; immutable items cannot be changed or updated. All single-item variables are mutable. Some group-item variables like lists and dictionaries are mutable. Tuples, however, are immutable.
Here are some examples of data types and their internal representation.
illustration not visible in this excerpt
When objects of these data types are created and assigned to variables, the variables point to these objects. Internally, the above assignments look something like this:
illustration not visible in this excerpt
You can delete references to objects using the del statement as in the code below.
del itemcopy, mytel
Numbers
Python supports four number types:
- int (signed integers)
- long (long integers, which can also be represented in octal and hexadecimal)
- float (floating point real values)
- complex (complex numbers)
Here are some examples of number types.
illustration not visible in this excerpt
- Python allows you to use a lowercase l with long, but it is strongly recommended that you use only an uppercase L to avoid confusion with the number 1. It displays long integers with an uppercase L.
- A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.
Strings
A string is a sequence of characters enclosed between a pair of quotation marks of the same type. Python allows you to use a single (') or double ('') quote. You cannot mix the quote for the same string.
You can get subsets of strings from a string by using the slice operator ([ ]or [:]) with indexes. Index always starts with a 0 at the beginning of a string. Index can also start with -1 at the end of the string.
The plus sign (+) in the string acts as a concatenation (join) operator and the asterisk (*) acts as a repetition operator.
Here are some examples.
illustration not visible in this excerpt
Lists
A list contains (mutable) items separated by commas and enclosed within square brackets ([]). They are similar to arrays, but list items need not be of the same data type.
Like strings, you can access list items using the slice operator ([] and [:]).
Here are some examples.
list = ['iPhone 10', 500.00, 'black']
list2 = ['john', 'sally']
print (list) # prints complete list
print (list[0]) # prints first element of the list
print (list[1:3]) # prints elements starting from 2nd till 3rd
print (list[2:]) # prints elements starting from 3rd element
print (list2 * 2) # prints list two times
print (list + list2) # prints concatenated lists
The above code produces the following output:
illustration not visible in this excerpt
You can add, delete or change items in a list.
Tuples
Tuples items are immutable – they cannot be changed. Tuple items are separated by commas and enclosed within curved brackets (()).
The main difference between a list and tuple is that list items can be updated whereas tuple items cannot be updated. Tuples can be thought of as read-only lists.
Like lists, you can access tuple items using the slice operator ([] and [:]).
Here are some examples.
illustration not visible in this excerpt
The above code produces the following output:
illustration not visible in this excerpt
A dictionary contains a collection of paired items in the form of key: value and enclosed within braces or curly brackets ({}). The items in a dictionary can be strings or numbers.
Dictionary items are accessed by their key values or by using functions like keys() and values() as shown in the code below.
illustration not visible in this excerpt
Note that dictionary items are unordered, so the concept of order doesn’t arise.
2.15 Input/Output Statements
The input statement (function) is used to read data from the Keyboard. It takes the form
variable = input ('prompt')
where variable stores the data entered, and prompt prompts the user to enter the data.
The statement terminates when the user presses the Enter key.
Here is an example.
x = input('Enter a value: ')
Enter a value prompts the user to enter a value and x stores the value entered.
You can insert escape sequences inside an input function. For example, to display the prompt on a new line, you can use '\n' as in the following code:
y = input('\nEnter a value: ')
The print function is used for displaying output (results) on the monitor. It takes the form
print (output-list)
where output-list is a list of variables or expressions that you want to print/display.
Here is an example.
illustration not visible in this excerpt
This will produce the flowing output.
5 7
You can also include labels and escape sequences within the print statement (function) as in the code below.
illustration not visible in this excerpt
This will produce the following output.
illustration not visible in this excerpt
2.16 Importing Modules
A typical Python program will include several standard library/built-in functions and methods to perform a variety of tasks such as getting the length of a string, converting data from one type to another, reading input form the keyboard, sending output to the monitor or file, etc.
However, Python doesn’t provide all the functions that users will need. But there are many modules (also called classes) available on the Net that contain functions (also called methods) to perform all sorts of tasks – mathematical, statistical, random number generation, string processing, and plotting graphs. To use these functions, you need to import the modules (classes) that contain these functions.
The import statement takes the form import module For example, to import functions from math and random modules, you will use statements import math import random To import a specific function, say randint from the random module, you will use the statement
illustration not visible in this excerpt
where random is the module and randint is the function.
Exercise
1. List the Python data types.
2. Which of the following identifiers are invalid?
(a) some-value
(b) interest rate
(c) roi%
(d) $salary
(e) cityName
(f) net__pay
(g) sum_of_x&y
(h) 123store
(i) store123
(j) #comment
(k) _alias
(l) __init__
3. Given x = 10, y = 7 and z = 2 which of the following expressions are False?
(a) x > y + z
(b) z <= 7
(c) x == y
(d) x != z
(e) y + z <= x
(f) x – y > z
(g) x % y == 3
(h) z ** 2 > x
(i) -(–x – z) >= y
(j) x – y - x
4. Given integer variables x, y and z with values 10, 7, 2 respectively, write code to compute the value of each of the following arithmetic expressions:
(a) x + 2 * y - z
(b) x / z -(x * x + y)
(c) (x * y) % z
(d) 5*(x + y + z)- x/z
(e) x * y – x * z
(f) y *(x + z)*(x - y)
5. Given integer variables a = 2, b = 5, c = 7 and floating-point variables x = 10.0, y = 10.5, z = 20.0, write code to obtain the correct result for each of the following expressions:
(a) y + a/b
(b) a + b * z / a)
(c) x + (b / a) * c
6. Using the values given in question 5, calculate the value of each of the following expressions:
(a) a++
(b) a < 2 && y > 5.0
(c) c >= a
(d) a < b || b > c
(e) z != 10.0
(f) a == 25
7. Given the following assignment statements:
i = 4, j = 21
x = 94.55
a = 'z', b = 't', c = ' '
p = q = r = 7
Determine the value of the variable on the left-hand side in the following statements:
(a) k = i * j
(b) y = x + i
(c) y = k = j
(d) a = b = c
(e) i += j
(f) j -= (k = 5)
(g) p + x - i
8. Which of the following comments are valid?
(a) 'majestic mountains'
(b) "I can't believe that!'
(c) 'why don't you believe?"
(d) """sure, things will be brighter next year" '
(e) 'that is not "what I really said"'
(f) "it's OK, """is it really OK? """ "
9. Trace the output of the following code:
x = y = z = 57
a, b, c = 22, 33, 55
p, q = 22.35, 79.82
r1 = x + a
r2 = z + b
x = c + q
print (r1, r2, x)
10. Given x = 4, y = 21, z = 94.55, a = 'nice', b = 'meal', c = ' ', write to compute the following
z – 2 * (x + y)
a + c + b
a * 3
y % x + z
(a + c + b) * 3
((a + c + b + c + c)*3)
((a + c + b + c*2) * 3)
Chapter 3 Control Structures
Learning Outcomes:
After completing this chapter, the student will be able to
- Explain control structures in programs.
- Use if , if…else, if…elif…else statements.
- Use for, for…else, while and while…else loops.
- Use range function.
- Use nested loop.s
- Use break, continue and pass statements.
Control structure refers to the order of execution of instructions/statements in a computer program. Basically there are three types/structures of control flows: sequence, decision making and loop (also called repetition/ iteration). Besides these, there are also other control flows for exiting or continuing a loop before it ends normally.
3.1 Sequence
This is the simplest control flow structure. In this structure, statements are executed sequentially - one by one starting from the first to the last.
Here is an example.
illustration not visible in this excerpt
The above statements are executed in that order from x = 5 to print (z).
This control structure alone is insufficient to solve real-life problems. You need other control structures such as decision making and looping.
3.2 Decision Making
The decision control structure allows a program to branch off or jump to another section of the code based on a certain condition, for example, to display the grade Fail if a student’s mark is less than 50 and the grade Pass if the mark is 50 or above.
This control flow comes in three forms:
1) if
2) if…else
3) if…elif…else
We will discuss each of these in the sequel.
§ if
This type takes the form
if (expression):
statement(s) # code block
If the expression evaluates to True, the statements in the code block will be executed; otherwise, the statements will be skipped. Any expression that evaluates or takes a non-zero value is evaluated to True; otherwise, it is evaluated to False.
Here are some simple sample programs (code snippets).
Program (code snippet) 3.1 tests if x < y. Since it is True, it displays the message in the print statement. If the expression is y < x, nothing will be displayed because it will evaluate to False.
Program 3.1
illustration not visible in this excerpt
Output
x is smaller than y
Program 3.2 tests the expression x && y. Since it evaluate to False, there will be no output.
illustration not visible in this excerpt
Program 3.3 tests the compound expression x<y && p||q. Since it evaluates to True, it will output the message in the print statement.
Program 3.3
illustration not visible in this excerpt
Output
The whole expression is true.
Program 3.4 tests if y evaluates to True. As y is not zero, it evaluates to True; so the code will display the message in the print statement.
Program 3.4
illustration not visible in this excerpt
Output
y evaluates to True
Program 3.5 tests if x evaluates to True. As x is zero, it evaluates to False; so the code will not display the message in the first print statement. However, it will display the message in the second print statement because the string s evaluates to True.
Program 3.5
illustration not visible in this excerpt
Output
True condition
Program 3.6 will not display the message in the first print statement (as b is False) but will display the message in the second print statement (as speed > 110 is True).
Program 3.6
illustration not visible in this excerpt
Output
You have committed a traffic offense!
Program 3.7 will display the message in the print statement as the expression speed==110 evaluates to True.
Program 3.7
illustration not visible in this excerpt
Output:
Beware - you are driving at maximum speed!
Here are more examples.
Program 3.8
illustration not visible in this excerpt
Output
You have passed!
Program 3.9
illustration not visible in this excerpt
Output:
The mark is valid.
§ if…else
illustration not visible in this excerpt
If expression evaluates to True, statement1 (code block) is executed; otherwise statement2 (code block) is executed. Only one of the code blocks will be executed.
Here are some examples.
Program 3.10 will execute only the second print statement as the first condition evaluates to False so control passes to the else block.
Program 3.10
illustration not visible in this excerpt
Output
The mark is invalid.
Program 3.11 will execute only the first print statement as the first condition evaluates to True.
Program 3.11
illustration not visible in this excerpt
Output
Your speed is OK!
Here are more examples.
Program 3.12
illustration not visible in this excerpt
Output
You are driving recklessly!
Program 3.13
illustration not visible in this excerpt
Output
Congrats - you passed the test!
[...]
- Arbeit zitieren
- Palaniappan Sellappan (Autor:in), 2018, Learn Python. The Easy Way, München, GRIN Verlag, https://www.grin.com/document/435037
Kostenlos Autor werden
Kommentare