0% found this document useful (0 votes)
8 views28 pages

Basic Python Language Introduction

This document provides an introduction to Python programming, covering its features, data types, and basic concepts such as variables and operators. Python is a high-level, easy-to-learn language that supports multiple programming paradigms and has a large ecosystem of libraries. It also explains type conversion, variable naming rules, and includes examples of common data types and operations.

Uploaded by

Jiya
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)
8 views28 pages

Basic Python Language Introduction

This document provides an introduction to Python programming, covering its features, data types, and basic concepts such as variables and operators. Python is a high-level, easy-to-learn language that supports multiple programming paradigms and has a large ecosystem of libraries. It also explains type conversion, variable naming rules, and includes examples of common data types and operations.

Uploaded by

Jiya
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

Beginner Notes: Introduction to Python Programming

1. What is Python?
● Python is a high-level programming language.
● It is used to build websites, apps, games, data science models, and more.
● Easy to learn, looks like English, and has simple rules.

2. Features of Python
Easy to Learn and Use

Python has a simple and readable syntax that makes it beginner-


friendly and easy to understand.

Interpreted Language

Python code is executed line by line, which makes debugging easier


and faster.

Dynamically Typed

You don’t need to declare variable types explicitly; Python figures it out
at runtime.

High-Level Language

Python abstracts many low-level details like memory management,


making coding easier.

Object-Oriented

Python supports Object-Oriented Programming (OOP) which allows the


creation and use of classes and objects.
Extensive Standard Library

Python comes with a vast library of modules and functions to handle


tasks like file I/O, system calls, internet protocols, and more.

Cross-Platform

Python runs on many operating systems like Windows, Linux, macOS,


etc., without requiring code changes.

Open Source

Python is free to use, modify, and distribute. It has a large, active


community that contributes to its development.

Portable

Python code written on one platform can run on any other platform with
a Python interpreter.

Supports Multiple Programming Paradigms

Python supports procedural, object-oriented, and functional


programming styles.

Automatic Memory Management

Python handles memory allocation and garbage collection


automatically.

Extensible and Embeddable


You can write some parts of your program in other languages like C or
C++ and embed Python code within those programs.

Large Ecosystem and Libraries

There are thousands of third-party libraries for web development, data


science, AI, machine learning, automation, and more.

3. Python Data Types (Values)


What is type() in Python?
● type() is a built-in function used to check the data type of a variable or
value.
● Example:
x =5

print(type(x)) # <class 'int'>

Do You Need to Write type() Everywhere?


● No! You only use type() when you want to check or confirm the data type.
● Python handles data types automatically.

Situation Should You Use type()?

Learning or debugging Yes

Checking type manually Yes

Writing regular code No

Performing calculations No

What are Data Types in Python?

In Python, data types define the kind of value a variable can hold. They help
the interpreter understand how the data will be used. Every value in Python
has a data type, and Python automatically assigns it based on the value
assigned to the variable.
Common Data Types in Python with Examples

Here are the most commonly used data types in Python:

1. Numeric Types

● int: Integer (whole numbers)

● float: Floating point (decimal numbers)

● complex: Complex numbers

python
CopyEdit
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex

2. Text Type

● str: String (sequence of characters)

python
CopyEdit
name = "Alice" # str
greeting = 'Hello, World!' # str

3. Boolean Type

● bool: Represents True or False

python
CopyEdit
is_active = True # bool
is_logged_in = False

4. Sequence Types

● list: Ordered, mutable collection

● tuple: Ordered, immutable collection

● range: Sequence of numbers

python
CopyEdit
fruits = ["apple", "banana", "cherry"] # list
coordinates = (10, 20) # tuple
numbers = range(1, 5) # range (1, 2, 3, 4)
5. Mapping Type

● dict: Collection of key-value pairs

python
CopyEdit
person = {
"name": "John",
"age": 30
} # dict

6. Set Types

● set: Unordered collection of unique items

● frozenset: Immutable version of set

python
CopyEdit
colors = {"red", "green", "blue"} # set
immutable_colors = frozenset(["red", "green", "blue"]) # frozenset
7. None Type

● NoneType: Represents the absence of a value

python
CopyEdit
result = None # NoneType

