Você está na página 1de 81

UNIT: I Problem Solving, Programming and Python Lectures:

Programming 07 Hrs
• General problem solving concepts :

• Problem solving in everyday life,


• types of problems, problem solving with computers,

• difficulties with problem solving

• problem solving aspects, top down design. Problem Solving Strategies

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


algorithms.
• Basics of Python Programming: Features of Python, History and Future of Python, Writing and executing
Python program, Literal constants, variables and identifiers, Data Types, Input operation, Comments,
Reserved words, Indentation, Operators and expressions, Expressions in Python.


What is problem?
The problem is defined as the objective or the specific output that we want to attain;
through a sequence of steps and activities and, specific input.
Basic Skills required to be an Engineer
• Technical
• Problem solving
• Quick learning
• Applied Knowledge
• Soft skill
Example problem in daily life
Students do science experiment

Mechanics repair a
broken car Workers goes to work

Problem?

Doctors find new bacteria Kids want eat sweets


Placing a clock on wall
• Generate questions
• Analyze which questions will become constraints for solving problem.
• Revise problem statement
Sr.No Questions Constraints

1 Which Wall? Left wall

2 At what height? 10 feet height

3 Type of clock? NA

4 Size of clock? Weight 200gm

5 Which location on wall? Centre of wall

6 Places with the help of nails? Nails are to be used

7 Pasted on wall? NA

8 Purpose of clock? NA

9 Shape of clock? NA
Exercise
• Create computer application to issue book from college library
How to solve
the problem?
Problem Solving Definition
A Systematic approach to defining problem(question or situation that presents
uncertainty or difficulty) and creating a vast number of possible solutions without judging these
solutions.
Problem Solving in Everyday Life
There are six step in problem solving:
Problem Solving in Everyday Life

Can I skip
the step?

According to Sprankle and Hubbard


(2012), if the six step not completed
well, the result may be less than
desired
Example problems…
Baking a cake according to certain specifications, input available are the ingredients (such
as eggs, flour, milk …etc.), then followed by activities or procedures that should be done
sequentially, taking into consideration that any mistake happens by doing any procedure
before the other, results in an unsuitable and undesirable cake.

List
instructions
Identify the Understand Identify Select the Evaluate
the problem that enable the
problem alternative best way you to solve solution
the problem
Group Activities
In in group of 4 persons, think a problems in your daily life at home, office,
park, school, shopping mall or wherever your go. Please explain how you solve
the problem using the six steps of problem solving.
Types of problems
❖ Well-defined problems
Ex: list out presidents of India since 1947
❖ Poorly defined problems
Ex: How to improve communication?

->problem based on algorithmic solution(eg. Making cup of tea)


->problem based on heuristic solution(eg. Which book I should
purchase)
Problems

Computational Problem Social Problem Management Problem


(Ex.find best route A to B) (Ex. Flood, dispute between 2 friends) (Ex. Arranging Birthday Party )

Decision Searching & Sorting Counting Optimization Problem


Problem Problem Problem (best solution)
(Boolean Ans) (ascending/descending) (how many diff.
types of items)

1.Concurrent (ex. MS word with Music )


2. Sequential (ex. printer)
3.Distributed (ex. Google sheet)
4. Event Based(ex. ATM,mobile app)
Problem Solving with Computer
Two methodologies used to develop computer solutions to
a problem
– Top-down design focuses on the tasks to be done
– Object-oriented design focuses on the data involved in the solution
A General Example
top-down approach
Planning a large party

Subdividing the party planning


Currency conversion
Difficulties with problem solving
• Do not understand problem correctly
• Do not define problem correctly/adequately
• Afraid of taking decision
• List of alternative is incomplete
• Sequence of solutions to the problem is not logical
• Writing instructions on computer
Problem solving strategies
Steps-
• Clearly define problem in simple and precise language
• Analyze problem to find out different ways to solve
• Evaluate all options and choose best one
• Define steps to get solution
• Write steps in programming language
Requirements Analysis

Software
Design
Development
LifeCycle: Implementation

Testing

s/w deployment, training, support

Maintenance
Problem Design tools
i. Algorithm
ii. Flowchart
iii. Pseudo code
Algorithm
Finite set of instructions for performing a particular task, instructions
are nothing but statements in simple English Language.

