Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
101 views

Python Notes by Risabh Mishra

Uploaded by

MD sahir ansari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Python Notes by Risabh Mishra

Uploaded by

MD sahir ansari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

PYTHON TUTORIAL FOR BEGINNERS

Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 01

Introduction to Python
• What is programming
• What is Python
• Popular programming languages
• Why Python
• Career with Python

What is Programming Language?

Programming is the process of creating sets of instructions that tell a computer


how to perform specific tasks. These instructions, known as code, are written in
programming languages that computer understand and executes to carry out
various operations, such as solving problems, analysing data, or controlling
device.
Popular programming languages: Python, C, C++, Java, Go, C#, etc.

What is Python?
Python is a high-level programming language known for its simplicity and
readability.
Just like we use Hindi language to communicate and express ourselves,
Python is a language for computers to understand our instructions & perform
tasks.
Note: Python was created by Guido van Rossum in 1991.

P y t h o n N o t e s b y R i s h a b h M i s h ra
Popular programming languages
As per statista survey, Python is the most popular programming language.

Why Python?
Python is one of the easiest programming languages to learn and known for its
versatility and user-friendly syntax, is a top choice among programmers.
Also, python is an open source (free) programming language and have extensive
libraries to make programming easy. Python has massive use across different
industries with excellent job opportunities.

Python is Dynamically Typed Example


In Python there is no declaration of a variable, just an assignment statement.
x=8 # here x is a integer

x = "Python by Rishabh Mishra" # here x is a string

print(type(x)) # you can check the type of x

Python - Easy to Read & Write


Ques1: Write a program to print “Hello World”

P y t h o n N o t e s b y R i s h a b h M i s h ra
Ques2: Write a program to print numbers from 1 to 10

In above examples we can see that Python is simple in writing & reading the code.

Careers with Python


Python is not only one of the most popular programming languages in the world,
but it also offers great career opportunities. The demand for Python developers is
growing every year.

Python Tutorial Playlist:


https://www.youtube.com/@RishabhMishraOfficial

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 02

Python Installation & Setup + Visual Studio Code Installation


• Python installation
• Visual Studio Code installation

Install Python
Step 1: Go to website: https://www.python.org/downloads/
Step 2: Click on “Download Python” button
(Download the latest version for Windows or macOS or Linux or other)
Step 3: Run Executable Installer
Step 4: Add Python to Path
Step 5: Verify Python Was Installed on Windows
Open the command prompt and run the following command:
python --version

Install Python IDE (code editor)


Step 1: Go to website: https://code.visualstudio.com/download
Step 2: Click on “Download” button
(Download the latest version for Windows or mac or Linux or other)
Step 3: Run Executable Installer
Step 4: Click “Add to Path”
Step 5: Finish & launch the app
Popular Python IDE: VS Code, PyCharm, Jupyter Notebook & more

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 03

First Python Program


• Print- Hello World!
• Python As a Calculator
• Running the Python code
• Python Execution Steps
• Interpreter v/s Compiler

First Python Program - Hello World


Printing "Hello World" as the first program in Python.
print is a keyword word that has special meaning for Python.
It means, "Display what’s inside the parentheses."
print("Hello World")

Instructor = "Rishabh Mishra"


print("Python by", Instructor, sep="-")

Python As a Calculator
Python can be used as a powerful calculator for performing a wide range of
arithmetic operations.
2+5 # add two numbers
print(10/5) # divide two numbers

# print sum of two numbers


a = 2
b = 5
print(a+b)

P y t h o n N o t e s b y R i s h a b h M i s h ra
Comments: Comments are used to annotate codes, and they are not
interpreted by Python. It starts with the hash character #
Comments are used as notes or short descriptions along with the code to increase
its readability.

Running the Python Code


• Create a new text file and inside it write – print(“Welcome to the Python
Course by Rishabh Mishra”)
• Save file with extension .py – firstcode.py
• Open command prompt on windows (or Terminal on MacOS)
• Enter the location where firstcode.py file is saved – cd downloads
• Finally run the file as – python firstcode.py

Python Execution Flow

P y t h o n N o t e s b y R i s h a b h M i s h ra
Python Code Execution Steps

1. Lexical Analysis: The interpreter breaks down the code into smaller parts
called tokens, identifying words, numbers, symbols, and punctuation.
2. Syntax Parsing: It checks the structure of the code to ensure it follows the
rules of Python syntax. If there are any errors, like missing parentheses or
incorrect indentation, it stops and shows a SyntaxError.
3. Bytecode Generation: Once the code is validated, the interpreter translates
it into a simpler set of instructions called bytecode. This bytecode is easier
for the computer to understand and execute.
4. Execution by PVM: The Python Virtual Machine (PVM) takes the bytecode
and runs it step by step. It follows the instructions and performs calculations,
assigns values to variables, and executes functions.
5. Error Handling and Output: If there are any errors during execution, like
trying to divide by zero or accessing a variable that doesn't exist, the
interpreter raises an exception. If the code runs without errors, it displays
any output, such as printed messages or returned values, to the user.

Python Syntax

The syntax of the Python programming language, is the set of rules that defines
how a Python program will be written and interpreted (by both the runtime system
& by human readers).
my_name = "Madhav"
my_name = Madhav
# Use quotes "" for strings in Python

P y t h o n N o t e s b y R i s h a b h M i s h ra
Interpreter vs Compiler

Interpreter Compiler
An interpreter translates and A compiler translates the entire code
executes a source code line by line into machine code before the
as the code runs. program runs.

Execution: Line by line. Execution: Entire program at once.

Speed: Faster execution because it


Speed: Slower execution because
translates the entire program at once.
it translates each line on the fly.
Debugging: Easier to debug as it Debugging: Harder to debug
stops at the first error encountered. because errors are reported after the
entire code is compiled
Examples: Python, Ruby,
Examples: C, C++, Java, and Go.
JavaScript, and PHP.

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 04

