[Go to site: main page, start]

0% found this document useful (0 votes)
12 views13 pages

Python Programming Basics Overview

This document provides an overview of Python programming basics, covering its features, data types, variables, input operations, comments, reserved words, indentation, operators, and functions. It explains the concept of literal constants, identifiers, and how to handle user input, along with best practices for comments and indentation. Additionally, it discusses various Python constructs such as loops, conditional statements, and modules.

Uploaded by

soumya.mohapatra
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)
12 views13 pages

Python Programming Basics Overview

This document provides an overview of Python programming basics, covering its features, data types, variables, input operations, comments, reserved words, indentation, operators, and functions. It explains the concept of literal constants, identifiers, and how to handle user input, along with best practices for comments and indentation. Additionally, it discusses various Python constructs such as loops, conditional statements, and modules.

Uploaded by

soumya.mohapatra
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 Basics - Brief

Notes
1. Features and History of Python
• Created by Guido van Rossum, first released in 1991.

• Interpreted, dynamically typed, and open-source.

• Easy syntax, large standard library, and supports multiple paradigms.

2. Literal Constants
🔹 Literal Constants in Python

A literal constant is a fixed value that appears directly in the source code. These are the
values that do not change during program execution. Python supports several types of
literal constants:

🔸 Types of Literal Constants:

1. Numeric Literals

 Represent numbers and are of types:


o int (e.g., 10, -25)
o float (e.g., 3.14, -0.001)
o complex (e.g., 3+5j)

Example:

x = 100 # Integer literal


y = 3.14 # Float literal
z = 2 + 3j # Complex literal

2. String Literals

 Sequence of characters enclosed in:


o single quotes '...'
o double quotes "..."
o triple quotes '''...''' or """...""" for multi-line
Example:

name = "Alice"
text = '''This is
a multi-line
string.'''

3. Boolean Literals

 Represents truth values:


o True
o False

Example:

flag = True
is_equal = (5 == 5) # Returns True

4. Special Literal: None

 Used to denote absence of a value or null value.

Example:

result = None

5. Literal Collections

While not constants in strict sense, you can have literals for:

 List: [1, 2, 3]
 Tuple: (1, 2, 3)
 Set: {1, 2, 3}
 Dict: {'a': 1, 'b': 2}
🔸 Summary Table:
Type Example Description

Integer 42, -7 Whole numbers

Float 3.14, -0.5 Decimal numbers

String "hello" Sequence of characters

Boolean True, False Logical values

None None Absence of value

3. Variables and Identifiers


Variables store data. Identifiers must start with a letter or underscore and are case-
sensitive.

Variables:

A variable in Python is a name used to store data that can change during program
execution. You don't need to declare its type explicitly — Python automatically
determines the type based on the assigned value.

Example:

name = "Alice" # String


age = 25 # Integer
price = 10.5 # Float

 Variables act as containers for data values.


 The type of the variable can change dynamically:

x = 10 # Initially an integer
x = "Ten" # Now it's a string

🔸 Identifiers:

Identifiers are the names used to identify variables, functions, classes, modules, etc.

Rules for Identifiers:

1. Must begin with a letter (A–Z or a–z) or an underscore (_)


2. Can be followed by letters, digits (0–9), or underscores.
3. Case-sensitive: Age and age are different.
4. Cannot use Python keywords (e.g., if, def, while) as identifiers.

Valid Identifiers:

my_var = 10
_name = "Soumya"
marks123 = 95

Invalid Identifiers:

2name = "John" # Starts with digit → ❌


my-name = "John" # Contains hyphen → ❌
for = 5 # Uses keyword → ❌

✅ In Summary:

 Variable: A named reference to a value.


 Identifier: The name you give to variables, functions, etc., following naming
rules.
 Python is dynamically typed, so variable types are inferred at runtime.

4. Data Types

In Python, data types define the kind of value a variable can hold. Python is
dynamically typed, so the type is inferred automatically based on the value assigned.

🔸 1. Numeric Types
Type Description Example

int Integer numbers a = 10

float Decimal numbers b = 3.14

complex Complex numbers c = 2 + 3j


🔸 2. Sequence Types
Type Description Example

str String of characters name = "Python"

list Ordered, mutable collection nums = [1, 2, 3]

tuple Ordered, immutable collection t = (1, 2, 3)

🔸 3. Set Types
Type Description Example

set Unordered, no duplicates s = {1, 2, 3}

frozenset Immutable set fs = frozenset([1, 2, 3])

🔸 4. Mapping Type
Type Description Example

dict Key-value pairs d = {'name': 'Alice', 'age': 25}

🔸 5. Boolean Type
Type Description Example

bool Logical values flag = True

🔸 6. Binary Types
Type Description Example

bytes Immutable byte sequence b = b'hello'

bytearray Mutable byte sequence ba = bytearray(b'hello')

memoryview View object on byte data mv = memoryview(b'abc')


🔸 7. None Type
Type Description Example

None Represents no value/null x = None

✅ Summary Table:
Type Category Types

Numeric int, float, complex

Sequence str, list, tuple

Set set, frozenset

