Problem Solving With Python1

 

UNIT-I

INTRODUCTION TO COMPUTING AND PROBLEM SOLVING:

Fundamentals of Computing

The word computer is derived from the word compute. Compute means to calculate. The computer was originally defined as a super fast calculator. It had the capacity to solve complex arithmetic and scientific problems at very high speed. But now a days computers  can perform many other tasks like accepting, sorting, selecting, moving, comparing various types of information. They also perform arithmetic and logical operations on alphabetic, numeric and other types of information. This information provided by the user to the computer is data.

The information in one form which is presented to the computer is the input information or input data.

A Computer is an electronic device that processes data and converts it into information that is useful to people.

Characteristics of computer

1) Speed: The processing speed of the computer is generally measured in nanoseconds (10-9 seconds). A computer can add two 18 digit numbers within one nano second.

2) Accuracy: Computers can do calculations without mistakes. A human being may make mistakes in calculating a certain range of calculations. But the results given by computer will always be accurate.

3) Reliable: The major reason behind the reliability of computers is that at hardware level, it does not require any human intervention between its processing operations. A human being sometimes knowingly or unknowingly gives results which may be biased. But a computer being impartial, gives always reliable results which can be relied upon by all.

4) Storage Capacity: A computer can store large quantity of data. The storage capacity of the computer can be increased further by secondary memory devices. The data can be saved and used at any time in future.

5) Diligence: A computer can do the work for days together. It will work without any boredom and tiredness. Even if it does the same work many times, it won’t get frustrated like a human being. Moreover a computer will work with same tempo from beginning to end.

6) Versatility: Computer can perform multiple tasks simultaneously with equal ease. They feed data, calculate sums, perform programming and provide multimedia facilities. That is why they are used in all types of business.

7) Networking Capacity: A computer can be connected with other computers & share the resources like data, printer etc. This feature of connectivity with other computers lead to evolution of computer networking. We can communicate with people in the world because of networking which ultimately leads to evolution of internet.

8) Compactness: Computers occupy very small space in offices or organizations. Now-a-days size of computers has decreased a lot due to increased technology. The laptop & notebook computers can be taken outside. They can be operated in cars, railways, buses etc. In spite of their small size, their efficiency has increased a lot.

9) Easy Maintenance: Computers can be managed easily. They can be repaired immediately. The maintenance cost of computers is small. They need not require much electricity.

10) Programmable: The computer can be programmed to work automatically. They start the work as per our program and terminate the work until we are satisfied.

Generations of Computers:

The evolution of computers can be divided into the following Five generations

First Generation  1940-1956: The computers of the period 1940-1956 are considered as the First Generation Computers. The first generation computers were slow, huge and expensive. These computers used vacuum tubes. First generation computers operated only on machine language.

Example: UNIVAC and ENIAC.

Second Generation - 1956-1963: The computers of the period 1956-1963 are considered as the Second Generation Computers. These computers used transistors. These computers used assembly language.

In the second generation computers:

·       Size of the computers started reducing

·       Concept of stored program emerged

·       High level languages were invented.

Example: IBM 7094 series, IBM 1400 series and CDC 164etc.

Third Generation - 1964-1971 : The computers of the period 1964-1971 are considered as the Third Generation Computers. These computers used Integrated circuits (ICs).

·   Phenomenal increase in computation speed

· Substantial reduction in size and power consumption of the machines

·   Commercial production of computers.

Example: IBM 370, UNIVAC 1108etc.

Fourth Generation - 1971-Present : The computers of the period 1971-present are considered as the Fourth Generation Computers. These computers used microprocessors.

·       Use of Very Large Scale Integration

·       Invention of microcomputers

·       Introduction of Personal Computers

·       Networking

·       Fourth Generation Languages.

Example: Apple Macintosh and IBM PC.

Fifth Generation - Present and Beyond: The computers of present and beyond are considered as the Fifth Generation Computers. These computing devices are based on ‘artificial intelligence’. Many advances in the science of computer design and technology are coming together to enable the creation of fifth generation computers.

Example: IBM Watson computer,SGI Origin 2000 , PARAM 10000

 

Computing Devices

Computers can be classified as general-purpose computers, specific purpose computers or super computers.

General-purpose computers compute a range of tasks but lack super speed and efficiency. The purpose of computers in this category might differ from one another: 

Examples are:

Desktop computers

Laptops

Tablets

Smartphones.

Specific purpose computers handle a specific problem or task. It uses a high level of accuracy and processing power. 

Examples are:

Servers

Embedded devices.



 


















Identification of Computational Problems

(Discuss about identification of computational problems.)

We (humans) write computer programs to solve problems. In this context, a problem is a description of some desired output we wish to obtain from a specific, defined type of input.

An algorithm is a finite, unambiguous, sequence of instructions that yields a correct solution to a problem.  (yields the correct output for each possible input value.)

Computer programs are implementations of algorithms.  We choose a language and use the syntax of that language to implement the algorithm.  So, before we can write a single line of code for a program, we must know what algorithm we are trying to implement.

 

Algorithms :

An algorithm is method of representing step by step procedure for solving a problem.

An algorithm is a part of the plan for the computer program. In fact, an algorithm is‘an effective procedure for solving a problem in a finite number of steps’.

An algorithm is very useful for finding the right answer to a problem or breaking the difficult problem into simple cases.

Steps for Algorithm Development:-

1. Initially understand the problem

2. Then, identify the expected output for the problem

3. Identify the necessary input for the problem.

4. Develop the logic that produces the expected output from the selected input.

5. Finally, test the algorithm with various set of inputs.

Characteristics of Algorithm:-

An Algorithm must process the following characteristics

1. Finiteness

2. Definiteness

3. Effectiveness

4. Input

5. Output

1. Finiteness

An Algorithm should terminate in a finite number of steps

2. Definiteness

Each step of algorithm must be clear and unambiguous.

3. Effectiveness

Each step must be effective, in the sense that, it should be easily convertible into program