Variables in Python
• What is a Variable
• Variables - examples
• Variable Naming Rules

Variables in Python
A variable in Python is a symbolic name that is a reference or pointer to an
object.
In simple terms, variables are like containers that you can fill in with different
types of data values. Once a variable is assigned a value, you can use that
variable in place of the value.
We assign value to a variable using the assignment operator (=).
Syntax: variable_name = value
Example: greeting = "Hello World"
print(greeting)

Variable Examples
Python can be used as a powerful calculator for performing a wide range of
arithmetic operations.
PythonLevel = "Beginner" # pascal case
pythonLevel = "Beginner" # camel case
pythonlevel = "Beginner" # flat case
python_level = "Beginner" # Snake case

P y t h o n N o t e s b y R i s h a b h M i s h ra
x = 10
print(x+1) # add number to a variable

a, b, c = 1, 2, 3
print(a, b, c) # assign multiple variables

Variable Naming Rules


1. Must start with a letter or an underscore ( _ ).
2. Can contain letters, numbers, and underscores.
3. Case-sensitive (my_name and my_Name are different).
4. Cannot be a reserved keyword (like for, if, while, etc.).

_my_name = "Madhav"
for = 26
# ‘for’ is a reserved word in Python

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 05

Data Types in Python


• What are Data types
• Types of data types
• Data types examples

Data Types in Python


In Python, a data type is a classification that specifies the type of value a
variable can hold. We can check data type using type() function.
Examples:
1. my_name = "Madhav"
>>> type(my_name)
O/P: <class 'str’>
2. value = 101
>>> type(value)
O/P: <class 'int'>

Basic Data Types in Python


Python can be used as a powerful calculator for performing a wide range of
arithmetic operations.
1. Numeric: Integer, Float, Complex
2. Sequence: String, List, Tuple
3. Dictionary
4. Set
5. Boolean
6. Binary: Bytes, Bytearray, Memoryview

P y t h o n N o t e s b y R i s h a b h M i s h ra
Python Tutorial Playlist: Click Here
https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 06

Type Casting in Python


• What is type casting
• Type Casting examples
• Type Casting - Types

Type Casting
Type casting in Python refers to the process of converting a value from one data
type to another. This can be useful in various situations, such as when you need
to perform operations between different types or when you need to format data in
a specific way. Also known as data type conversion.
Python has several built-in functions for type casting:
int(): Converts a value to an integer.
float(): Converts a value to a floating-point number.
str(): Converts a value to a string.
list(), tuple(), set(), dict() and bool()

Type Casting Examples


Basic examples of type casting in python:
# Converting String to Integer:
str_num = "26"
int_num = int(str_num)
print(int_num) # Output: 26
print(type(int_num)) # Output: <class 'int'>

P y t h o n N o t e s b y R i s h a b h M i s h ra
# Converting Float to Integer:
float_num = 108.56
int_num = int(float_num)
print(int_num) # Output: 108
print(type(int_num)) # Output: <class 'int'>

Types of Typecasting
There are two types of type casting in python:
• Implicit type casting
• Explicit type casting

Implicit Type Casting


Also known as coercion, is performed automatically by the Python interpreter. This
usually occurs when performing operations between different data types, and
Python implicitly converts one data type to another to avoid data loss or errors.

# Implicit type casting from integer to float


num_int = 10
num_float = 5.5
result = num_int + num_float # Integer is automatically
converted to float
print(result) # Output: 15.5
print(type(result)) # Output: <class 'float'>

Explicit Type Casting


Also known as type conversion, is performed manually by the programmer
using built-in functions. This is done to ensure the desired type conversion and to
avoid unexpected behavior.

# Converting String to Integer:


str_num = "26"

P y t h o n N o t e s b y R i s h a b h M i s h ra
int_num = int(str_num)
print(int_num) # Output: 26
print(type(int_num)) # Output: <class 'int’>

# Converting a value to boolean:


bool(0) # Output: False
bool(1) # Output: True

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 07

Input Function in Python


• Input Function – Definition
• Input Function – Example
• Handling Different Data Types

Input Function in Python


The input function is an essential feature in Python that allows to take input from
the user. This is particularly useful when you want to create interactive programs
where the user can provide data during execution.
Also known as user input function.
How input Function Works:
The input function waits for the user to type something and then press Enter. It
reads the input as a string and returns it.
Example:
# Prompting the user for their name
name = input("Enter your name: ")
# Displaying the user's input
print("Hello, " + name + "!")

Input Function – Add 2 Numbers


A simple program that takes two numbers as input from the user and prints their
sum.
# Prompting the user for the first and second number
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")

P y t h o n N o t e s b y R i s h a b h M i s h ra
# Since input() returns a string, we need to convert it to an integer

num1 = int(num1)
num2 = int(num2)
# Calculating the sum and display the result

sum = num1 + num2


print("The sum of", num1, "and", num2, "is:", sum)

Multiple Input from User & Handling different Data Types


# input from user to add two number and print result
x = input("Enter first number: ")
y = input("Enter second number: ")
# casting input numbers to int, to perform sum
print(f"Sum of {x} & {y} is {int(x) + int(y)}")

Home Work – User input and print result


Write a program to input student name and marks of 3 subjects. Print name and
percentage in output.
# Prompting the user for their name and 3 subject marks

name = input("Enter your name: ")


hindi_marks = input("Enter Hindi Marks: ")
maths_marks = input("Enter Maths Marks: ")
science_marks = input("Enter Science Marks: ")
# Calculating percentage for 3 subjects

percentage = ((int(hindi_marks) + int(maths_marks) +


int(science_marks))/300)*100
# Printing the final results

