0% found this document useful (0 votes)
44 views14 pages

Py Unit1

Uploaded by

ggowtham92089
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)
44 views14 pages

Py Unit1

Uploaded by

ggowtham92089
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
You are on page 1/ 14

PYTHON UNIT-1 Subject code: 23UCS31

Basics of Python Programming: History of Python-Features of Python-Literal-


Constants-Variables - Identifiers–Keywords-Built-in Data Types-Output
Statements – Input Statements-Comments – Indentation- Operators-
Expressions-Type conversions.
Python Arrays: Defining and Processing Arrays – Array methods.

History of Python:

1.Creation: Developed by Guido van Rossum in the late 1980s; first released in
1991.

2. Name Origin: Named after the comedy series "Monty Python's Flying
Circus."

3. Python 2.0: Released in 2000; introduced features like list comprehensions


and garbage collection.

4.Python 3.0: Launched in 2008; a major update that improved consistency but
was not backward compatible with Python 2.

5. Community Growth: A strong community has contributed libraries and


frameworks, enhancing Python's capabilities.

6. Current Status: Python continues to evolve, with ongoing updates; Python 3.x
is the standard version today.
Features of Python:

1. Easy Syntax: Readable and straightforward syntax makes it beginner-


friendly.

2. Interpreted Language: Executes code line by line, facilitating debugging and


development.

3. Dynamic Typing: No need for variable declarations; types are determined at


runtime.

4. Rich Standard Library: Extensive built-in modules for various tasks.

5. Cross-Platform: Runs on multiple operating systems without modification.

6. Object-Oriented: Supports OOP principles like inheritance and encapsulation.

7. Extensive Libraries: A vast ecosystem of libraries and frameworks for diverse


applications.

8. Community Support: A large, active community provides resources and


support.

9. Multiple Paradigms: Supports procedural, object-oriented, and functional


programming.

10. Integration Capabilities: Easily integrates with other languages and tools.
Literal:

1. String Literals: Text values, defined with quotes.


- Example: 'Hello'

2. Numeric Literals: Numbers, either integers or floats.


- Example: 42, 3.14

3. Boolean Literals: Truth values, either `True` or `False`.

4. List Literals: Ordered collections in square brackets.


- Example: [1, 2, 3]

5. Tuple Literals: Immutable ordered collections in parentheses.


- Example: (1, 2, 3)

6. Dictionary Literals: Key-value pairs in curly braces.


- Example: {'name': 'Alice'}

7. Set Literals: Unordered unique items in curly braces.


- Example: {1, 2, 3}
Constants:

1. Naming Convention: Constants are typically written in uppercase with


underscores
(e.g., PI = 3.14).

2. No Built-in Type: Python does not enforce constants; they are regular
variables meant to remain unchanged.

Example:
PI = 3.14159
MAX_USERS = 50

Variables:

What is a Variable?
A variable is a named storage location in memory that holds a value. You can
change the value stored in a variable throughout your program.

1. Declaration: You create a variable by assigning a value using the equals sign
(`=`).
- Example: age = 25

2. No Explicit Type: Python is dynamically typed, so you don’t need to declare


the type of a variable.
- Example: name = "Alice" (string) and height = 5.7 (float)
3. Naming Rules:
- Must start with a letter or underscore (`_`).
- Can contain letters, numbers, and underscores.
- Cannot contain spaces or special characters (like `@`, `#`, etc.).

4. Case Sensitivity: Variable names are case-sensitive. For example, `age` and
`Age` are different variables.

5. Reassignment: You can change the value of a variable at any time.


- Example:
python
age = 25
age = 30 # Now age is 30

Identifier:

What is an Identifier?

An identifier is a name used to identify a variable, function, class, module, or


other objects in Python.

- Naming Rules:
- Must start with a letter or underscore (`_`).
- Can include letters, numbers, and underscores.
- Cannot start with a number or contain spaces/special characters.