Mapping dict

Boolean bool

Binary bytes, bytearray, memoryview

Special NoneType

5. Input Operations

In Python, input operations are used to take user input from the keyboard during
program execution.

🔸 Using input() Function

 input() reads a line of text as a string.


 You can convert the input to other data types using typecasting.

✅ Syntax:

variable = input("Prompt message")

🔸 Examples:

1. Basic String Input


name = input("Enter your name: ")
print("Hello", name)
2. Integer Input
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)

3. Float Input
price = float(input("Enter price: "))
print("Price with tax:", price * 1.18)

🔸 Multiple Inputs (Using split())


x, y = input("Enter two numbers: ").split()
print("Sum:", int(x) + int(y))

🔸 Using eval() for Expression Input


expr = input("Enter a math expression: ") # e.g., 3 + 4
result = eval(expr)
print("Result =", result)

⚠️Use eval() carefully as it executes arbitrary code.

✅ Summary:

 input() always returns a string.


 Use int(), float() etc. for type conversion.
 Use split() to take multiple inputs.

6. Comments

Comments are lines in the code that are not executed by Python. They are used to:

 Explain the logic of code


 Improve readability
 Disable code temporarily during debugging

🔸 Types of Comments

✅ 1. Single-line Comment

 Begins with a # symbol.


 Everything after # on that line is ignored by the interpreter.

Example:
# This is a single-line comment
print("Hello") # This prints a greeting

✅ 2. Multi-line Comment