print(f"{name}, have {percentage}%. Well done & keep


working hard!!")

P y t h o n N o t e s b y R i s h a b h M i s h ra
Python Tutorial Playlist: Click Here
https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 08

Operators in Python
• What are Operators
• Types of Operators
• Operators Examples

Operators in Python
Operators in Python are special symbols or keywords used to perform
operations on operands (variables and values).
Operators: These are the special symbols/keywords. Eg: + , * , /, etc.
Operand: It is the value on which the operator is applied.
# Examples
Addition operator '+': a + b
Equal operator '==': a == b
and operator 'and': a > 10 and b < 20

Types of Operators
Python supports various types of operators, which can be broadly categorized as:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Identity Operators
7. Membership Operators

P y t h o n N o t e s b y R i s h a b h M i s h ra
Operators Cheat Sheet

Operator Description
() Parentheses
** Exponentiation
+, -, ~ Positive, Negative, Bitwise NOT
*, /, //, % Multiplication, Division, Floor Division, Modulus
+, - Addition, Subtraction
==, !=, >, >=, <, <= Comparison operators
is, is not, in, not in Identity, Membership Operators
NOT, AND, OR Logical NOT, Logical AND, Logical OR
<<, >> Bitwise Left Shift, Bitwise Right Shift
&, ^, | Bitwise AND, Bitwise XOR, Bitwise OR

1. Arithmetic Operators
Arithmetic operators are used with numeric values to perform mathematical
operations such as addition, subtraction, multiplication, and division.

P y t h o n N o t e s b y R i s h a b h M i s h ra
Precedence of Arithmetic Operators in Python:
P – Parentheses
E – Exponentiation
M – Multiplication
D – Division
A – Addition
S – Subtraction

2. Comparison (Relational) Operators


Comparison operators are used to compare two values and return a Boolean
result (True or False).

3. Assignment Operators
Assignment operators are used to assign values to variables.

P y t h o n N o t e s b y R i s h a b h M i s h ra
4. Logical Operators
Logical operators are used to combine conditional statements.

5. Identity & Membership Operators


Identity operators are used to compare the memory locations of two objects, not
just equal but if they are the same objects.
Membership operators checks whether a given value is a member of a sequence
(such as strings, lists, and tuples) or not.

6. Bitwise Operators
Bitwise operators perform operations on binary numbers.

P y t h o n N o t e s b y R i s h a b h M i s h ra
Bitwise Operators Example:
# Compare each bit in these numbers. Eg:1

0101 (This is 5 in binary) a = 5 # 0101


0011 (This is 3 in binary) b = 3 # 0011
------- print(a & b)
0001 (This is the result of 5 & 3) # Output: 1 # 0001

# Rules: 0 – False, 1 - True Eg:2


True + True = True a = 5 # 0101
True + False = False b = 8 # 1000
False + False = False print(a & b)
# Output: 0 # 0000

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 09

Conditional Statements in Python


• Conditional Statement definition
• Types of Conditional Statement
• Conditional Statement examples

Conditional Statements in Python


Conditional statements allow you to execute code based on condition evaluates
to True or False. They are essential for controlling the flow of a program and
making decisions based on different inputs or conditions.
# Examples
a = 26
b = 108
if b > a:
print("b is greater than a")
# Indentation - whitespace at the beginning of a line

Types of Conditional Statements


There are 5 types of conditional statements in Python:
1. 'if' Statement
2. 'if-else' statement
3. 'if-elif-else' statement
4. Nested 'if else' statement
5. Conditional Expressions (Ternary Operator)

P y t h o n N o t e s b y R i s h a b h M i s h ra
1. 'if' Conditional Statement
The if statement is used to test a condition and execute a block of code only if
the condition is true.
Syntax:
if condition:
# Code to execute if the condition is true

Example:
age = 26
if age > 19:
print("You are an adult")

'if' statement flow diagram:

P y t h o n N o t e s b y R i s h a b h M i s h ra
2. 'if-else' Conditional Statement
The if-else statement provides an alternative block of code to execute if the
condition is false.

Syntax:
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false

Example:
temperature = 30
if temperature > 25:
print("It's a hot day.")
else:
print("It's a cool day.")

'if-else' statement flow diagram:

P y t h o n N o t e s b y R i s h a b h M i s h ra
3. 'if-elif-else' Conditional Statement
The if-elif-else statement allows to check multiple conditions and execute
different blocks of code based on which condition is true.

Syntax:
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if none of the above conditions are true

Example:
Grading system: Let’s write a code to classify the student’s grade based on their
total marks (out of hundred).
score = 85
if score >= 90:
print("Grade - A")
elif score >= 80:
print("Grade - B")
elif score >= 70:
print("Grade - C")
else:
print("Grade - D")

4. Nested 'if-else' Conditional Statement


A nested if-else statement in Python involves placing an if-else statement
inside another if-else statement. This allows for more complex decision-making
by checking multiple conditions that depend on each other.

P y t h o n N o t e s b y R i s h a b h M i s h ra
Syntax:
if condition1:
# Code block for condition1 being True
if condition2:
# Code block for condition2 being True
else:
# Code block for condition2 being False
else:
# Code block for condition1 being False
... ..

Example:
Number Classification: Let's say you want to classify a number as positive,
negative, or zero and further classify positive numbers as even or odd.
number = 10
if number > 0: # First check if the number is positive
if number % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive and odd.")
else: # The number is not positive
if number == 0:
print("The number is zero.")
else:
print("The number is negative.")

5. Conditional Expressions
Conditional expressions provide a shorthand way to write simple if-else
statements. Also known as Ternary Operator.

P y t h o n N o t e s b y R i s h a b h M i s h ra
Syntax:
value_if_true if condition else value_if_false

Example:
age = 16
status = "Adult" if age >= 18 else "Minor"
print(status)

Conditional Statements- HW
Q1: what is expected output and reason?

value = None

if value:
print("Value is True")
else:
print("Value is False")

Q2: write a simple program to determine if a given year is a leap


year using user input.

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 10

Functions in Python
• Functions definition
• Types of Functions
• Function examples

Functions in Python
A function is a block of code that performs a specific task. You can use it
whenever you want by calling its name, which saves you from writing the same
code multiple times.
Benefits of Using Function: Increases code Readability & Reusability.
Basic Concepts:
• Create function: Use the def keyword to define a function.
• Call function: Use the function's name followed by () to run it.
• Parameter: The variable listed inside parentheses in function definition.
• Argument: The actual value you pass to function when you call it.

Types of Functions
Below are the two types of functions in Python:
1. Built-in library function:
• These are Standard functions in Python that are available to use.
• Examples: print(), input(), type(), sum(), max(), etc
2. User-defined function:
• We can create our own functions based on our requirements.
• Examples: create your own function :)

