0% found this document useful (0 votes)
9 views14 pages

Unit-1

The document provides an overview of problem-solving using Python, covering fundamental concepts such as computers, algorithms, flowcharts, and the history and features of Python. It explains Python's data types, operators, and string manipulation techniques, along with examples of code and output. Additionally, it highlights Python's applications in various domains, emphasizing its versatility and ease of use.

Uploaded by

Gladio Nexus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views14 pages

Unit-1

The document provides an overview of problem-solving using Python, covering fundamental concepts such as computers, algorithms, flowcharts, and the history and features of Python. It explains Python's data types, operators, and string manipulation techniques, along with examples of code and output. Additionally, it highlights Python's applications in various domains, emphasizing its versatility and ease of use.

Uploaded by

Gladio Nexus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

Problem Solving Using Python

Unit-1
Computers: A computer is an electronic machine that takes instructions and performs
computations based on those instructions
Instructions: Commands given to the computers.
Programs: A set of instructions in computer language is called a program.
Algorithm: formally defined procedure for doing some calculation. It gives logic of a
program, i.e step by step approach to come to a solution.
Flowcharts: Graphical or symbolic representation of an algorithm.

Start/end
Input/Output

Decision

Processing
Connector

Pseudocodes: is a compact and high-level description of an algorithm.


Compiler: converts a high-level language to low level language.Generates Object code from
source code.
Linker: Converts the object code to executable code.
Interpreter: converts a high-level language to low level language line by line.
Assemblers: An assembler is a type of computer program that interprets software programs
written in assembly language into machine language, code and instructions that can be
executed by a computer.
Scripting Language:Scripting languages are usually interpreted at runtime rather
than compiled. Python is an interpreted language. It is processed at run time by an interpreter. It
is a scripting language. The python interpreter/compiler converts the source code into byte code,
which makes python platform independent.

History of Python: Python was conceived in the late 1980s by Guido van Rossum at Centrum
Wiskunde& Informatica (CWI) in the Netherlands as a successor to the ABC programming
language, which was inspired by SETL, capable of exception handling and interfacing with
the Amoeba operating system. Its implementation began in December 1989. Its version 1.0
was released in 1991 followed by version 2.0 in 2000. Python 2.7, Python 2.8 and Python
3.6.4 are all released today.
Note: Before execution python do not need compilation.
Need for Python/Features of Python:
1. Software Quality: Python code is readable, reusable and maintainable. It supports
object oriented and function programming concepts.
2. Simple: Python instructions are generally in English, hence easy to understand.
3. Versatile: can develop wide range of applications from simple text processing to
games.
4. Free and Open source: Anyone can freely distribute it, read it, edit it.
5. High level Language: Instructions are written in English.
6. Interactive: Programmers can easily interact with the interpreter directly at the
Python prompt to write their programs.
7. Portable: The byte code of the python makes python portable.
8. Object Oriented: Python supports object oriented as well as Procedure oriented
programming paradigms.
9. Interpreted: The python compiler/interpreter converts the source code to byte code
at run time. The compilation of the program is not required before execution.
10. Multi-threading: Python supports multi-threading.
11. Garbage Collection: Python supports garbage collection.
Application of Python:
1. Python can be used for web based, desktop based, graphic design, scientific and
computational design applications.
2. It is used to develop wide range of applications: image processing, text processing,
scientific and numeric data processing.
3. Embedded Scripting language: It is used as an embedded scripting language for
various testing /building and deployment application.
4. 3D software: 3D software uses Python.
5. Web Development: Python is an extendable language, i.e it can easily integrate with
the database. Hence it is used for web development.
Python Block: A block is a piece of Python program text that is executed as a unit. The
following are blocks: a module, a function body, and a class definition. Each command
typed interactively is a block. Example
a=5
b=6
sum=a+b
print(sum)
Keywords
(33 keywords in python) (Altered in different version of python))
Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other
object.
Rules of forming an identifier
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9).
Literals: It is also called as a literal constant. It comes to the right side of a variable. Its
value cannot be changed.
Eg
a=2, here “a “is a variable and 2 is a literal.
Data Types
Python supports various data types, these data types defines the operations possible on
the variables and the storage method. Below is the list of standard data types available in
Python:

