Monday, 19 August 2019

1.15 Operators and expressions


Operators and expressions:
Arithmetic Operators:
Addition +, Add two operands
 Substraction -, Subtract two operands
 Multiplication *, multiply two operands
Division /, divide two operands
floor division //, Divide and round off
Modulo division % , divide and give reminder as output
Program:
x=11
y=5
addition = x+y
substraction = x-y
multiplication=x*y
division= x/y
floordivision=x//y
modulodiv=x%y
print('x=',x,'y=',y)
print('addition=',addition)
print('substraction=',substraction)
print('multiplication',multiplication)
print('division',division)
print('floordivision',floordivision)
print('modulodiv',modulodiv)
Output:
x= 11 y= 5                                                                                                                       
addition= 16                                                                                                                     
substraction= 6                                                                                                                  
multiplication 55                                                                                                                
division 2.2                                                                                                                     
floordivision 2                                                                                                                  
modulodiv 1      

Logical Operators:
Logical AND, true if both operands are true else false.  x and y
Logical OR, true if any one of the operands is true else false.  x or y
Logical NOT, true if operand is false. not x
Relational Operators:
Greater Than >
Less Than <
Equal to ==
Not Equal to !=
Greater than equal >=
Less than equal <=

Expressions in Python
Expressions are representations of value. They are different from statement in the fact that statements do something while expressions are representation of value. For example, any string is also an expression since it represents the value of the string as well.

1.14 Input operation Comments Indentation


Input operation:
Input operation is used for taking input from command line/prompt that is from user.
username = input(‘Enter user name:’)
print(username)

Comments:
In Python comments are followed by ‘#’ sign.
Reserved words
A keyword is an identifier that has predefined meaning in a programming language and therefore cannot be used as a “regular” identifier. Doing so will result in a syntax error.

Indentation
indentation is four spaces.
Don't use tabs, don't mix them with spaces. Use four spaces, not two, not three, not five. Just use four.
To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example if-statement are both indented four spaces, which is a typical amount of indentation for Python

order_total = 247 # GBP
# classic if/else form
if order_total > 100:
    discount = 25 # GBP
else:
    discount = 0 # GBP
print(order_total, discount)

1.13 Variables and Identifiers, Data types


Variables and Identifiers-
A variable is a name that is associated with a value. The assignment operator is used to assign values to variables. An immutable value is a value that cannot be changed.
Num= 10
An identifier is a sequence of one or more characters used to name a given program element. In
Python, an identifier may contain letters and digits, but cannot begin with a digit. The special underscore character can also be used.


Data Types
1.      Integers
2.      Booleans
3.      Floating-Point Types 
Integers
Python integers have unlimited range, subject only to the available virtual memory. This means that it doesn't really matter how big a number you want to store: as long as it can fit in your computer's memory, Python will take care of it. Integer numbers can be positive, negative, and 0 (zero). They support all the basic mathematical operations, as shown in the following example:
>>> a = 12
>>> b = 3

Booleans
There are two built-in Boolean objects: True and False. Like all other Python data types (whether built-in, library, or custom), the bool data type can be called as a function—with no arguments it returns False, with a bool argument it returns a copy of the argument, and with any other argument it attempts to convert the given object to a bool. All the built-in and standard library data types can be converted to produce a Boolean value, and it is easy to provide Boolean conversions for custom data types. Here are a couple of Boolean assignments and a couple of Boolean expressions:
>>> t = True
>>> f = False
>>> t and f
False
>>> t and True
True

