Python Unit 1
Python Unit 1
• Introduction
• Python Fundamentals
• Features of Python
• Python Basics
INTRODUCTION
• It was created in the late 1980s by Guido van Rossum and was first released
in 1991.
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)
• 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:
“#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.’)
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 the PyCharm Community Edition using the default settings. Select the update
path variable and create a shortcut while installation.
• 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.
“number” and “name” are the identifiers given to the variables. These hold the
values 7 and “Python” respectively.
Rules for Naming Identifiers in Python
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
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
• 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 [ ]
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)
String is a sequence of characters represented by either single or double quotes. For example,
name = 'Python'
print(name)
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,
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
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.
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
%= Remainder Assignment a %= 10 # a = a % 10
print('Sum: ', a)
# Output: 15
a=5
b=2
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)
• 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
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.
• A code is written to allow making choices and several pathways through the
program to be followed depending on shifts in variable values.
Conditions, loops, and calling functions significantly influence how a Python program is
controlled.
• 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 <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
• 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)
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
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
There are generally two loop statements to implement the repetition structure:
• 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:
• 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)
To convert user input into a number we can use int() or float() functions as:
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')
Here, the print() function displays the string enclosed inside the single quotation.
Syntax of print():
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.
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!
• 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
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))