0% found this document useful (0 votes)
2 views46 pages

Python Programming Unit i

This document provides an introduction to Python programming, covering its key features such as interpreted language, dynamic typing, and readability. It details core programming fundamentals, how to run Python code, and the rules for naming identifiers and variables, including reserved keywords. Additionally, it explains the importance of comments and indentation in Python syntax.

Uploaded by

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

Python Programming Unit i

This document provides an introduction to Python programming, covering its key features such as interpreted language, dynamic typing, and readability. It details core programming fundamentals, how to run Python code, and the rules for naming identifiers and variables, including reserved keywords. Additionally, it explains the importance of comments and indentation in Python syntax.

Uploaded by

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

PYTHON PROGRAMMING

UNIT-1
INTRODUCTION TO PYTHON

Python is a popular, high-level, general-purpose programming language known for its


simple, readable syntax that uses indentation to define code blocks. It supports multiple
programming paradigms (procedural, object-oriented, and functional) and is widely used
for web development, data science, AI/ML, and automation.

Key Concepts
 Interpreted Language: Python code runs on an interpreter system, allowing for quick
prototyping and immediate execution.

 Dynamic Typing: You don't need to declare variable types explicitly; Python tracks the
types of values at runtime.

 Readability: Python's design emphasizes clean, English-like syntax, which makes it an


excellent language for beginners.

 Extensive Libraries: Python has a vast standard library and a large ecosystem of third-
party packages (available through the Python Package Index (PyPI)) for a wide range of
applications.

Core Programming Fundamentals


Learning Python involves understanding several core programming concepts:
 Variables and Data Types: Variables store data in memory. Common data types
include int (integers), float (decimal numbers), str (strings/text),
and bool (Boolean: True or False ).

 Operators: Symbols like + , - , * , / , and == are used to perform operations and


comparisons on values.

 Control Flow:

o Conditional Statements: Use if , elif (else if), and else to make decisions in your
code based on whether a condition is true or false.

o Loops: Use for and while loops to repeat a block of code multiple times.
 Functions: Reusable blocks of code that perform a specific task, defined using
the def keyword. They help organize code and improve efficiency.

 Data Structures: Python offers built-in data structures for grouping related values:

o Lists: Ordered, mutable (changeable) collections of items enclosed in square


brackets [] .

o Tuples: Ordered, immutable (unchangeable) collections of items enclosed in


parentheses () .

o Dictionaries: Unordered collections of key-value pairs enclosed in curly braces {} .

o Sets: Unordered collections of unique items enclosed in curly braces {} .

HOW TO RUN PYTHON

You can run Python code using the command line/terminal, an Integrated
Development Environment (IDE), or an online environment.

Method 1: Using the Command Line/Terminal


This is the most fundamental way to run a Python script file (which typically has
a .py extension).

1. Install Python: Ensure Python is installed on your [Link] installation on


Windows, ensure the option "Add Python to PATH" is checked for easier access.

2. Open your Terminal/Command Prompt:

0. Windows: Search for "Command Prompt" or "PowerShell" in the Start


menu.

1. macOS/Linux: Open "Terminal" (usually found in Applications > Utilities


on macOS, or via Ctrl+Alt+T on Linux).

3. Navigate to your file's directory: Use the cd (change directory) command to go to the
folder where you saved your Python file (e.g., cd Documents/pyscripts ).

4. Run the script: Type the appropriate command followed by your filename:

0. Windows: python [Link] or py [Link] .


1. macOS/Linux: python3 [Link] (since some systems still default python to older
versions like Python 2).

Method 2: Using an IDE or Code Editor


IDEs and advanced code editors provide a user-friendly interface with features like
debugging and syntax highlighting.

1. Install Python: As above, you must have the Python interpreter installed on your
system.

2. Install an IDE/Editor: Popular choices include Visual Studio Code, PyCharm


(JetBrains), or IDLE (which comes bundled with Python).

3. Install the Python Extension: In editors like VS Code, install the official Python
extension from the marketplace.

4. Open your file and run:

0. Open your Python file within the IDE.

1. Most IDEs have a "Run" button (often a green play icon ▶) in the top bar
or a "Run Module" option in the menus (like pressing F5 in IDLE or Visual
Studio).