Floating-Point Types
Python provides three kinds of floating-point values: the built-in float and complex types, and the decimal. Decimal type from the standard library. All three are immutable. Type float holds double-precision floating-point numbers whose range depends on the C (or C# or Java) compiler Python was built with; they have limited precision and cannot reliably be compared for equality.
Numbers of type float are written with a decimal point, or using exponential notation, for example, 0.0, 4., 5.7, -2.5, -2e9, 8.9e-4.

1.12 String Formatting


String Formatting
Built-in function format can be used to control how strings are displayed.
We saw above the use of built-in function format for controlling how numerical values are displayed. We now look at how the format function can be used to control how strings are displayed. As given above, the format function has the form,
format (value, format_specifier)
where value is the value to be displayed, and format_specifier can contain a combination of formatting options. For example, to produce the string 'Hello' left-justified in a field width of 20 characters would be done as follows,
format('Hello', ' < 20') 'Hello '
To right-justify the string, the following would be used,
format('Hello', ' > 20') ' Hello'
Formatted strings are left-justified by default. To center the string the '^' character is used:
format('Hello', '^20'). Another use of the format function is to create strings of blank characters, which is sometimes useful.

1.11 Literal constants


Literal constants-
A literal is a sequence of one or more characters that stands for itself.
The numbers such as 2,51,100.12 are literal constant as value of its is constant.
Also strings such as “Welcome to Python tutorial” are also literal constants.
Numeric Literals
A numeric literal is a literal containing only the digits 0–9, an optional sign character (1 or 2), and a possible decimal point. (The letter e is also used in exponential notation, shown in the next
subsection). If a numeric literal contains a decimal point, then it denotes a floating-point value, or “float (e.g., 10.24); otherwise, it denotes an integer value (e.g., 10). Commas are never used in numeric literals.

The numbers such as -2, +51, 100.12, -100.12
Limits of Range in Floating-Point Representation
There is no limit to the size of an integer that can be represented in Python. Floating-point values,
however, have both a limited range and a limited precision. Python uses a double-precision standard format (IEEE 754) providing a range of 10 2 308 to 10 308 with 16 to 17 digits of precision. To denote such a range of values, floating-points can be represented in scientific notation.

Arithmetic overflow occurs when a calculated result is too large in magnitude to be represented.
Arithmetic underflow occurs when a calculated result is too small in magnitude to be represented.
String Literals:
Numerical values are not the only literal values in programming. String literals, or “strings,” represent a sequence of characters,
'Hello' 'Smith, John' "Baltimore, Maryland 21210"
In Python, string literals may be delimited (surrounded) by a matching pair of either single (') or
double (") quotes. Strings must be contained all on one line (except when delimited by triple quotes). We have already seen the use of strings in Chapter 1 for displaying screen output,
... print ('Welcome to Python!')
Welcome to Python!

1.10 IDE

IDE- Integrated Development Environment
Pycharm 

1.9 Writing and executing Python program


Writing and executing Python program
·         Python code can be written using any plain text editor that can load and save text using either the ASCII or the UTF-8 Unicode encoding.
·         By default, Python files are assumed to use the UTF-8-character encoding, a superset of ASCII that can represent pretty well every character in every language.
·         Python files normally have an extension of .py, although on some Unix-like systems (e.g., Linux and Mac OS X) some Python applications have no extension, and Python GUI (Graphical User Interface) programs usually have an extension of. pyw, particularly on Windows and Mac OSX. In this book we always use an extension of .py for Python console programs and Python modules, and. pyw for GUI programs.
·         Just to make sure that everything is set up correctly, and to show the classical first example, create a file called hello.py in a plain text editor (Windows Notepad is fine—we’ll use a better editor shortly), with the following contents:

#!/usr/bin/env python3

print("Hello", "World!")

·         The first line is a comment. In Python, comments begin with a # and continue to the end of the line. (We will explain the rather cryptic comment in a moment.)

·         The second line is blank—outside quoted strings, Python ignores blank lines, but they are often useful to humans to break up large blocks of code to make them easier to read.

·         The third line is Python code. Here, the print() function is called with two arguments, each of type str (string; i.e., a sequence of characters).
·         Each statement encountered in a .py file is executed in turn, starting with the first one and progressing line by line. This is different from some other languages, for example, C++ and Java, which have a particular function or method with a special name where they start from.
·         The flow of control can of course be diverted as we will see when we discuss Python’s control structures in the next section.

Now that we have a program, we can run it.
·         Python programs are executed by the Python interpreter, and normally this is done inside a console window. On Windows the console is called “Console”, or “DOS Prompt”, or “MS-DOS Prompt”.
·         Start up a console, and on Windows enter the following commands (which assume that Python is installed in the default location)—the console’s output is shown in lightface; what you type is shown in bold:
C:\>cd c:\py3eg
C:\py3eg\>c:\python31\python.exe hello.py

·         Since the cd (change directory) command has an absolute path, it doesn’t matter which directory you start out from. Unix users enter this instead (assuming that Python 3 is in the PATH):
$ cd $HOME/py3eg
$ python3 hello.py
In both cases the output should be the same:
Hello World!

1.8 History and Future of Python


History and Future of Python:
Guido van Rossum is the creator of the Python programming language, first released in the early 1990s. Its name comes from a 1970s British comedy sketch television show called Monty Python’s Flying Circus.  (Check them out on YouTube!)
The development environment IDLE provided with Python (discussed below) comes from the name of a member of the comic group.
Python has a simple syntax. Python programs are clear and easy to read. At the same time, Python provides powerful programming features, and is widely used.
 Companies and organizations that use Python include YouTube, Google, Yahoo, and NASA. Python is well supported and freely available at www.python.org. (See the Python 3 Programmers’ Reference at the end of the text for how to download and install Python.)

1.7 Python features


 Python features:
1)      Easy to Learn and Use - easy to learn, use, developer-friendly and high-level programming language.

2)      Expressive Language- more expressive means that it is more understandable and readable

3)      Interpreted Language - an interpreted language i.e. interpreter executes the code line by line at a time. This makes debugging easy and thus suitable for beginners.