Summary Table:
Type Example Description
int 10 Integer number
float 3.14 Decimal number
complex 2 + 3j Complex number
str "Hello" Text/string
bool True, False Boolean values
list [1, 2, 3] Ordered, mutable sequence
tuple (1, 2, 3) Ordered, immutable
sequence
range range(5) Sequence of numbers
dict {"key": "value"} Key-value mapping
set {1, 2, 3} Unordered collection, no
duplicates
frozens frozenset([1, 2]) Immutable set
et
NoneTy None No value
pe

print(type(10)) # int

print(type(3.14)) # float

print(type("Hello")) # str

print(type(True)) # bool

print(type([1, 2])) # list

print(type((1, 2))) # tuple

print(type({"a": 1})) # dict

print(type({1, 2, 3})) # set

4. Variables in Python
● Variables store data like numbers or text.
● You don’t need to tell Python what type it is!
name="Alice"

age =25

5. Variable Names and Keywords


Rules for Variable Names
● Must start with a letter or _
● Cannot start with a number
● Cannot use Python keywords
● Are case-sensitive (Name and name are different)

Python Keywords
● Keywords are reserved words that have special meaning in Python.
● You cannot use them as variable names.

Here is a table of common Python keywords:

Keyword Meaning

False Boolean false value

True Boolean true value

None Represents no value

and Logical AND

or Logical OR

not Logical NOT

if Conditional statement

elif Else if condition

else Else condition


for Looping construct

while Looping while a condition is true

break Exit the loop

continue Skip to next iteration in loop

def Define a function

return Return value from function

import Import modules

from Import specific parts from module

as Give imported module an alias

class Define a class

pass Do nothing (empty block)

global Declare global variable

nonlocal Declare non-local variable

try Try block for error checking

except Handle error

finally Always execute block

assert Debug check

yield Return from generator

lambda Create anonymous function

del Delete variable or item

is Check object identity

in Check if value is in sequence

To see all current Python keywords:

import keyword

print(len([Link])) # Total number of keywords

print([Link]) # List of all keywords

As of Python 3.11, there are 35 keywords:

['False' 'None' 'True' 'and' 'as'

'assert' 'async' 'await' 'break' 'class' 'continue'

'def'

'del' 'elif' 'else' 'except' 'finally' 'for'

'from' 'global'

'if' 'import' 'in' 'is' 'lambda' 'nonlocal'

'not'
'or' 'pass' 'raise' 'return' 'try' 'while'

'with' 'yield']

Note: Keywords like async and await are used in advanced asynchronous programming and may not appear in beginner [Link] import
keyword print([Link])
False, True, None, and, or, not, if, elif, else,

for, while, break, continue, def, return,

import, from, as, global, nonlocal, try, except,

finally, class, pass, assert, yield, lambda, del, is, in

To view all keywords in your Python version:

import keyword

print([Link])

Rules for Naming Variables in Python

When you create variable names (identifiers), you must follow these rules:

1. Variable names can contain letters (a–z, A–Z), digits (0–9), and
underscores (_).

my_var = 10
user123 = "Alice"
_temp = 5

1. Variable names must start with a letter or an underscore, NOT a digit.

python

CopyEdit

age = 25 # Valid

_name = "Bob" # Valid


2nd_place = 2 # Invalid - starts with a digit

2. Variable names are case-sensitive.

var = 1

Var = 2
VAR = 3
# These are all different variables.

3. You cannot use Python keywords as variable names.

if = 5 # Invalid, 'if' is a keyword.


4. No spaces or special characters (like @, $, %, etc.) allowed in variable
names.

user_name = "Alice" # Valid

user-name = "Alice" # Invalid (hyphen not allowed)

5. Variable names should be meaningful and descriptive for better


readability.

python

CopyEdit

count = 10 # Good
c = 10 # Less descriptive

6. Type Conversion (Changing Type)


Type conversion means changing the data type of a value from one type to another.

Python does this in two ways:

1. Implicit Type Conversion


● Done automatically by Python.
● Happens when combining different data types in expressions.
● Python converts smaller type to a larger type to avoid data loss.
a =5# int

b =2.5# float

result = a + b # int is converted to float

print(result) # 7.5

print(type(result)) # <class 'float'>

2. Explicit Type Conversion (Type Casting)


● Done manually using built-in functions.
● You decide how to change the type.

Common Conversion Functions:


Function Converts to Example

int() Integer int("10") → 10

float() Floating point float("3.14") → 3.14

str() String str(123) → "123"

bool() Boolean bool(0) → False

list() List list("abc") → ['a', 'b', 'c']

tuple() Tuple tuple([1, 2]) → (1, 2)