• Procedure for performing some calculations


• Gives logic of program-steps to arrive solution
• Procedure implemented using formal language called programming
• Achieve software reuse
Add 2 nos and print result in third no
Step 1: Start
Step 2: Read the first no in variable num1
Step 3: Read the second no in variable num2
Step 4: Perform Addition and store the result in variable sum
Step 5: Display sum
Step 6: Stop
ALGORITHM TO FIND THE AREA OF Circle..
• ALGORITHM TO FIND THE Average of 3 marks
• ALGORITHM TO FIND THE percentage ..
Approches to design Algo
• Top-down
• Bottom-up

Top-own
Bottom-
own
• Control flow statement:
1)Sequence- Each step executed in specified order.
Ex. Algorithm to add 2 numbers

2)Decision- When outcome depend on situation.


Ex. Algorithm to find given 2 numbers are equal or not?
Algorithm to find given 2 numbers are equal or not?

Step 1: Start
Step 2: Read the first no in variable num1
Step 3: Read the second no in variable num2
Step 4: If num1=num2
print “EQUAL”
Else
print ”UNEQUAL”
Step 5: Stop
Exercise

1. Algorithm to find given number no. is even or not?


2. Algorithm to find given number no. is prime or not?
3. Algorithm to compare 2 nos.(greater)
4. Algorithm to Swap 2 nos
Comparing 2 nos
if
Else if
else
• Print grade obtained by student
Above 75 -> outstanding
60-75 -> Excellent
50-60 -> very good
40-50 -> good
Repetition
• Executing one or more steps for no. of times
Algorithm to print first 10 numbes
Step 1: Start
Step 2: Set I=1, N=10
Step 3: Repeat step 3 & 4
while I <= N
display I
Step 4: set I=I+1
Step 5: Stop
Algorithm to find sum of first 5 natural numbers
Step 1: Start
Step 2: Set i=1, sum=10
Step 3: Repeat step 4 & 5
while i < =5
Step 4: set sum=sum+1
Step 5: set i=i+1
Step 6: print sum
Step 5: Stop
Flowchart
• Graphical or Symbolic representation of process used to design
document to visualize logic of process.
• Each step of flow-chart shown by different symbol and associated
with short description
Flowchart Symbols
Start Arrows
End

Process/calculations Decision

input
output
Connector
• Addition of 2 no
• Calculate average of 2 no
• Calculate sum of first 10 numbers
• Comparison of 2 no.
3. Pseudo code
• Compact and informal high level description of algorithm that uses
structural conventions of programming language.
• Ideal pseudo code describes entire logic of program which directly
translated to program.
• Meant for human reading than machine reading so it omits details
which are not essential for human
E.g. variable declaration
• Should not contain keyword of computer language.
• Purpose- enhance human understandability of solution
• No std define to write pseudocode
Calculate total price
• Take integer price
• Read sales tax rate
• Calculate tax= price of item * sales tax rate
• Calculate total prize= tax + price of items
• Print total prize

Variable: price of item, sales tax rate, total price


Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
Programming basics
• code or source code: The sequence of instructions in a program.
• syntax: The set of legal structures and commands that can be used in a particular
programming language.
• output: The messages printed to the user by a program.
• console: The text box onto which output is printed.
– Some source code editors pop up the console as an external window, and
others contain their own console window.
What is Python?
• Python is a general purpose interpreted ,interactive, object oriented and high level
programming language.

•The language places strong emphasis on code reliability and simplicity so that the
programmers can develop applications rapidly

• Python supports cross platform development and is available through open source.

• Python is widely used for scripting in Game menu applications effectively