4)      Cross-platform Language- can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a portable language

5)      Free and Open Source - freely available at official web address. The source-code is also available. Therefore, it is open source.

6)      Object-Oriented Language - supports object-oriented language and concepts of classes and objects come into existence.

7)      Extensible- It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our python code.

8)      Large Standard Library - a large and broad library and provides rich set of module and functions for rapid application development.

9)      GUI Programming Support.

10)  It can be easily integrated with languages like C, C++, JAVA etc.

Sunday, 18 August 2019

Program Design Tools


Program Design Tools: Algorithms, Flowcharts and Pseudo-codes, implementation of algorithms

Algorithms

A programming algorithm is a computer procedure that is a lot like a recipe (called a procedure) and tells your computer precisely what steps to take to solve a problem or reach a goal. ... We looked at a simple example of an algorithm that does some preparation, asks a user for an email address, and decides what to do.

An algorithm is a finite number of clearly described, unambiguous “doable” steps that can be
systematically followed to produce a desired result for given input in a finite amount of time.

 A programming algorithm describes how to do something, and your computer will do it exactly that way every time. Well, it will once you convert your algorithm into a language it understands!

However, it's important to note that a programming algorithm is not computer code. It's written in simple English (or whatever the programmer speaks). It doesn't beat around the bush--it has a start, a middle, and an end.

In fact, you will probably label the first step 'start' and the last step 'end.' It includes only what you need to carry out the task. It does not include anything unclear, often called ambiguous in computer lingo, that someone reading it might wonder about.

It always leads to a solution and tries to be the most efficient solution we can think up. It's often a good idea to number the steps, but you don't have to. Instead of numbered steps, some folks use indentation and write in pseudocode, which is a semi-programming language used to describe the steps in an algorithm. But we won't use that here since simplicity is the main thing.   



Flowchart:

Program flowchart is a diagram that uses a set of standard graphic symbols to represent the sequence of coded instructions fed into a computer, enabling it to perform specified logical and arithmetical operations. It is a great tool to improve work efficiency. There are four basic symbols in program flowchart, start, process, decision and end. Each symbol represents a piece of the code written for the program.


Start event symbol signals the first step of a process.

Program flowchart shapes like start, process, decision and end are available here.

Process is a series of actions or steps taken in order to achieve a particular end.

Decision is the action or process of deciding something or of resolving a question.

End event symbol stands for the result of a process.












Problem solving aspects,Top Down Design

 
Problem solving aspects

1.       Identify the problem

2.      Understand the problem

3.      Identify alternative ways to solve the problem

4.      Select the best way to solve the problem from the list of alternative solutions.

5.      List instructions that enable you to solve the problem using the selected solution.

6.      Evaluate the solution.