statement and can be performed exactly in a finite amount of time.

4. Input

Each algorithm must take Zero, one or more quantities as input data

5. Output

Each algorithm must produce at least one output.

Example 1: To find sum of two numbers

Step 1: Start/begin

Step 2: Declare Num1, Num2 and Sum

Step 3: Read Num1 , Num2

Step 4: Sum Num1 + Num2

Step 5: Print or Display Sum

Step 6: Stop/End

Advantages of Algorithms:

· It provides the core solution to a given problem. The solution can be implemented on a computer system using any programming language of user’s choice.

·  It facilitates program development by acting as a design document or a blue print of a given problem solution.

·  It ensures easy comprehension of a problem solution as compared to an equivalent computer program.

· It eases identification and removal of logical errors in a program.

· It facilitates algorithm analysis to find out the most efficient solution to a given problem. 

Disadvantages of Algorithms:

·       In large algorithms the flow of program control becomes difficult to track.

·       Algorithms lack visual representation of programming constructs like flowcharts; thus understanding the logic becomes relatively difficult.

 Different ways of stating Algorithms

An algorithm can be written in following two ways:

1. Pseudo code

2. Flow chart



PseudoCode :-

àOne of the commonly used tools to define algorithms is the pseudocode.

The word pseudo means imitation and code means instructions written some programming language.

A pseudocode is an English-like presentation of the code required for an algorithm.

Pseudo code describes the complete logic of some program so that implementation become easy. It does not use any syntax or symbols.

àAn algorithm can be written in any of the natural languages such as English, German, French, etc.

àIt is partly English and partly computer language structure code. The structure code is nothing but syntax constructs of a programming language.


Pseudo Code Algorithm:-

Algorithm sort(ref A<integer>, val N<integer>)

Pre      array A to be sorted

Post    sorted array A

Return None

  1. if(N < 1) goto step (4)
  2. M = N − 1
  3. For I = 1 to M do

For J = I + 1 to N do

 begin

if(A(I) > A(J))

then

                        begin

T = A(I)

A(I) = A(J)

A(J) = T

                         end

              end if

        end

4. stop

 

FLOWCHARTS:- (What is Flowchart ?Explain Various Notations used for flowchart)

A Flowchart is a type of diagram (graphical or symbolic) that represents an algorithm or process.

Each step in the process is represented by a different symbol and contains a short description of the process step.

The flow chart symbols are linked together with arrows showing the process flow direction.

A flowchart describes what operations (and in what sequence) are required to solve a given problem

Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields

 


 



















BUILDING BLOCKS OF ALGORITHMS (Explain Building Blocks of Algorithms?)

Algorithms can be constructed from basic building blocks namely, sequence, selection and iteration.

Statements:

Statement is a single action in a computer. In a computer statements might include some of the following actions

Input data-information given to the program

Process data-perform operation on a given input

Output data-processed result

A selection statement causes the program control to be transferred to a specific part of the program based upon the condition.

If the conditional test is true, one part of the program will be executed, otherwise it willexecute the other part of the program.

State:

Transition from one process to another process under specified condition with in a time is called state.

Control flow:

The process of executing the individual statements in a given order is called control flow.

The control can be executed in three ways

1. Sequence

2. Selection

3. Iteration

Sequence:

An algorithm is a sequence of instructions, which can be a simple instruction (input, output, or assignment) or either of the other two constructs. All the instructions are executed one after another is called sequence execution.

Algorithm computes the area of a circle.

Pre None

Post None

Return None

1. Read Radius

2. AreaOfCircle = 2 * 3.142 * Radius * Radius

3. Print AreaOfCircle

4. Stop

 

Selection/Decision:

Some problems cannot be solved with the help of just a sequence of simple instructions.Sometimes, we need to test the conditions. If the result of the testing is true, we follow a sequence of instructions; if it is false, we follow a different sequence of instructions. This is called decision or selection construct

Algorithm Compare two numbers to print the maximum among them.

Pre None

Post None

Return None

1. Read two numbers Num1 and Num2

2. If Num1 > Num2

Then Print Num1

Else Print Num2

3. Stop

 

Iteration:

In some programs, certain set of statements are executed again and again based upon conditional test. i.e. executed more than one time. This type of execution is called looping or iteration.

Repetition construct

Pre None

Post None

Return SUM

1. Read N

2. Let SUM = 0 and Index = 1

3. while Index <= N do

SUM = SUM + Index

Index = Index + 1

end while

4. Return SUM

 

Functions:

Function is a sub program which consists of block of code(set of instructions) that performs a particular task.

For complex problems, the problem is been divided into smaller and simpler tasks during algorithm design.

Write an algorithm to compute the following: P = n!/(n − r)!

Pre None

Post None

Return Result

1. Read n and r

2. Let

(a) A = FACT(n) and

(b) B = FACT(n − r)

3. Result = A / B

4. Print Result

5. Stop

Here FACT is the function to compute the factorial of a number as

n! = n × (n - 1) × (n - 2) × ... × 1

 

Function  FACT

1. Read n

2. Let Result = 1

3. while(n not equal to 1) do

Result = Result × n

n = n – 1

end while

4. Return Result

 

Introduction to Python Programming:

2.0 Python Introduction

Python is the world's most popular and fastest-growing computer programming language. It is a multi-purpose and high-level programming language.

Python was invented by Guido Van Rossum in the year 1989, but it was introduced into the market on 20th February 1991.

The Python programming language has been used by many people like Software Engineers, Data Analysts, Network Engineers, Mathematicians, Accountants, Scientists, and many more. Using Python, one can solve complex problems in less time with fewer lines of code.

Features of Python

The Python is a very popular programming language with the following features.

▪ Python is easy to learn and easy to understand.

▪ The Python is an interpreted programming language. It executes the code line by line.

The Python is a cross-platform programming language. It can be used with any operating system like Windows, Linux, MAC OS, etc.

The Python is a free and open-source programming language.

