SIBMT-MCA-I SEM-I
UNIT 1
Fundamentals of Python Programming
1.1 Introduction
1.2 Keywords, Identifiers, Literals, Operators
1.3 Data Types- Number, Strings, Lists, Tuples, Dictionaries, Sets
1.4 Understanding Python blocks
1.5 Control flow- if, else, elif
1.6 Loops- while, for, continue, break
1.7 Loop manipulation using pass, continue, break and else
1.8 For loop using ranges, string, list and dictionaries
1.9 Programming using Python conditional and loops block
1.10 Comprehensions on List, Tuple, Dictionaries
1.Introduction
• Python is one of the top programming languages in the world, widely used in fields such as AI,
machine learning, data science, and web development.
• The simple and English-like syntax of Python makes it a go-to language for beginners who want to
get into coding quickly.Because Python is used in multiple fields, there is a high demand for Python
developers, with competitive base salaries.
• In the late 1980s, Guido van Rossum dreamed of developing Python. The first version of Python
0.9.0 was released in 1991. Since its release, Python started gaining popularity.
• According to reports, Python is now the most popular programming language among developers
because of its high demands in the tech realm.
• Python is a versatile, high-level programming language that is widely supported across all major
operating systems.
• To execute Python code, you need to have a Python interpreter installed on your system..Jupyter
Notebook is an open-source web application that allows you to create and share documents that
contain live code, equations, visualizations, and narrative text.
• Uses include data cleaning and transformation, numerical simulation, statistical modeling, data
visualization, machine learning, and much more.
Getting Started with Python
Installing Jupyter Notebook on Windows
• Jupyter Notebook can be installed by using either of the two ways described below:
• Using Anaconda:Install Python and Jupyter using the Anaconda Distribution, which includes
Python, the Jupyter Notebook, and other commonly used packages for scientific computing and data
science
• Using PIP:Install Jupyter using the PIP package manager used to install and manage software
packages/libraries written in Python.
Installing Jupyter Notebook using Anaconda
• Anaconda is an open-source software that contains Jupyter, spyder, etc that are used
for large data processing, data analytics, heavy scientific computing.
• Anaconda works for R and python programming language. Spyder(sub-application
of Anaconda) is used for python.
• Opencv for python will work in spyder. Package versions are managed by the package
management system called conda.
To install Jupyter using Anaconda, just go through the following instructions:
Step 1: First, Launch the Anaconda Navigator
Step 2: Click on the Install Jupyter Notebook Button
The installation process is begin to Start!
Loading Packages:
Finished Installation:
Step 3: Now, click on Launch button to Launch the Jupyter.
Our First Program
Working of the Program
In Python, anything inside print() is displayed on the screen.
There are two things to note about print():
• Everything we want to display on the screen is included inside the parentheses ().
• The text we want to print is placed within double quotes " ".We can also use single
quotes to print text on the screen.
What is Programming: -
Writing Code:
You write code in a programming language, like Python or Java.
Compilation or Interpretation: The code needs to be translated into machine language
(binary) that the computer can understand.
This is done in two main ways:
Compilation: A program called a compiler translates your entire code into machine
language all at once. For example, C++ uses a compiler.
Interpretation: An interpreter translates and executes your code line by line. Python uses
an interpreter.
Execution: Once the code is translated into binary, the computer’s processor can execute it,
performing the tasks you’ve programmed.
1.2 Keywords, Identifiers/ varaibles , Literals, Operators
variables
• A variable is a name given to a memory location in a program.
• Value can be change according to need.
name = “Python Programing"
age = 55
price = 25.99
Memory Allocation
IDENTIFIRES
• Identifiers are the name given to variables, classes, methods(functions), etc.
• For example,
language = 'Python'
Here, language is a variable (an identifier) which holds the value 'Python'.
We cannot use keywords as variable names as they are reserved names that are built-
in to Python.
For example,continue = 'Python'
The above code is wrong because we have used continue as a variable name.
Things to Remember:-
• Python is a case-sensitive language.
• This means, Variable and variable are not the same
• Always give the identifiers a name that makes sense. While c = 10 is a valid name,
writing count = 10 would make more sense, and it would be easier to figure out what it
represents when you look at your code after a long gap.
• Identifiers cannot be a keyword.
• Identifiers are case-sensitive.
• Whitespaces are not allowed.
RULES FOR Naming IDENTIFIRES
LITERALS
Python Literals can be defined as data that is given in a variable or constant.
Data types
In computer programming, data types specify the type of data that can be stored inside a
variable.
For example,
num = 24
Here, 24 (an integer) is assigned to the num variable. So the data type of num is of
the int class.
1 Integer- Positive ,negative ,
2 String - Word or any Sentence
3 Float - Decimal values
4 Boolean- True/False
5 None – No Value
Python Basic Data Types
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, frozen set hold collection of unique items
Since everything is an object in Python programming, data types are
actually classes and variables are instances(object) of these classes.
Keywords
• Keywords are the reserved words in Python.
• We cannot use a keyword as a variable name, function name or any other identifier.
• 36 Keywords available in python.
OPERATORS
• Operators are special symbols that perform operations on variables and values.
• An operator is symbol that performs a certain operation between operands.
Python Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
2. Python comparison Operators
3. Python Assignment Operators
4. Python Logical Operators
Type Conversion
Key Points to Remember
1. Type Conversion is the conversion of an object from one data type to another data type.
2. Implicit Type Conversion is automatically performed by the Python interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using
predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.
Comments in python
INPUT IN PYTHON
input( ) statement is used to accept values (using keyboard) from user.
Syntax:-
input( )#result for input( ) is always a str
Eg:-
input(“enter name :”)
int ( input(“ enter any num :” ) )#int we use type casting
float ( input( ) )#float
Practice question:
1. WAP to input side of a square & print its area.
2. Write a Program to input 2 numbers & print their sum.
3. WAP to input 2 floating point numbers & print their average.
4. WAP to input 2 int numbers, a and b.Print True if a is greater than or equal to b. If not print False.
5.Write a Python program to input the radius of a circle and print its area.
6.Write a Python program to input two numbers and print their sum.
7.Write a Python program to input a student's name and age, and then print a message like "Hello [Name],
you are [Age] years old."
8.Write a Python program to input the length and width of a rectangle and print its perimeter.
Data type –
1.String
String is a data type that stores a sequence of characters.Strings are immutable in
Python.Create String in 3 Different ways.
Examples:
"hello" + "world" = "helloworld"- Basic Operations:- Concatenation-
Length of string: len(str)
In the above example,
we have created string-type variables: name and message with values "Python" and "I love
Python" respectively.
Here, we have used double quotes to represent strings, but we can use single quotes too.
In the above example, anything inside the enclosing triple quotes is one multiline string.
In the above example, we have used the + operator to join two strings: greet and name.
Methods of Python String
List:
Note:
• Lists are similar to arrays (or dynamic arrays) in other programming languages. When
people refer to arrays in Python, they often mean lists, even though there is a numeric
array type in Python.
Access List Elements
SLICING:
Add Elements at the Specified Index
The insert() method adds an element at the specified index. For example,
Add Elements to a List From Other list
We use the extend() method to add elements to a list from other iterables. For example,
Note: We can also use the del statement to delete the entire list.
For example,
Python List Length
We can use the built-in len() function to find the number of elements in a list. For example,
Tuple:
Dictionary
Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages like C++,JAVA Uses braces{} to define block of code
• Python uses indentation to indicate a block of code.Generally 4 White Spaces are used for
indentation (1 tab)
• Python uses indentation to indicate the scope of code blocks such as functions, loops, conditionals,
classes, etc.
Indentation Looks Like:
CONDITIONAL STATEMENTS (IF-ELIF-ELSE)
• Decision making is the most important aspect of almost all the programming languages.
• As the name implies, decision making allows us to run a particular block of code for a particular
decision.
• Here, the decisions are made on the validity of the particular conditions.
• Condition checking is the backbone of decision making.
Python If-else statements
• Decision making is the most important aspect of almost all the programming languages.
• As the name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions.
• Condition checking is the backbone of decision making.
In python, decision making is performed by the following statement
IF STATEMENT:
Note : Indentation is Required, It has only one condition to check
The If_else Statement
The if else elif statement:-
Example :Weekly Calendar:
Question- Solve
WAP To Find out Absolute Value of an input number.
WAP that takes an integer input from the user and prints "Positive" if the number is greater than
zero.
WAP program that takes a number from the user and checks if it is a multiple of 5. If it is, print
"Multiple of 5
Ans:-
WAP to Calculate Absolute value
WAP To check check number is divisible by 5 or not
Solve the Following:-
1. WAP To Find entered number is even or odd.
2. WAP that takes a person's age as input and uses an if-else condition to check if the person is eligible to
vote.
3. WAP that takes a single character as input and checks whether it is uppercase or lowercase. Print
"Uppercase" if it's uppercase, otherwise print "Lowercase".4.
4. Write a Python program that takes a year as input and checks if it is a leap year. A leap year must be
divisible by 4 but not by 100, unless it is also divisible by 400. Use if-else to print "Leap year" or "Not a
leap year"
IF-ELIF-ELSE Question
1.WAP that takes the lengths of three sides of a triangle as input and uses if-elif-else to determine the type of
triangle:Equilateral: All sides are equal.Isosceles: Two sides are equal.Scalene: All sides are different.If the inputs
do not form a valid triangle, print "Invalid triangle".
2.WAP that takes a student's score (0-100) as input and assigns a grade based on the following rules:90 and above:
"A"80 to 89: "B"70 to 79: "C" 60 to 69: "D" Below 60: "F" If the score is out of range, print "Invalid score".
3.Write a Python program that takes the number of units of electricity consumed as input and calculates the bill
based on the following slab rates:First 100 units: ₹5 per unitNext 100 units (101-200): ₹6 per unitAbove 200 units:
₹7 per unit Use if-elif-else to compute the bill.
5.Write a Python program that takes a password as input and checks its strength:If the password is less than 8
characters long, print "Weak".If the password has both numbers and letters (any combination), print "Strong".If it
has only letters or only numbers, print "Moderate"
Loops:-
Slide 71
While Loop
Practice Question:-
Break & Continue:
Examples:
1. Print the first 10 natural numbers
Write a Python program using a while loop to print the first 10 natural numbers (1 to 10).
# Initialize the variable
x=1
# While loop to print the first 10 natural numbers
while x <= 10:
print(x)
x += 1 # Increment x by 1
Expected output:
10
2. Factorial of a number
Write a Python program using a while loop to calculate the factorial of a given number.
# Get input from the user
n = int(input("Enter a number: "))
factorial = 1
x=1
# While loop to calculate factorial
while x <= n:
factorial *= x # Multiply factorial by current value of x
x += 1 # Increment x by 1
print(f"The factorial of {n} is: {factorial}")
Example output for input 5:
The factorial of 5 is: 120
3. Sum of even numbers from 1 to 50
Write a Python program to find the sum of all even numbers from 1 to 50 using a while loop.
# Initialize variables
x=2
sum_even = 0
# While loop to add all even numbers from 1 to 50
while x <= 50:
sum_even += x # Add x to sum_even
x += 2 # Increment x by 2 (next even number)
print("The sum of even numbers from 1 to 50 is:", sum_even)
Expected output:
The sum of even numbers from 1 to 50 is: 650
4. Reverse a number
Write a Python program using a while loop to reverse the digits of an integer input by the user.
# Get input from the user
n = int(input("Enter a number: "))
reversed_num = 0
# While loop to reverse the number
while n > 0:
digit = n % 10 # Extract the last digit
reversed_num = reversed_num * 10 + digit # Add digit to reversed_num
n = n // 10 # Remove the last digit
print("Reversed number is:", reversed_num)
Example output for input 1234:
Reversed number is: 4321
5. Sum of digits of a number
Write a Python program using a while loop to calculate the sum of digits of a given number.
# Get input from the user
n = int(input("Enter a number: "))
sum_digits = 0
# While loop to calculate the sum of digits
while n > 0:
digit = n % 10 # Extract the last digit
sum_digits += digit # Add the digit to sum_digits
n = n // 10 # Remove the last digit
print("Sum of digits is:", sum_digits)
Example output for input 456:
Sum of digits is: 15
6. Check if a number is prime
Question:
Write a Python program using a while loop to check if a given number is prime.
# Get input from the user
n = int(input("Enter a number: "))
is_prime = True
x=2
# While loop to check for prime
while x <= n // 2:
if n % x == 0:
is_prime = False # Set is_prime to False if a factor is found
break
x += 1
if is_prime and n > 1:
print(f"{n} is a prime number")
else:
print(f"{n} is not a prime number")
Example output for input 7:
7 is a prime number
7. Find the greatest common divisor (GCD) of two numbers
Write a Python program using a while loop to find the GCD of two numbers entered by the user.
# Get input from the user
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
# While loop to calculate GCD
while b != 0:
a, b = b, a % b # Replace a by b, and b by the remainder
print("The GCD is:", a)
Example output for input 48 and 18:
The GCD is: 6
8. Find the smallest divisor of a number
Write a Python program using a while loop to find the smallest divisor of a given number other than 1.
# Get input from the user
n = int(input("Enter a number: "))
x=2
# While loop to find the smallest divisor
while n % x != 0:
x += 1
print("The smallest divisor is:", x)
Example output for input 35:
The smallest divisor is: 5
9. Find the power of a number
Write a Python program using a while loop to find the power of a number. The user should input the base and the
exponent.
# Get inputs from the user
base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = 1
x=0
# While loop to calculate the power
while x < exponent:
result *= base # Multiply result by the base
x += 1 # Increment the counter
print(f"{base} to the power of {exponent} is: {result}")
Example output for base 2 and exponent 3:
2 to the power of 3 is: 8
10. Count digits in a number
Question:
Write a Python program using a while loop to count the number of digits in an integer entered by the user
n = int(input("Enter a number: ")) .# Get input from the user
count = 0 # While loop to count the digits
while n > 0:
n = n // 10 # Remove the last digit
count += 1 # Increment the count
print("The number of digits is:", count) Example output for input 9876: The number of digits is: 4