Top Down Design

A top-down design is generally a plan made in plain, simple English for the program. It is very important to note that a top-down design must be independent of any programming language. The top-down design must never incorporate references to library functions or syntactic elements specific to a particular language.

That is the reason why top-down designs are written in plain English. The concept driving a top-down design is to break up the task that a program executes into a very few extensive subtasks.

The highest level is known as the main module, top level or level 0. At this point, the volume of subtasks must be small. Most programs at this level usually include three to seven subtasks. For small-sized programs, the volume of subtasks must be at the low end of the mentioned range.

Division of tasks into subtasks essentially splits the problem into various smaller programs, which helps developers to easily code these simpler parts. It is usually possible that many of these subtasks are so basic that they can immediately determine how to write the code to complete that part.

However, this is generally not the case at the top level. If a subtask takes more than a very few lines of code, it is recommended to repeat the subdivision process. Typically, for every subtask at top level, a new module is started at level 1. These subtasks are then considered individually, and yet again divided into various other subtasks. This subdivision and new level creation processes should be continued until the coders can implement every portion of the problem using computer code.

Questions


Questions

1. What are the six steps of problem solving?

2. What is an algorithmic solution to a problem?

3. Name three current problems in your life that could be solved through an algorithmic process. Explain why each of these problems is algorithmic in nature.

4. What is a heuristic solution to a problem?

5. Name three current problems in your life that might be solved through a heuristic approach. Explain why each of these problems is heuristic in nature.

6. Name three problems that might arise at home, at school, or in a business that could be solved more efficiently with computer assistance. Do these problems require an algorithmic or heuristic solution? Why?

7. State a reason why each of the six problem-solving steps is important in developing the best solution for a problem. Give one reason for each step.

Problem Solving with Computers


Problem Solving with Computers

The term solution means the instructions listed during step 5 of problem solving—the instructions that must be followed to produce the best results.

Results means the outcome or the completed computer-assisted answer.

Program means the set of instructions that make up the solution after they have been coded into a particular computer language.

Computers are built to deal with algorithmic solutions, which are often difficult or very time consuming for humans.

People are better than computers at developing heuristic solutions.

Solving a complicated calculus problem or alphabetizing 10,000 names is an easy task for the computer, but the problem of how to throw a ball or how to speak English is not.

The difficulty lies in the programming. How can problems such as how to throw a ball or speak English be solved in a set of steps that the computer can understand? The field of computers that deals with heuristic types of problems is called artificial intelligence.

Artificial intelligence enables a computer to do things like build its own knowledge bank and speak in a human language. As a result, the computer’s problem-solving abilities are similar to those of a human being.

Artificial intelligence is an expanding computer field, especially with the increased use of Robotics. Until computers can be built to think like humans, people will process most heuristic solutions and computers will process many algorithmic solutions.



Difficulties with Problem Solving

People have many problems with problem solving.

Some have not been taught how to solve problems. Others are afraid to make a decision for fear it will be the wrong one.

Often, when people go through the problem-solving process, they complete one or more of the steps inadequately.

They may not define the problem correctly or may not generate a sufficient list of alternatives. When choosing the best alternative, they may eliminate good alternatives or list the pros and cons too hastily.

They may not use a logical sequence of steps in their solution, or they may focus on details before the framework for the solution is in place.

Finally, they may incorrectly or haphazardly evaluate the solution.

The problem-solving process is not easy. It takes practice and time to perfect, but in the long run the process proves to be of great benefit.

When solving problems on the computer, one of the most difficult tasks for the problem solver is writing the instructions.

Take the task of deciding which number is the largest from a group of three numbers. Almost anyone can immediately tell which is the largest, but many cannot explain the steps they followed to arrive at it.

Most people will say, “I can’t explain how I know, I just know it!” This explanation is not good enough for the computer. The computer is a tool that will perform only tasks that the user can explain.

The computer has a specific system of communication that programmers and users must learn. This system demands that no step in the solution to a problem be left unstated and that all steps be in the proper order.

You must assume the computer knows nothing except what you tell it and think of it as an ignorant but efficient aid to problem solving.