The Python is an Object-Oriented, Procedural and Functional programming language

The Python is a multi-purpose programming language

The Python is a high-level programming language

▪ Python has a huge Community to get help all over the globe.

▪ Python has a large Ecosystem of Libraries, Frameworks, and Tools to work with it.

Python Interpreter

Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.

1. Interactive mode

2. Script mode

 

Python Interactive Mode(What is Python Interpreter and Interactive Mode? )

In the interactive mode, We can query some statements, and python will interpret/execute them and give you the output.

▪ Interactive mode is useful to test out our code before keeping them to the scripts.

We can do operations like simple calculations, and printing some variables and etc.

To bring up the interactive python shell, Search for IDLE in windows.

For Linux and Mac user, Goto Terminal and bring up the interactive python shell by running python command.

  


We can write our statements into interactive shell, In above case we written print("Hello Python") statement and pressed enter.

Then python immediately executed our print statement and displayed the output.

This is called interactive mode.

Where we can perform simple operations and get the results.

Disadvantages of interactive mode

▪ The interactive mode is not suitable for large programs.

The interactive mode doesn’t save the statements. Once we make a program it is for that time itself, we cannot use it in the future. In order to use it in the future, we need to retype all the statements.

Editing the code written in interactive mode is a tedious task. We need to revisit all our previous commands and if still, we could not edit we need to type everything again.

 Python Script Mode

Script mode in Python is where we first write the Python program inside a script file and execute it after that.

We can execute the script of code either using the Command prompt or using Python IDE installed in our system.

In order to run a code in script mode follow the following steps.

Step 1: Make a file using a text editor. You can use any text editor of your choice (Here I use notepad).

Step 2: After writing the code save the file using “.py” extension.

Step 3: Now open the command prompt and command directory to the one where your file is stored.

Step 4: Type python “filename.py” and press enter.

Step 5: You will see the output on your command prompt.

Example:

In order to execute "Hello Python" using script mode we first make a file and save it

Variables(What is a Variable? Explain?)

Variable is a named placeholder to hold any type of data which the program can use to assign and modify during the course of execution. In Python, there is no need to declare a variable explicitly by specifying whether the variable is an integer or a float or any other type.

To define a new variable in Python, we simply assign a value to a name.

Legal Variable Names

Follow the below-mentioned rules for creating legal variable names in Python.

• Variable names can consist of any number of letters, underscores and digits.

• Variable should not start with a number.

• Python Keywords are not allowed as variable names.

• Variable names are case-sensitive.

For example, computer and Computer are differentvariables.

• Python variables use lowercase letters with words separated by underscores

Ex: whats_up, how_are_you.

• Avoid naming a variable where the first character is an underscore.

• Ensure variable names are descriptive and clear enough.

Assigning Values to Variables

The general format for assigning values to variables is as follows:

variable_name = expression

The equal sign (=) also known as simple assignment operator is used to assign values to variables.

1. >>> number =100            # Here integer type value is assigned to a variable number

2. >>> miles =1000.0            # Here float type value has been assigned to variable miles

3. >>> name ="Python"       # Here string type value is assigned to variable name.

4. >>> number

100

5. >>> miles

1000.0

6. >>> name

'Python'                                 Lines ,andprints the value assigned to these variables.

 

In Python, not only the value of a variable may change during program execution but also the type of data that is assigned. You can assign an integer value to a variable, use it as an integer for a while and then assign a string to the variable.

 

For example,

1. >>> century = 100

2. >>> century

100

3. >>> century = "hundred"

4. >>> century

'hundred'

Python allows you to assign a single value to several variables simultaneously. Forexample,

1. >>> a = b = c =1

 Identifiers

An identifier is a name given to a variable, function, class or module. Identifiers may beone or more characters in the following format:

 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z)or digits (0 to 9) or an underscore (_).

Ex:Names like myCountry, other_1 and good_morning, all are valid examples.

 A Python identifier can begin with an alphabet(A – Z and a – z and _).

 An identifier cannot start with a digit but is allowed everywhere else.

Ex:1plus isinvalid, but plus1 is perfectly fine.

 Keywords cannot be used as identifiers.

 One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.

 Identifier can be of any length.

Data Types

Data types specify the type of data like numbers and characters to be stored and manipulated within a program. Basic data types of Python are

• Numbers

• Boolean

• Strings

• None

Numbers

Integers, floating point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex class in Python.

Integers can be of any length; it is only limited by the memory available. A floating point number is accurate upto 15 decimal places. Integer and floating points are separated by decimal points.

1 is an integer, 1.0 is floating point number. Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

Boolean

A condition is really just a yes-or-no question, the answer to that question is a Boolean value, either True or False. The Boolean values, True and False are treated as reserved words.

Strings

A string consists of a sequence of one or more characters, which can include letters, numbers, and other types of characters.

A string can also contain spaces. You can use single quotes or double quotes to represent strings and it is also called a string literal.

Multilinestrings can be denoted using triple quotes, ''' or """. These are fixed values, not variablesthat you literally provide in your script. For example,

1. >>> s = 'This is single quote string'

2. >>> s = "This is double quote string"

3. >>> s = '''This is

Multiline

