0% found this document useful (0 votes)
1 views91 pages

Python Unit 1

The document provides an introduction to Python programming, covering its history, capabilities, and syntax. It explains Python's versatility for web development, software development, and data handling, and highlights its readability and ease of use. Additionally, it discusses variables, data types, user input, and basic programming concepts such as indentation and comments.

Uploaded by

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

Python Unit 1

The document provides an introduction to Python programming, covering its history, capabilities, and syntax. It explains Python's versatility for web development, software development, and data handling, and highlights its readability and ease of use. Additionally, it discusses variables, data types, user input, and basic programming concepts such as indentation and comments.

Uploaded by

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

PYTHON

PROGRAMMING
UNIT I
INTRODUCTION TO PYTHON
04-08-2023

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.
04-08-2023

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.
04-08-2023

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 SYNTAX COMPARED TO 04-08-2023

OTHER PROGRAMMING LANGUAGES

• Python was designed for readability, and has some similarities to the
English language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as
the scope of loops, functions and classes. Other programming languages
often use curly-brackets for this purpose.
04-08-2023

• Python is an interpreted programming language.


• Python source code is compiled to bytecode as a .pyc file, and this
bytecode can be interpreted.
• There are two modes for using the Python interpreter:

• Interactive Mode
• Script Mode
04-08-2023

INTERACTIVE MODE
• Without passing the python script file to the interpreter, directly
execute code to Python prompt.
04-08-2023

SCRIPT MODE

• You can store Python script source code in a file with the .py extension,
and use the interpreter to execute the contents of the file.
• If you have a script name MyFile.py and you're working on Unix, to run the
script you have to type:
• python MyFile.py
• Working with the interactive mode is better if you deal with small pieces
of code
• If the code is more than 2-4 lines, using the script for coding can help to
modify and use the code in future.
04-08-2023

FIRST PYTHON PROGRAM

print("Hello, World!")

Exercise 1 : Write a python program to print your Address/ biodata.


04-08-2023

The Python Command Line


Python can be run as a command line itself.

C:\Users\Your Name>python

To start python.

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>> print("Hello, World!")
Which will write "Hello, World!" in the command
line:
04-08-2023

Whenever you are done in the python command line, you


can simply type the following to quit the python command
line interface:

exit()
FEW ALGORITHMS 04-08-2023

Find the difference between 2


Find the Sum of 2 numbers
numbers

Find the greatest number Accept a number from the


among the 2 numbers user and print if it is positive,
negative or zero
PYTHON INDENTATION 04-08-2023

• Indentation refers to the spaces at the beginning of a code line.


• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
• if 5 > 2:
print("Five is greater than two!")
• The number of spaces is up to you as a programmer, but it has to be at least
one.
• You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error.
04-08-2023

PYTHON COMMENTS

• Comments can be used to explain Python code.


• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.

Creating a Comment
• Comments starts with a #, and Python will ignore them:
• #This is a comment
print("Hello, World!")
04-08-2023

MULTI LINE COMMENTS

• Or, not quite as intended, you can


• Python does not really have a use a multiline string.
syntax for multi line
• Since Python will ignore string
comments. literals that are not assigned to a
variable, you can add a multiline
• To add a multiline comment
string (triple quotes) in your code,
you could insert a # for each and place your comment inside it:
line:
"""
#This is a comment This is a comment
#written in written in
more than just one line
#more than just one line """
print("Hello, World!") print("Hello, World!")
VALUES AND TYPES
04-08-2023

• A value is one of the most basic things in any program works with.
• A value may be characters i.e. ‘Hello, World!’ or a number like 1,2.2 ,3.5
etc.
• Values belong to different types:
• 1 is an integer
• 2.2 is a float
• “Hello, World!” is a string
• etc.
VARIABLES
04-08-2023

• A variable is nothing but a name that refers to a value.


• Variables are created when the moment you first assign a value to it.
• An assignment statement creates new variables and gives them values.
• Python has no command for declaring a variable.
Example
Example
x=5
y = "John"
x=5
print(x) //5
y = "Hello,
print(y)
World!"
//John
04-08-2023