2. Alternatively, you can right-click in the editor window and select Run
Python File in Terminal.

Method 3: Using an Online Environment


If you want to run Python without installing anything on your computer, you can use an
online interpreter (REPL - Read-Eval-Print Loop).
 Visit a platform like Replit or Google Colab.

 Paste or type your code into the editor provided.

 Click the "Run" button to execute your code and see the output immediately in the
console area.
IDENTIFIERS:
DEF:
In Python, an identifier is a user-defined name used to identify a variable, function, class, module, or
other object. Identifiers are essential for writing readable and maintainable code, as they allow
you to refer to specific entities within a program.

Rules for Python Identifiers


All identifiers must adhere to a specific set of rules in Python:
 Allowed Characters: Identifiers can only contain letters (A-Z, a-z), digits (0-9), and
underscores (_).

 Cannot Start with a Digit: An identifier must begin with a letter or an underscore. For
example, total_marks is valid, but 1st_place is not.

 Case-Sensitive: Python is a case-sensitive language, meaning name and Name are


considered two different identifiers.

 No Special Characters or Spaces: Punctuation characters like @ , # , $ , % , and spaces


are not allowed.

 Cannot Be a Keyword: Identifiers cannot use Python's reserved keywords


(e.g., if , for , class , return ). The full list of keywords can be found in the Python
documentation or accessed using [Link] in the Python shell.

 Length: There is no length limit imposed by the language itself; however, following
the PEP 8 style guide suggests keeping lines (and names) to a reasonable length for
readability.

Types and Examples


Identifiers are used to name various programming elements:
 Variables: user_name , age

 Functions: calculate_sum() , display_info()

 Classes: Student , BankAccount

 Modules: math , os (when imported)

 Objects: s1 = Student()
Example:

import keyword

print("student_name".isidentifier()) # True

print("2marks".isidentifier()) # False (starts with a digit)

print("for".isidentifier()) # True (syntactically valid as a name)

print([Link]("for")) # True (is a reserved keyword)

RESERVED WORDS IN PYTHON (KEYWORDS):


DEFINITION:
Python has a specific set of reserved words (or keywords) that have special meanings and are used
to define the syntax and structure of the language. These words cannot be used as variable names,
function names, or any other identifiers.

List of Python Reserved Words


 False - Boolean value

 None - Represents a null value or the absence of a value

 True - Boolean value

 and - Logical operator

 as - Used to create an alias, often with import or with statements

 assert - For debugging, checks if a condition is true

 async - Used to define an asynchronous function (coroutine)

 await - Used to wait for an asynchronous operation to complete

 break - Exits the current loop

 class - Defines a new class

 continue - Skips the current iteration of a loop

 def - Defines a function or method


 del - Deletes an object or variable

 elif - Short for "else if", used in conditional statements

 else - Used in conditional and loop statements to define a block of code to run when
conditions are not met

 except - Catches exceptions during error handling with try

 finally - Defines a block of code that will be executed no matter what in exception
handling

 for - Creates a loop for iteration

 from - Used to import specific parts of a module

 global - Declares a variable as global within a function

 if - Creates a conditional statement

 import - Imports a module

 in - Membership operator, checks if a value is present in a sequence

 is - Identity operator, checks if two variables are the same object in memory

 lambda - Creates an anonymous function

 match - Used for pattern matching (added in Python 3.10)

 None - Represents a null value.

 nonlocal - Declares a variable as non-local in nested functions

 not - Logical operator

 or - Logical operator

 pass - A null statement, acts as a placeholder that does nothing

 raise - Explicitly raises an exception

 return - Exits a function and returns a value

 try - Defines a block of code for exception handling

 while - Creates a loop that executes as long as a condition is true


 with - Simplifies exception handling by using context managers

 yield - Returns a value from a generator function

Key Characteristics
 Case Sensitivity: Python keywords are case-sensitive. For example, False is a
keyword, but false is not.

 Cannot be Identifiers: You will get a SyntaxError if you try to use a keyword as a
variable or function name.

 Built-in Functions: Words like list , dict , and print are built-in functions, not
keywords, but you should still avoid using them as variable names to prevent issues
(known as "shadowing").

You can view a list of all keywords in your current Python environment by using
the keyword module in the console:
python
import keyword
print([Link])

