0% found this document useful (0 votes)
36 views108 pages

Python Ppt for Chapter 1

Uploaded by

Harshal Kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
36 views108 pages

Python Ppt for Chapter 1

Uploaded by

Harshal Kadam
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 108

--Prof.

More Shekhar
Chapter 1

Fundamentals of
Python
Introduction
• What is Python?
• Python is a popular programming language. It was
created by Guido van Rossum, and released in
1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
Features of python:
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a student to pick up the language quickly.
• Easy-to-read: Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain: Python's source code is fairly easy-to-maintain.
• A broad standard library: Python's bulk of the library is very portable and
Cross platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.
• Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
• Databases: Python provides interfaces to all major commercial databases.
• GUI Programming: Python supports GUI applications that can be created and ported
What can Python do?

• Python can be used on a server to create web


applications.
• Python can be used alongside software to create
workflows.
• Python can connect to database systems. It can also
read and modify files.
• Python can be used to handle big data and perform
complex mathematics.
• Python can be used for rapid prototyping, or for
production-ready software development.
Why Python?

• Python works on different platforms (Windows, Mac, Linux,


Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs
with fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code can
be executed as soon as it is written. This means that
prototyping can be very quick.
• Python can be treated in a procedural way, an object-
oriented way or a functional way.
Python Install
• Many PCs and Macs will have python already installed.
• To check if you have python installed on a Windows PC, search
in the start bar for Python or run the following on the
Command Line (cmd.exe):
C:\Users\Your Name>python --version
• To check if you have python installed on a Linux or Mac, then on
linux open the command line or on Mac open the Terminal and
type:
python --version
• If you find that you do not have Python installed on your
computer, then you can download it for free from the following
website: https://www.python.org/
Structure of Python
• Comments: Comments are used to explain the purpose of the code or to make notes for other
programmers. They start with a ‘#’ symbol and are ignored by the interpreter.
• Import Statements: Import statements are used to import modules or libraries into the
program. These modules contain predefined functions that can be used to accomplish tasks.
• Variables: Variables are used to store data in memory for later use. In Python, variables do not
need to be declared with a specific type.
• Data Types: Python supports several built-in data types including integers, floats, strings,
booleans, and lists.
• Operators: Operators are used to perform operations on variables and data. Python supports
arithmetic, comparison, and logical operators.
• Control Structures: Control structures are used to control the flow of a program. Python
supports if-else statements, for loops, and while loops.
• Functions: Functions are used to group a set of related statements together and give them a
name. They can be reused throughout a program.
• Classes: Classes are used to define objects that have specific attributes and methods. They are
used to create more complex data structures and encapsulate code.
• Exceptions: Exceptions are used to handle errors that may occur during the execution of a
program.
Example of a simple Python program
• # This is a comment

import random # Importing a module

# Defining variables
x = 10
y = "Hello, World!"
z = True

# Performing arithmetic operation


result = x + 5

# Using if-else statement


if z:
print(y)
else:
print(result)

# Defining a function
def greet(name):
print("Hello, " + name + "!")

# Using the function


greet("Alice")
EXPLANATION
• In this example, we start with a comment that explains the purpose
of the code. Then, we import the random module to generate
random numbers later in the program.
• Next, we define three variables with different data types: x is an
integer, y is a string, and z is a boolean. We then perform an
arithmetic operation on x and store the result in the result variable.
• We use an if-else statement to check the value of z. If z is True, we
print the string stored in y, otherwise, we print the value of result.
• Finally, we define a function called greet() that takes a parameter
called name and prints a greeting message. We call the function
with the argument "Alice" to print "Hello, Alice!" to the console.
Python Keywords

Every language contains words and a set of


rules that would make a sentence meaningful.
Similarly, in Python programming language,
there are a set of predefined words, called
Keywords which along with Identifiers will
form meaningful sentences when used
together. Python keywords cannot be used as
the names of variables, functions, and classes.
• Python Keywords are some predefined and
reserved words in Python that have special
meanings. Keywords are used to define the
syntax of the coding. The keyword cannot be
used as an identifier, function, or variable
name. All the keywords in Python are written
in lowercase except True and False. There are
35 keywords in Python 3.11.
List of Python Keywords
EXAMPLE
• Print each number from 1 to 8:
for x in range(1, 9):
print(x)
The for keyword is used to create a for loop.
It can be used to iterate through a sequence, like
a list, tuple, etc.
EXAMPLE
• Loop through all items in a list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
O/P-
apple
banana
cherry
Identifiers in Python

• Identifier is a user-defined name given to a


variable, function, class, module, etc. The
identifier is a combination of character digits
and an underscore. They are case-sensitive
i.e., ‘num’ and ‘Num’ and ‘NUM’ are three
different identifiers in python. It is a good
programming practice to give meaningful
names to identifiers to make the code
understandable.
Rules for Naming Python Identifiers

• It cannot be a reserved python keyword.


• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or
underscore.
• It should start with an alphabet character or
an underscore ( _ ).
• It should not contain any special character
other than an underscore ( _ ).
Examples of Python Identifiers

• Valid identifiers:
• var1
• _var1
• _1_var
• var_1

Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1
Literals in Python

• A literal in Python is a syntax that is used to


completely express a fixed value of a specific
data type. Literals are constants that are self-
explanatory and don’t need to be computed
or evaluated. They are used to provide
variable values or to directly utilize them in
expressions. Generally, literals are a notation
for representing a fixed value in source code.
Types of Literals in Python

Python supports various types of literals, such as


numeric literals, string literals, Boolean literals,
and more. Let’s explore different types of
literals in Python with examples:
• String literals
• Numeric literals
• Boolean literals
• Literal Collections
• Special literals
Types and Examples of Literals
Type of Literal Description Example

Numeric Literal Values that represent numeric data 123, 10.5


types

String Literal Sequence of characters surrounded by "Hello", 'Python'


quotes

Boolean Literal Represents two truth values: True and True, False
False

None Literal Represents the absence of value or a None


null value

Complex Literal Combination of real and imaginary 3+4j


parts

List, Dict, Set, Tuple Literals Compound data types with their [1, 2], {"key":"value"}, {1,2,3}, (1,2)
specific literals
PYTHON Data Types
• There are different types of data types in Python.
Some built-in Python data types are:
• Numeric data types: int, float, complex
• String data types: str
• Sequence types: list, tuple, range
• Binary types: bytes, byte array, memory view
• Mapping data type: dict
• Boolean type: bool
• Set data types: set, frozen set
Python Numeric Data Type

• Python Numeric Data Type


• int - holds signed integers of non-limited
length.
• long- holds long integers(exists in Python 2.x,
deprecated in Python 3.x).
• float- holds floating precision numbers and it’s
accurate up to 15 decimal places.
• complex- holds complex numbers.
EXAMPLE
• #create a variable with integer value.
a=100
print("The type of variable having value", a, " is ", type(a))

• #create a variable with float value.


b=10.2345
print("The type of variable having value", b, " is ", type(b))

• #create a variable with complex value.


c=100+3j
print("The type of variable having value", c, " is ", type(c))
OUTPUT
Python String Data Type

• The string is a sequence of characters. Python


supports Unicode characters. Generally, strings are
represented by either single or double-quotes.
EXAMPLE
• a = "string in a double quote"
• b= 'string in a single quote'
print(a)
print(b)
# using ',' to concatenate the two or several strings
print(a, "concatenated with",b)
#using '+' to concate the two or several strings
print(a+" concated with "+b)
OUTPUT
Python List Data Type

• The list is a versatile data type exclusive in


Python. In a sense, it is the same as the array
in C/C++. But the interesting thing about the
list in Python is it can simultaneously hold
different types of data. Formally list is an
ordered sequence of some data written using
square brackets([]) and commas(,).
• #list of having only integers
a= [1,2,3,4,5,6]
print(a)

#list of having only strings


b=["hello","john","reese"]
print(b)

#list of having both integers and strings


c= ["hey","you",1,2,3,"go"]
print(c)
OUTPUT
Python Tuple

• The tuple is another data type which is a


sequence of data similar to a list. But it is
immutable. That means data in a tuple is
write-protected. Data in a tuple is written
using parenthesis and commas.
EXAMPLE
tuple having only integer type of data.
a=(1,2,3,4)
print(a) #prints the whole tuple
tuple having multiple type of data.
b=("hello", 1,2,3,"go")
print(b) #prints the whole tuple
#index of tuples are also 0 based.
OUTPUT
Python Dictionary

Python Dictionary is an unordered sequence of


data of key-value pair form. It is similar to the
hash table type.
Dictionaries are written within curly braces in
the form key:value.
It is very useful to retrieve data in an optimized
way among a large amount of data.
EXAMPLE
# sample dictionary variable
• a = {1:"first name",2:"last name", "age":33}
#print value having key=1
print(a[1])
#print value having key=2
print(a[2])
• #print value having key="age"
print(a["age"])
OUTPUT
Python Sets

• A Set in Python programming is an unordered


collection data type that is iterable, mutable
and has no duplicate elements.
• Set are represented by { } (values enclosed in
curly braces)
EXAMPLE
var = {"Geeks", "for", "Geeks"}
type(var)

Output:
set
EXAMPLE
thisset = {"apple", "banana", "cherry"}
print(thisset)

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
OUTPUT
• {'banana', 'apple', 'cherry'} // FIRST O/P
# Note: the set list is unordered, meaning: the items
will appear in a random order.

• {'banana', 'cherry', 'apple'} //SECOND O/P


# Sets cannot have two items with the same value.
Duplicates Not Allowed.

.
Understanding Python blocks
• Python is a high-level, interpreted
programming language that is easy to learn
and use. It has a simple and easy-to-
understand syntax that emphasizes readability
and reduces the cost of program maintenance.
The basic structure of a Python program
consists of the following components:
Structure of Python
• Comments: Comments are used to explain the purpose of the code or to make notes for
other programmers. They start with a ‘#’ symbol and are ignored by the interpreter.
• Import Statements: Import statements are used to import modules or libraries into the
program. These modules contain predefined functions that can be used to accomplish
tasks.
• Variables: Variables are used to store data in memory for later use. In Python, variables do
not need to be declared with a specific type.
• Data Types: Python supports several built-in data types including integers, floats, strings,
booleans, and lists.
• Operators: Operators are used to perform operations on variables and data. Python
supports arithmetic, comparison, and logical operators.
• Control Structures: Control structures are used to control the flow of a program. Python
supports if-else statements, for loops, and while loops.
• Functions: Functions are used to group a set of related statements together and give them a
name. They can be reused throughout a program.
• Classes: Classes are used to define objects that have specific attributes and methods. They
are used to create more complex data structures and encapsulate code.
• Exceptions: Exceptions are used to handle errors that may occur during the execution of a
program.
EXAMPLE
• # This is a comment

import random # Importing a module

# Defining variables
x = 10
y = "Hello, World!"
z = True

# Performing arithmetic operation


result = x + 5

# Using if-else statement


if z:
print(y)
else:
print(result)

# Defining a function
def greet(name):
print("Hello, " + name + "!")

# Using the function


greet("Alice")
EXPLANATION OF CODE
• we start with a comment that explains the purpose of the code. Then, we
import the random module to generate random numbers later in the
program.

• Next, we define three variables with different data types: x is an


integer, y is a string, and z is a boolean. We then perform an arithmetic
operation on x and store the result in the result variable.

• We use an if-else statement to check the value of z. If z is True, we print


the string stored in y, otherwise, we print the value of result.

• Finally, we define a function called greet() that takes a parameter


called name and prints a greeting message. We call the function with the
argument "Alice" to print "Hello, Alice!" to the console.
Indentation in Python

• Whitespace is used for indentation in Python.


Unlike many other programming languages
which only serve to make the code easier to
read, Python indentation is mandatory.
EXAMPLE
The lines print(‘Logging on to geeksforgeeks…’)
and print(‘retype the URL.’) are two separate
code blocks. The two blocks of code in our
example if-statement are both indented four
spaces. The final print(‘All set!’) is not
indented, so it does not belong to the else-
block.
OUTPUT
Logging on to geeksforgeeks...
All set !
Control Flow in Python
• Python program control flow is regulated by
various types of conditional statements, loops,
and function calls. By default, the instructions in a
computer program are executed in a sequential
manner, from top to bottom, or from start to end.
However, such sequentially executing programs
can perform only simplistic tasks. We would like
the program to have a decision-making ability, so
that it performs different steps depending on
different conditions.
Types of Control Flow in Python
• Python If Statement
• Python If Else Statement
• Python Nested If Statement
• Python Elif
• Ternary Statement | Short Hand If Else Statem
ent
Python If Statement

The if statement is the most simple decision-making statement. It is used to decide whether a

certain statement or block of statements will be executed or not .


• Flowchart of If Statement
Syntax of If Statement in Python

• # if syntax Python

if condition:
# Statements to execute if
# condition is true
EXAMPLE
• # python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output-
I am Not in if
Python If Else Statement

• The if statement alone tells us that if a


condition is true it will execute a block of
statements and if the condition is false it
won’t. But if we want to do something else if
the condition is false, we can use the else
statement with the if statement Python to
execute a block of code when the Python if
condition is false.
Flowchart of If Else Statement
Syntax of If Else in Python

• if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
EXAMPLE
• # python program to illustrate else if in Python
statement
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
OUTPUT
i is greater than 15
I'm in else Block
I'm not in if and not in else Block
Python Nested If Statement

A nested if is an if statement that is the target of


another if statement. Nested if statements
mean an if statement inside another if
statement.
Flowchart of Python Nested if Statement
SYNTAX
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
EXAMPLE
• # python program to illustrate nested If statement
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
OUTPUT
i is smaller than 15
i is smaller than 12 too
Python Elif

• Here, a user can decide among multiple


options. The if statements are executed from
the top down.
Flowchart of Elif Statement in Python
Syntax
• if (condition):
statement
elif (condition):
statement
.
.
else:
statement
EXAMPLE
# Python program to illustrate if-elif-else ladder
i = 25
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
OUTPUT
i is not present
Ternary Statement | Short Hand If Else Statement

Whenever there is only a single statement to be


executed inside the if block then shorthand if
can be used. The statement can be put on the
same line as the if statement.
Example of Python If shorthand

• In the given example, we have a condition that


if the number is less than 15, then further code
will be executed.
if condition: statement
# Python program to illustrate short hand if
i = 10
if i < 15: print("i is less than 15")
OUTPUT:-
i is less than 15
Loops in Python

1)While
2) for
3)Continue
4) break
For loop
for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set,
or a string).
With the for loop we can execute a set of
statements, once for each item in a list, tuple,
set etc.
EXAMPLE
• Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
OUTPUT:-
apple
banana
cherry
While loop
In Python, a while loop is used to execute a
block of statements repeatedly until a given
condition is satisfied. When the condition
becomes false, the line immediately after the
loop in the program is executed.
• Python While Loop Syntax:
while expression:
statement(s)
EXAMPLE
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
OUTPUT:-
Hello Geek
Hello Geek
Hello Geek
The continue Statement