VARIABLES
• The type of a variable means the type of the value it refers to.
• Variables do not need to be declared with any particular type, and can even
change type after they have been set.
x=4 # x is of
type int
x = "Sally" # x is now of
type str
print(x)
• You can do assignments on more than one variable “simultaneously” on the
same line
a, b, c = "Make", "Me", "Analyst"
04-08-2023

Casting

If you want to specify the data type of a variable, this can be done
with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
04-08-2023

Get the Type

You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Identifiers
Identifiers are names used to identify variables, functions, classes, modules, and
other objects.
An identifier must start with a letter (A-Z or a-z) or an underscore (_), followed by any
number of letters, digits (0-9), or underscores.
Examples of valid identifiers:
variable1
_my_variable
ClassName
Examples of invalid identifiers:
1variable # starts with a digit
my-variable # contains a hyphen
class # is a reserved keyword
04-08-2023

Single or Double Case-Sensitive


Quotes? Variable names are case-sensitive.

String variables can be Example:


declared either by using This will create two variables:
single or double quotes:
a=4
Example: A = "Sally“
x = "John" print(a) # 4
# is the same as print(A) #sally
x = 'John' #A will not overwrite a
Variable Names 04-08-2023

A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for Python variables:
1. A variable name must start with a letter or the underscore character
2. A variable name cannot start with a number
3. A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
4. Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
Legal variable names: Illegal variable names:
myvar = "John" 2myvar = "John"
my_var = "John" my-var = "John"
_my_var = "John" my var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
04-08-2023

MULTI WORDS VARIABLE NAMES


• Variable names with more than one word can be difficult to read.
• There are several techniques you can use to make them more
readable:
• Camel Case
• Each word, except the first, starts with a capital letter:

myVariableName = "John“
• Pascal Case
• Each word starts with a capital letter:

MyVariableName = "John“
04-08-2023

MULTI WORDS VARIABLE NAMES

Snake Case
• Each word is separated by an underscore character:
• my_variable_name = "John"
04-08-2023

PYTHON VARIABLES - ASSIGN MULTIPLE


VALUES
• Many Values to Multiple Variables
• Python allows you to assign values to multiple variables in one line:
• Example
• x, y, z,= "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
• Note: Make sure the number of variables matches the number of
values, or else you will get an error.
04-08-2023

ONE VALUE TO MULTIPLE VARIABLES

• And you can assign the same value to multiple variables in one line:
• Example
• x = y = z = "Orange"
print(x)
print(y)
print(z)
04-08-2023

UNPACK A COLLECTION

• If you have a collection of values in a list, tuple etc. Python allows you
to extract the values into variables. This is called unpacking.
• Example
• Unpack a list:
• fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
04-08-2023

TUPLE ASSIGNMENT

• Tuple assignment is a quite useful and special feature

• The unpacking or tuple assignment is the process that assigns the values on the
right-hand side to the left-hand side variables.
• The process of assigning values to a tuple is known as packing.

• Number of variables on the left-hand side and the number of elements in the tuple
should be equal
• In unpacking, we basically extract the values of the tuple into a single variable.

• Example:

number = (1, 2, 3)
x, y, z = number or x, y, z = (1,2,3)
print(x, y, z)
04-08-2023

PYTHON - OUTPUT VARIABLES

• Output Variables
• The Python print statement is often used to output variables.
• To combine both text and a variable, Python uses the + character:
Example Example
Example x = "Python is " x=5
y = "awesome" y = "John"
• x = "awesome" print(x + y)
z= x+y
print("Python is " + x) print(z)
04-08-2023

PYTHON NUMBERS

• There are three numeric types in Python:

Int ,float, complex


• Variables of numeric types are created when you assign a value to them:

• x = 1 # int
y = 2.8 # float
z = 1+1j # complex
• To verify the type of any object in Python, use the type() function:

• print(type(x)) #int
print(type(y)) #float
print(type(z)) #complex
04-08-2023

PYTHON DATA TYPES

• In programming, data type is an important concept.