VARIABLES:
DEFINITION:
In Python, a variable is a symbolic name (or label) that acts as a reference to an object or value stored
in memory. Unlike some other programming languages, Python is dynamically typed, meaning
you do not need to explicitly declare the variable's data type; it is automatically determined by
the value you assign to it.
Key Concepts
 Assignment: Variables are created using the assignment operator ( = ). The value on
the right is assigned to the variable name on the left.

python
# Examples of variable assignment
name = "Alice" # A string variable
age = 30 # An integer variable
height = 5.9 # A float variable
is_student = True # A boolean variable
 Dynamic Typing: A variable's type can change after it has been set by simply
assigning a new value of a different type.

python
data = 100 # data is now an integer
data = "hello" # data is now a string
 Object References: Variables in Python hold references to objects, not the objects
themselves. Assigning one variable to another makes both variables refer to the same
object in memory.

 Case Sensitivity: Variable names are case-sensitive. age and Age are two different
variables.

Naming Rules and Conventions


When naming variables, you must follow these rules:

 Names must start with a letter or an underscore ( _ ).

 Names cannot start with a number.

 Names can only contain alphanumeric characters and underscores ( A-z , 0-9 , and _ ).

 Names cannot be any of Python's reserved keywords (e.g., if , for , while ).

Best Practice (PEP 8 convention): Use snake_case (all lowercase words separated
by underscores) for variable names to improve code readability.
Multiple Assignment
Python allows you to assign values to multiple variables in a single line:
 Multiple values to multiple variables:

python
x, y, z = "Orange", "Banana", "Cherry"
 One value to multiple variables:

