PYTHON
ALGORITHMIC THINKING WITH
ALGORITHMIC THINKING WITH PYTHON
3. Execute the Program:
Open Terminal or Command Prompt:
Windows: Open Command Prompt (Gh
PowerShell.
macO$/Linux: Open Terminal.
o Navigate to the File Location: Use the cd command
CHAPTER 4
change to the directory where your Python file is save ESSENTIALS OF PYTHON
cd path/toyour/directory PROGRAMMING
Run the Program: Execute the script by ty
Python [Link] or Python3 [Link]
(Depending on your Python installation.)
3. Using an Integrated Development Environment (IDE) 4.1 BASIC SYNTAX OF PYTHON
1. Open the IDE: Launch your chosen IDE (such as PyCharm, VSCa Understanding basic Python syntax is esential for writing, reading
or Thonny). and executing Python code effectively. Basic furndamentals of Python
syntax and concepts are discussed below:
2. Open or Create a Python File:
Indentation: Python uses indentation to define blocks of code
Open an existing file: Use the file explorer within the Consistent indentation is crucial as it indicates a block of code,such as
to navigate to and open your -py file.
the body of a loop or a function.
Create a new file: Create a new project or file within the
and write your Python code.
if5>2:
3. Run the Program:
print("Five is greater than two!") #Output: Fve is greater than twa!
Most IDEs have a "Run" button or similar option in i
toolbar or menu. Click this to execute your code.
Constants: Constants are typically used to represent fixed values that
Alternatively,you may use a shortcut key provided by shouldn't change throughout the program.
IDE, such as Shift +F10 in PyCharm or F5 in VS Code.
Pl=3.14159
4. Using Online Editors
Comments: Comments start with a # and are used to explain code.
1. Open the Online Editor: Go to an online Python editor like Repli They are ignored by the Python interpreter.
Google Colab, or any other web-based coding platform.
2. Write or Paste Your Code: Enter your Python code into the provide # This is a comment
editor window. print("Hello, World!'") #Outgut: Hello, World!
3. Execute the Program: Click the "Run" button or use the provide
execution command to run your code. The output willbe displaye! In ython, multiline comments are typically created using triple
in the output console of the online editor. quotes (" or "n).
Module 1 Page 3.8 Module 1 Page 4.1
ALGORITHMIC THINKING WITH PYTHON
ALGORITHMIC THINKING WITH PYTHON
This is a mutiine comment. Control Flow Statements:
It spans multiple lines. condition
You can use triple single quotes for this purpose. ifStatements: Used to execute code based on a
print("Hell, wonld!") #Output: Hello. World! X=25
ifx> 0:
Variables: Variables are created when you assign a value to . print('x is positive")
Python is dynamically typed, so you don't need to declare the type #Output
elif x== 0:
a variable. print("x is zero") xis positive
else:
print('x is negative")
X=5
y= "Hello, World!" #0utput
5 Loops: for and while loops are used to iterate over sequences or
print(x) execute code repeatedly
printky) Hello, World!
for i in range(5): #Output
print(i)
Data Types: Common data types include integers (int), floating-po 2
numbers (float), strings (str), and booleans (bool). In programming. 3
literal is a fixed value that appears directly in the code and represe
aspecific data type. It is the way a value is written or displayed in
code, allowing the programmer to specify data values explicity.
x=5 #Dutput 5
a=10 #int while x >D:
print() 3
b=3.14#float X-=| 2
C= "Python #str #lutput
d= True # bool
printa) <class int'>
printtype(a)) 3.14 Functions: Functions are defined using the def kevword. They can take
arguments and return values.
print(b) <class 'float'
print(type(b)) Pythan def greet(): #Output: Hello Peter!
print(c) <class'str'> return "Hello Peter!"
print(type(c) True print(grt)
print(d) <class 'bool'>
print(type(d) Lists: Lists are ordered collections of items. They are mutable, meaning
their contents can be changed.
Operators: Arithmetic Operators: +, -," /, %, ** (exponentiation), //
(floor division). Comparison Operators: ==, !=, >, <, >,<=, Logica fruits =('apple"."banana". "therry #utput: ['aple. banana', thery.
Operators: and, or, not.
[Link]("'dates") 'dates]
print(fruits)
Module 1 Page 4.2
Module 1 Page 4.3
ALGORITHMIC THINKING WITH
PYTHON ALGORITHMIC THINKING WITH PYTHON
key-value pairs. They
Dictionaries: Dictionaries are collections of Rules for Naming Variables/Identifiers
unordered and mutable
Identifiers must start with a letter
person =('namie:"Peter" "age" 25)
#0utputPeter 1. Start with a Letter or Underscore:
print(personl'name"]) (A-Z or a-z) or an underscore ().
name ="Jovan"
standard library age=25
Modules and Libraries: Python has a rich
third-party modules. You can import them using
the imn
supports
After the first
statement. 2. Followed by Letters, Digits, or Underscores:
#Output4.0 character, identifiers can contain letters, digits (0-9), or underscores.
import math
print(mathsort(l6) namel ="Aditya"
2nd valug =42
4.2 CONSTANTS
2 Case-Sensitive: Identifiers are case-sensitive. For example, name
Constants are used to represent fixed values like mathematig and Name are differentidentifiers.
constants, configuration settings, or predefined limits whose valye name = "Rohan"
intended to remain unchanged throughout the execution of a progra Name ="Neha"
While Python does not have built-in support for constants like son
other languages (e.g., const in Cor final in Java), developers ollo same as Python keywords
naming conventions tosignal that a variable is intended to be constanA NoKevywords: Identifiers cannot be the
By convention, constant names are written in all uppercase letters. (e.g., if,else, while, etc.).
# Invalid identifier
Pl=31459 if=|0 # 1his will cause a syntax error
GRAVITY =9.8
SPEED OF LIGHT= 299792458 # meters per second
5. No Special Characters: Identifiers cannot contain special characters
like !, @, #, $, etc.
Example using a constant:
# Invalid identifier
RADIUS =5 #lutput: namela ="Ee" #This willcause asyntax errar
area = PI*RADIUS*2 Area of the circle: 78.53975
print('Area of the circle". Examples
area)
Valid ldentifiers Invalid ldentifiers
4.3 VARIABLES my var =l0 I23var =40 #Starts with adigit
_mylar =20 my-var =50 # Contains a hyphen
In programming, variables (or identifiers) are names used to refert varl23 =30 it- 60 #lises akeyward
values stored in memory. They allow programmers to store, retrien
and manipulate data throughout their programs.
Module 1 Page 4.5
Module 1 Page 44
ALGORITHMIC THINKING WITH PYTHON
ALGORITHMIC THINKING WITH PYTHON
4.3.1 Creating Variables
you toswap the values of two
Swapping Variables: Python allows
variable by assigning a value
1) Assignment: You create a
variables easily.
the = operator.
a.b,c= 121, 85,39 #lutput
# int printla)
121
name = "Peter #str print(b) 85
is active =True #bool a.b=b.a
printla)
Typing: Python is dynamically typed, meanine print(b) 85
2) Dynamic
don't need to declare the type of a variable. The type is inten 12
from the value assigned.
Example
8ge = 25 # int Here's a simple example that demonstrates creating and using
height =5.9 # foat Variables:The above example creates variables for a person's name,
greeting ="Hello" #str age, and height, prints their values, and then updates the age.
# Creating variables
4.3.2 Using Variables name = "Peter"
usin
1) Printing Variables: You can print the value of a variable
age =30
print() function. height - 5.5
#Dutput
10
# Using variables #Output
name = "Shivanika"
Shivanika print("Name:"+ name) Name: Peter
print() print("Age:"+ str(age)) Age: 30
print(name)
print("Height:"+ str(height) +" Height: 5.5 feet
feet") Updated Age: 3
2) Updating Variables: You can update the value of a variable # Updating variables
reassigning it. age = age +|
x= (0 #Output print("Updated Age:"* strlage)
X=x+5 #Now xis 15
print(r)
4.4 KEYWORDS IN PYTHON
3) Multiple Assignments: You can assign values to multi
variables in one line. Python keywords are reserved words that have special meaning and
ab.c=l.2.3 #0utput cannot be used as variable names, function names, or any other
print(a) identifiers. They are the building blocks of Python syntax and are
print(b) 2 always available in the language. As of Python 3.8, there are 35
print(c) keywords. Some of the most commonly used ones are given below:
Module 1 Page 4.6
Module 1 Page 4.7
ALGORITHMIC THINKING WITH PYTHON ALGORITHMIC THINKING WITH PYTHON
and Logical operator for canjunction
Or
Logical operator far disjunction
Creates an alias
pass Anull statement. a placeholder for future code
break Exits the current loop
return Exits afunction and returns a value
class Jsed to define a class
true Representsa boolean true value
continue Skips the rest of the code inside the loop for the current iteratign
try Used to catch exceptions
def Used to define a function
while Used to create awhile loop
del Deletes an object
with Used to wrap the execution of a block of code
elif Stands for "else if", used in conditional statements
yield Used to return a generator
else Used in conditional statements
Used to handle exceptions 4.5 PYTHON DATA TYPES
except
false Python has a variety of built-in data types that are used to store
Represents a boolean false value different kinds of data. The following data types are fundamental to
Python and are used in various operations and functions.
finally Executes cade regardless of whether an exception occurred ar ngt
1. Numeric Types:
for Used to create a for loop int: Integer values, e.g., 42
float: Floating-point numbers, e.g.,3.14
from Imports specific parts of a module. complex: Complex numbers, e.g., 1 +2j
2. Text Type:
global Declares a glabal variable str: String, a sequence of characters, e.g., "Hello, World!"
3. Sequence Types:
if Jsed for conditional statements
list: Ordered, mutable collection of items, e.g.. [1, 2, 3]
tuple: Ordered, immutable collection of items, e.g., (1, 2, 3)
import Imports a module
range: Represents a sequence of numbers, e.g., range(5)
lambda Creates an anonymous tunction 4. Mapping Type:
dict: Dictionary, a collection of key-value pairs, e.g., ('name":
None Represents a nullvalue "Peter", "age": 25}
5. Set Types:
nonlocal Declares a non-local variable set: Unordered collection of unique items, e.g.. {1, 2, 3)
frozenset: Immutable version of a set, e.g., frozenset([1, 2, 3])
not Logical operator far negation
Module 1 Page 4.8 Module 1 Page 4.9
ALGORITHMIC THINKING WITH PYTHON
ALGORITHMIC THINKING WITH PYTHON
6. Boolean Type:
bool: Boolean values, True or False a45e3 #0utput: <class Fioat'>
7. Binary Types: b=32E4 <class 'Flat'>
bytes: Immutable sequence of bytes, e.g., b'hello' c=-25.7elOO <class Float'
bytearray: Mutable sequence of bytes, e.g, bytearray(5) print(type(Y)
memoryview: Memory view object,
print(type(b)
memoryview (bytes (5) printtype(c)
8. None Type:
NoneType: Represents the absence of a value, e.g., Non
3. Complex Numbers (complex):
4.5.1 Numeric and String data types in Python Represents complex numbers, which have a real and an imaginary
part.
In Python, numeric and string are two fundamental data types usedle2+3i. where 2 is the real part, and 3j is the imaginary part.
represent numbers and text.
y-2+3j #utput: (2+3j)
Numeric Data Types print(y) camplex
type(y)
1. Integers (int):
Represents whole numbers, positive or negative, without any decima
point. String Data Types
print(20) #Output:20 Strings (str): Represents a sequence of characters enclosed in single,
print(-20) -20 double, or triple quotes. Strings can include letters, numbers, symbols,
print(0X32) 50 and whitespace. Example: "Hello, World!", 'Python 3.8, "mThis is a
multiline string"nm
print(Obi0) 2
t= "Hello, Pythan!" #Output: [Link]!
print(t) str
#Output: 10 print(type(t)
print(a)
t="This is a multiline string"
print(t) This is a multiline string
To verify the type of any object in Python, use the type) function:
type(a) #Dutput: int 4.6 USING THE MATH MODULE
2. Floating-Point Numbers (float): The math module in Python provides a wide range of mathematical
Represents real numbers, which include a fractional component. functions and constants that are essential for scientific, engineering,
y-2.8 and mathematical computations. To use the math module, you need to
#Output: 2.8 import it first:
print(y) float
type(y) impart math
Module 1 Page 4.10 Module 1 Page 4.11
ALGORITHMIC THINKING WITH PYTHON PYTHON
ALGORITHMIC THINKING WITH
with math module i
Some of the numnber functionsavailable
below import math
1. [Link](x): Returns the smallest integer greater than Or equa
# Power functions
(x). print([Link](2. 3)) # 0utput: 8.0
2. [Link] (x): Returns the largest integer less than or equal fo
3. pow(x, y) :Returns the value of x to the power of y (xy). print(math exp(2) # Dutput: 73890560989306495
[Link] : constant, returns the value of PI (3.14...)
4.
5. [Link](x): Returns the absolute value of (x). # Logarithmic functions
6. [Link](x): Returns the factorial of (x ). print([Link]{8. 2)) # Dutput: 3.0
7. [Link](%, y): Returns the remainder of ( x )divided bu , print(math.log2(8) # Dutput: 3.0
8. [Link](x): Returns the mantissa and exponent print([Link](100) # Output: 2.0
(m, e)).
of(x)as apa
9 [Link](x): Returns the truncated integer value of (x). Trigonometric Functions
10. [Link]() : Returns the square root of a number 1. [Link](x): Returns the sine of ( x)(in radians).
2. [Link](x): Returns the cosine of(x )(in radians).
import math 3. [Link](x):Returns the tangent of ( x) (in radians),.
#Example usage 4. [Link](x): Returns the arc sine of (x)(in radians).
print([Link](4.2) # Dutput: 5 5. [Link](x): Returns the arc cosine of (x ) (in radians).
print([Link](4.2) # Dutput: 4 6. [Link](x): Returns the arc tangent of (x ) (in radians).
print(pow(2, 3)) # Dutput: 8
7. math.atan2(y, x): Returns the arc tangent of ( y/x ) in radians,
considering the signs of both arguments to determine the
print([Link]) # Dutput: 3.141592653589793 correct quadrant.
print([Link](-4.2)) # Output: 4.2
Angular Conversion Functions
print([Link](5) # Output: 120
print([Link](20. 3)) # Dutput: 2.0 1. [Link](x): Converts angle (x )from radians to degrees.
print([Link](8) # 0utput: (0.5, 4) 2 [Link](x): Converts angle (x) from degrees to radians.
print{[Link](4.9)) # Output: 4 Hypotenuse and Distance Functions
print( [Link](16) # Output: 4.0 1. [Link](x, y): Returns the Euclidean norm, (\ sqrt(x^2 +
y^2} ).
Power Functions 2. [Link](p, q): Returns the Euclidean distance between
1. [Link](x, y): Returns (x)raised to the power of (y )(x^y)l points ( p) and (q).
2. [Link](x): Returns (e)raised to the power of (x )((e^x).
3. pow(x, y): A built-in function that also returns (x ) raised to t import math
power of (y ). # Trigonometric functions
print([Link](math, pi / 6) # Output: 049999999999999994
Logarithmic Functions print(math. cos(math pi / 3)) # Output: 0.500000O000000001
1. [Link](x, base): Returns the logarithm of (x ) to the specifig print([Link]([Link] / 4)) # Output: 0.9999999999999999
base. If the base is not provided, it returns the natural logarithr
(base (e )). # Angular conversion functions
2. math.log2(x): Returns the base-2 logarithmof (x ). print([Link]([Link] / 6)) # Output: 29,999999999999996
3. math.log10(x): Returns the base-10 1logarithm of (x ).
Module 1 Page 4.12 Module 1 Page 4.13
coluctn Pre wnettrn co ddes
ALGORITHMIC THINKING WITH PYTHON ALGORITHMIC THINKING WITH PYTHON
print([Link](180) # Output: 3.141592653589793
# Hypotenuse and distance functions name = "Peter" #Output Peter, Age 30
print([Link](3. 4)) # Output: 5.0 age = 30
print([Link](l.2). (4. 6)) #Output: 5.0 # Using f-string to embed varíables
directly ir the string
print(f"Narme: (name). Age: (age))
4.7 USING THE PYTHON STANDARD LIBRA
FOR HANDLING BASIC VO
String Concatenation: Concatenate strings and variables using + and
The Python Standard Library provides simple yet powerful funck convert non-strings to strings with str).
for handling basic input and output (1/0) operations. Two of the name ="Jovan" #Output: Hello. Jovan!
commonly used functions are print() and input(). print("Helo,"name +"T)
print) Function
The print) function is used to display output to the console. In Py input) Function
the print) function is versatile and can be used in several ways
format and display output. You can print strings, The input() function is used to take input from the user. It always
humbers,
[Link] items can be printed when separated . n s the input as a string. First you need to prop ue
a r
Spaceseperator like comma. input.
# Dutput: Hello, world! name= input("Enter your name:") #0utput:
print("Hello, world!") orint("You entered.". name) Enter your name: Meera
print(42) 42
name ="Peter" Peter You entered. Meera
print(name) Hello world 42
print("Hello","world", 42) input) function returns a string, you may need to convert it to other
types if required.
Using Separator With print():Use the sep parameterto specifyasti age =int(input("Enter your age: ") #[Link] yaur age: l8
that will be inserted between items.
print("Your age is:". age) Your age is:8
print("Pythan", "is". "fun'. Sep="") #Output: Python--is--fun
The int) function in the above example converts the string returned
Using End Character With print): By default, print() ends with by input() into an integer. This is necessary because input() alwavs
newline. You can change this using the end [Link] the en returns a string, and if you want to perform numerical operations (like
parameter to specify what to print at the end of the line. By default arithmetic) on the input, you need it to be in a numerical format.
is anewline character (\n).
# Taking user input #Output:
print("Hello., end-"") name = input("Enter your name: ") Enter your name: Arnav
# Output: Hello. World!
print("Warld!") age =input("Enter your age:") Enter your age: 15
#-0isplaying the output Hello, Arnav! You are l5 years old.
print("Hello,"+ name+"! You are"+ age + years
Formatted Strings: You can use formatted string literals (f-strings) fo old.")
more complex output.
Module 1 Page 4.14 Module 1 Page 4.15
ALGORITHMIC THIN
PYTHON. OPERATORS
THINKING WITH PYTHON
ALGORITHMIC
1 P A r i t h m e t i cO p e r a t o r s
4.8
to perform basic
operators
are
used
mathematical 8.2 Assignment Operators
to assign values to
variables:
These
Addition: + hese operators are used
is
used to add two operands.
Assignmnent: = right to the
assign the value on the
operator
This
This operator is used to
Subtraction: - variable on the left.
is used to
subtract two
This
operator
operands Add and Assign: += operators. This
" Multiplication: * combination of "+" and "="
This operator is a variable on left to
ito multiply two operands. current value of the
is used operator first adds the assigns the result to the
value on the right and then
operator
This the
variable on the left.
Division:/
used to divide two operands.
operator is
This Subtract and Assig:=
of "-" and "=" operators. This
Floor Division://
This operator returns the largest integer that is les This operator is a combination value of the variable on the
operator first subtracts the current
assigns the result to
result of the division left from the value on the right and then
equal to the
the variable on the left.
Modulus: %
This operator gives the remainder after the divisig Multiply and Assign: *=
This operator is a combination of "*"
and "=" operators. This
value of the variable on
operator first multiplies the current
operands.
the result to the
Exponentiation:
left to the value on the right and then assigns
This operator performs exponential (power) calau variable on the left.
operands.
Divide and Assign: /=
operators. This
This operator is a combination of"/" and "=" variable on the
a =5 operator first divides the current value of the
to the
b=3 left by the value on the right and then assigns the result
print(a +b) # Dutput: 8 variable on the left.
print{a- b) # Output: 2
printla " b) # Dutput: 15 Modulus and Assign: %=
"=" operators. This
print(a /b) # Output: .CGGG66G66BGG6GE7 This operator is a combination of "%" and
printla //b) # Dutput:I operator first takes the remainder of the current value of the
printa %b) # Output: 2 variable on left when divided by the value on the right and
print(a ** b) #Output: 125 then assigns the result to the variable on the left.
Exponentiation and Assign: **=
Performs exponential (power) calculation on operands and
assigns value to the left operand.
Module 1 Page 4.16 Module 1 Page 4.17