• Variables can store data of different types, and different types can do different
things.
• Python has the following data types built-in by default, in these categories:
• Text Type: str
• Numeric Types: int, float, complex
• Sequence Types:list, tuple, range
• Mapping Type:dict
• Set Types:set, frozenset
• Boolean Type:bool
• Binary Types: bytes, bytearray, memoryview
PYTHON DATA TYPES 04-08-2023
04-08-2023

PYTHON CODE: STR DATA TYPE

• x = "apple"
• #display x:
• print(x)
• #display the data type of x:
• print(type(x))
04-08-2023

TYPE CONVERSION
• You can convert from one type to another with the int(), float(),
and complex() methods:
x=1 # int
#convert from int to float:
a = float(x)
print(x)
print(type(x))
• Note: You cannot convert complex numbers into another number type.
04-08-2023

STATEMENTS
• Statements are instructions or piece of codes that Python interpreter can
execute.
• End of a statement is marked by a newline character.
• Example: print satement, assignment statement, etc.
• Multi-line statement - In Python, end of a statement is marked by a newline
character. But, can write a statement with multiple lines using character (\) or
st = "I " + "am" + " st = ("I " + "am" + "
using ( ) or [ ] or { }. Mr." +
Mr." + \
" X."+" I live in " \ " X."+" I live in " I am Mr. X. I live
"city Y.") in city Y.
"city Y."
print(st)
print(st)
04-08-2023

TAKING USER INPUT IN PYTHON

• While Python provides us with two inbuilt functions to read the input
from the keyboard.

• input ( prompt )
• input ( ) : This function first takes the input from the user and then
evaluates the expression, which means Python automatically identifies
whether user entered a string or a number or list. If the input provided
is not correct then either syntax error or exception is raised by python.
For example –
04-08-2023

TAKING USER INPUT IN PYTHON

• # Python program showing a use of input()

• val = input("Enter your value: ")


• print(val)
04-08-2023

HOW THE INPUT FUNCTION WORKS IN


PYTHON
• When input() function executes program flow will be stopped until the
user has given an input.
• The text or message display on the output screen to ask a user to
enter input value is optional i.e. the prompt, will be printed on the
screen is optional.
• Whatever you enter as input, input function convert it into a string. if
you enter an integer value still input() function convert it into a string.
You need to explicitly convert it into an integer in your code using
typecasting.
04-08-2023

# PROGRAM TO CHECK INPUT TYPE IN


PYTHON

num = input ("Enter number :")


print(num)
name1 = input("Enter name : ")
print(name1)
# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))
04-08-2023

TYPECASTING
• Typecasting the input to Integer: There might be conditions when you
might require integer input from user/Console, the following code takes two
input(integer/float) from console and typecasts them to integer then prints
the sum.
• # input
• num1 = int(input())
• num2 = int(input())
• # printing the sum in integer
• print(num1 + num2)
04-08-2023

KEYWORDS
• Python reserves 33 keywords in 3.3 versions for its use.
• keywords are reserved words that have special meaning and are used to define
the syntax and structure of the language.
• Keywords are case sensitive in python.
• You can’t use a keyword as variable name, function name or any other identifier
name.
04-08-2023

EXERCISE

• Write a python program to add two numbers


• Write a python program to compute area of triangle
• Write a python program to find square root of a number
04-08-2023

# PYTHON PROGRAM TO CALCULATE THE


SQUARE ROOT

• # Note: change this value for a different result


• num = 8
• num_sqrt = num ** 0.5
• print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
04-08-2023

PYTHON PROGRAM TO COMPUTE AREA


AND CIRCUMFERENCE OF A CIRCLE
04-08-2023

EXERCISE
• Write a python program to Convert kilometers to miles
• Write a python program to to swap two numbers
• Write a python program to convert temperature from Faranheit to
Celcius
• Write a python program to study the data types
• Write a program to perform type conversions
OPERATORS
1. What are operators in python?
• Operators are special symbols in Python that carry out arithmetic or
logical computation. The value that the operator operates on is called
the operand.
• For example:

>>> 2+3
5

04-08-2023