P y t h o n N o t e s b y R i s h a b h M i s h ra
Syntax:

# return result is optional, Use if you want the function to give back a value

Function without Parameters


Example:1

# Create or Define Function


def greetings():
print("Welcome to Python tutorial by Rishabh")

# Use or call this Function


greetings()

# Output: Welcome to Python tutorial by Rishabh

P y t h o n N o t e s b y R i s h a b h M i s h ra
Function with Parameters
Example:2

# function to adds two numbers & print result.


def add2numbers(a, b):
result = a + b
print("The sum is:", result)

# Calling this function with arguments


add2numbers(5, 3)

# Output: The sum is: 8

The return Statement


The return statement is used in a function to send a result back to the place
where the function was called. When return is executed, the function stops
running and immediately returns the specified value.
Example:
def add(a, b):
return a + b # This line sends back sum of a and b
result = add(3, 5)
print(result)

# Output: 8

Function with a Return value


Example:3

P y t h o n N o t e s b y R i s h a b h M i s h ra
# function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return Fahrenheit

# Calling this function to return a value


temp_f = celsius_to_fahrenheit(25)
print("Temperature in Fahrenheit:", temp_f)

# Output: Temperature in Fahrenheit: 77.0

The pass Statement


The pass statement is a placeholder in a function or loop. It does nothing and is
used when you need to write code that will be added later or to define an empty
function.
Example:
def myfunction():
pass # This does nothing for now

Functions – HW
Write a Python program to create a calculator that can perform at least five
different mathematical operations such as addition, subtraction, multiplication,
division and average. Ensure that the program is user-friendly, prompting for input
and displaying the results clearly.

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 11

Function Arguments in Python


• Function Arguments
• Types of Functions Arguments
• Function Arguments examples

Arguments in Function
Arguments are the values that are passed into a function when it’s called. A
function must be called with the right number of arguments. If a function has 2
parameters, you must provide 2 arguments when calling it.

Example: function defined using one parameter (variable)

def greetings(name): # name is a parameter


print("Hello, " + name + "!")

greetings("Madhav") # Madhav as argument


# Output: Hello, Madhav!

Types of Function Arguments


Python supports various types of arguments that can be passed at the time of the
function call.
1. Required arguments (Single/Multiple arguments)
2. Default argument
3. Keyword arguments (named arguments)
4. Arbitrary arguments (variable-length arguments *args and **kwargs)

P y t h o n N o t e s b y R i s h a b h M i s h ra
Required Arguments (same as above)
Required arguments are the arguments passed to a function in correct positional order. A
function must be called with the right number of arguments. If a function has 2
parameters, you must provide 2 arguments when calling it.

Example: function defined using one parameter (variable)

def greetings(name): # name is a parameter


print("Hello, " + name + "!")

greetings("Madhav") # Madhav as argument


# Output: Hello, Madhav!

Default Arguments
You can assign default values to arguments in a function definition. If a value isn't
provided when the function is called, the default value is used.
Example: function defined using one parameter & default value

def greetings(name = "World"): # default value


print("Hello, " + name + "!")

greetings() # No argument passed


# Output: Hello, World!

greetings("Madhav") # Madhav as argument


# Output: Hello, Madhav!

Keyword Arguments
When calling a function, you can specify arguments by the parameter name. These are
called keyword arguments and can be given in any order.
Example: function defined using two parameters

def divide(a, b): # a,b are 2 parameters


return a / b

result = divide(b=10, a=20) # with keyword arguments


print(result) # Output: 2

P y t h o n N o t e s b y R i s h a b h M i s h ra
result = divide(10, 20) # positional arguments
print(result) # Output: 0.5

Arbitrary Positional Arguments (*args)


If you're unsure how many arguments will be passed, use *args to accept any number of
positional arguments.
Purpose: Allows you to pass a variable number of positional arguments.
Type: The arguments are stored as a tuple.
Usage: Use when you want to pass multiple values that are accessed by position.
Example 1:

def add_numbers(*args):
return sum(args)

# Any number of arguments


result = add_numbers(1, 2, 3, 4)
print(result) # Output: 10

Note: Here, *args collects all the passed arguments into a tuple, & sum() function adds them.

Example 2:

def greetings(*names):
for name in names:
print(f"Hello, {name}!")
greetings("Madhav", "Rishabh", "Visakha")
# Output:
Hello, Madhav!
Hello, Rishabh!
Hello, Visakha!

Arbitrary Keyword Arguments (**kwargs)


If you want to pass a variable number of keyword arguments, use **kwargs.
Purpose: Allows you to pass a variable number of keyword arguments (arguments with
names).
Type: The arguments are stored as a dictionary.
Usage: Use when you want to pass multiple values that are accessed by name.

P y t h o n N o t e s b y R i s h a b h M i s h ra
Example 1:
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_details(name="Madhav", age=26, city="Delhi")

# Output:
name: Madhav
age: 26
city: Delhi

Example 2:

def shopping_cart(**products):
total = 0
print("Items Purchased:")
for item, price in products.items():
print(f"{item}: ₹{price}")
total += price
print(f"Total: ₹{total}")