With the continue statement we can stop the


current iteration of the loop, and continue
with the next:
EXAMPLE
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
OUTPUT:-
apple
cherry
EXAMPLE
for letter in 'Python': # First Example
if letter == 'h':
continue
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print ("Good bye!")
OUTPUT
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Good bye!
The break Statement

With the break statement we can stop the loop


before it has looped through all the items:
EXAMPLE
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
OUTPUT:-
apple
banana
EXAMPLE
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!")
OUTPUT
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
The Pass Statement

• The pass statement in Python is used when a


statement is required syntactically but you do
not want any command or code to execute.
• The pass statement is a null operation;
nothing happens when it executes.
EXAMPLE
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block') \
print ('Current Letter :', letter)
print ("Good bye!")
OUTPUT
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
For loop using ranges, string, list
and dictionaries
1. Python for Loop with List

Python program to iterate over a list of items


using for loop. This program prints all the
names stored in the list.
EXAMPLE
names = ["alex", "brian", "charles"]
for x in names:
print('Current name is :', x)

OUTPUT:-
Current name is : alex
Current name is : brian
Current name is : charles
2. Python for Loop with Tuple

Python program to iterate over a tuple of items


using for loop. This program prints all the
names stored in the list.
EXAMPLE
mytuple = ("item1", "item1", "item3")
for e in mytuple:
print("Current item is", e)

