Python Unit 1
Python Unit 1
PROGRAMMING
UNIT I
INTRODUCTION TO PYTHON
04-08-2023
WHAT IS PYTHON?
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
• 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
• 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
print("Hello, World!")
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
exit()
FEW ALGORITHMS 04-08-2023
PYTHON COMMENTS
Creating a Comment
• Comments starts with a #, and Python will ignore them:
• #This is a comment
print("Hello, World!")
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
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
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
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
myVariableName = "John“
• Pascal Case
• Each word starts with a capital letter:
MyVariableName = "John“
04-08-2023
Snake Case
• Each word is separated by an underscore character:
• my_variable_name = "John"
04-08-2023
• 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
• 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
• 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
• 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
• 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
• 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
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
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
04-08-2023
49
04-08-2023
50
COMPARISON/RELATIONAL OPERATORS
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
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.
• 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 :
print(min)
59
04-08-2023
ORDER OF OPERATIONS
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
04-08-2023
64
PYTHON - FUNCTIONS
• 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
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 —
• 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
• 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 code block within every function starts with a colon (:) and is indented.
def fun():
print(“Welcome to Python")
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
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(*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)
my_function(fruits)
04-08-2023
90
RETURN VALUES
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
04-08-2023
94
END OF UNIT I
THANK YOU
04-08-2023
95