python
x = y = z = "Orange”
COMMENTS IN PYTHON:
DEFINITION:
In Python, comments are used to explain code and are ignored by the interpreter during
execution. There are two primary ways to create comments:
 Single-line comments: Start with a hash symbol ( # ). Anything after the # on the same
line is considered a comment.

python
# This is a single-line comment
x = 10 # This is an inline comment
 Multi-line comments: Python does not have a dedicated syntax for multi-line
comments like other languages (e.g., /* */ in C). The recommended way to create
block comments is by placing a hash symbol at the beginning of each line.

python
# This is the first line of a multi-line comment
# This is the second line
# And so on
Alternatively, unassigned triple-quoted strings ( """ or ''' ) can serve a similar purpose
because they are ignored by the interpreter if not assigned to a variable.
python
"""
This string literal is not assigned to a variable,
so it functions as a multi-line comment.
"""

Best Practices
 Explain "Why," Not "What": Good comments explain the reasoning or intent behind a
piece of code, rather than simply restating what the code does.

 Keep them updated: Outdated comments can be worse than no comments, leading to
confusion.

 Use Sparingly: Strive to write self-explanatory code and use comments only when the
logic is complex or non-obvious.
 Use Shortcuts: Most IDEs and editors offer keyboard shortcuts (commonly Ctrl
+ / or Cmd + / ) to quickly comment out or uncomment blocks of code.

INDENTATION IN PYTHON:
DEFINITION:
In Python, indentation is mandatory and defines code blocks, unlike most other languages
where it is merely a matter of style for readability. The Python interpreter uses the
amount of leading whitespace to determine the grouping and hierarchy of statements
within structures like loops, conditionals, functions, and classes.

Key Rules and Best Practices


 Mandatory Use: Indentation is a core part of the syntax. Omitting or inconsistently
using it will raise an IndentationError .

 Consistency: All statements within the same block must have the same level of
indentation.

 Recommended Standard: The official style guide, PEP 8, strongly recommends


using 4 spaces per indentation level.

 Spaces over Tabs: The Python community prefers spaces over tabs. Mixing tabs and
spaces in the same file can cause errors.

 Start at Zero: The first line of Python code should not be indented.

 Example
 The following example demonstrates how indentation defines the scope of
the if and else blocks:

 python
 age = 18
 if age >= 18:
 print("You are an adult.") # Indented, part of the if block
 else:
 print("You are a minor.") # Indented, part of the else block
 print("Done.") # Not indented, outside both blocks
MULTI LINE COMMENTS:
DEFINITION:
Multi-line comments are used to add explanatory text or temporarily disable large blocks of
code across multiple lines. The syntax for these comments varies depending on the
programming language.
Common Multi-Line Comment Syntaxes
Language Syntax Source(s)

C, C++, C#, Java, /* ... */


JavaScript, PHP, CSS

Python Python does not have a dedicated multi-line comment


syntax. The common workarounds are:

* Prefix each line with a hash symbol (#).

* Use triple-quotes (""" or ''') to create a multi-line string


literal which is ignored if not assigned to a variable.

HTML <!-- ... -->

Go /* ... */

SQL /* ... */

Usage and Best Practices


 Documentation: Multi-line comments, especially in the form of docstrings in Python,
are often used to provide comprehensive documentation for modules, classes, and
functions.

 Debugging: They are useful for temporarily disabling sections of code during testing
and debugging.

 IDE Support: Most modern Integrated Development Environments (IDEs) and text
editors provide a keyboard shortcut (commonly Ctrl + / or Cmd + / ) to automatically
comment out or uncomment a selected block of code, which often uses the single-line
comment syntax for each line.
 Clarity: Use comments to explain complex logic or the "why" behind your code, rather
than simply restating the "what".

MULTIPLE STATEMENT GROUP(SUITE)


DEFINITION:
A suite in programming, particularly Python, is a group of one or more related
statements (a code block) controlled by a clause (like if , def , class , for ). Suites are
indented and can contain multiple simple statements separated by semicolons on the
same line, acting as a single block of code.

Key Aspects of Suites:

 Definition: A collection of statements forming a single block in Python, commonly used


with control structures ( if , while , for ) or definitions ( def , class ).
 Syntax: Usually indented below a header statement.
 Single-Line Alternative: Multiple statements within a suite can be written on one line
using semicolons (e.g., if x: a=1; b=2 ).
 Compound Statements: Python's compound statements often use suites to group
actions, such as if , try , or loops.

For example, a def function definition requires a suite to define its body:

python
def my_function():
print("Hello") # Suite starts
return True

QUOTES IN PYTHON:
DEFINITION
In Python, strings can be enclosed using single quotes ( ' ' ), double quotes ( " " ),
or triple quotes ( ''' ''' or """ """ ). All three types function identically for defining a string
and are primarily a matter of style and convenience.
Standard Quotes (Single and Double)
Single and double quotes can be used interchangeably to define standard, single-line
strings.

 'hello' is the same as "hello" .

The primary reason for having both is to easily include one type of quote within a string
without using escape characters.

 To include a single quote (apostrophe) in a string, enclose it in double quotes:

python

print("It's a beautiful day!")# Output: It's a beautiful day!



 To include double quotes in a string, enclose it in single quotes:

python

print('He is called "Johnny"')# Output: He is called "Johnny"



 If a string must contain both types of quotes, or to maintain consistency with a chosen
style, you can use a backslash ( \ ) as an escape character before the inner quote:

python

print('She said, "It\\\'s a beautiful day!"')# Output: She said, "It's a


beautiful day!"

Triple Quotes (Multi-line Strings and Docstrings)


Triple quotes, using three consecutive single or double quotes, allow a string to span
multiple lines while preserving line breaks and formatting.

 Multi-line strings:

python

paragraph = """
This is a multi-line string.
It spans across several lines
and retains its formatting."""
print(paragraph)

 Docstrings: Triple quotes are the standard and recommended way for writing
documentation strings (docstrings) for modules, classes, methods, and functions, as
specified in PEP 257. The convention is to use triple double quotes ( """ """) for
docstrings.

INPUT IN PYTHON
In Python, the built-in input() function is used to take user input from the keyboard. This
function pauses the program's execution and waits for the user to type something and
press Enter.

Basic Usage
The most straightforward way to use input() is by assigning the result to a variable:

python
user_response = input("Enter your name: ")
print("Hello,", user_response)
 "Enter your name: " : This is an optional prompt message displayed to the user to guide
them on what to enter.
 user_response : The value the user enters (e.g., "John") is stored in this variable.
Handling Different Data Types
By default, the input() function always returns the input as a string ( str ). To use the input
as a number (for calculations, for example), you must convert it using type
casting functions like int() or float() :

 Integer Input:

python

age = int(input("Enter your age: "))


print("Next year, you will be", age + 1)
 If a user enters non-integer input in this case, a ValueError will occur. It is a best practice
to handle such errors using try-except blocks.
 Float Input:

python

price = float(input("Enter a price with decimals: "))


print("Price with tax:", price * 1.18)

Taking Multiple Inputs


You can take multiple inputs on a single line by using the .split() method, which
separates the input string into a list based on whitespace (or a specified separator):

python
# For string inputsfirst_name, last_name = input("Enter your first and last
name: ").split()
print("First name:", first_name)
print("Last name:", last_name)
# For integer inputs, use `map()` with `split()`x, y = map(int, input("Enter
two numbers (separated by a space): ").split())
print("The sum is:", x + y)
The map() function applies the int() conversion to each item in the split list.

OUTPUT IN PYTHON
DEFINITION:
In Python, the primary way to produce output is using the built-in print() function. This
function displays text, variables, and expressions to the console (standard output).

Using the print() function


The basic syntax for the print() function is print(object(s)) , where object(s) are the values
you want to display.

 Printing a simple string:

python

print("Hello, World!") # Output: Hello, World!



 Printing variables:

python

name = "Alice"age = 30
print("Name:", name, "Age:", age)# Output: Name: Alice Age: 30

By default, multiple items separated by commas within the print() function are
automatically separated by a single space in the output.
 Printing numbers and expressions:

python

print(3 * 4 + 2)# Output: 14


# The result of an expression can be assigned to a variable and
printedsum_value = 2 + 2
print("The sum:", sum_value)# Output: The sum: 4
Customizing Output

The print() function allows for custom formatting using specific arguments:

 sep : Modifies the default space between objects.


 end : Changes the default newline character at the end.
 file : Sends output to a file instead of the console.

Advanced Formatting (f-strings)

Formatted string literals (f-strings) provide a concise way to embed expressions inside
string literals for output.

IMPORT FUNCTIONS:

In Python, importing functions allows you to reuse code from other files
(modules) or built-in libraries.

Here are the main ways to import functions:

1 Import an Entire Module


1️⃣

import math

result = [Link](16)
print(result)

✔ You must use the module name ([Link]).

2️⃣Import a Specific Function

from math import sqrt

result = sqrt(16)
print(result)
✔ No need to write math. before the function.

3️⃣Import Multiple Functions

from math import sqrt, pow

print(sqrt(25))
print(pow(2, 3))

4️⃣Import All Functions (Not Recommended)

from math import *

⚠ This can cause naming conflicts and makes code harder to read.

5️⃣Import with an Alias

Module Alias:

import math as m

print([Link](36))

Function Alias:

from math import sqrt as square_root

print(square_root(49))

6️⃣Import From Your Own Python File

Suppose you have a file:

[Link]

def greet(name):
return f"Hello {name}"

Then in another file:


from myfile import greet

print(greet("Alice"))

Both files must be in the same folder (or properly structured package).

7️⃣Import From a Package

Example with NumPy:

import numpy as np

arr = [Link]([1, 2, 3])


print(arr)

Quick Summary

Syntax Meaning
import module Import whole module
from module import function Import specific function
import module as alias Import with nickname
from module import * Import everything (avoid)
OPERATORS IN PYTHON
In Python programming, Operators in general are used to perform operations on
values and variables.
 Operators: Special symbols like -, + , * , /, etc.
 Operands: Value on which the operator is applied.
Types of Operators in Python
Arithmetic Operator:
An arithmetic operator is a symbol used to perform mathematical calculations on numbers.

It is used to do operations like addition, subtraction, multiplication, division, etc.

Operat
Name Definition
or

+ Addition Adds two values

- Subtraction Subtracts right value from left

* Multiplication Multiplies two values

/ Division Divides left by right (returns float)

Divides and returns whole number (removes decimal


// Floor Division
part)

% Modulus Returns the remainder of division

** Exponent Raises left value to the power of right

EXAMPLE:

+ (Addition)
Definition: Adds two values.
Example: 5 + 3 → 8

- (Subtraction)

Definition: Subtracts the right value from the left value.


Example: 10 - 4 → 6

* (Multiplication)

Definition: Multiplies two values.


Example: 6 * 2 → 12

/ (Division)

Definition: Divides left value by right value and returns a float.


Example: 7 / 2 → 3.5

// (Floor Division)

Definition: Divides and returns the whole number part only.


Example: 7 // 2 → 3

% (Modulus)

Definition: Returns the remainder after division.


Example: 7 % 2 → 1

** (Exponent)

Definition: Raises left value to the power of right value.


Example: 2 ** 3 → 8

Comparison (Relational) Operators:


A comparison operator is a symbol used to compare two values.
It checks the relationship between them and returns either True or False.
Operat
Name Definition
or

== Equal to Returns True if both values are


Operat
Name Definition
or

equal

!= Not equal to Returns True if values are not equal

> Greater than True if left value is greater

< Less than True if left value is smaller

Greater than or
>= True if left is greater or equal
equal

<= Less than or equal True if left is smaller or equal

== (Equal to)

Definition: Checks if two values are equal.


Example: 5 == 5 → True

!= (Not equal to)

Definition: Checks if two values are not equal.


Example: 5 != 3 → True

> (Greater than)

Definition: Checks if left value is greater than right value.


Example: 8 > 3 → True

< (Less than)

Definition: Checks if left value is less than right value.


Example: 2 < 5 → True

>= (Greater than or equal to)

Definition: Checks if left value is greater than or equal to right value.


Example: 5 >= 5 → True

<= (Less than or equal to)

Definition: Checks if left value is less than or equal to right value.


Example: 4 <= 6 → True
Logical Operators
Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
EXAMPLE:
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Output
False
True
False

Bitwise Operators
Python Bitwise operators act on bits and perform bit-by-bit operations. These are
used to operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR

EXAMPLE:
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Output
0
14
-11
14
2
40

Assignment Operators
Python Assignment operators are used to assign values to the variables. This
operator is used to assign the value of the right side of the expression to the left
side operand.

Example

a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

Output
10
20
10
100
102400

Identity Operators
In Python, is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are equal do
not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
EXAMPLE:
a = 10
b = 20
c=a
print(a is not b)
print(a is c)

Output
True
True

Membership Operators
In Python, in and not in are the membership operators that are used to test whether
a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
EXAMPLE:
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list

Ternary Operator
in Python, Ternary operators also known as conditional expressions are operators
that evaluate something based on a condition being true or false. It was added to
Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else,
making the code compact.
Syntax : [on_true] if [expression] else [on_false]
EXAMPLE:
a, b = 10, 20
min = a if a < b else b

print(min)

Output
10

Precedence and Associativity of Operators


In Python, Operator precedence and associativity determine the priorities of the
operator.

Operator Precedence

This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.
EXAMPLE:
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0
if name == "Alex" or name == "John" and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")

Output
610
Hello! Welcome.

Operator Associativity

If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from
Right to Left.
EXAMPLE:
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)

Output
100.0
6
0
512

DATATYPES AND OPERATIONS:

1️⃣Integer (int)

Definition:
An integer is a whole number (positive, negative, or zero) without decimals.

Example:
x = 10
y = -5
print(type(x)) # <class 'int'>

OPERATIONS:

print(x + y) # Addition → 13
print(x - y) # Subtraction → 7
print(x * y) # Multiplication → 30
print(x / y) # Division → 3.3333
print(x // y) # Floor division → 3
print(x % y) # Modulus → 1
print(x ** y) # Exponent → 1000

2️⃣Float (float)

Definition:
A float is a number with a decimal point.

Example:

pi = 3.14
price = 99.99
print(type(pi)) # <class 'float'>

OPERATIONS:

print(a + b) # 7.5
print(a - b) # 3.5
print(a * b) # 11.0
print(a / b) # 2.75

3️⃣Complex (complex)

Definition:
A complex number has a real part and an imaginary part (written with j).
Example:

z = 2 + 3j
print(type(z)) # <class 'complex'>

OPERATIONS:

print(z1 + z2) # (3+2j)


print(z1 * z2) # (5+1j)
print([Link]) # 2.0
print([Link]) # 3.0

4️⃣String (str)

Definition:
A string is a sequence of characters enclosed in quotes.

Example:

name = "Python"
message = 'Hello'
print(type(name)) # <class 'str'>

OPERATIONS:

print([Link]()) # "PYTHON"
print([Link]()) # "python"
print(name[0]) # 'P' (indexing)
print(name[0:4]) # 'Pyth' (slicing)
print(name + "3") # "Python3" (concatenation)
print(name * 2) # "PythonPython" (repetition)

5️⃣List (list)

Definition:
A list is an ordered and changeable collection of elements.
Example:

numbers = [1, 2, 3, 4]
[Link](5)
print(numbers) # [1, 2, 3, 4, 5]

OPERATIONS:

[Link](5) # [1, 2, 3, 4, 5]
[Link](2) # [1, 3, 4, 5]
print(numbers[0]) #1
print(numbers[1:3]) # [3, 4]
len(numbers) #4

6️⃣Tuple (tuple)

Definition:
A tuple is an ordered but unchangeable collection of elements.

Example:

point = (10, 20)


print(point[0]) # 10

OPERATIONS:

print(point[0]) # 10
print(point[1:3]) # (20, 30)
len(point) #3
# Cannot add or remove elements (immutable)

7️⃣Dictionary (dict)
Definition:
A dictionary stores data in key–value pairs.

Example:

student = {"name": "John", "age": 20}


print(student["name"]) # John

OPERATIONS:

print(student["name"]) # John
student["age"] = 21 # Update value
student["grade"] = "A" # Add key
print([Link]()) # dict_keys(['name','age','grade'])
print([Link]()) # dict_values(['John',21,'A'])

8️⃣Set (set)

Definition:
A set is an unordered collection of unique elements.

Example:

s = {1, 2, 3, 3}

OPERATIONS:
print(s) # {1, 2, 3}
[Link](4) # {1,2,3,4}
[Link](2) # {1,3,4}
print([Link]({5,6})) # {1,3,4,5,6}
print([Link]({3,4,7})) # {3,4}

9️⃣Boolean (bool)
Definition:
A boolean represents one of two values: True or False.

Example:

is_valid = True
print(type(is_valid)) # <class 'bool'>

OPERATIONS:

print(x and y) # False


print(x or y) # True
print(not x) # False
print(5 > 3) # True
print(2 == 2) # True
print(3 != 4) # True

DATA TYPE CONVERSION:


DEFINITION:
In programming, type conversion is the process of converting data of one type to
another. For example: converting int data to str.

There are two types of type conversion in Python.

 Implicit Conversion - automatic type conversion


 Explicit Conversion - manual type conversion

Python Implicit Type Conversion


In certain situations, Python automatically converts one data type to another.
This is known as implicit type conversion.
Example 1: Converting integer to float
Let's see an example where Python promotes the conversion of the lower
data type (integer) to the higher data type (float) to avoid data loss.

In the above example, we have created two


variables: integer_number and float_number of int and float type
respectively.

Then we added these two variables and stored the result in new_number .

EXAMPLE:

integer_number = 123

float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type

print("Value:",new_number)

print("Data Type:",type(new_number))

OUTPUT:

Value: 124.23

Data Type: <class 'float'>

In the above example, we have created two


variables: integer_number and float_number of int and float type
respectively.

Then we added these two variables and stored the result in new_number .
Explicit Type Conversion
In Explicit Type Conversion, users convert the data type of an object to
required data type.

We use the built-in functions like int(), float(), str(), etc to perform explicit type
conversion.

This type of conversion is also called typecasting because the user casts
(changes) the data type of the objects.

Example 2: Addition of string and integer


Using Explicit Conversion
num_string = '12'

num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion

num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)

print("Data type of num_sum:",type(num_sum))


OUTPUT:

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>

Sum: 35

Data type of num_sum: <class 'int'>

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.

Control Flow in python:


Conditional statements in Python are used to execute certain blocks of code based
on specific conditions. These statements help control the flow of a program,
making it behave differently in different situations.

If Conditional Statement

If statement is the simplest form of a conditional statement. It executes a block of


code if the given condition is true.
Example:
age = 20
if age >= 18:
print("Eligible to vote.")
Output:

Eligible to vote.

If else Conditional Statement

If Else allows us to specify a block of code that will execute if the condition(s)
associated with an if or elif statement evaluates to False. Else block provides a
way to handle all other cases that don't meet the specified conditions.

Example:
age = 10
if age <= 12:

print("Travel for free.")

else:

print("Pay for ticket.")

Output
Travel for free.

elif Statement

elif statement in Python stands for "else if." It allows us to check multiple
conditions, providing a way to execute different blocks of code based on which
condition is true. Using elif statements makes our code more readable and
efficient by eliminating the need for multiple nested if statements.

Example:

age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Output
Young adult.

The code checks the value of age using if-elif-else. Since age is 25, it skips the
first two conditions (age <= 12 and age <= 19), and the third condition (age <=
35) is True, so it prints "Young adult.".

Nested if..else Conditional Statement

Nested if..else means an if-else statement inside another if statement. We can use
nested if statements to check conditions within conditions.

Example:
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output

30% senior discount!

Ternary Conditional Statement


A ternary conditional statement is a compact way to write an if-else condition in a
single line. It’s sometimes called a "conditional expression."
Example:
# Assign a value based on a condition
age = 20
s = "Adult" if age >= 18 else "Minor"
print(s)

Output
Adult
Here:
 If age >= 18 is True, status is assigned "Adult".
 Otherwise, status is assigned "Minor".

Match-Case Statement
match-case statement is Python's version of a switch-case found in other
languages. It allows us to match a variable's value against a set of patterns.
Example:
number = 2

match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")
Output:
Two or Three

Loops in Python
Loops in Python are used to repeat actions efficiently. The main types are For loops
(counting through items) and While loops (based on conditions).

For Loop
For loops is used to iterate over a sequence such as a list, tuple, string or range. It
allow to execute a block of code repeatedly, once for each item in the sequenc e
Example:
n = 4

for i in range(0, n):

print(i)

Output
0
1
2
3
Explanation: This code prints the numbers from 0 to 3 (inclusive) using a for
loop that iterates over a range from 0 to n-1 (where n = 4).
Example:
li = ["geeks", "for", "geeks"]
for x in li:
print(x)
tup = ("geeks", "for", "geeks")
for x in tup:
print(x)
s = "abc"
for x in s:
print(x)
d = dict({'x':123, 'y':354})
for x in d:
print("%s %d" % (x, d[x]))
Iterating by Index of Sequences

We can also use the index of elements in the sequence to iterate. The key idea is
to first calculate the length of the list and then iterate over the sequence within the
range of this length.
li = ["geeks", "for", "geeks"]
for index in range(len(li)):
print(li[index])

Output
geeks
for
geeks
Explanation: This code iterates through each element of the list using its index
and prints each element one by one. The range(len(list)) generates indices from 0
to the length of the list minus 1.

While Loop
In Python, a while loop is used to execute a block of statements repeatedly until a
given condition is satisfied. When the condition becomes false, the line
immediately after the loop in the program is executed.
In below code, loop runs as long as the condition cnt < 3 is true. It increments the
counter by 1 on each iteration and prints "Hello Geek" three times.
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello Geek
set1 = {10, 30, 20}
for x in set1:
print(x),
Output:
geeks
for
geeks
geeks
for
geeks
a
b
c
x 123
y 354
10
20
30

Nested Loops
Python programming language allows to use one loop inside another loop which
is called nested loop. Following example illustrates the concept.
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
22
333
4444
Explanation: In the above code we use nested loops to print the value of i
multiple times in each row, where the number of times it prints i increases with
each iteration of the outer loop. The print() function prints the value of i and
moves to the next line after each row.
A final note on loop nesting is that we can put any type of loop inside of any
other type of loops in Python. For example, a for loop can be inside a while loop
or vice versa.

Loop Control Statements


Loop control statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed. Python supports the following control statements.

Continue Statement

The continue statement in Python returns the control to the beginning of the loop.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Explanation: The continue statement is used to skip the current iteration of a
loop and move to the next iteration. It is useful when we want to bypass certain
conditions without terminating the loop.
Break Statement
The break statement in Python brings control out of the loop.
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
break

print('Current Letter :', letter)

Output
Current Letter : e
Explanation: break statement is used to exit the loop prematurely when a
specified condition is met. In this example, the loop breaks when the letter is
either 'e' or 's', stopping further iteration.

Pass Statement

We use pass statement in Python to write empty loops. Pass is also used for
empty control statements, functions and classes.
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Output
Last Letter : s
Explanation: In this example, the loop iterates over each letter in 'geeksforgeeks'
but doesn't perform any operation, and after the loop finishes, the last letter ('s') is
printed.

You might also like