OUTPUT:-
Current item is item1
Current item is item1
Current item is item3
3. Python for Loop with Dictionary

A dictionary is a collection data type and we


can iterate over its key-value pairs as follows:
EXAMPLE
colors_dict = {'color': 'blue', 'fruit': 'apple', 'pet':
'dog'}
for key in colors_dict.keys():
print(key)
for item in colors_dict.items():
print(item)
OUTPUT
Color
fruit
pet
('color', 'blue')
('fruit', 'apple')
('pet', 'dog')
Python for Loop with range()

In Python, the for loop can be used with


range() function as well. The range() generates
a sequence of values starting with 0 by
default. For example, range(10) will generate
numbers from 0 to 9 (10 numbers).
EXAMPLE
for i in range(5):
print(i)

OUTPUT:-
0
1
2
3
4
Comprehensions on List, Tuple,
Dictionaries
Python List Comprehension

We can define a list comprehension by


wrapping a suitable expression with square
brackets. Let's convert the members of a list to
upper-case if they contain the letter 'o' with
the following example:
Python Tuple Comprehension

The tuple is a sequence data type so there is no


problem for it to be the source for a
comprehension. Tuple elements cannot
change, but there is no problem to get our
result out of a tuple:
Python Dictionary Comprehension

You can take advantage of a dictionary


