0% found this document useful (0 votes)
9 views30 pages

Python Basics: Variables, Data Types & Operators

The document compares interpreters and compilers, highlighting that interpreters execute code line by line while compilers translate the entire code at once, resulting in faster execution for compilers. It also covers Python programming concepts such as variables, data types, type casting, input functions, operators, and conditional statements, providing examples and rules for each topic. The content is structured as a tutorial for beginners learning Python.

Uploaded by

hanifmarwa715
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views30 pages

Python Basics: Variables, Data Types & Operators

The document compares interpreters and compilers, highlighting that interpreters execute code line by line while compilers translate the entire code at once, resulting in faster execution for compilers. It also covers Python programming concepts such as variables, data types, type casting, input functions, operators, and conditional statements, providing examples and rules for each topic. The content is structured as a tutorial for beginners learning Python.

Uploaded by

hanifmarwa715
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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


[Link]

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: [Link]/@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


[Link]

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: [Link]/@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
[Link]

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: [Link]/@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


[Link]

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: [Link]/@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
[Link]
PYTHON TUTORIAL FOR BEGINNERS
Source: [Link]/@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


[Link]

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: [Link]/@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


[Link]

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: [Link]/@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


[Link]

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: [Link]/@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


[Link]

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

You might also like