- Case Sensitivity: Identifiers are case-sensitive (e.g., `var` ≠ `Var`).

- Reserved Keywords: Cannot use Python's keywords (like `if`, `for`).


- Conventions: Use descriptive names; variables in lowercase, classes in
CamelCase.

Example:
user_name = "Alice" # Valid
1st_number = 10 # Invalid (starts with a number)

Keywords:

- Definition: Reserved words that have special meaning in Python and cannot be
used as identifiers (variable names, function names, etc.).

- Characteristics:
- Keywords are case-sensitive (e.g., if is different from IF).
- Used to define the syntax and structure of the Python language.

- Common Keywords:
- Control Flow: if, else, elif, for, while
- Function Definition: def`, return
- Data Types: True, False,None
- Exception Handling: try, except, finally
- Class Definition: class

- Total Count: There are 35 keywords in Python 3.x (e.g., `import`, `in`, `is`,
`with`).
Example:
if condition:
print("Hello") # 'if' is a keyword

Built-in Data Types:

1. Numeric Types:
o int: Integer values (e.g., 42)
o float: Floating-point values (e.g., 3.14)
o complex: Complex numbers (e.g., 1 + 2j)

2. Sequence Types:
o str: String (e.g., "Hello")
o list: Ordered, mutable collection (e.g., [1, 2, 3])
o tuple: Ordered, immutable collection (e.g., (1, 2, 3))

3. Mapping Type:
o dict: Key-value pairs (e.g., {"name": "Alice", "age": 25})

4. Set Types:
o set: Unordered collection of unique items (e.g., {1, 2, 3})
o frozenset: Immutable version of a set (e.g., frozenset([1, 2, 3]))

5. Boolean Type:
o bool: Represents truth values (True or False)

6. None Type:
o NoneType: Represents the absence of a value (e.g., None)

Output Statements – Input Statements:

Output Statements

1. print() Function: Used to display output to the console.


o Example:

print("Hello, World!")
print("The answer is:", 42)

2. Formatted Output: You can format strings using f-strings (Python 3.6+)
or the format() method.
o Example with f-strings:

name = "Alice"
age = 30
print(f"{name} is {age} years old.")

Input Statements

1. input() Function: Used to take user input from the console. Returns the
input as a string.
o Example:

user_name = input("Enter your name: ")


print(f"Hello, {user_name}!")

2. Type Conversion: Since input() returns a string, you may need to convert
it to other data types.
o Example:

age = int(input("Enter your age: ")) # Convert to integer

Comments:

- Single-Line Comments: Start with #. Used for brief explanations.

- Example: # This is a comment

- Multi-Line Comments: Use triple quotes (''' or """) for longer comments.

- Example:

"""
This is a multi-line comment.

It can span multiple lines.

"""

Indentation:

- Purpose: Indentation is crucial in Python, as it defines the structure and scope


of code blocks (e.g., loops, functions, conditionals).

- Conventions: Use four spaces per indentation level (no tabs). Inconsistent
indentation can lead to errors.

Operators:

1. Arithmetic Operators

Perform basic mathematical operations:

 + : Addition
 - : Subtraction
 * : Multiplication
 / : Division (returns float)
 // : Floor Division (returns integer)
 % : Modulus (remainder)
 ** : Exponentiation

2. Comparison Operators

Compare values and return Boolean results:

 == : Equal to
 != : Not equal to
 < : Less than
 > : Greater than
 <= : Less than or equal to
 >= : Greater than or equal to

3. Logical Operators
Combine Boolean expressions:

 and : True if both expressions are true


 or : True if at least one expression is true
 not : Inverts the Boolean value

4. Assignment Operators

Assign values to variables:

 = : Simple assignment
 += : Add and assign
 -= : Subtract and assign
 *= : Multiply and assign
 /= : Divide and assign
 %= : Modulus and assign

5. Bitwise Operators

Operate on binary representations of integers:

 & : Bitwise AND


 | : Bitwise OR
 ^ : Bitwise XOR
 ~ : Bitwise NOT
 << : Left Shift
 >> : Right Shift

6. Identity Operators

Check if two variables refer to the same object:

 is : Returns True if both variables point to the same object


 is not : Returns True if both variables do not point to the same object

7. Membership Operators

Test for membership in a sequence (like lists, strings, tuples):


 in : Returns True if a value is found in the sequence
 not in : Returns True if a value is not found in the sequence

Expression:

What is an Expression?

An expression is a combination of values, variables, operators, and function


calls that can be evaluated to produce a value.

Types of Expressions

1. Arithmetic Expressions: Use arithmetic operators to compute numeric


values.
o Example: result = 3 + 5 * 2 (evaluates to 13)

2. Comparison Expressions: Compare values and return Boolean results.


o Example: is_equal = (10 == 10) (evaluates to True)

3. Logical Expressions: Combine Boolean values using logical operators.


o Example: is_valid = (True and False) (evaluates to False)

4. String Expressions: Combine or manipulate strings.


o Example: full_name = "John" + " " + "Doe" (evaluates to "John
Doe")

5. List Expressions: Create or manipulate lists.


o Example: squared_numbers = [x**2 for x in range(5)] (evaluates to
[0, 1, 4, 9, 16])

Type Conversions:

1. Implicit Conversion (Automatic):


o Python automatically converts one data type to another when
needed.
o Example:

x = 10 # int
y = 3.5 # float
result = x + y # x is converted to float

2. Explicit Conversion (Manual):


o You can manually convert one data type to another using built-in
functions.
o int(): Converts a value to an integer.
 Example: int(3.7) → 3

o float(): Converts a value to a float.


 Example: float(5) → 5.0

o str(): Converts a value to a string.


 Example: str(100) → "100"

o list(): Converts a string or other iterable to a list.


 Example: list("hello") → ['h', 'e', 'l', 'l', 'o']

o tuple(): Converts a list or other iterable to a tuple.


 Example: tuple([1, 2, 3]) → (1, 2, 3)

o set(): Converts a list or other iterable to a set (removing


duplicates).
 Example: set([1, 2, 2, 3]) → {1, 2, 3}

Python Arrays: Defining and Processing Arrays – Array methods:

Python Arrays:

In Python, arrays are typically handled using the array module or NumPy, a
popular library for numerical computations. Here’s how to work with both:

Using the array Module:

1. Defining an Array:
- Import the array module and create an array.

- Syntax: array(typecode, [initializer])

- Example:

from array import array

arr = array('i', [1, 2, 3, 4]) # i indicates an array of integers

2. Processing Arrays:

- Access elements using indexing (zero-based).

- Example:

print(arr[0]) # Output: 1

Common Array Methods:

- append(value): Adds a new element at the end of the array.

arr.append(5)

- insert(index, value): Inserts a new element at a specified index.

arr.insert(2, 10) # Inserts 10 at index 2

- remove(value): Removes the first occurrence of a value.

arr.remove(2)

- pop(index): Removes and returns the element at the specified index.

last_element = arr.pop() # Removes the last element

- extend(iterable): Adds elements from an iterable (like a list) to the end of the
array.

arr.extend([6, 7])
- index(value): Returns the index of the first occurrence of a value.

index_of_3 = arr.index(3)

- reverse(): Reverses the order of the elements in the array.

arr.reverse()

- sort(): Sorts the elements of the array in ascending order.

arr.sort()

Using NumPy Array:

For more advanced array handling, NumPy is the go-to library:

1. Defining a NumPy Array:

- Import NumPy and create an array.

- Example:

import numpy as np

np_arr = np.array([1, 2, 3, 4])

2. Processing NumPy Arrays:

- Similar operations can be performed as with regular arrays, but NumPy


offers more functionality, including mathematical operations, slicing, and
reshaping.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy