0% found this document useful (0 votes)
9 views

Python Unit 1

Uploaded by

netflixbasic500
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python Unit 1

Uploaded by

netflixbasic500
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Unit 1

Prof. Kuljeet Singh


Contents

• Introduction

• Python Fundamentals

• Features of Python

• Components of a Python Program

• Understanding the Interpreter

• Python Basics
INTRODUCTION

• Python is a high-level, interpreted programming language widely used for


various purposes such as web development, scientific computing, data
analysis, artificial intelligence, and more.

• It was created in the late 1980s by Guido van Rossum and was first released
in 1991.

• Python is a general-purpose scripting language that is often applied in


scripting roles.

• Python is a programming language as well as a scripting language. Python is


also called as Interpreted language.
DIFFERENCE BETWEEN PROGRAM AND SCRIPTING
LANGUAGE

Program Scripting
Program is executed (i.e. the source is Scripting is interpreted. A "script" is code
first compiled, and the result of that written in a scripting language.
compilation is expected)

A "program" in general, is a sequence of A scripting language is nothing but a type


instructions written so that a computer of programming language in which we can
can perform certain task. write code to control another software
application.
PYTHON PROGRAMMING
• Python is an easy-to-learn programming language for beginners, and the
codes written by Python are quite easy to read when compared to other
programming languages.
• It requires less time, effort, and lines of code to perform the same
operations.
• Portable and extensible since python is portable, so it is supported by all
the platforms of the industries like Windows, Linux, Macintosh as well as
play stations support python.
• It supports computer graphics so it is used for desktop applications
specially Game Development.
• It is free and open source.
WHY PYTHON PROGRAMMING?
• According to IEEE Spectrum the top programming languages are:
• The most popular coding languages are:
WHY DO PEOPLE USE PYTHON PROGRAMMING?
The following primary factors cited by Python users seem to be these:

• Python is object-oriented
• Structure supports such concepts as polymorphism, operation overloading, and
multiple inheritance.
• Indentation
• Indentation is one of the greatest future in Python.
• It's free (open source)
• Downloading and installing Python is free and easy Source code is easily
accessible
• It's powerful
• Dynamic typing
• Built-in types and tools
• Library utilities
• Third party utilities (e.g. Numeric, NumPy, SciPy)
• Automatic memory management
WHY DO PEOPLE USE PYTHON PROGRAMMING?
• It's portable
• Python runs virtually every major platform used today
• As long as you have a compatible Python interpreter installed, Python programs
will run in exactly the same manner, irrespective of platform.
• It's mixable
• Python can be linked to components written in other languages easily
• Linking to fast, compiled code is useful to computationally intensive problems
• Python/C integration is quite common
• It's easy to use
• No intermediate compile and link steps as in C/C++
• Python programs are compiled automatically to an intermediate form called
bytecode, which the interpreter then reads
• This gives Python the development speed of an interpreter without the performance
loss inherent in purely interpreted languages
• It's easy to learn
• Structure and syntax are pretty intuitive and easy to grasp
FEATURES OF PYTHON
• Easy to Learn: Python has a simple syntax and is relatively easy to learn, making it a
great language for beginners.
• High-Level Language: Python is a high-level language, meaning it abstracts away
many low-level details, allowing developers to focus on the logic of the program
without worrying about memory management and other details.
• Interpreted Language: Python code is interpreted rather than compiled, making it easy
to write and test code quickly.
• Object-Oriented: Python is an object-oriented language, which means it organizes code
into objects that contain data and functions that operate on that data.
• Indentation: Indentation is one of the greatest features in Python, making the code more
readable and easier to understand.
• Free and Open-Source: Python is free and open-source, making it easy to download
and install.
• Powerful: Python is a powerful language with dynamic typing, built-in types and tools,
library utilities, and third-party utilities.
COMPONENTS OF PYTHON PROGRAM
1. Expression: An Expression is a phrase of code that Python assesses to produce a value.
We build different expressions by getting sub expressions together with the operators and
delimiters.
For example:
>>> 1+1
2
Even though expressions contain values, variables, and operators, not every expression
contains all of these elements. A value all by itself is viewed as an expression, as is a
variable.

2. Statements: It is a logical unit of code that can be executed by the Python interpreter.

At the point when we type the statement at the command prompt, it will execute the
code in the statement and give the result, as long as the code is error-free.
COMPONENTS OF PYTHON PROGRAM
3. Comments: As programs get bigger and more complicated, they get harder to read.
Formal languages are thick, and it is frequently hard to take a look at a piece of code and
sort out what it is doing, or why.

For example:

Percentage = (minute * 100) / 60 #caution: integer division

“#caution: integer division” is the comment in the program. Everything from the # to the
end of the line is ignored; it has no impact on the program. The comment is intended for the
programmer or for future developers who may utilize this code.

4. Functions: Functions are a convenient strategy to separate your code into useful blocks,
permitting us to arrange our code, make it more readable, reuse it, and save some time. Also,
functions are a key way to characterize interfaces so programmers can share their code.
COMPONENTS OF PYTHON PROGRAM
5. One of the most distinctive features of Python is its utilization of indentation to mark
blocks of code. Consider the ‘if-statement’ from the simple password-checking program:

For example:

If pwd == ‘apple’:
print (‘Logging on…….’)
else:
print (‘Incorrect password.’)

print (‘All Done’)

The lines print (‘Logging on …’) and print (‘Incorrect password.’) are two different code
blocks.
SETTING UP PYTHON
• Download and install Python from the official website.

• Install an Integrated Development Environment (IDE) like PyCharm, VSCode, or use


Jupyter Notebook.

• Verify installation with a simple command: ‘python –version’.

• Download PyCharm Community Edition from


https://www.jetbrains.com/pycharm/download/?section=windows

• Install the PyCharm Community Edition using the default settings. Select the update
path variable and create a shortcut while installation.

• While creating the project Python will be downloaded automatically.


Your First Python Program

• Open your IDE or text editor.

• Write the code and run it using Shift+F10 or the Play like button at the top.
print("Hello Python World!")
What are Identifiers in Python?
• In Python Programming language, the naming words are called Identifiers.

• Identifiers are the tokens in Python that are used to name entities like
variables, functions, classes, etc.

• These are the user-defined names.

Example of identifiers in Python:


• number = 7
• name = “Python“

“number” and “name” are the identifiers given to the variables. These hold the
values 7 and “Python” respectively.
Rules for Naming Identifiers in Python

Example of getting error on starting


identifier with number:
• 1num=4

Output:
• SyntaxError: invalid syntax
Rules for Naming Identifiers in Python
Example of using keyword as identifier giving an error:
None=0

Output:
• SyntaxError: cannot assign to None

 It should only contain alpha-numeric characters and underscores (i.e., A-Z,


a-z 0-9, and _ ). Any other character is not valid. Even spaces are not
allowed.

 The length of the identifier can be as long as possible, unless it exceeds the
available memory. It is suggested to not keep more than 79 characters in a
line according to the PEP-8 rules.
Rules for Naming Identifiers in Python
To sum it up, identifier lexically

• Identifier => (letter | _) (letters | digit | _) #begins with letters or _ and


contains only letters, numbers and _
• Letter => lowercase | uppercase #letters can be either uppercase or lower case
• Lowercase => ‘a’ … ‘z’ # lowercase letters go from a to z
• Uppercase => ‘A’ ….’Z’ #uppercase letters go from A to Z
• Digit => ‘0’…’9’ #Digits include integers from 0 to 9
Rules for Naming Identifiers in Python
Based on the naming rules, the names are of two types. The first ones are legal
identifiers, those that follow the conventions for naming and the second type are
the illegal ones that don’t follow.
Built-in 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:

Data Types Classes Description


Numeric int, float, complex holds numeric values
String str holds sequence of characters
Sequence list, tuple, range holds collection of items
Mapping dict holds data in key-value pair form
Boolean bool holds either True or False
Set set, frozenset hold collection of unique items
Built-in Data Types
Python Numeric Data type

• num1 = 7
print(num1, 'is of type', type(num1))

• num2 = 7.0
print(num2, 'is of type', type(num2))

• num3 = 7+2j
print(num3, 'is of type', type(num3))

We have also used the type() function to know which class a certain variable
belongs to.
Built-in Data Types
Python List Data Type

List is an ordered collection of similar or different types of items separated by commas and
enclosed within brackets [ ]

languages = ["Swift", "Java", "Python"]


Here, we have created a list named languages with 3 string values inside it.

# access element at index 0


print(languages[0]) # Swift

# access element at index 2


print(languages[2]) # Python

we have used the index values to access items from the languages list.
Built-in Data Types
Python Tuple Data Type

Tuple is an ordered sequence of items same as a list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
In Python, we use the parentheses () to store items of a tuple. For example,

# create a tuple
product = ('Microsoft', 'Xbox', 499.99)

# access element at index 0


print(product[0]) # Microsoft

# access element at index 1


print(product[1]) # Xbox
Built-in Data Types
Python String Data Type

String is a sequence of characters represented by either single or double quotes. For example,

name = 'Python'
print(name)

message = 'Python for beginners'


print(message)

we have created string-type variables: name and message with values 'Python' and 'Python for
beginners' respectively.
Built-in Data Types
Python Set Data Type

Set is an unordered collection of unique items. Set is defined by values separated by commas
inside braces { }. For example,

# create a set named student_id


student_id = {112, 114, 116, 118, 115}

# display student_id elements


print(student_id)

# display type of student_id


print(type(student_id))

Here, we have created a set named student_id with 5 integer values. Since sets are unordered
collections, indexing has no meaning.
Built-in Data Types
Python Dictionary Data Type

Python dictionary is an ordered collection of items. It stores elements in key/value pairs.


Here, keys are unique identifiers that are associated with each value.

# create a dictionary named capital_city


capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

print(capital_city['Nepal']) # prints Kathmandu

print(capital_city['Kathmandu']) # throws error message

Since 'Nepal' is key, capital_city['Nepal'] accesses its respective value i.e. Kathmandu

However, 'Kathmandu' is the value for the 'Nepal' key, so capital_city['Kathmandu'] throws an
error message.
Python Operators
Operators are special symbols that perform operations on variables and values.
For example,

print(5 + 6) # 11
Here, + is an operator that adds two numbers: 5 and 6.

Types of Python Operators

1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
1. Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc. For example,
sub = 15 - 5 #10
Here, - is an arithmetic operator that subtracts two values or variables.
Operator Operation Example

+ Addition 5+2=7

- Subtraction 4-2=2

* Multiplication 2*3=6

/ Division 4/2=2

// Floor Division 10 // 3 = 3

% Modulo 5%2=1

** Power 4 ** 2 = 16
1. Python Arithmetic Operators
Example 1: Arithmetic Operators in Python

a=7
b=2 # division
print ('Division: ', a / b)
# addition
print ('Sum: ', a + b) # floor division
print ('Floor Division: ', a // b)
# subtraction
print ('Subtraction: ', a - b) # modulo
print ('Modulo: ', a % b)
# multiplication
print ('Multiplication: ', a * b) # a to the power b
print ('Power: ', a ** b)
2. Python Assignment Operators
Assignment operators are used to assign values to variables. For example,

# assign 5 to x
x=5
Here, = is an assignment operator that assigns 5 to x.
Operator Name Example

= Assignment Operator a=7

+= Addition Assignment a += 1 #a=a+1

-= Subtraction Assignment a -= 3 #a=a-3

*= Multiplication Assignment a *= 4 #a=a*4

/= Division Assignment a /= 3 #a=a/3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10


2. Python Assignment Operators
# assign 10 to a
a = 10
# assign 5 to b
b=5

# assign the sum of a and b to a


a += b # a = a + b

print('Sum: ', a)

# Output: 15

#Do it for all the assignment operators.


3. Python Comparison Operators
Comparison operators compare two values/variables and return a boolean
result: True or False. For example,
a=5
b=2
print (a > b) # True
Here, the > comparison operator is used to compare whether a is greater than b or not.
Operator Meaning Example

== Is Equal To 3 == 5 gives us False

!= Not Equal To 3 != 5 gives us True

> Greater Than 3 > 5 gives us False

< Less Than 3 < 5 gives us True

>= Greater Than or Equal To 3 >= 5 give us False

<= Less Than or Equal To 3 <= 5 gives us True


3. Python Comparison Operators
Example:

a=5
b=2

print('a = = b =', a = = b) # equal to operator


print('a != b =', a != b) # not equal to operator
print('a > b =', a > b) # greater than operator
print('a < b =', a < b) # less than operator
print('a >= b =', a >= b) # greater than or equal to operator
print('a <= b =', a <= b) # less than or equal to operator
4. Python Logical Operators
Logical operators are used to check whether an expression is True or False. They are used in
decision-making. For example,
a=5
b=6
print((a > 2) and (b >= 6)) # True
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is
True.
Operator Example Meaning

Logical AND:
and a and b
True only if both the operands are True

Logical OR:
or a or b
True if at least one of the operands is True

Logical NOT:
not not a True if the operand is False and vice-
versa.
5. Python 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)

Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)


Precedence and Associativity of Operators in Python
Precedence of Python Operators

• The combination of values, variables, operators, and function calls is termed as an


expression. The Python interpreter can evaluate a valid expression.
Example, 2 - 7 = -5
Here 2 - 7 is an expression. There can be more than one operator in an expression.

• To evaluate these types of expressions there is a rule of precedence in Python. It guides the
order in which these operations are carried out.
For example, multiplication has higher precedence than subtraction.
12 – 2 * 5 = 2