48
ARITHMETIC OPERATORS

• Arithmetic operators are used to perform mathematical operations like


addition, subtraction, multiplication, etc.

04-08-2023

49
04-08-2023

50
COMPARISON/RELATIONAL OPERATORS

• Comparison operators are used to compare values. It returns


either True or False according to the condition.

04-08-2023

51
04-08-2023

52
LOGICAL OPERATORS

04-08-2023

53
04-08-2023

54
BITWISE OPERATORS

• Bitwise operators act on operands as if they were strings of binary digits. They
operate bit by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.
• In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000
0100 in binary)

04-08-2023

55
ASSIGNMENT OPERATORS

• Assignment operators are used in Python to assign values to variables.


• a = 5 is a simple assignment operator that assigns the value 5 on the
right to the variable a on the left.
• There are various compound operators in Python like a += 5 that adds
to the variable and later assigns the same. It is equivalent to a = a +
5.

04-08-2023

56
ASSIGNMENT OPERATORS

04-08-2023

57
INCREMENT AND DECREMENT
OPERATORS
• Python does not allow using the “(++ and –)” operators. To increment
or decrement a variable in python we can simply reassign it. So,
the “++” and “–” symbols do not exist in Python.

• In python, if you want to increment a variable we can use “+=” or


we can simply reassign it “x=x+1” to increment a variable value by 1.

• x = 20

• x = x+1

• print(x)
To decrement a variable in python we can use “-=” or “x=x-
1” operators in python to reduce the value of a variable by 1.
04-08-2023

58
TERNARY OPERATOR
• Ternary operators are also known as conditional expressions

• are operators that evaluate something based on a condition being true or false
It simply allows testing a condition in a single line replacing the multiline if-else
making the code compact.

• Syntax :

• [on_true] if [expression] else [on_false]


# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
04-08-2023

print(min)
59
04-08-2023

ORDER OF OPERATIONS

• If more than one operator appears in an expression, the order of evaluation


depends on the rules of precedence.
• For mathematical operators, Python follows mathematical convention.
• The acronym PEMDAS is a useful way to remember the rules:
• Parentheses have the highest precedence.
• Exponentiation has the next highest precedence
• Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence.
04-08-2023

ORDER OF OPERATIONS

• Operators with the same precedence are evaluated from left to right.
• When you have doubt, always put parentheses in your expressions to make sure
the computations are performed in the order you intend.
04-08-2023
04-08-2023
EXERCISE

• Python Program to study different types of operators

04-08-2023

64
PYTHON - FUNCTIONS

A function is a block of organized, reusable code that is used to perform a single,


related action.
• It Provides better modularity for your application and a high degree of code
reusing.
•It runs / executes only when it is called.
•You can pass data, known as parameters, into a function.
•A function can return data as a result.
USER-DEFINED FUNCTIONS 04-08-2023

• Functions that we define ourselves to do certain specific task are referred as user-
defined functions.
• example Hello.py file , we created our own function to perform certain operation.
• Advantages of user-defined functions

✔ User-defined functions help to decompose a large program into small


segments which makes program easy to understand, maintain and debug.
✔ If repeated code occurs in a program. Function can be used to include those
codes and execute when needed by calling that function.
EXAMPLE

def my_function():
print("Hello from a function")

my_function()
04-08-2023

BUILT-IN FUNCTIONS

• Python has several functions that are readily available for use. These functions
are called built-in functions.
• Example - abs(),delattr(),hash(),memoryview(),set(), etc ...
04-08-2023

LAMBDA FUNCTIONS
• They are called as anonymous function that are defined without a name.
• While normal functions are defined using the def keyword in Python, anonymous
functions are defined using the lambda keyword.
• Use of Lambda Function in python —

• To require a nameless function for a short period of time.


• Generally use it as an argument to a higher-order function (a function that
takes in other functions as arguments).
• Lambda functions are used along with built-in functions like filter(), map() etc.
LAMBDA FUNCTIONS EXAMPLES 04-08-2023

