Wednesday, 4 September 2019

Program for Prime Number test in Python


Prime numbers:

Test for prime number
1)      Number should be greater than 1.
2)      There should not be any positive divisor other than 1 and itself.
 Example: 3,5,7,11,13,17,19 etc

 Composite number:

Composite numbers are the natural numbers other than Prime Numbers.
Other natural numbers that are not prime numbers are called composite numbers.
 Example : 4,6,8,9,10,12,14,15,18,20 etc

Program :
#Program for Prime number checking
num = int(input('Enter a Number for Prime number test:'))
if(num>1):
     for i in range(2,num):
          if(num%i==0):
               print(num,'is not a Prime Number')
               break
     else:
          print(num, 'is Prime Number')
else:
     print(num,"Number is not Prime Number")

Output:
RESTART: C:/Users/shrik/AppData/Local/Programs/Python/Python37-32/testprume.py
Enter a Number for prime number test:5
5 is prime number
>>>
 RESTART: C:/Users/shrik/AppData/Local/Programs/Python/Python37-32/testprume.py
Enter a Number for prime number test:6
6 is not a prime number
>>>
 RESTART: C:/Users/shrik/AppData/Local/Programs/Python/Python37-32/testprume.py
Enter a Number for Prime number test:1
1 Number is not Prime Number
>>> 


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.