Python does not have a dedicated multi-line comment syntax, but triple quotes ''' or """
can be used as docstrings or informal block comments.

Example:

'''
This is a multi-line comment
used to describe the code block
'''
print("Python")

🔸 Note: Technically, triple-quoted strings are not real comments — they are string
literals not assigned to a variable. Python ignores them if not used as docstrings.

🔸 Best Practices:

 Use comments to explain why, not what.


 Keep comments concise and relevant.
 Update comments as code changes.

✅ Summary:
Type Syntax Example

Single-line # # This is a comment

Multi-line '''...''' or """...""" ''' Multi-line comment '''

7. Reserved Words

Keywords like: if, else, while, for, def, return, lambda, try, import, etc.

Reserved words, also called keywords, are special words that are predefined in Python
and cannot be used as identifiers (variable names, function names, etc.). These words
have special meanings and are used to define the syntax and structure of Python
programs.
🔸 Examples of Python Keywords:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

🔹 Total: 35 keywords in Python 3.x (as of latest versions)

🔸 Using the keyword Module

You can list all keywords in your version of Python using:

import keyword
print([Link])

🔸 Examples in Code:
# Correct usage
if True:
print("This is true")

# Incorrect usage: using a keyword as a variable


# def = 5 ❌ SyntaxError

✅ Summary:
Feature Description

What are they? Predefined, reserved words in Python

Can you use them? ❌ Cannot be used as variable or function names

How to list? Use import keyword; print([Link])

8. Indentation
Used to define blocks of code.

Example:

if True:
print('Yes')
Indentation refers to the spaces or tabs used at the beginning of a line to define the
structure and hierarchy of code blocks in Python.

🔸 Why Indentation is Important:

 Unlike other languages (like C, Java, etc.), Python uses indentation to define
blocks of code instead of braces {}.
 Consistent indentation is required, or Python will raise an IndentationError.

🔸 Basic Example:
if True:
print("This is indented") # Inside the if-block
print("This is outside") # Outside the block

🔸 Incorrect Indentation (Error):


if True:
print("Hello") # ❌ IndentationError: expected an indented block

🔸 Loops and Functions with Indentation:


def greet(name):
print("Hello", name) # Indented inside function

for i in range(3):
print(i) # Inside for-loop

🔸 Best Practices:

 Use 4 spaces per indentation level (PEP 8 recommendation).


 Do not mix tabs and spaces in the same file.

✅ Summary:
Feature Description

Purpose Defines code blocks

Required? ✅ Yes, mandatory in Python

Common Standard 4 spaces per indentation level


Feature Description

Error if misused IndentationError or unexpected behavior

9. Operators and Expressions


• Arithmetic: +, -, *, /, %, **, //

• Comparison: ==, !=, <, >, <=, >=

• Logical: and, or, not

• Bitwise: &, |, ^, ~

• Membership: in, not in

• Identity: is, is not

10. Operations on Strings


s = 'Python'

print([Link]()), print(s[0:3]), print(len(s))

11. Other Data Types


• List: [1, 2, 3]

• Tuple: (1, 2, 3)

• Set: {1, 2, 3}

• Dictionary: {'a': 1, 'b': 2}

12. Conditional Branching Statements


if condition:
...
elif condition:
...
else:
...
13. Loop Structures
• for i in range(5): ...

• while condition: ...

14. Break, Continue, Pass, Else in Loops


for i in range(5):
if i == 2: break
elif i == 1: continue
else: pass
else:
print('Done')

15. Functions
def greet(name):
return 'Hello ' + name

print(greet('Soumya'))

16. Variable Scope and Lifetime


• Local: Inside function
• Global: Outside all functions
• Nonlocal: In nested functions

17. Return Statement


def add(x, y):
return x + y

18. More on Defining Functions


def greet(name='Guest'):
print('Hello', name)

def func(*args, **kwargs):


pass

19. Lambda Functions


add = lambda x, y: x + y
print(add(2, 3))
20. Recursive Functions
def fact(n):
if n==0: return 1
return n * fact(n-1)

21. Modules and Packages


import math
print([Link](16))

Packages are collections of modules with __init__.py

22. globals(), locals(), reload()


globals(): returns global scope
locals(): returns local scope

reload(): reload a module (use from importlib import reload)

Common questions

Powered by AI

Python's reserved words (keywords) like `if`, `else`, `while`, and `def` are essential elements of the language syntax and cannot be used as identifiers for variables or function names . This constraint ensures clarity and prevents conflicts within the execution of Python code. Developers must avoid these keywords in naming conventions and can instead choose descriptive identifiers that follow Python's rules: starting with a letter or underscore, may include numbers, and are case-sensitive. By using meaningful names and adhering to these rules, developers can maintain code readability and functionality without conflicts .

Indentation in Python defines blocks of code, serving as a structural guide in place of braces used in other languages like C or Java . Correct indentation is crucial as inconsistent indentation leads to IndentationError and potentially unexpected behaviors in the program . Consistent use of four spaces (as per PEP 8 guidelines) is recommended to avoid these issues. Incorrect indentation can cause logic errors or crashes, making it essential for maintaining readable and error-free code .

Python's type system is dynamic, meaning that the type of a variable is determined at runtime, based on the value assigned to it . This contrasts with statically typed languages where the type must be explicitly declared at compile-time. Advantages of Python's approach include increased flexibility and faster prototyping since developers don't need to specify types and can change variable types easily. However, it can lead to runtime errors if not carefully managed .

Python's literal constants, such as integers, strings, boolean values, and special use literals like `None`, enhance code readability by providing clear and unchanging representations of data . For instance, using `True` and `False` as boolean literals makes conditional logic easier to understand. Numerical literals like `42` or `3.14` prevent confusion about number types during operations. Special literals like `None` signal a clear absence of value or placeholder in data structures . These literals, therefore, make code more readable and reduce errors by maintaining consistent value representation throughout execution .

Comments in Python, marked by the `#` symbol, serve as documentation tools for explaining code logic, enhancing readability, and aiding in debugging by allowing sections to be disabled temporarily . They are not executed by the interpreter, unlike triple-quoted strings, which are considered string literals. Although triple-quoted strings can be used for documentation purposes as informal block comments or docstrings, they occupy memory as part of the bytecode unless explicitly assigned for documentation strings (docstrings). Comments help maintain code clarity without adding runtime overhead, whereas triple-quoted strings are intended for more formal documentation within classes and function definitions .

Python accommodates different data through its various data types, including numeric (int, float, complex), sequence (str, list, tuple), set (set, frozenset), mapping (dict), and others specifically including `None` . Mutable types, such as lists and dictionaries, allow changes after creation, enable dynamic data structures, but also introduce complexity regarding changes and concurrent modifications. Immutable types, like strings and tuples, preserve data integrity, leading to safer operations in multi-threaded environments as they cannot be altered. The choice between mutable and immutable types affects performance, memory usage, and the predictability of data structures in Python programs .

Lists in Python are mutable, meaning they can be changed after creation, allowing item additions, removals, and updates. This flexibility makes lists suitable for collections where data changes frequently . Conversely, tuples are immutable; once defined, their values cannot change, so they are often used for fixed data collections or as keys in dictionaries where immutability is required . The choice between lists and tuples affects performance, with tuples generally having faster access times and lower memory usage due to their immutability, influencing decisions in high-performance and memory-sensitive applications .

Python's handling of variables supports polymorphism inherently due to its dynamic typing system, where the type of a variable is determined at runtime . For example, a variable declared as `x = 10` starts as an integer, but if reassigned as `x = 'Ten'`, Python treats it as a string without explicit type conversion . This allows the same operation or function to act on different types as long as the operation is supported by those types, leveraging polymorphic behavior where functions can process data irrespective of its form, thus enhancing flexibility and code reusability .

In a scenario where a program requires users to input a variety of data types, combining input methods like `input()`, `split()`, and typecasting functions can optimize user interaction. For example, a program might ask the user to enter their name, age, and favorite numbers all in one go. Using `name, age, *numbers = input("Enter your name, age, and favorite numbers: ").split()`, the inputs can be processed simultaneously, with `age` converted to an integer and numbers converted to a list of integers using `map(int, numbers)`. This approach minimizes code and simplifies the input process .

The `eval()` function executes expressions passed as strings which can be useful for evaluating mathematical expressions dynamically input by users . Benefits include its ability to handle complex expressions and convert them directly from strings to evaluated results without additional parsing. However, the primary risk is that it can execute arbitrary and potentially harmful code if not controlled properly, as it operates with the same permissions as the executing script. This makes security a significant concern when using `eval()` in a program .

You might also like