Numbers: Numbers means numeric values. There are three types of numbers in python:
1.integers
2.floating point
3.complex numbers.
Built-in format function ()- gives output in string format with the precision specified.
format(float(16/float(3))), ‘.2f’)= ‘5.33’
format(3**50,’.5e’)
=’7.17898e+23’
format(123456,’,’)
=’123,456’
Declaring numeric data type:
1. a=2
2. b=3456789222
3. c=2.34
4. comp=a+2j
Boolean Data Types:The boolean data type is either True or False. In Python, boolean
variables are defined by the True and False keywords.

>>> a = True
>>> type(a)
<class 'bool'>

>>> b = False
>>> type(b)
<class 'bool'>

>>>zero_int = 0
>>> bool(zero_int)
False

>>>pos_int = 1
>>> bool(pos_int)
True

>>>neg_flt = -5.1
>>> bool(neg_flt)
True
Other Data Types
List: List contains elements in square bracket separated by commas. List may contain
elements of different data types. The values stored in a list are accessed using index. The
first element is at index 0 and last element is at (n-1).
Tuple: tuple contains elements in first bracket separated by commas. The difference
between list and tuple is , we can change element of a list but we cannot change element of
a tuple.
Set: set contains elements separated by commas and in curly bracket. Difference between
list, tuple and set is that, set does not contain duplicate elements. Set location cannot be
indexed.
Dictionary: Stores element in key value pair. The key and values are separated by colon. To
access an element of a dictionary, we should access it with the key.
a=1+2j
print(type(a))
b=False
print(type(b))
print(format(1000000,','))
print(format(16/float(3),'.3f'))
L=['a',1,2.3]
print(type(L))
print(L[1])
t=(1,5.4,'b')
print(type(t))
print(t[1])
#t[1]=2.3
print(t)
s={1,5.4,'b'}
print(type(s))
s1={1,1,3.4}
print(s1)
#print(s[1])
#s1[0]=2
#print(s1)
d={1:'apple',2:'ball'}
print(type(d))
print(d[2])
d1={'a':'apple','b':'ball'}
print(type(d1))
print(d1['b'])
O/P:
<class 'complex'>
<class 'bool'>
1,000,000
5.333
<class 'list'>
1
<class 'tuple'>
5.4
(1, 5.4, 'b')
<class 'set'>
{1, 3.4}
<class 'dict'>
ball
<class 'dict'>
Ball
a=format(float(16/float(3)), '.2f')
print(a)
num1 = 5
print(type(num1))
num2 = 9.2
print(type(num2))
num2=int(num2)
num3=complex(num1,num2)
print(type(num3))
print(num3)
b=bool(-5.16)
print(b)
c=bool(1)
print(c)
d=bool(0)
print(d)
name="Priya"
print(f"Hi,{name}")
print(type(name))
l=[1,'a',2.3]
print(l)
print(l[0])
l[0]=5
print(l)
t=(1,'c',4.6)
print(t)
print(t[0])
#t[0]=2
#print(t)
s={1,1, 2.3,'d'}
print(s)
#print(s[0])
#s[0]=2
#print(s)
d={'a':1,'b':2}
print(d)
print(d['a'])
d['a']=3
print(d)
O/P:
5.33
<class 'int'>
<class 'float'>
<class 'complex'>
(5+9j)
True
True
False
Hi,Priya
<class 'str'>
[1, 'a', 2.3]
1
[5, 'a', 2.3]
(1, 'c', 4.6)
1
{1, 2.3, 'd'}
{'a': 1, 'b': 2}
1
{'a': 3, 'b': 2}
Operators
1. Arithmetic=(+,-,*,/,//,%,**)
2. Relational(>,>=,<,<=,==,!=)-output is always Boolean value
3. Logical(True and True, True and False, False and True, False and False, True or True,
True or False, False or True, False or False, not(True),not(False))
Multiple Assignments:
a,b=2,3
Precedence of Operators
1. ()
2. **
3. %,//,*,/ (left to right)
4. +,-(left to right)
Type Conversion
External type conversion (explicit type conversion): Forceful type conversion (type casting)
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which
string is if the data type is a string.

2. float(): This function is used to convert any data type to a floating-point number

3. ord() : This function is used to convert a character to integer.

4. hex() : This function is to convert integer to hexadecimal string.

5. oct() : This function is to convert integer to octal string.


int can be converted to float
float can be converted to int
int can be converted to string
string can be converted to int
string can be converted to float
list can be converted to tuple
tuple can be converted to list
set can be converted to tuple
tuple can be converted to set
set can be converted to list
list can be converted to set
ord(x)-converts single character to its ascii values
chr(x)=converts ascii values to corresponding character

Internal type conversion (Coercion): Conversion that happens at run time or compile time is
called implicit type conversion.
Ascii Values : (a to z)-97 to 122
(A to Z)= 65 to 90

Other Operators:
Assignment/In-place or shortcut operators
1.c=2
2.+= (a+=b)
3.-=(a-=b)
4.*=(a*=b)
5./=(a/=b)
6.//=(a//=b)
7.**=(a**=b)

Unary Operators
a.Bitwise Operators:
1.Bitwise AND(&)
a=10 (1010)
b=4 (0100)
a&b=0

2. Bitwise Or(|)
a=10 (1010)
b=4 (0100)
a|b=14

3.Bitwise Exclusive Or(^)


a=10 (1010)
b=4 (0100)
a^b =14

4.Bitwise Not (~)


a=10 (1010)
~a=-11
~(1010)=0101=5
-11(1011)=2’s compliment=0101=5

b. Shift Operators
There are two shift operators in python
a. Left shift(<<)-means number is multiplied by 2 raised to the power of bits shifted
b. Right shift(>>)
1. Left Shift (zero comes at the right most position)
X= 0001 1101=29
X<<1= 0011 1010 =58
X=0001 1101=29
X<<2 = 01110100=116
2. Right Shift (number is divided by 2 raised to the power of bits shifted)
Zero comes at the left most position
X= 0001 1101
x>>1= 0000 1110 = 14
x>>2 = 0000 111 =7

Membership Operators
a. in operator : returns true if value is present in the sequence
print(‘undescore ’ in ‘A variable name can only contain alphanumeric character and
underscore’)
output: True
b. not in operator : returns true if value is not present in the sequence
print (‘alpha’ is not in ‘A variable name may contain underscore’)
output: True
Strings
String Indexing
String indexing is the process of pulling out specific characters from a string in a particular
order. In Python, strings are indexed using square brackets [ ]. An important point to
remember:
Python counting starts at 0 and ends at n-1.
Consider the word below.
Solution
The letter S is at index zero, the letter o is at index one. The last letter of the word Solution is
n. n is in the seventh index. Even though the word Solution has eight letters, the last letter is
in the seventh index. This is because Python indexing starts at 0 and ends at n-1.

>>> word = 'Solution'


>>> word[0]
'S'
>>> word[1]
'o'
>>> word[7]
'n'
If the eighth index of the word Solution is called, an error is returned.
>>> word[8]
IndexError: string index out of range
Negative Indexing

 Python supports negative indexing too, starting with -(length of string) till -1.

 Placing a negative number inside of the square brackets pulls a character out of a
string starting from the end of the string.

>>> word[-1]
'n'
>>> word[-2]
'o'

Concatenation: adding of two strings in python


Example:
print(“hello dear”+”!”+”how are you”)
output: hello dear! how are you
print(‘what a weather!’+’voww ’)
output :what a weather!voww
print(‘2’+’4’)
output:24
Multiplication (Repetition of string)
print(‘hello’*5)
output: hello hello hello hello hello
Addition and multiplication on strings
name=’john’
print(name +’4’)
output: john 4
print(name*5)
output: john john john john john
String slicing
This means extracting subsets of a string.
st=’python is easy !!’
print(st)
output: python is easy !!
print(st[0])
output:p
print(st[3:9])
output: hon is
print(st[4:])
output: on is easy !!
print(st[-1])
output:!
print(st[:5])
output:python
print(st[::-1])
output: prints string in reverse
name: ‘ASTRING’
print(name[1:5:2])
output: SR
print(name[-1:-12:-2])
output: GITA
b=”Hello World!”
print(b[-5:-2])
output: orl
x=’python is easy’
print(x[1:3])
output:yt
String methods
Method Description Code output
lower() Converts a string a=’HELLO’ hello
into lower case print(a.lower())
upper() Converts a string a=’hello’ HELLO
into upper case print(a.upper())
capitalize() Converts the first a=’hello’ Hello
character to upper print(a.capitalize())
case
title() Converts the first b= ‘hello all’ Hello All
character of each print(b.title())
word to upper case
swapcase() Lower case a= ‘Hi’ hI
becomes upper print(a.swapcase())
case and vice versa
islower() Returns true if all b=’python’ True
characters in the print(b.islower())
string are lower
case
isupper() Returns true if all c=’PYTHON’ True
characters in the print(b.upper())
string are upper
case
isdigit() Returns true if all x=’123’ True
characters in the print(x.isdigit())
string are digits
isalpha() Returns true if all x=’abc’ True
characters in the print(x.isalpha())
string are alphabets
isalnum() Returns true if all x=’abc123’ True
characters in the print(x.isalnum())
string are alpha
numeric
strip() Returns a trimmed x=’-------Python-----’ Python
version of a string print(x.strip(‘-’))
lstrip() Returns a left trim x=’-------Python-----’ Python-------
version of a string print(x.lstrip(‘-’))
rstrip() Returns a right trim x=’-------Python-----’ ----------Python
version of a string print(x.rstrip(‘-’))
startswith() Returns true if the x= Python True
string starts with print(x.startswith(‘P’))
the specified value
False
print(x.startswith(‘p’))

endsswith() Returns true if the x= Python True


string ends with print(x.endswith(‘n’))
the specified value False
print(x.startswith(‘N’))

count() Returns number of x= Python 1


times a specified print(x.count(‘P’))
value occurs in a 1
string print(x.count(‘t’))

index() Returns true if the x= Python True


string starts with print(x.startswith(‘P’))
the specified value False
print(x.startswith(‘p’))

startswith() Returns true if the x= Python True


string starts with print(x.startswith(‘P’))
the specified value False
print(x.startswith(‘p’))

Input and Output Functions:


A program needs to interact with the user to accomplish the desired task; this can be achieved using Input-
Output functions.

The input() function helps to enter data at run time by the user and the output function print() is used to
display the result of the program on the screen after execution.

1. The print() function

In Python, the print() function is used to display result on the screen. The syntax for print() is as follows:

Example
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3” ……)