comprehension by following the same
expression guidelines as before but wrapping
them in curly brackets. Let us define a
dictionary and extract its keys in a list:
EXAMPLES
• Python Program to Print Hello world!
• Python Program to Add Two Numbers
• Python Program to Find the Square Root
• Python Program to Calculate the Area of a Triangle
• Python Program to Solve Quadratic Equation
• Python Program to Swap Two Variables
• Python Program to Generate a Random Number
• Python Program to Convert Kilometers to Miles
• Python Program to Convert Celsius To Fahrenheit
• Python Program to Check if a Number is Positive, Negative or 0
• Python Program to Check if a Number is Odd or Even
• Python Program to Check Leap Year
• Python Program to Find the Largest Among Three Numbers
• Python Program to Check Prime Number
• Python Program to Print all Prime Numbers in an Interval
• Python Program to Find the Factorial of a Number
• Python Program to Display the multiplication Table
• Python Program to Print the Fibonacci sequence
Python Program to Print Hello world!

# This program prints Hello, world!


print('Hello, world!')
Python Program to Add Two Numbers

• This program adds two numbers


num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Output
• The sum of 1.5 and 6.3 is 7.8
Python Program to Find the Square Root

# Python Program to calculate the square root


num = 8
# To take the input from the user
num1 = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%
(num ,num_sqrt))
Output:-

The square root of 8.000 is 2.828


Python Program to Swap Two Variables

# Python program to swap two variables


x=5
y = 10
# To take inputs from the user
x = input('Enter value of x: ')
y = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = x
x=y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Python Program to Find the Largest Among Three Numbers

num1 = 10
num2 = 14
num3 = 12
take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
o/p- The largest number is 14

You might also like