History of Python
•Python is created by Guido Van Rossum in the 1980s.
•Rossum published the first version of Python code (0.9.0) in
February 1991 at the CWI (Centrum Wiskunde & Informatics)
in the Netherlands , Amsterdam.
•Python is derived from ABC programming language, which is a
general-purpose programming
•Rossum chose the name "Python", since he was a big fan of
Monty Python's Flying Circus.
•Python is now maintained by a core development team at the
institute, although Rossum still holds a vital role in directing its
progress.

Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
History of Python
• Developed by Guideo Van Rossum at Netherland
• Python 1.0 released in 1994 with features like lambda, map filter
• Python 2.0 released in 2000 with added features like list,
comprehensions, garbage collection etc
• Python 2.7 released in December 3,2018 for rectifying fundamentals
of flow of languages
Python Versions
➢ Release dates for the major and minor versions:
➢ Python 1.0 - January 1994
➢ Python 1.5 - December 31, 1997
➢ Python 1.6 - September 5, 2000
➢ Python 2.0 - October 16, 2000
➢ Python 2.1 - April 17, 2001
➢ Python 2.2 - December 21, 2001
➢ Python 2.3 - July 29, 2003
➢ Python 2.4 - November 30, 2004
➢ Python 2.5 - September 19, 2006
➢ Python 2.6 - October 1, 2008
➢ Python 2.7 - July 3, 2010

➢ Release dates for the major and minor versions:


➢ Python 3.0 - December 3, 2008
➢ Python 3.1 - June 27, 2009
➢ Python 3.2 - February 20, 2011
➢ Python 3.3 - September 29, 2012
➢ Python 3.4 - March 16, 2014
➢ Python 3.5 - September 13, 2015

Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
Why do people use Python…?
The following primary factors cited by Python users seem to be these:
Python is object-oriented Structure supports such concepts as polymorphism,
operation overloading, and multiple inheritance.
Indentation is one of the greatest future in Python.
It's free (open source)
Downloading and installing Python is free and easy Source code is easily accessible

Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
Features of Python
• Simple
• Easy to Learn
• Versatile
• Free and Open Source
• High level Language
• Interactive
• Portable
• Object Oriented
• Interpreted
• Dynamic
• Extensible
• Embeddable
• Easy Maintenance
• Robust
• Multi-threaded
• Garbage Collection
Applications
• Desktop Applications
• Image Processing Applications
• Scientific and Computational Applications
• Games
• Enterprise &Business Applications
• Operating systems
• Language Development
• Web Development
• 3-D software
• Teaching
Future of Python
• Top Companies Embracing Python Programming Language
Not only small companies but even top companies are using Python as their
business application development.
• Central Intelligence Agency (CIA) is using Python to maintain their websites.
• Web Development:
• Machine Learning: (Suppose you have to develop a code to determine the
picture whether it is a car or a bike. ML typically implements an algorithm that
automatically detects a pattern in the given inputs.)
• Data Analysis and Data Visualization:
it also helps in the analysis of a large amount of data through its high
performance libraries and tools.
Python Code Execution
Python’s traditional runtime execution model: source code you type is translated to byte
code, which is then run by the Python Virtual Machine. Your code is automatically
compiled, but then it is interpreted.

Source code extension is .py


Byte code extension is .pyc (compiled python code)
Your First Program
• To develop the Python program ,click on the File and select NewFile.
• This will open a new text editor where you can write your first program.
# Prints the words Hello Python

print(“Hello Python”)
print(“Its nice learning Python”)
print(“Python is easy to learn”)

Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
Literal Constants
• Number- numeric value
• Integer ex.80
• long integer ex. 53563385246L
• Float point ex.4.35
• Complex number ex.a+bi

• String-group of characters
Ex. ‘Hello’ “Hello”

‘’’ Good Morning!!


How are u? ’’’
Example
>>>a = 5

Print( type(a))

>>>a = 2.0

print(a, "is of type", type(a))

>>>a = 1+2j

Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
Operations on numbers
10+7 =17 5*3.0= 15.0
• Division by zero
15/0 generate error
• Quotient & Reminder
15/3= 5.0 15%3=0
15//3=5
• Exponential
5**3=125
String

• String is sequence of Unicode characters. We can use single quotes or


double quotes to represent strings. Multi-line strings can be denoted
using triple quotes, ''' or """.
s = "This is a string“
s = '''a multiline

• slicing operator [ ] can be used with string. Strings are immutable