# multiple keyword arguments


shopping_cart(apple=15, orange=12, mango=10)

# Output:
Items Purchased:
apple: ₹15
orange: ₹12
mango: ₹10
Total: ₹37

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 12

Strings in Python (Part-1)


• Strings and Examples
• Formatted Strings
• Escape Characters
• String Operators

Strings in Python
A string is a sequence of characters. In Python, strings are enclosed within single (') or
double (") or triple (""") quotation marks.

Examples:

print('Hello World!') # use type() to check data type


print("Won’t Give Up!")
print('''"Quotes" and 'single quotes' can be tricky.''')
print("\"Quotes\" and 'single quotes' can be tricky.")

Types of Function Arguments


A formatted string in Python is a way to insert variables or expressions inside a string. It
allows you to format the output in a readable and controlled way.
There are multiple ways to format strings in Python:

1. Old-style formatting (% operator)


2. str.format() method
3. F-strings (formatted string literals)

P y t h o n N o t e s b y R i s h a b h M i s h ra
Formatted String - % Operator
Old-style formatting (% operator)
This approach uses the % operator and is similar to string formatting in languages like C.

Syntax: "string % value"

Example:

name = "Madhav"
age = 16
print("My name is %s and I’m %d." % (name, age))
# %s, %d are placeholders for strings and integers

Formatted String - str.format()


str.format() method
In Python 3, the format() method is more powerful and flexible than the old-style %
formatting.

Syntax: "string {}".format(value)

Example:

name = "Madhav"
age = 16
print("My name is {} and I’m {}.".format(name, age))
# You can also reference the variables by index or keyword:
print("My name is {0} and I’m {1}.".format(name, age))
print("My name is {name} and I’m {age}.".format(name="Madhav",
age=28))

P y t h o n N o t e s b y R i s h a b h M i s h ra
Formatted String – F-strings
F-strings (formatted string literals)
In Python 3.6, F-strings are the most concise and efficient way to format strings. You
prefix the string with an f or F, and variables or expressions are embedded directly within
curly braces {}.

Syntax: f"string {variable}"

Example:

name = "Madhav"
age = 16
print(f"My name is {name} and I’m {age}.")
# You can also perform expressions inside the placeholders:
print(f"In 5 years, I will be {age + 5} years old.")

Escape Characters
Escape characters in Python are special characters used in strings to represent
whitespace, symbols, or control characters that would otherwise be difficult to include.
An escape character is a backslash \ followed by the character you want to insert.

Examples:

print('Hello\nWorld!') # \n for new line


print('Hello\tWorld!') # \t for tab
print("\"Quotes\" and 'single quotes' can be tricky.") # print
single and double quotes

P y t h o n N o t e s b y R i s h a b h M i s h ra
String Operators

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 13

Strings in Python (Part-2)


• String Indexing
• String Slicing
• String Methods

String Indexing
You can access individual characters in a string using their index. Python uses zero-based
indexing, meaning the first character has an index of 0. Index: Position of the character.

Syntax:
string[Index_Value]

Example:
name = "MADHAV"

P y t h o n N o t e s b y R i s h a b h M i s h ra
String Indexing – Positive & Negative Index

String Slicing
Slicing in Python is a feature that enables accessing parts of the sequence. String slicing
allows you to get subset of characters from a string using a specified range of indices.

Syntax:
string[start : end : step]

• start : The index to start slicing (inclusive). Default value is 0.


• end : The index to stop slicing (exclusive). Default value is length of string.
• Step : How much to increment the index after each character. Default value is 1.

Example:

name = "MADHAV"
name[0:2] = 'MA'
name[0:5:2] = 'MDA'

P y t h o n N o t e s b y R i s h a b h M i s h ra
String Slicing - Examples

Example:

name = "MADHAV"

name[0:1] = name[:1] = 'M' # first char


name[0:2] = name[:2] = 'MA' # first 2 chars
name[2:5] = 'DHA' # third to fifth chars
name[5:] = name[-1:] = 'V' # last char
name[4:] = name[-2:] = 'AV' # last 2 chars
name[0:5:2] = name[0::2] = 'MDA' # every second chars
name[1:-1] = 'ADHA' # exclude first & last chars
name[:] = name[::] = 'MADHAV' # all chars
name[::-1] = 'VAHDAM' # reverse the string

String Methods

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 14

Loops in Python
• Loops & Types
• While Loop
• For Loop
• Range Function
• Loop Control Statements

Loops in Python

Loops enable you to perform repetitive tasks efficiently without writing redundant code. They
iterate over a sequence (like a list, tuple, string, or range) or execute a block of code as long as a
specific condition is met.

Types of Loops in Python


1. While loop
2. For loop
3. Nested loop

While Loop
The while loop repeatedly executes a block of code as long as a given condition remains
True. It checks the condition before each iteration.

Syntax:
while condition:
# Code block to execute
Example: Print numbers from 0 to 3
count = 0
while count < 4: # Condition
print(count)
count += 1
# Output: 0 1 2 3

P y t h o n N o t e s b y R i s h a b h M i s h ra
While Loop Example
else Statement: An else clause can be added to loops. It executes after the loop
finishes normally (i.e., not terminated by break). Example:
count = 3
while count > 0: # Condition
print("Countdown:", count)
count -= 1
else:
print("Liftoff!") # Run after while loop ends

For Loop
The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary,
set, or string) and execute a block of code for each element in that sequence.

Syntax:
for variable in sequence:
# Code block to execute
Example: iterate over each character in language
language = 'Python’
for x in language:
print(x) # Output: P y t h o n

Using range() Function


To repeat a block of code a specified number of times, we use the range() function.
The range() function returns a sequence of numbers, starting from 0 by default,
increments by 1 (by default), and stops before a specified number.
Syntax:
range(stop)
range(start, stop)
range(start, stop, step)