set() Set set([1, 1, 2]) → {1, 2}

Examples:
x ="100"

print(int(x)) # 100

y =25

print(str(y)) # "25"
z =0

print(bool(z)) # False

Aspect Implicit Conversion Explicit Conversion


Who Python interpreter Programmer (manually)
performs it
How Automatically during Using conversion functions like int(),
operations float(), str(), etc.
Control No control by user Full control by user
Use case Mixed type operations When specific conversion is required
Example 5 + 3.2 → 5 converted int("123") converts string to int
to 5.0

Important Notes:
● Not all conversions are allowed.
● Some may raise errors if the format is wrong.
int("hello") # Error: invalid literal for int()

Summary:
Type Done by When Example

Implicit Python Automatically 5 + 2.5 → 7.5

Explicit Programmer Using functions int("5") → 5 python

int(“5”) # 5

float(“3.5”) # 3.5

str(100) # “100”

bool(1) # True

---
7. Operators and Operands

- **Operands**: The data or variables used in the operation.

- **Operators**: The symbol that performs an action.

1. Arithmetic Operators

Used to perform math operations:

| Operator | Description | Example | Result |

|----------|------------------|-------------|----------|

| `+` | Addition | `5 + 3` |8 |

| `-` | Subtraction | `5 - 2` |3 |

| `*` | Multiplication | `5 * 2` | 10 |

| `/` | Division | `6 / 2` | 3.0 |

| `//` | Floor Division | `7 // 2` | 3 |

| `%` | Modulus (remainder) | `7 % 2` | 1 |

| `**` | Exponentiation | `2 ** 3` | 8 |

EXAMPLE: 

# Arithmetic Operators Example

a = 15

b = 4

print("Addition (a + b) :", a + b) # 19

print("Subtraction (a - b) :", a - b) # 11

print("Multiplication (a * b) :", a * b) # 60

print("Division (a / b) :", a / b) # 3.75