Example
1. >>>’aaaaaa’ o/p: ‘aaaaaa’
2. >>>print(‘aaa’) o/p: aaa
3. >>> print(“aaaa”) o/p: aaaa
4. >>>print(‘navin’s laptop’) o/p: error
5. >>>print(“navin’s laptop”) o/p: navin’s laptop
6. >>> print(‘navin “laptop”’) o/p: navin “laptop”
7. >>>print(‘navin ‘s “laptop”’) o/p: error
8. >>> print(‘navin\’s “laptop”’) o/p: navin’s “laptop”

Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
>>>’navin’ + ’navin’ o/p: ‘navinnavin’
>>>’navin’*5
>>>print(‘navin\nsingh’)
>>>print(r’ navin\nsingh’)
• s = 'Hello world!’
• # s[4] = ? print("s[4] = ", s[4])
• # Strings are immutable in Python s[5] =?
Variables
• Store piece of information in a variable
• It is part of memory
• Assigned with name
• Are identifiers

• Rules- Punctuation characters(%,$,@) not allowed


- case sensitive
- first character either underscore or alphabet
Data Types
• Variable holds values of different types.
Ex- person- id - 201
name -rahul
salary - 48480.50
5 std data types:
number
string
list
tuple
dictionary
Initialization
Declaration is done automatically when initialization is done
= sign is used
Ex.
❑Num=7;
print(Num)
❑code=’A’
print(code)
Boolean
• 2 values- true,false; 0,1
Ex. print(20==30)
print(“python”==“python”)
Input operation
• To take input from user
• Input function() is used
• Always takes ‘string’ as an input

Ex. Input(“Enter Name”)


o/p: *******is *****years old
name=input(“Enter name”)
age=input(“Enter age”)

print(name+”is”+age+”years old”)
Comments(#)
• Non-executable statements in program
• Interpreters ignores the comments
• # is used
Ex.
#program to display Hello
print(“Hello”) #display hello
A=10 #initialization
Reserved words
• Words with predefined meaning
• Cannot be used for naming identifiers

and Or class continue del is


exec finally from global import else
not break print if try with
except assert for pass raise def
return elif in while lambda yield
Indentation
• White space at the beginning of line is called Indentation
• Include space and tabs
• It is used to associate group statements
• Python strictly checks indentation level
• Python uses indentation to form block
• Ex.

age=21
print(age) #error of indentation
Operators &expression
• operators + - * / etc
• operands numbers, variables
ex. sum= a + b

1. arithmetic 5. Unary
2. comparison 6. Bitwise
3. assignment 7. Membership
4. logical 8. Identity
Arithmetic
+, -, *, /, %, **, //
ex.
Operation output

40/10 4.0

40%10 0

12//5 2

12/5 2.4

2**3 8
Comparison

Operator Example (a=100,b=200) output

== a==b False

!= a!=b True

> a>b False

< a<b True

>= a>=b False

<= a<=b True


Assignment shortcut
+= a += b a= a+b
-= a -=b a= a – b
*= a *=b a= a * b
/= a /=b a= a / b
%= a %=b a= a % b
//= a //=b a= a // b
**= a **=b a= a ** b
What will be the output?
str1=“good”
str2=“bye”
Str1+=str2
print(str1)
Unary
• Python supports unary plus and minus operator
• subtract second operand from first operand
• when operator preceded by minus sign , unary operator negates its
value
• ex. a=10
• -a = -10
Bitwise operator
• perform operations at bit level

• Conversion:
expressions, Expressions in Python
An expression is a combination of symbols that evaluates to a value.
Expressions, most commonly, consist of a combination of operators
and operands

example of expression –
4 + (3 * k)
What is mixed-type expressions, arithmetic expression

• A mixed-type expression is an expression with operands of different


type.

example of arithmetic expression - (any example)


(5 + 3) * 4

example of mixed type expression - (any example)


2 + 4.5
Types of Expression
1. Based on Position of operator in an expression

• Infix : operators are placed in between operands


Ex. A=B+C
• Prefix: operators are placed before operands
Ex. =A+BC
• Postfix: operators are placed after operands
Ex. ABC+=
2. Based on Data Type of result:
• Constant Expression: contain only constants.
ex: 2+6=8
• Floating point Expression: produces floating point result
ex: a=4 b=3 c=a/b
• Relational Expression: returns either true or false.
ex. c= a>b
• Logical Expression: combines 2 or more relational exp and return true
or false ex. a>b && c!=0
• a>b || c!=0
• Bitwise Expression: manipulate data at bit level
ex. c= a & b
• Assignment Expression: assigns value to a variable

Você também pode gostar