• start: (optional) The beginning of the sequence. Defaults is 0. (inclusive)


• stop: The end of the sequence (exclusive).
• step: (optional) The difference between each number in the sequence.
Defaults is 1.

P y t h o n N o t e s b y R i s h a b h M i s h ra
range() Function Example
Example1: Basic usage with One Argument - Stop
for i in range(5):
print(i)
# Output: 0 1 2 3 4
Example2: Basic usage with Start, Stop and Step
for i in range(1, 10, 2):
print(i)
# Output: 1 3 5 7 9

For Loop Example


else Statement: An else clause can be added to loops. It executes after the loop
finishes normally (i.e., not terminated by break).

Example:
for i in range(3):
print(i)
else:
print("Loop completed")
# Output: 0 1 2 Loop Completed

while loop VS for loop


while loop
• A while loop keeps running as long as a condition is true.
• It is generally used when you don’t know how many iterations will be
needed beforehand, and loop continues based on a condition.

for loop
• A for loop iterates over a sequence (like a strings, list, tuple, or range) and
runs the loop for each item in that sequence.
• It is used when you know in advance how many times you want to repeat a
block of code.

P y t h o n N o t e s b y R i s h a b h M i s h ra
Loop Control Statements
Loop control statements allow you to alter the normal flow of a loop.
Python supports 3 clauses within loops:

• pass statement
• break Statement
• continue Statement

Loop Control - pass Statement


pass Statement: The pass statement is used as a placeholder (it does nothing) for
the future code, and runs entire code without causing any syntax error. (already covered
in functions)

Example:
for i in range(5):
# code to be updated
pass

Above example, the loop executes without error using pass statement

Loop Control - break Statement


break Statement: The break statement terminates the loop entirely, exiting from it
immediately.

Example:
for i in range(5):
if i == 3:
break
print(i) # Output: 0 1 2

Above example, the loop terminated when condition met true for i == 3

P y t h o n N o t e s b y R i s h a b h M i s h ra
Loop Control - continue Statement
continue Statement: The continue statement skips the current iteration and moves
to the next one.

Example:
for i in range(5):
if i == 3:
continue
print(i) # Output: 0 1 2 4

Above example, the loop skips when condition met true for i == 3

break vs continue Statement


break Statement example
# pass statement
count = 5
while count > 0:
if count == 3:
pass
else:
print(count)
count -= 1

# Output: 5 4 2 1

continue Statement example


# continue statement: don't try - infinite loop
count = 5
while count > 0:
if count == 3:
# continue
else:
print(count)
count -= 1

# Output: 5 4 3 3…….

P y t h o n N o t e s b y R i s h a b h M i s h ra
Validate User Input
# validate user input: controlled infinite while loop using
break statement

while True:
user_input = input("Enter 'exit' to STOP: ")
if user_input == 'exit':
print("congarts! You guessed it right!")
break
print("sorry, you entered: ", user_input)

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 15

Nested Loops in Python


• Nested Loops Definition
• Nested Loops Examples
• Nested Loops Interview Ques

Nested Loops in Python


Loop inside another loop is nested loop. This means that for every single time the outer
loop runs, the inner loop runs all of its iterations.

Why Use Nested Loops?


• Handling Multi-Dimensional Data: Such as matrices, grids, or lists of lists.
• Complex Iterations: Operations depend on multiple variables or dimensions.
• Pattern Generation: Creating patterns, such as in graphics or games.

Nested Loop Syntax

Syntax:

Outer_loop:
inner_loop:
# Code block to execute - inner loop
# Code block to execute - outer loop

P y t h o n N o t e s b y R i s h a b h M i s h ra
Nested Loop Example
Example: Print numbers from 1 to 3, for 3 times using for-for
nested loop

for i in range(3): # Outer for loop (runs 3 times)


for j in range(1,4):
print(j)
print()

Example: Print numbers from 1 to 3, for 3 times using while-


for nested loop

i = 1
while i < 4: # Outer while loop (runs 3 times)
for j in range(1, 4):
print(j)

print()
i += 1

Nested Loop Interview Question


Example: Print prime numbers from 2 to 10

for num in range(2, 10):


for i in range(2, num):
if num % i == 0:
break
else:
print(num)

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 16

List in Python
• What is List
• Create Lists
• Access List: Indexing & Slicing
• Modify List
• List Methods
• Join Lists
• List Comprehensions
• Lists Iteration

List in Python
A list in Python is a collection of items (elements) that are ordered, changeable
(mutable), and allow duplicate elements.
Lists are one of the most versatile data structures in Python and are used to store
multiple items in a single variable.
Example:
fruits = ["apple", "orange", "cherry", "apple"]
print(fruits)
# Output: ['apple', 'orange', 'cherry', 'apple']

Create List in Python


You can create lists in Python by placing comma-separated values between square
brackets []. Lists can contain elements of different data types, including other lists.

Syntax: list_name = [element1, element2, element3, ...]


# List of strings
colors = ["red", "green", "blue"]
# List of integers
numbers = [1, 2, 3, 4, 5]
# Mixed data types
mixed = [1, "hello", 3.14, True]
# Nested list
nested = [1, [2, 3], [4, 5, 6]]

P y t h o n N o t e s b y R i s h a b h M i s h ra
Accessing List Elements - Indexing
You can access elements in a list by referring to their index. Python uses zero-based
indexing, meaning the first element has an index of 0.

Syntax: list_name[index]
Example:
fruits = ["apple", "orange", "cherry", "apple", "mango"]

# Access first element


print(fruits[0]) # Output: apple
# Access third element
print(fruits[2]) # Output: cherry
# Access last element using negative index
print(fruits[-1]) # Output: mango

List Slicing
Slicing allows you to access a range of elements in a list. You can specify the start and
stop indices, and Python returns a new list containing the specified elements.
Syntax: list_name[start:stop:step]