• filter() — Used to filter the iterables as per the conditions. It filters the original
iterable & passes the items that returns True for the function provided to filter.
• map() — Executes all the conditions of a function on the items in the iterable
and allows you to apply a function on it and then passes it to the output which
can have same as well as different values .
04-08-2023

RECURSIVE FUNCTION
• A recursive function is a function defined in terms of itself via self-
referential expressions.
• The function will continue to call itself and repeat its behavior until
some condition is met to return a result
• Syntax
04-08-2023

RECURSIVE FUNCTION - EXAMPLE


04-08-2023

USER DEFINED FUNCTIONS IN DETAILS


RULES TO DEFINE A FUNCTION IN PYTHON.

• Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).

• Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.

• The first statement of a function can be an optional statement - the documentation


string of the function or docstring.

• The code block within every function starts with a colon (:) and is indented.

• The statement return [expression] exits a function, optionally passing back an


expression to the caller. A return statement with no arguments is the same as return
None.
SYNTAX

def functionname( parameters ): "function_docstring"


function_suite
return [expression]
CALLING A FUNCTION
After creating a function we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.

# A simple Python function

def fun():
print(“Welcome to Python")

# Driver code to call a function


fun()
04-08-2023

FLOW OF EXECUTION
• The order in which statements are executed is called the flow of execution
• Execution always begins at the first statement of the program.
• Statements are executed one at a time, in order, from top to bottom.
• Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the
function is called.
• Function calls are like a bypass in the flow of execution. Instead of going
to the next statement, the flow jumps to the first line of the called
function, executes all the statements there, and then comes back to pick
up where it left off.
FLOW OF EXECUTION 04-08-2023

Note:

• When you read a program, don‟t read from top to bottom. Instead, follow
the flow of execution.

• This means that you will read the def statements as you are scanning
from top to bottom, but you should skip the statements of the function
definition until you reach a point where that function is called.
ARGUMENTS OF A FUNCTION

• Arguments are the values passed inside the parenthesis of the function.
• A function can have any number of arguments separated by a comma.
• By default, a function must be called with the correct number of arguments.
If your function expects 2 arguments, you have to call the function
with 2 arguments, not more, and not less.
04-08-2023

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good
morning!")

greet('Paul')
Hello, Paul. Good morning!
PROGRAM

# A simple Python function to check


# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

Output:
even
odd
TYPES OF ARGUMENTS
• A default argument is a parameter that assumes a default value
if a value is not provided in the function call for that argument.
# Python program to demonstrate
def myFun(x, y=50):
# default arguments print("x: ", x)
def my_function(country = "Norway"): print("y: ", y)
print("I am from " + country)
# Driver code (We call myFun() with
only
my_function("Sweden")
# argument)
my_function("India")
my_function() myFun(10)
my_function("Brazil")
Output:
('x: ', 10)
('y: ', 50)
KEYWORD ARGUMENTS

The idea is to allow the caller to specify the argument name with values so that caller
does not need to remember the order of parameters.

def my_function(child3, child2, child1):


print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linux")


ARBITRARY ARGUMENTS, *ARGS
• If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the items accordingly:

def my_function(*kid):
print("His last name is " + kid[0])

my_function("Tobias","Refsnes")

04-08-2023

89
PASSING A LIST AS AN ARGUMENT
• You can send any data types of argument to a function (string, number,
list, dictionary etc.), and it will be treated as the same data type inside the
function.

def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

04-08-2023

90
RETURN VALUES

• To let a function return a value, use the return statement:

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

04-08-2023

91
THE RETURN STATEMENT
• The function return statement is used to exit from a function and go back to the function caller and
return the specified value or data item to the caller.
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

Output:
4
16
THE PASS STATEMENT
• function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to
avoid getting an error.

def myfunction():
pass

04-08-2023

93
EXERCISE

1. Write a Python function to find the Max of three numbers.


2. Write a Python function to calculate the factorial of a number.
3. Write a Python function that takes a number as a parameter and check
the number is prime or not.
4. Write a Python function to check whether a number is palindrome or
not.

04-08-2023

94
END OF UNIT I
THANK YOU

04-08-2023

95

You might also like