But we can change this order using parentheses () as it has higher precedence than
multiplication.
(12 – 2) * 5 = 50
Precedence and Associativity of Operators in Python
The operator precedence in Python is listed in the following table. It is in descending order
(upper group has higher precedence than the lower ones).
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR
Precedence and Associativity of Operators in Python
Associativity of Python Operators

• We can see in the precedence table that more than one operator exists in the same group.
These operators have the same precedence.

• When two operators have the same precedence, associativity helps to determine the order
of operations.

• Associativity is the order in which an expression is evaluated that has multiple operators of
the same precedence. Almost all the operators have left-to-right associativity.

For example, multiplication and floor division have the same precedence. Hence, if both of
them are present in an expression, the left one is evaluated first.

print(5 * 2 // 3) #3
print(5 * (2 // 3)) #0
Precedence and Associativity of Operators in Python

Operator Description Associativity


() Parentheses left to right
** Exponent right to left
*/% Multiplication / division / modulus left to right
+- Addition / subtraction left to right
<< >> Bitwise left shift / Bitwise right shift left to right
< <= Relational operators: less than / less than or equal left to right
> >= to / greater than / greater than or equal to
== != Relational operators: is equal to / is not equal to left to right
is, is not Identity operators left to right
in, not in Membership operators
Precedence and Associativity of Operators in Python

Operator Description Associativity


& Bitwise AND operator left to right
^ Bitwise exclusive OR operator left to right
| Bitwise inclusive OR operator left to right
not Logical NOT right to left
and Logical AND left to right
or Logical OR left to right
= Assignment operators: right to left
+= -= Addition / subtraction
*= /= Multiplication / division
%= &= Modulus / bitwise AND
^= |= Bitwise exclusive / inclusive OR
<<= >>= Bitwise shift left / right shift
Precedence and Associativity of Operators in Python

Non-associative operators

• Some operators like assignment operators and comparison operators do not have
associativity in Python. There are separate rules for sequences of this kind of operator and
cannot be expressed as associativity.

• For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is equivalent to
x < y and y < z, and is evaluated from left-to-right.

• Furthermore, while chaining of assignments like x = y = z = 1 is perfectly valid, x = y =


z+= 2 will result in error.
Control Structures in Python
• Most programs don't operate by carrying out a straightforward sequence of
statements.

• A code is written to allow making choices and several pathways through the
program to be followed depending on shifts in variable values.

• All programming languages contain a pre-included set of control structures


that enable these control flows to execute, which makes it conceivable.
Types of Control Structures
Control flow refers to the sequence a program will follow during its execution.

Conditions, loops, and calling functions significantly influence how a Python program is
controlled.

There are three types of control structures in Python:

• Sequential - The default working of a program


• Selection - This structure is used for making decisions by checking conditions and
branching
• Repetition - This structure is used for looping, i.e., repeatedly executing a certain piece of
a code block.
Types of Control Structures
Sequential:

• Sequential statements are a set of statements whose execution process happens in a


sequence. The problem with sequential statements is that if the logic has broken in any one
of the lines, then the complete source code execution will break.

Selection/Decision Control Statements:

• The statements used in selecting control structures are also referred to as branching
statements or, as their fundamental role is to make decisions, decision control statements.

• A program can test many conditions using these selection statements, and depending on
whether the given condition is true or not, it can execute different code blocks.
Selection/Decision Control Statements:
There can be many forms of decision control structures. Here are some most commonly used
control structures:

• if
• if-else
• nested if
• if-elif-else
Selection/Decision Control Statements:
1. Simple if

• If statements in Python are called control flow statements.


• The selection statements assist us in running a certain piece of code, but only in certain
circumstances.
• There is only one condition to test in a basic if statement.

The if statement's fundamental structure is as follows:


Syntax

if <conditional expression> :
The code block to be executed if the condition is True
Selection/Decision Control Statements:
• All the statements written indented after the if statement will run if the condition giver
after the if the keyword is True.

• Python uses these types of indentations to identify a code block of a particular control flow
statement.
# Initializing some variables
v=5 # Creating the second control structure
t=4 if v < t :
print("The initial value of v is", v, "and that of t print(v , "is smaller than ", t)
is ",t) v += 1

print("the new value of v is ", v)


# Creating a selection control structure
if v > t : # Creating the third control structure
print(v, "is bigger than ", t) if v == t:
v -= 2 print("The value of v, ", v, " and t,", t, ", are
equal")
print("The new value of v is", v, "and the t is ",t
Selection/Decision Control Statements:
2. if-else

• If the condition given in if is False, the if-else block will perform the code t=given in the
else block.
# Initializing two variables
v=4
t=5
print("The value of v is ", v, "and that of t is ", t)

# Checking the condition


if v > t :
print("v is greater than t")
# Giving the instructions to perform if the if condition is not tr
ue
else :
print("v is less than t")
Selection/Decision Control Statements:
3. Nested if

• if statements inside the if statements, this is called nested if statements.

x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Selection/Decision Control Statements:
4. if - elif - else

• For executing different blocks of code based on certain conditions.

if condition: age = 18
# code to execute if condition is true if age >= 18:
elif another_condition: print("You are an adult.")
# code to execute if the another_condition is true elif age < 18 and age > 0:
else: print("You are a minor.")
# code to execute if none of the above conditions are true else:
print("Invalid age.")
Repetition

• To repeat a certain set of statements, we use the repetition structure.

There are generally two loop statements to implement the repetition structure:

• The for loop


• The while loop
Repetition
For Loop

• We use a for loop to iterate over an iterable Python sequence. Examples of these data
structures are lists, strings, tuples, dictionaries, etc.
• Under the for loop code block, we write the commands we want to execute repeatedly for
each sequence item.
• 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)
Repetition
While Loop

• While loops are also used to execute a certain code block repeatedly, the difference is that
loops continue to work until a given precondition is satisfied.
• The expression is checked before each execution. Once the condition results in Boolean
False, the loop stops the iteration.

Example,

b=9 a=2
# The condition a < b will be checked before each iteration
while a < b:
print(a, end = " ")
a=a+1
print("While loop is completed")
Python Input
While programming, when we want to take the input from the user. In Python, we can use the
input() function.

Syntax of input():
input(prompt)

Here, prompt is the string we wish to display on the screen. It is optional.

Example: Python User Input


# using input() to take user input Output:

num = input('Enter a number: ') Enter a number: 7


print('You Entered:', num) You Entered: 7
print('Data type of num:', type(num)) Data type of num: <class 'str'>
Python Input
We have used the input() function to take input from the user and stored the user input in the
num variable.

It is important to note that the entered value 7 is a string, not a number.


So, type(num) returns <class 'str'>.

To convert user input into a number we can use int() or float() functions as:

num = int(input('Enter a number: '))

Here, the data type of the user input is converted from string to integer .
Python Output
In Python, we can simply use the print() function to print output. For example,

print('Python in CHRIST')

#Output: Python in CHRIST

Here, the print() function displays the string enclosed inside the single quotation.

Syntax of print():

In the above code, the print() function is taking a single parameter.

However, the actual syntax of the print function accepts 5 parameters

print(object= separator= end= file= flush=)


Python Output
• Here, in the statement print(object= separator= end= file= flush=)

• object - value(s) to be printed


• sep (optional) - allows us to separate multiple objects inside print().
• end (optional) - allows us to add specific values like new line "\n", tab "\t"
• file (optional) - where the values are printed. It's default value is sys.stdout (screen)
• flush (optional) - boolean specifying if the output is flushed or buffered. Default: False

Example 1: Python Print Statement


print('Good Morning!')
print('It is rainy today')

Output:
Good Morning!
It is rainy today
Python Output
• The print() statement only includes the object to be printed. Here, the value for end is not
used. Hence, it takes the default value '\n‘. So we get the output in two different lines.

Example 2: Python print() with end Parameter


# print with end whitespace
print('Good Morning!', end= ' ')
print('It is rainy today')

Output:
Good Morning! It is rainy today

• Notice that we have included the end= ' ' after the end of the first print() statement.
• Hence, we get the output in a single line separated by space.
Python Output
Example 3: Python print() with sep parameter
print(‘Hello Students', 2024, ‘Learn Python!', sep= '. ')

Output:
Hello Students. 2024. Learn Python!

The print() statement includes multiple items separated by a comma.


we have used the optional parameter sep= ". " inside the print() statement.

Hence, the output includes items separated by . not comma.

• We can use the print() function to print Python variables. For example,
number = 10.5 name = Python
print(5) print(number) print(name) #Print variables and literals
Python Output
Example 4: Print Concatenated Strings

We can join two strings together inside the print() statement. For example,
print(‘Python is’ + ‘Interesting’)

Output:
Python is Interesting

Here, the + operator joins two strings Python is and Interesting


the print() function prints the joined string
Python Output
Example 5: Output formatting

Sometimes, we can format our output to make it look attractive. This can be done by using
the str.format() method. For example,

x=5
y = 10
print(‘The value of x is {} and y is {}’.format(x,y))

Here, the curly braces {} are used as placeholders.


THANK YOU

You might also like