Example: numbers = [10, 20, 30, 40, 50, 60]

# Slice from index 1 to 3


print(numbers[1:4]) # Output: [20, 30, 40]

# Slice from start to index 2


print(numbers[:3]) # Output: [10, 20, 30]

# Slice all alternate elements


print(numbers[0::2]) # Output: [10, 30, 50]

# Slice with negative indices


print(numbers[-4:-1]) # Output: [30, 40, 50]

P y t h o n N o t e s b y R i s h a b h M i s h ra
# Reverse list
print(numbers[::-1]) # Output: [60,50,40,30,20,10]

Modifying List
Lists are mutable, meaning you can change their content after creation. You can add,
remove, or change elements in a list.

# Initial list: fruits = ["apple", "banana", "cherry"]

# Changing an element
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']

# Adding an element
fruits.append("mango")
print(fruits) # Output: ['apple', 'blueberry', 'cherry’, 'mango']

# Removing an element
fruits.remove("cherry")
print(fruits) # Output: ['apple', 'blueberry', 'mango']

List Methods
Python provides several built-in methods to modify and operate on lists. Eg:

P y t h o n N o t e s b y R i s h a b h M i s h ra
Join Lists
There are several ways to join, or concatenate, two or more lists in Python.
list1 = [1, 2]
list2 = ["a", "b"]

# One of the easiest ways are by using the + operator


list3 = list1 + list2
print(list3) # Output: [1, 2, 'a', 'b']

# using append method


for x in list2:
list1.append(x)
# appending all the items from list2 into list1, one by one
print(list1) # Output: [1, 2, 'a', 'b']

# using extend method


list1.extend(list2) # add elements from one list to another
list
print(list1) # Output: [1, 2, 'a', 'b']

List Comprehensions
List comprehensions provide a concise way to create lists. They consist of brackets
containing an expression followed by a for clause, and optionally if clauses.

# Syntax:
new_list = [expression for item in iterable if condition]

# Creating a list of squares:


squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]

# Filtering even numbers:


even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]

# Applying a function to each element:


fruits = ["apple", "banana", "cherry"]
uppercase_fruits = [fruit.upper() for fruit in fruits]
print(uppercase_fruits) # Output: ['APPLE', 'BANANA', 'CHERRY']

P y t h o n N o t e s b y R i s h a b h M i s h ra
List Comprehensions - Flatten a List

Flatten a Nested List - using List Comprehension


def flatten_list(lst):
return [item for sublist in lst for item in sublist]
# Example
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = flatten_list(nested_list)
print(flattened)
# Output: [1, 2, 3, 4, 5, 6]

Iterating Over Lists


Iterating allows you to traverse each element in a list, typically using loops.
#Example: fruits = ["apple", "banana", "cherry"]

# Using for loop


for fruit in fruits:
print(fruit)

# Using while loop


index = 0
while index < len(fruits):
print(fruits[index])
index += 1

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Chapter - 17

Tuple in Python
• What is Tuple
• Create Tuples
• Access Tuples: Indexing & Slicing
• Tuple Operations
• Tuple Iteration
• Tuple Methods
• Tuple Functions
• Unpack Tuples
• Modify Tuple

Tuple in Python
A tuple is a collection of items in Python that is ordered, unchangeable (immutable) and
allow duplicate values.
Tuples are used to store multiple items in a single variable.
Note: Ordered – Tuple items have a defined order, but that order will not change.
Example:
fruits = ("apple", "orange", "cherry", "apple")
print(fruits)
# Output: ('apple', 'orange', 'cherry', 'apple')

Create Tuple in Python

There are several ways to create a tuple in Python:

1. Using Parentheses ()
colors = ("red", "green", "blue")
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)
nested = (1, [2, 3], (4, 5, 6))

P y t h o n N o t e s b y R i s h a b h M i s h ra
2. Without Parentheses (Comma-Separated)
also_numbers = 1, 2, 3, 4, 5

3. Using the tuple() Constructor


new_tuple = tuple(("apple", "banana", "cherry")) # use doble
brackets
list_items = ["x", "y", "z"] # Creating a tuple from a list
tuple_items = tuple(list_items) # ('x', 'y', 'z’)

4. Single-Item Tuple
tuplesingle = ("only",)

Accessing Tuple Elements - Indexing

You can access elements in a tuple by referring to their index. Python uses zero-based
indexing, meaning the first element has an index of 0.

Syntax: tuple_name[index]

Example:
fruits = ("apple", "orange", "cherry", "apple", "mango")

# Access first element


print(fruits[0]) # Output: apple
# Access third element
print(fruits[2]) # Output: cherry
# Access last element using negative index
print(fruits[-1]) # Output: mango

Tuple Slicing
Slicing allows you to access a range of elements in a tuple. You can specify the start and
stop indices, and Python returns a new tuple containing the specified elements.

Syntax: tuple_name[start:stop:step]

P y t h o n N o t e s b y R i s h a b h M i s h ra
Example:
numbers = (10, 20, 30, 40, 50, 60)

# Slice from index 1 to 3


print(numbers[1:4]) # Output: (20, 30, 40)
# Slice from start to index 2
print(numbers[:3]) # Output: (10, 20, 30)
# Slice all alternate elements
print(numbers[0::2]) # Output: (10, 30, 50)
# Slice with negative indices
print(numbers[-4:-1]) # Output: (30, 40, 50)
# Reverse list
print(numbers[::-1]) # Output: (60,50,40,30,20,10)

Tuple Operations
1. Concatenation
# You can join two or more tuples using the + operator.
tuple1 = (1, 2, 3)
tuple2 = (4, 5)
combined = tuple1 + tuple2
print(combined) # Output: (1, 2, 3, 4, 5)

2. Repetition
# You can repeat a tuple multiple times using the * operator.
tuple3 = ("hello",) * 3
print(tuple3) # Output: ('hello', 'hello', 'hello’)