print("Floor Division (a // b):", a // b) # 3

print("Modulus (a % b) :", a % b) # 3

print("Exponent (a ** b) :", a ** b) # 50625

2. Comparison Operators

Compare two values and return True or False:

| Operator | Description | Example | Result |

|----------|----------------|--------------|------------|

| `==` | Equal to | `5 == 5` | True |

| `!=` | Not equal to | `5 != 3` | True |


| `>` | Greater than | `5 > 2` | True |

| `<` | Less than | `5 < 2` | False |

| `>=` | Greater or equal | `5 >= 5` | True |

| `<=` | Less or equal | `5 <= 4` | False |

# Comparison Operators Example

a = 10

b = 5

print("a == b:", a == b) # False (10 is not equal to 5)

print("a != b:", a != b) # True (10 is not equal to 5)

print("a > b :", a > b) # True (10 is greater than 5)

print("a < b :", a < b) # False (10 is not less than 5)

print("a >= b:", a >= b) # True (10 is greater than or equal to 5)

print("a <= b:", a <= b) # False (10 is not less than or equal to 5)

Expressio Resu
n lt Explanation
Fals
a == b e Equal to
a != b True Not equal to
a > b True Greater than
Fals
a < b e Less than
Greater than or
a >= b True equal to
Fals
a <= b e Less than or equal to

3. Logical Operators

Used for combining conditions:


| Operator | Description | Example | Result |

|----------|--------------------|-------------------------|------------|

| `and` | True if both True | `True and False` | False |

| `or` | True if one is True| `True or False` | True |

| `not` | Reverses condition | `not True` | False |

# Logical Operators Example

x = True

y = False

print("x and y:", x and y) # False (both must be True)

print("x or y :", x or y) # True (only one needs to be True)

print("not x :", not x) # False (reverses x)

print("not y :", not y) # True (reverses y)

EXAMPLE 2 :

a = 10

b = 5

print((a > 5) and (b < 10)) # True and True → True

print((a < 5) or (b < 10)) # False or True → True

print(not (a == 10)) # not True → False

not
Operan Operand
Operand 1 and Or
d 2 1
False False False False True
False True False True True
True False False True False
True True True True False
4. Assignment Operators

Assign values to variables:

| Operator | Meaning | Example |

|----------|-------------------|-----------------|

| `=` | Assign | `a = 5` |

| `+=` | Add and assign | `a += 2` (a = a+2) |

| `-=` | Subtract and assign| `a -= 1` (a = a-1) |

| `*=` | Multiply and assign| `a *= 3` |

| `/=` | Divide and assign | `a /= 2` |

---

x = 10 # Assign value

x += 5 # x = x + 5 → 15

x -= 3 # x = x - 3 → 12

x *= 2 # x = x * 2 → 24

x /= 4 # x = x / 4 → 6.0

x %= 5 # x = x % 5 → 1.0

x **= 3 # x = x ** 3 → 1.0

x //= 2 # x = x // 2 → 0.0

8. Expressions

- **Expressions** are code that gives a value using variables, values, and operators.

```python

a = 10

b = 2

result = a + b * 3 

# 10 + (2*3) = 16

&, |, ~ → Bitwise Operators


● Used with integers (binary level)

● Operate on the bits of the numbers

Example:
a = 5# 0101 in binary
b = 3# 0011 in binary

print(a & b) # 0001 → 1 (bitwise AND)


print(a | b) # 0111 → 7 (bitwise OR)
print(~a) # Inverts all bits → -6 (in 2's complement form)
~B
A A& A^ ~A (Decima
B A | B
B B (Decimal) l)
0
0 0 0 0 -1 -1
0
1 0 1 1 -1 -2
1
0 0 1 1 -2 -1
1
1 1 1 0 -2 -2

Other Special Symbols

Symb
ol Use Example Purpose

# Comment # Hello Adds a comment


Starts an indented
: Block start if x > 0: block
Parenthese Group expressions or
() s print(5) functions
Square
[] brackets list[0] List or index

Curly
{} braces { "a": 1 } Dictionary or set

, Separator a, b = 1, 2 Separates values


Dot Access object
. operator [Link]() properties/methods
Quotation
' " marks "text" Define strings
Newline
\n escape print("A\nB") Moves to new line

9. Interactive Mode vs Script Mode


● Interactive Mode: Use Python shell to run one line at a time.
>>> print("Hello")

● Script Mode: Save your code in a .py file and run it.

Interactive Mode vs Script Mode in Python


Feature Interactive Mode Script Mode
How it Python code is executed line-by- Python code is written in a
works line immediately as you type file and executed all at once
Usage Mainly used for testing, Used to write complete
debugging, or learning programs or applications
Environmen Python interpreter prompt (>>>) Text editor or IDE to write .py
t files
Execution Code executed immediately Code executed after running
the script file
Saving Code is not saved automatically Code is saved in a .py file
Code
Output Output appears right after each Output appears after running
command the entire script

Examples
1. Interactive Mode

● You open a terminal or command prompt.


● Type python or python3 to enter interactive mode.

● You can type commands and see immediate results.

>>> print("Hello, Interactive Mode!")


Hello, Interactive Mode!
>>> 2 + 3
5
>>> for i in range(3):
... print(i)
...
0
1
2

2. Script Mode

● You write code in a file, e.g., [Link].

python
CopyEdit
# [Link]
print("Hello, Script Mode!")

for i in range(3):
print(i)

● Save the file and run it from the command line:

python [Link]

● Output:

Hello, Script Mode!


0
1
2

10. Order of Operations (PEMDAS)


Python follows math rules when solving expressions:

● P: Parentheses ()
● E: Exponent **
● MD: Multiplication/Division * /
● AS: Addition/Subtraction + -
x =5+2*3# 11

x = (5+2) *3# 21

Relationship Between Iterable, Iterator, and Iteration:

Term Meaning Example


Iterable

An object you can loop through

List, String, Tuple

Iterator
An object that produces items one at a time

Created using iter()


Iteration

The process of going through elements


Looping using for or next()

Analogy:
● Iterable = A playlist

● Iterator = The music player that plays one song at a time

● Iteration = The act of playing each song

Example:

nums = [1, 2, 3] # Iterable

it = iter(nums) # Iterator

print(next(it)) # Iteration: prints 1

print(next(it)) # prints 2

print(next(it)) # prints 3

nums is iterable

it is an iterator

next(it) performs iteration

Conditional Statements

Definition:
Conditional statements are used to make decisions in your code based on whether a condition is true or false.

Keywords:
● if

● if-else

● elif (Python) or else if (Java/C/C++)

When to Use:
Use conditional statements when you want to execute certain code only if specific conditions are met.

1. if Statement
Executes a block of code only if a specified condition is True.

Syntax:

if condition:

# Code block to execute if condition is True

Example: 

x = 10
if x > 5:
print("x is greater than 5")

2. if-else Statement
Executes one block if the condition is True, otherwise executes another block.

Syntax:

if condition:

# Code block to execute if condition is True

else:

# Code block to execute if condition is False

Example:

x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")

[Link]
In Python, elif is short for “else if”, and it is used to add multiple conditions in an if-else structure. It allows you to check multiple expressions for True and execute a block of
code as soon as one of the conditions evaluates to True. If none of the conditions are True, the else block (if present) is executed.

Syntax of if-elif-else
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
elif condition3:
# Code to execute if condition3 is True
else:
# Code to execute if none of the above conditions are True
How it Works
1. Python checks the first if condition:

o If True, its block runs and the rest are ignored.

o If False, Python moves to the next elif.

2. Each elif condition is checked in order.

3. If none of the if/elif conditions are True, the else block is executed (if present).

Example
x = 10

if x > 20:

print("x is greater than 20")

elif x > 15:

print("x is greater than 15 but less than or equal to 20")

elif x > 5:

print("x is greater than 5 but less than or equal to 15")

else:

print("x is less than or equal to 5")

Output:

x is greater than 5 but less than or equal to 15

Important Points about elif


● You can have multiple elif statements, but only one else block.

● elif can only appear after if.

● Once a condition is satisfied, Python does not check further conditions.

● You can write an if statement without else or elif.

Real-Life Example
marks = 85

if marks >= 90:


print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
Output: Grade: A
3. nested if-else Statement
An if or else block can contain another if-else.

Syntax: 

if condition1:

if condition2:

# Code block if both condition1 and condition2 are True

else:

# Code block if condition1 is True but condition2 is False

else:

# Code block if condition1 is False

Example: 

x = 7
if x > 0:
if x < 10:
print("x is between 1 and 9")
else:
print("x is 10 or more")
else:
print("x is 0 or negative")

Looping
Definition:
Looping is used to repeat a block of code multiple times, either for a fixed number of times (for loop) or while a condition is true (while loop).

Keywords:
● for

● while

● Nested loops

When to Use:
Use loops when you need to repeat actions, such as going through a list, running a calculation multiple times, etc.

1. for Loop
Used to iterate over a sequence (like list, range, string, etc.)

Syntax:

for variable in sequence:

# Code block to execute for each element in the sequence

Example:

for i in range(5):
print(i) # Prints 0 to 4
2. while Loop
Repeats a block of code as long as the condition is True.

Syntax:

while condition:

# Code block to execute as long as condition is True

Example:

i = 0
while i < 5:
print(i)
i += 1

3. Nested Loops
A nested loop means a loop inside another loop.

In this case:

● The outer loop (for i in range(3)) runs 3 times

● The inner loop (for j in range(2)) runs 2 times for each iteration of the outer loop

So, total iterations = 3 × 2 = 6 times

Step-by-Step Execution:
Outer loop: for i in range(3) → i = 0, 1, 2
Inner loop: for j in range(2) → j = 0, 1
Here’s how it runs:

Outer Loop (i) Inner Loop (j) Output

0 0 i=0, j=0

0 1 i=0, j=1

1 0 i=1, j=0

1 1 i=1, j=1

2 0 i=2, j=0

2 1 i=2, j=1
A loop inside another loop.

for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")

Control Statements
Definition:
Control statements change the flow of execution inside loops or conditionals — they are used to skip, stop, or pass certain parts of code.

Keywords:
● break → exit loop early

● continue → skip current iteration

● pass → do nothing (placeholder)

When to Use:
Use control statements inside loops or conditionals to fine-tune how they behave.

1. break (Terminating Loops)


Exits the current loop prematurely.

for i in range(10):
if i == 5:
break
print(i)

2. continue (Skipping Specific Conditions)


Skips the rest of the code inside the loop for the current iteration.

for i in range(5):
if i == 2:
continue
print(i) # Will skip printing 2

3. pass(Do Nothing)
A placeholder that does nothing. Often used where syntactically a statement is required but no action is needed.

Why Use pass?


You use pass when:

1. You're structuring your code, but haven't written the logic yet.

2. A statement is syntactically required, but no action is needed.

3. To define empty functions, classes, loops, or conditionals temporarily.

Examples
1. Empty Function:
def future_function():
pass # Function does nothing (yet)
2. Empty Class:
class Placeholder:
pass # No attributes or methods yet

3. Inside Loops or Conditionals:


for i in range(5):
if i == 3:
pass # Do nothing for i == 3
else:
print(i)

You might also like