string'''

4. >>> s = "a"

None

None is another special data type in Python. None is frequently used to represent the absence of a value. For example,

1. >>> money = None

None value is assigned to variable money .


Indentation

In Python, Programs get structured through indentation . Usually, we expectindentation from any program code, but in Python it is a requirement and not a matter ofstyle. This principle makes the code look cleaner and easier to understand and read. Anystatements written under another statement with the same indentation is interpreted tobelong to the same code block. If there is a next statement with less indentation to the left,then it just means the end of the previous code block.

In other words, if a code block has to be deeply nested, then the nested statements need to be indented further to the right. In the above diagram, Block 2 and Block 3 are nested under Block 1. Usually, four whitespaces are used for indentation and are preferred over tabs. Incorrect indentation will result in Indentation Error.

 


Values and Types

A value is one of the basic things a program works with, like a letter or a number. 

Some values we have seen so far are 2, 42.0, and 'Hello, World!' 

Here  2 is an integer, 42.0 is a floating-point number, and 'Hello, World!' is a string.

If you are not sure what type a value has, the interpreter can tell you:

>>> type(2)

<class 'int'>

>>> type(42.0)

<class 'float'>

>>> type('Hello, World!')

<class 'str'>

In these results, the word “class” is used in the sense of a category; a type is a category of values.

 

Not surprisingly, integers belong to the type int, strings belong to str, and floating point numbers belong to float.

 

>>> type('2')

<class 'str'>

>>> type('42.0')

<class 'str'>

They’re strings.

 

What about values like '2' and '42.0'? They look like numbers, but they are in quotation marks like strings:

 

 

 

>>> 1,000,000

(1, 0, 0)

When you type a large integer, you might be tempted to use commas between groups of digits, as in 1,000,000. This is not a legal integer in Python, but it is legal:

 

Comments

A comment is a text that describes what the program or a particular part of the program is trying to do and is ignored by the Python interpreter. Comments are used to help you and other programmers understand, maintain, and debug the program. Python uses two types of comments: single-line comment and multiline comments.

Single Line Comment

In Python, use the hash (#) symbol to start writing a comment. Hash (#) symbol makes alltext following it on the same line into a comment. For example,

#This is single line Python comment

Multiline Comments

If the comment extends multiple lines use hash (#) symbol at the beginning of each line.

#This is

#multiline comments

#in Python

Another way of doing this is to use triple quotes, either ''' or """.  For example,

'''This is

multiline comment

in Python using triple quotes'''


Keywords


Keywords are a list of reserved words that have predefined meaning. Keywords are special vocabulary and cannot be used by programmers as identifiers for variables, functions, constants or with any identifier name. Attempting to use a keyword as an identifier name will cause an error. The Table shows the Python keywords.

 





Operators

Python language supports a wide range of operators. They are

1. Arithmetic Operators

2. Assignment Operators

3. Comparison Operators

4. Logical Operators

5. Bitwise Operators

Arithmetic Operators:(Explain about Arithmetic operators with an example program.)

Python provides operators, which are special symbols that represent computations like addition and multiplication. The operators +, -, and * perform addition, subtraction, and multiplication, as in the following examples:









>>> 40 + 2

42

>>> 43 - 1

42

>>> 6 * 7

42

The operator / performs division:

>>> 84 / 2

42.0

The operator ** performs exponentiation; that is, it raises a number to apower:

>>> 6**2 + 6

42

In some other languages, ^ is used for exponentiation, but in Python it is a bitwise operator called XOR.

>>> 6 ^ 2

4

 

Assignment Operators

Assignment operators are used for assigning the values generated after evaluating the right operand to the left operand. Assignment operation always works from right to left. Assignment operators are either simple assignment operator or compound assignment operators.



Ex: For example,

1. >>> p = 10

2. >>> q = 12

3. >>> q += p

4. >>> q

22

5. >>> q *= p

6. >>> q

220

Comparison Operators

When the values of two operands are to be compared then comparison operators are used. The output of these comparison operators is always a Boolean value, either True or False.


Logical Operators

The logical operators are used for comparing or negating the logical values of their operands and to return the resulting logical value. The result of the logical operator is always a Boolean value, True or False.


 

Bitwise Operators

Bitwise operators treat their operands as a sequence of bits (zeroes and ones) and perform bit by bit operation. For example, the decimal number ten has a binary representation of 1010. Bitwise operators perform their operations on such binary representations, but they return standard Python numerical values.



Due to this operation,

• Each of the bits in the operand (60) is shifted two places to the left.

• The two bit positions emptied on the right end are filled with 0s.

• The resulting value is 240.

 












Statements and Expressions

A statement is an instruction that the Python interpreter can execute. Python program consists of a sequence of statements. Statements are everything that can make up a line (or several lines) of Python code. When you type a statement, the interpreter executes it, which means that it does whatever the statement says.

Ex:

>>> n = 17

>>> print(n)

z = 1 is an assignment statement.


An expression is a combination of values, variables, and operators. A value all byitself is considered an expression, and so is a variable, so the following are all legalexpressions:

>>> 42

42

>>> n

17

>>> n + 25

42

 

 

In this example, n has the value 17 and n + 25 has the value 42.

 

An expression, when used in interactive mode is evaluated by the interpreter and result is displayed instantly. For example,

>>> 8 + 2

10


But the same expression when used in Python program does not show any output altogether.

You need to explicitly print the result.

 

Reading Input

In Python, input() function is used to gather data from the user.

The syntax for input functionis,

 

variable_name = input([prompt])

 

prompt is a string written inside the parenthesis that is printed on the screen.

Even when the user inputs a number, it is treated as a string which should be casted or converted to number explicitly using appropriate type casting function.

Example:

1. >>> person = input("What is your name?")

2. What is your name? Carrey

3. >>> person

'Carrey'

Line the input() function prints the prompt statement on the screen (in this case "What is your name?") indicating the user that keyboard input is expected at that point and then it waits for a line to be typed in. User types in his response in line . The input() function reads the line from the user and converts the line into a string. As can be seen in line , the line typed by the user is assigned to the person variable.

 

Print Output

The print() function allows a program to display text onto the console. The print function will print everything as strings and anything that is not already a string is automatically converted to its string representation. For example,

1. >>> print("Hello World!!")

Hello World!!

Line prints the string Hello World!! onto the console. Notice that the string Hello World isenclosed within double quotes inside the print() function.

Even though there are different ways to print values in Python, Two majorstring formats which are used inside the print() function to display the contents onto theconsole are

1. str.format()

2. f-strings

str.format() Method

Use str.format() method if you need to insert the value of a variable, expression or an object into another string and display it to the user as a single string. The format() method returnsa new string with inserted values.

The format() method uses its arguments to substitute an appropriate value for each formatcode in the template.

The syntax for format() method is,

 

str.format(p0, p1, ..., k0=v0, k1=v1, ...)

 

where p0, p1,... are called as positional arguments and, k0, k1,... are keyword arguments with their assigned values of v0, v1,... respectively.

Positional arguments are a list of arguments that can be accessed with an index of argument inside curly braces like {index}. Index value starts from zero.

Keyword arguments are a list of arguments of type keyword = value, that can be accessed with the name of the argument inside curly braces like {keyword}.

Here, str is a mixture of text and curly braces of indexed or keyword types. The indexed or keyword curly braces are replaced by their corresponding argument values and is displayed as a single string to the user.

 

Examples:

Program to Demonstrate input() and print() Functions


Program to Demonstrate the Positional Change of Indexes of Arguments

You can have as many arguments as you want, as long as the indexes in curly braces have a matching argument in the argument list . {0} index gets replaced with the data value of variable a and {1} with the data value of variable b . This allows for re-arranging the order of display without changing the arguments .


The keyword argument {ball} gets replaced with its assigned value .

 

f-strings

Formatted strings or f-strings were introduced in Python 3.6. A f-string is a string literal thatis prefixed with “f”. These strings may contain replacement fields, which are expressionsenclosed within curly braces {}. The expressions are replaced with their values. In the realworld, it means that you need to specify the name of the variable inside the curly bracesto display its value. An f at the beginning of the string tells Python to allow any currentlyvalid variable names within the string.

 

Program  Code to Demonstrate the Use of f-strings with print() Function

1. country = input("Which country do you live in?")

2. print(f"I live in {country}")

Output

Which country do you live in? India

I live in India

Input string is assigned to variable country in Line. Observe the character f prefixed before thequotes and the variable name is specified within the curly braces .

 

Program Given the Radius, Write Python Program to Find the Area and Circumference of a Circle

1. radius = int(input("Enter the radius of a circle"))

2. area_of_a_circle = 3.1415 * radius * radius

3. circumference_of_a_circle = 2 * 3.1415 * radius

4. print(f"Area = {area_of_a_circle} and Circumference = {circumference_of_a_circle}")

Output

Enter the radius of a circle 5

Area = 78.53750000000001 and Circumference = 31.415000000000003

 

Program Write Python Program to Convert the Given Number of Days to a Measure of Time Given in Years, Weeks and Days. For Example,375 Days Is Equal to 1 Year, 1 Week and 3 Days (Ignore Leap Year).

1. number_of_days = int(input("Enter number of days"))

2. number_of_years = int(number_of_days/365)

3. number_of_weeks = int(number_of_days % 365 / 7)

4. remaining_number_of_days = int(number_of_days % 365 % 7)

5. print(f"Years = {number_of_years},Weeks={number_of_weeks}, Days ={remaining_number_of_days}")

Output

Enter number of days375

Years = 1, Weeks = 1, Days = 3

 

Type Conversions

You can explicitly cast, or convert, a variable from one type to another.

The int() Function

To explicitly convert a float number or a string to an integer, cast the number using int()function.

Program to Demonstrate int() Casting Function

1. float_to_int = int(3.5)

2. string_to_int = int("1")                #number treated as string

3. print(f"After Float to Integer Casting the result is {float_to_int}")

4. print(f"After String to Integer Casting the result is {string_to_int}")

Output

After Float to Integer Casting the result is 3

After String to Integer Casting the result is 1

Convert float and string values to integer and display the result .

 

1. >>>numerical_value = input("Enter a number")

Enter a number 9

2. >>> numerical_value

'9'

3. >>> numerical_value = int(input("Enter a number"))

Enter a number 9

4. >>> numerical_value

9

 

The float() Function

The float() function returns a floating point number constructed from a number or string.

Program to Demonstrate float() Casting Function

1. int_to_float = float(4)

2. string_to_float = float("1") #number treated as string

3. print(f"After Integer to Float Casting the result is {int_to_float}")

4. print(f"After String to Float Casting the result is {string_to_float}")

Output

After Integer to Float Casting the result is 4.0

After String to Float Casting the result is 1.0

Convert integer and string values to float and display the result .

 

The str() Function

The str() function returns a string which is fairly human readable.

Program to Demonstrate str() Casting Function

1. int_to_string = str(8)

2. float_to_string = str(3.5)

3. print(f"After Integer to String Casting the result is {int_to_string}")

4. print(f"After Float to String Casting the result is {float_to_string}")

 

Output

After Integer to String Casting the result is 8

After Float to String Casting the result is 3.5

Here, integer and float values are converted to string using str() function and results are displayed .

 

The chr() Function

Convert an integer to a string of one character whose ASCII code is same as the integerusing chr() function. The integer value should be in the range of 0–255.

Program to Demonstrate chr() Casting Function

1. ascii_to_char = chr(100)

2. print(f'Equivalent Character for ASCII value of 100 is {ascii_to_char}')

Output

Equivalent Character for ASCII value of 100 is d

An integer value corresponding to an ASCII code is converted to the character and printed

 

The complex() Function

Use complex() function to print a complex number with the value real + imag*j or convert a string or number to a complex number. If the first argument for the function is a string,it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex).

If imag is omitted, it defaults to zero and the function serves as a numeric conversion function like int(), long() and float(). If both arguments are omitted, the complex() function returns 0j.

Program to Demonstrate complex() Casting Function

1. complex_with_string = complex("1")

2. complex_with_number = complex(5, 8)

3. print(f"Result after using string in real part {complex_with_string}")

4. print(f"Result after using numbers in real and imaginary part {complex_with_number}")

Output

Result after using string in real part (1+0j)

Result after using numbers in real and imaginary part (5+8j)

 

The ord() Function

The ord() function returns an integer representing Unicode code point for the given Unicode character.

Program to Demonstrate ord() Casting Function

1. unicode_for_integer = ord('4')

2. unicode_for_alphabet = ord("Z")

3. unicode_for_character = ord("#")

4. print(f"Unicode code point for integer value of 4 is {unicode_for_integer}")

5. print(f"Unicode code point for alphabet 'A' is {unicode_for_alphabet}")

6. print(f"Unicode code point for character '$' is {unicode_for_character}")

Output

Unicode code point for integer value of 4 is 52

Unicode code point for alphabet 'A' is 90

Unicode code point for character '$' is 35

 

The hex() Function

Convert an integer number (of any size) to a lowercase hexadecimal string prefixed with“0x” using hex() function.

Program to Demonstrate hex() Casting Function

1. int_to_hex = hex(255)

2. print(f"After Integer to Hex Casting the result is {int_to_hex}")

Output

After Integer to Hex Casting the result is 0xff

 

The oct() Function

Convert an integer number (of any size) to an octal string prefixed with “0o” using oct()function.

Program to Demonstrate oct() Casting Function

1. int_to_oct = oct(255)

2. print(f"After Integer to Hex Casting the result is {int_to_oct}")

Output

After Integer to Hex Casting the result is 0o377

 

The type() Function and Is Operator

The type() function returns the data type of the given object.

The syntax for type() function is,

type(object)

1. >>> type(1)

<class 'int'>

2. >>> type(6.4)

<class 'float'>

3. >>> type("A")

<class 'str'>

4. >>> type(True)

<class 'bool'>

The type() function comes in handy if you forget the type of variable or an object during the course of writing programs.

The operators is and is not are identity operators. Operator is evaluates to True if the values of operands on either side of the operator point to the same object and False otherwise. The operator is not evaluates to False if the values of operands on either side of the operator point to the same object and True otherwise.

1. >>> x = "Seattle"

2. >>> y = "Seattle"

3. >>> x is y

True

Both x and y point to same object “Seattle” and results in True when evaluated usingis operator .

 

Dynamic and Strongly Typed Language

Python is a dynamic language as the type of the variable is determined during run-timeby the interpreter. Python is also a strongly typed language as the interpreter keeps trackof all the variables types. In a strongly typed language, you are simply not allowed to doanything that’s incompatible with the type of data you are working with. For example,

1. >>> 5 + 10  # Here values which are of integer types are added and they are compatible.

15

2. >>> 1 + "a" # when you try to add 1, "a" then it results they are not compatible.

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for +: 'int' and 'str'

In Python, Traceback is printed when an error occurs.

 

Control Flow Statements:(Explain the Conditional Statements in Python)

 


The statements inside your Python program are generally executed sequentially from top to bottom, in the order that they appear. Apart from sequential control flow statements it has decision making and looping control flow statements to break up the flow of execution thus enabling your program to conditionally execute particular blocks of code.

The control flow statements in Python Programming Language are

1. Sequential Control Flow Statements: This refers to the line by line execution, in which the statements are executed sequentially, in the same order in which they appear in the program.

2. Decision Control Flow Statements: Depending on whether a condition is True or False, the decision structure may skip the execution of an entire block of statements or even execute one block of statements instead of other (if, if…else and if…elif…else).

3. Loop Control Flow Statements: This is a control structure that allows the execution of a block of statements multiple times until a loop termination condition is met (for loop and while loop). Loop Control Flow Statements are also called Repetition statements or Iteration statements.

 

The if Decision Control Flow Statement

The if decision control flow statement starts with if keyword and ends with a colon. Theexpression in an if statement should be a Boolean expression.

If the Boolean expression evaluates to True then statements in the if block willbe executed; otherwise the result is False then none of the statements are executed.

The syntax for if statement is,

 


For example,

1. >>> if 20 > 10:

2. … print(f"20 is greater than 10")

Output

20 is greater than 10

Program Reads a Number and Prints a Message If It Is Positive

1. number = int(input("Enter a number"))

2. if number >= 0:

3.         print(f"The number entered by the user is a positive number")

Output

Enter a number 67

The number entered by the user is a positive number

 

The if…else Decision Control Flow Statement

The if…else statement allows for a two-way decision.

Statements in the if block are executed if the Boolean_Expression is True. Use the optional else block to execute statements if the Boolean_Expression is False.

The syntax for if…else statement is,

If the Boolean_Expression evaluates to True, then statement_1 is executed, otherwise it is evaluated to False then statement_2 is executed.

Program to Find If a Given Number Is Odd or Even

1. number = int(input("Enter a number"))

2. if number % 2 == 0:

3.        print(f"{number} is Even number")

4. else:

5.         print(f"{number} is Odd number")

Output

Enter a number: 45

45 is Odd number

 

 

The if…elif…else Decision Control Statement

The if…elif…else is also called as multi-way decision control statement. When you needto choose from several possible alternatives, then an elif statement is used along with an ifstatement. The keyword ‘elif’ is short for ‘else if’ and is useful to avoid excessive indentation.The else statement must always come last, and will again act as the default action.

The syntax for if…elif…else statement is,



This if…elif…else decision control statement is executed as follows:

• If Boolean_Expression_1 is True, then statement_1 is executed.

• If Boolean_Expression_1 is False and Boolean_Expression_2 is True, then statement_2 is executed.

• If Boolean_Expression_1 and Boolean_Expression_2 are False and Boolean_Expression_3 is True, then statement_3 is executed and so on.

• If none of the Boolean_Expression is True, then statement_last is executed.

Program to Display the Cost of Each Type of Fruit

1. fruit_type = input("Enter the Fruit Type:")

2. if fruit_type == "Oranges":

3.         print('Oranges are 100 RsPer Kg’)

4. elif fruit_type == "Apples":

5.         print('Apples are 150 Rs Per Kg’)

6. elif fruit_type == "Bananas":

7.         print('Bananas are 50 Rs Per Kg’)

8. elif fruit_type == "Cherries":

9.         print('Cherries are 80 Rs Per Kg’)

10. else:

11.       print(f'Sorry, we are out of {fruit_type}')

Output

Enter the Fruit Type: Cherries

Cherries are 80 Rs Per Kg

 

Nested if Statement

An if statement that contains another if statement either in its if block or else block is called a Nested if statement.

The syntax of the nested if statement is,

 


If the Boolean_Expression_1 is evaluated to True, then the control shifts to Boolean_Expression_2 and if the expression is evaluated to True, then statement_1 is executed, if the Boolean_Expression_2 is evaluated to False then the statement_2 is executed. If the Boolean_Expression_1 is evaluated to False, then statement_3 is executed.


Program to Check If a Given Year Is a Leap Year

1. year = int(input('Enter a year'))

2. if year % 4 == 0:

3.         if year % 100 == 0:

4.                     if year % 400 == 0:

5.                     print(f'{year} is a Leap Year')

6.                     else:

7.                     print(f'{year} is not a Leap Year')

8.         else:

9.         print(f'{year} is a Leap Year')

10. else:

11.       print(f'{year} is not a Leap Year')

Output

Enter a year 2014

2014 is not a Leap Year

Note:All years which are perfectly divisible by 4 are leap years except for century years (years ending with 00) which is a leap year only it is perfectly divisible by 400. For example, years like 2012, 2004, 1968 are leap years but 1971, 2006 are not leap years. Similarly, 1200, 1600, 2000, 2400 are leap years but 1700, 1800, 1900 are not.


(Explain Various Loops in Python with example)

The while Loop

The syntax for while loop is,


The while loop starts with the while keyword and ends with a colon.

If the Boolean expression evaluates to False,then the statements in the while loop block are never executed. If the Boolean expressionevaluates to True, then the while loop block is executed. After each iteration of the loopblock, the Boolean expression is again checked, and if it is True, the loop is iterated again.

Each repetition of the loop block is called an iteration of the loop. This process continues until the Boolean expression evaluates to False and at this point the while statement exits. Execution then continues with the first statement after the while loop.

Write Python Program to Display First 10 Numbers Using while Loop Starting from 0

1. i = 0

2. while i < 10:

3.         print(f"Current value of i is {i}")

4.         i = i + 1

Output

Current value of i is 0

Current value of i is 1

Current value of i is 2

Current value of i is 3

Current value of i is 4

Current value of i is 5

Current value of i is 6

Current value of i is 7

Current value of i is 8

Current value of i is 9


The for Loop

The syntax for the for loop is,


The for loop starts with for keyword and ends with a colon. The first item in the sequencegets assigned to the iteration variable iteration_variable. Here, iteration_variable can be anyvalid variable name. Then the statement block is executed. This process of assigning itemsfrom the sequence to the iteration_variable and then executing the statement continues untilall the items in the sequence are completed.

We take the liberty of introducing you to range() function which is a built-in function atthis stage as it is useful in demonstrating for loop. The range() function generates a sequenceof numbers which can be iterated through using for loop. The syntax for range() function is,range([start ,] stop [, step])Both start and step arguments are optional and the range argument value should alwaysbe an integer.

start → value indicates the beginning of the sequence. If the start argument is notspecified, then the sequence of numbers start from zero by default.

stop → Generates numbers up to this value but not including the number itself.

step → indicates the difference between every two consecutive numbers in thesequence. The step value can be both negative and positive but not zero.

NOTE: The square brackets in the syntax indicate that these arguments are optional. You can leave them out.


Write a Program to Find the Sum of All Odd and Even Numbers up to a Number Specified by the User.

1. number = int(input("Enter a number"))

2. even = 0

3. odd = 0

4. for i in range(number):

5.         if i % 2 == 0:

6.             even = even + i

7.         else:

8.             odd = odd + i

9. print(f"Sum of Even numbers are {even} and Odd numbers are {odd}")

Output

Enter a number 10

Sum of Even numbers are 20 and Odd numbers are 25

Program: Demonstrate for Loop Using range() Function

1. print("Only ''stop'' argument value specified in range function")

2. for i in range(3):

3.         print(f"{i}")

4. print("Both ''start'' and ''stop'' argument values specified in range function")

5. for i in range(2, 5):

6.         print(f"{i}")

7. print("All three arguments ''start'', ''stop'' and ''step'' specified in range function")

8. for i in range(1, 6, 3):

9.         print(f"{i}")

Output

Only ''stop'' argument value specified in range function

0

1

2

Both ''start'' and ''stop'' argument values specified in range function

2

3

4

All three arguments ''start'', ''stop'' and ''step'' specified in range function

1

4

Program to Iterate through Each Character in the String Using for Loop

1. for each_character in "Blue":

2.         print(f"Iterate through character {each_character} in the string 'Blue'")

Output

Iterate through character B in the string 'Blue'

Iterate through character l in the string 'Blue'

Iterate through character u in the string 'Blue'

Iterate through character e in the string 'Blue'

 

THE CONTINUE AND BREAK STATEMENTS

The break and continue statements provide greater control over the execution of code in a loop. Whenever the break statement is encountered, the execution control immediately jumps to the first instruction following the loop. To pass control to the next iteration without exiting the loop, use the continue statement. Both continue and break statements can be used in while and for loops.

Program to Demonstrate Infinite while Loop and break

1. n = 0

2. while True:

3.         print(f"The latest value of n is {n}")

4.         n = n + 1

 

. This is an infinite loop with no end in sight. You need to press Ctrl + C to terminatethis program. One way of ending this infinite loop is to use break statement along with ifcondition as shown in the following code.

1. n = 0

2. while True:

3.         print(f"The latest value of n is {n}")

4.         n = n + 1

5.         if n > 5:

6.         print(f"The value of n is greater than 5")

7.         break

Output

The latest value of n is 0

The latest value of n is 1

The latest value of n is 2

The latest value of n is 3

The latest value of n is 4

The latest value of n is 5

The value of n is greater than 5

Write a Program to Check Whether a Number Is Prime or Not

1. number = int(input('Enter a number > 1: '))

2. prime = True

3. for i in range(2, number):

4.         if number % i == 0:

5.         prime = False

6.         break

7. if prime:

8.         print(f"{number} is a prime number")

9. else:

10.     print(f"{number} is not a prime number")

Output

Enter a number > 1: 7

7 is a prime number

 

Program to Demonstrate continue Statement

1. n = 10

2. while n > 0:

3.         print(f"The current value of number is {n}")

4.         if n == 5:

5.         print(f"Breaking at {n}")

6.         n = 10

7.         continue

8.         n = n – 1

Output

The current value of number is 10

The current value of number is 9

The current value of number is 8

The current value of number is 7

The current value of number is 6

The current value of number is 5

Breaking at 5

The current value of number is 10

The current value of number is 9

The current value of number is 8

The current value of number is 7

The current value of number is 6

The current value of number is 5

 

Programs for practice

Example for The if Statement:

Program to Read Luggage Weight and Charge the Tax Accordingly

1. weight = int(input("How many pounds does your suitcase weigh?"))

2. if weight > 50:

3.         print(f"There is a $25 surcharge for heavy luggage")

4.         print(f"Thank you")

Output

How many pounds does your suitcase weigh? 75

There is a $25 surcharge for heavy luggage

Thank you

 

Example for The if…else Statement:

Program to Find the Greater of Two Numbers

1. number_1 = int(input("Enter the first number"))

2. number_2 = int(input("Enter the second number"))

3. if number_1 > number_2:

4.         print(f"{number_1} is greater than {number_2}")

5. else:

6.         print(f"{number_2} is greater than {number_1}")

Output

Enter the first number 8

Enter the second number 10

10 is greater than 8

 

Example for  The if…elif…else Decision Control Statements:

Write a Program to Prompt for a Score between 0.0 and 1.0. If the Score Is Out of Range, Print an Error. If the Score Is between 0.0 and 1.0, Print a Grade Using the Following Table

Score                      Grade

>= 0.9                         A

>= 0.8                         B

>= 0.7                         C

>= 0.6                         D

< 0.6                            F

1. score = float(input("Enter your score"))

2. if score < 0 or score > 1:

3.         print('Wrong Input')

4. elif score >= 0.9:

5.         print('Your Grade is "A" ')

6. elif score >= 0.8:

7.         print('Your Grade is "B" ')

8. elif score >= 0.7:

9.         print('Your Grade is "C" ')

10. elif score >= 0.6:

11.       print('Your Grade is "D" ')

12. else:

13.       print('Your Grade is "F" ')

Output

Enter your score0.92

Your Grade is "A"

 

Examples for  The while Loop:

Program: Write a Program to Find the Average of n Natural Numbers Where n Is the Input from the User

1. number = int(input("Enter a number up to which you want to find the average"))

2. i = 0

3. sum = 0

4. count = 0

5. while i < number:

6.         i = i + 1

7.         sum = sum + i

8.         count = count + 1

9. average = sum/count

10. print(f"The average of {number} natural numbers is {average}")

Output

Enter a number up to which you want to find the average 5

The average of 5 natural numbers is 3.0

 

Program: Program to Find the GCD of Two Positive Numbers

1. m = int(input("Enter first positive number"))

2. n = int(input("Enter second positive number"))

3. if m == 0 and n == 0:

4.         print("Invalid Input")

5. if m == 0:

6.         print(f"GCD is {n}")

7. if n == 0:

8.         print(f"GCD is {m}")

9. while m != n:

10.       if m > n:

11.           m = m – n

12.       if n > m:

13.           n = n – m

14. print(f"GCD of two numbers is {m}")

Output

Enter first positive number8

Enter second positive number12

GCD of two numbers is 4

 

Program : Write Python Program to Find the Sum of Digits in a Number

1. number = int(input('Enter a number'))

2. result=0

3. remainder=0

4. while number!=0:

5.         remainder = number%10

6.         result = result + remainder

7.         number = int(number/10)

8. print(f"The sum of all digits is{result}")

Output

Enter a number1234

The sum of all digits is 10

 

Program: Write a Program to Display the Fibonacci Sequences up to nth Term Where n is Provided by the User

1. nterms = int(input('How many terms?'))

2. current = 0

3. previous = 1

4. count = 0

5. next_term = 0

6. if nterms <= 0:

7.         print('Please enter a positive number')

8. elif nterms == 1:

9.         print('Fibonacci sequence')

10.       print('0')

11. else:

12.       print("Fibonacci sequence")

13.       while count < nterms:

14.                   print(next_term)

15.                   current = next_term

16.                   next_term = previous + current

17.                   previous = current

18.                   count += 1

Output

How many terms? 5

Fibonacci sequence

01123

 

Program: Program to Repeatedly Check for the Largest Number Until the User Enters “done”

1. largest_number = int(input("Enter the largest number initially"))

2. check_number = input("Enter a number to check whether it is largest or not")

3. while check_number != "done":

4.         if largest_number > int(check_number):

5.                     print(f"Largest Number is {largest_number}")

6.         else:

7.                     largest_number = int(check_number)

8.                     print(f"Largest Number is {largest_number}")

9.         check_number = input("Enter a number to check whether it is largest or not")

Output

Enter the largest number initially 5

Enter a number to check whether it is largest or not 1

Largest Number is 5

Enter a number to check whether it is largest or not 10

Largest Number is 10

Enter a number to check whether it is largest or not 8

Largest Number is 10

Enter a number to check whether it is largest or not done

Examples for  The for Loop:

Program: Write a Program to Find the Factorial of a Number

1. number = int(input('Enter a number'))

2. factorial = 1

3. if number < 0:

4.         print("Factorial doesn't exist for negative numbers")

5. elif number == 0:

6.         print('The factorial of 0 is 1')

7. else:

8.         for i in range(1, number + 1):

9.             factorial = factorial * i

10. print(f"The factorial of number {number} is {factorial}")

Output

Enter a number 5

The factorial of number 5 is 120

No comments:

Post a Comment