3. Checking for an Item


# Use the in keyword to check if an item exists in a tuple.
numbers = (10, 20, 30, 40)
print(20 in numbers) # Output: True

P y t h o n N o t e s b y R i s h a b h M i s h ra
Iterating Over Tuple

Iterating allows you to traverse each element in a tuple, using loops.

#Example: fruits = ("apple", "mango", "cherry")

# Using for loop


for fruit in fruits:
print(fruit)

# Using while loop

i = 0
while i < len(fruits):
print(fruits[i])
index += 1

Tuple Methods
Python provides two built-in methods to use on tuples.

# count
colors = ("red", "green", "blue", "green")
print(colors.count("green")) # Output: 2

# index
colors = ("red", "green", "blue", "green")
print(colors.index("blue")) # Output: 2

Tuple Functions
Python provides several built-in functions to use on tuples.

P y t h o n N o t e s b y R i s h a b h M i s h ra
numbers = (2, 3, 1, 4)

print(len(numbers)) # Output: 4

sorted_num = sorted(numbers)
print(sorted_num) # Output: [1,2,3,4]

print(sum(numbers)) # Output: 10
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 4

Packing and Unpacking Tuples


a. Packing is the process of putting multiple values into a single tuple.

a = "Madhav"
b = 21
c = "Engineer"
pack_tuple = a,b,c # Packing values into a tuple
print(pack_tuple)

b. Unpacking is extracting the values from a tuple into separate variables.

name, age, profession = person # Unpacking a tuple


print(name) # Output: Madhav
print(age) # Output: 21
print(profession) # Output: Engineer

Modifying Tuple - Immutable

Once a tuple is created, you cannot modify its elements. This means you cannot add,
remove, or change items.

# Creating a tuple
numbers = (1, 2, 3)

# Attempting to change an item


numbers[0] = 10
# This will raise an error

P y t h o n N o t e s b y R i s h a b h M i s h ra
Modifying Tuple
But there is a trick. You can convert the tuple into a list, change the list, and convert the
list back into a tuple.

my_tuple = ("apple", "mango", "cherry")

# type cast tuple to list


y = list(my_tuple)
y.append("orange")

# type cast back list to tuple


my_tuple = tuple(y)
print(my_tuple)

Tuple Use Case - Examples


Storing Fixed Data (Immutable Data)
Example: Storing geographic coordinates (latitude, longitude) or RGB color values, where
the values shouldn’t be changed after assignment.

coordinates = (40.7128, -74.0060) # Latitude and longitude for NYC


rgb_color = (255, 0, 0) # RGB value for red

Using Tuples as Keys in Dictionaries


Since tuples are immutable and hashable, they can be used as keys in dictionaries, unlike
lists.
location_data = {
(40.7128, -74.0060): "New York City",
(34.0522, -118.2437): "Los Angeles"
}
print(location_data[(40.7128, -74.0060)]) # Output: New York City

Python Tutorial Playlist: Click Here


https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

P y t h o n N o t e s b y R i s h a b h M i s h ra
PYTHON TUTORIAL FOR BEGINNERS
Source: www.youtube.com/@RishabhMishraOfficial

Assignment - 03

3 Question on If-else Conditional Statement


• Q1: Leap year
• Q2: Login Authentication
• Q3: Admission Eligibility

Q1: Leap Year


Write a simple program to determine if a given year is a leap year using user
input.
Note:
• Leap year occurs once every four years.
• A year is a leap year if it is divisible by 4, but not if it is divisible by 100
unless it is also divisible by 400.
Every year that is exactly divisible by 4 is a leap year, except for years that are
exactly divisible by 100, but these centurial years are leap years if they are exactly
divisible by 400. For eg, the years 1700, 1800, & 1900 are not leap years, but the
years 1600 and 2000 are.

Sol 1:
# User input
year = int(input("Enter a year (e.g. 2024): "))
# Check if the year is a leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

P y t h o n N o t e s b y R i s h a b h M i s h ra
Q2: Login Authentication
Login Authentication using conditional statement. Assume you have a predefined
username and password.
Write a program that prompts the user to enter a username and password and
checks whether they match. Provide appropriate messages for the following
cases:
• Both username and password are correct.
• Username is correct but password is incorrect.
• Username is incorrect.

Sol 2:
# Predefined username and password
predefined_username = "madhav"
predefined_password = "pass101"
# Prompt the user for username and password
input_username = input("Enter username: ")
input_password = input("Enter password: ")
# Check the username and password
if input_username == predefined_username:
if input_password == predefined_password:
print("Welcome! Login was successful.")
else:
print("Login failed: Incorrect password.")
else:
print("Login failed: Incorrect username.")

P y t h o n N o t e s b y R i s h a b h M i s h ra
Q3: Admission Eligibility
A university has the following eligibility criteria for admission:
• Marks in Mathematics >= 65
• Marks in Physics >= 55
• Marks in Chemistry >= 50
• Total marks in all three subjects >= 180 OR Total marks in Mathematics and
Physics >= 140
Write a program that takes marks in three subjects as input and prints whether the
student is eligible for admission.

Sol 3:
# Input marks from the user
print("Enter below PCM marks out of 100")
physics_marks = int(input("Physics: "))
chemistry_marks = int(input("Chemistry: "))
math_marks = int(input("Maths: "))
# Check the eligibility criteria
if (math_marks >= 65 and
physics_marks >= 55 and
chemistry_marks >= 50 and
(math_marks + physics_marks + chemistry_marks) >= 180) or
\
(math_marks + physics_marks) >= 140:
print("Eligible for admission!")
else:
print("Not eligible for admission")

P y t h o n N o t e s b y R i s h a b h M i s h ra
Python Tutorial Playlist: Click Here
https://www.youtube.com/playlist?list=PLdOKnrf8EcP384Ilxra4UlK9BDJGwawg9

You might also like