Example
>>>print (“Welcome to Python Programming”) Welcome to Python Programming
>>>x = 5
>>>y = 6
>>>z = x + y
>>>print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11

The print ( ) evaluates the expression before printing it on the monitor. The print () displays an entire
statement which is specified within print ( ). Comma ( , ) is used as a separator in print ( ) to print more than
one item.
2. input() function
In Python, input( ) function is used to accept data as input at run time.
The syntax for input() function is,
Variable = input (“prompt string”)
Where, prompt string in the syntax is a statement or message to the user, to know what input can be given.
If a prompt string is used, it is displayed on the monitor; the user can provide expected data from the input
device.
The input( ) takes whatever is typed from the keyboard and stores the entered data in the given variable.
If prompt string is not given in input( ) no message is displayed on the screen, thus, the user will not know
what is to be typed as input.
Example 1:input( ) with prompt string
>>>city=input (“Enter Your City: ”)
Enter Your City:Warangal
>>>print (“I am from “, city)
I am from Warangal
Example 2:input( ) without prompt string
>>> city=input()
Hanamkonda
>>> print (I am from", city)
I am from Hanamkonda
Note that in example-2, the input( ) is not having any prompt string, thus the user will not know what is to be
typed as input. If the user inputs irrelevant data as given in the above example, then the output will be
unexpected. So, to make your program more interactive, provide prompt string with input( ).
The input ( ) accepts all data as string or characters but not as numbers. If a numerical value is entered, the
input values should be explicitly converted into numeric data type. The int( ) function is used to convert string
data as integer data explicitly. We will learn about more such functions in later chapters.
Example 3:
x = int (input(“Enter Number 1: ”))
y = int (input(“Enter Number 2: ”))
print (“The sum = ”, x+y)
Output:
Enter Number 1: 34
Enter Number 2: 56
The sum = 90
Example 4: Alternate method for the above program
x,y=int (input("Enter Number 1 :")),int(input("Enter Number 2:"))
print ("X = ",x," Y = ",y)
Output:
Enter Number 1 :30
Enter Number 2:50
X = 30 Y = 50

You might also like