0% found this document useful (0 votes)
10 views8 pages

Python Basics: Operators, Types, and Use

The document provides a comprehensive overview of Python basics, covering topics such as membership operators, complex numbers, data types, and key features of Python. It also discusses Python applications in web development, data science, and machine learning, along with installation steps for Python and Anaconda. Additionally, it includes examples of various operations, data structures, and functions in Python.

Uploaded by

byjuslearn874
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)
10 views8 pages

Python Basics: Operators, Types, and Use

The document provides a comprehensive overview of Python basics, covering topics such as membership operators, complex numbers, data types, and key features of Python. It also discusses Python applications in web development, data science, and machine learning, along with installation steps for Python and Anaconda. Additionally, it includes examples of various operations, data structures, and functions in Python.

Uploaded by

byjuslearn874
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

Python Basics Summary

1. Membership Operator

fruits = ['apple', 'banana']

print('banana' in fruits) # True

2. Complex Number

z = 3 + 4j

print([Link], [Link])

3. Arithmetic vs Relational Operators

# Arithmetic

print(5 + 2, 5 - 2, 5 * 2, 5 / 2)

# Relational

print(5 > 2, 5 == 2, 5 != 2)

4. Data Types & Conversions

a=5

b = float(a) # 5.0

c = str(a) # '5'

5. Python Applications

- Web: Flask, Django

- Data Science: pandas, numpy

- ML: scikit-learn

- Automation: scripts

6. Identity vs Membership vs Logical

x = [1, 2]

y=x
Python Basics Summary

print(x is y) # Identity

print(2 in x) # Membership

print(1 in x and 3 in x) # Logical

7. Python Applications

- Web apps

- Data analysis

8. What is Anaconda?

A Python distribution for data science. Comes with Jupyter, Spyder, etc.

9. Numeric Types

from fractions import Fraction

a=5 # int

b = 2.5 # float

c = 2 + 3j # complex

d = Fraction(1, 3) # fraction

10. Key Features of Python

- Easy syntax

- Portable

- Large libraries

- Used in web, data science, ML

11. Installation Steps

1. Python: Download from [Link], install.

2. Anaconda: Download from [Link], install.

3. Spyder: Open from Anaconda Navigator.


Python Basics Summary

12. Variables & Data Types

name = "Alice"

age = 25

print(type(name), type(age))

13. Spyder vs Other IDEs

- Scientific tools built-in

- Targeted for data science

14. Define Variable

x = 10

name = "John"

15. What is Python?

A high-level, readable language used for web, ML, data science.

16. Data Types Examples

x = 10 # int

y = 3.14 # float

s = "Hi" # str

l = [1, 2] # list

d = {"a": 1} # dict

17. Basic Operators

- Arithmetic: + - * / % // **

- Relational: == != > <

- Logical: and or not

- Membership: in, not in

- Identity: is, is not


Python Basics Summary

18. Numeric Types & Use

from decimal import Decimal

print(100) # int

print(3.14) # float

print(2 + 3j) # complex

print(Decimal('0.1')) # precise calc

1. Output of capitalize()

s = "123hello WORLD"

res = [Link]()

print(res)

# Output: "123hello world" (first letter capital, rest lowercase)

2. Output of addToList()

def addToList(a):

a += [10]

b = [10, 20, 30, 40]

addToList(b)

print(len(b))

# Output: 5 (list is modified in-place)

3. Sets: Advantages & Disadvantages

- Advantages:

* No duplicates

* Fast membership testing

* Useful for mathematical operations

- Disadvantages:

* Unordered

* Can't access items by index


Python Basics Summary

4. Bitwise Operation Code

# Check EVEN/ODD

n=5

if n & 1:

print('Odd')

else:

print('Even')

# Swap using XOR

a, b = 3, 4

a ^= b

b ^= a

a ^= b

print(a, b)

5. Symmetrical or Palindrome Check

# Slicing Method

s = 'madam'

print(s == s[::-1]) # Palindrome

# Naïve Method

for i in range(len(s)//2):

if s[i] != s[-(i+1)]:

print('Not Palindrome')

break

else:

print('Palindrome')

6. Casting a Variable

a = '5'
Python Basics Summary

b = int(a) # Now b is 5 (int)

7. Output of dict with duplicate keys

d = {'a': 1, 'b': 2, 'a': 3}

print(d)

# Output: {'a': 3, 'b': 2}

8. input() vs print()

- input(): Takes input from user

- print(): Displays output to user

9. String Checks

# a) Starts with vowel

s = 'apple'

print(s[0].lower() in 'aeiou')

# b) Contains word

word = 'world'

print('world' in 'Hello world')

10. List Method Differences

- append(): Adds one item

- extend(): Adds multiple items

- pop(): Removes by index

- remove(): Removes by value

- count(): Frequency

- index(): First index of value

11. Boolean Operators

a, b = True, False
Python Basics Summary

print(a or b) # True

print(a and b) # False

print(not a) # False

12. Type Casting

x = '123'

y = int(x) # y becomes 123

13. Duplicate of Q1

Same as Q1. Output: "123hello world"

14. type() Function

x = 10

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

15. List vs Tuple vs Set

- List: [1, 2], mutable

- Tuple: (1, 2), immutable

- Set: {1, 2}, unordered, unique

16. List Slicing

s = [1, 2, 3, 4, 5, 6]

print(s[::-1]) # [6, 5, 4, 3, 2, 1]

print(s[::2]) # [1, 3, 5]

print(s[::2][::-1]) # [5, 3, 1]

print(s[4:0:-1]) # [5, 4, 3, 2]

17. String vs List (Mutability)

s = 'hello'
Python Basics Summary

# s[0] = 'H' => Error (immutable)

l = ['h', 'e', 'l']

l[0] = 'H' # Works

18. Count Vowels and Consonants

s = 'Hello World'

v, c = 0, 0

for ch in [Link]():

if [Link]():

if ch in 'aeiou':

v += 1

else:

c += 1

print('Vowels:', v, 'Consonants:', c)

Common questions

Powered by AI

In Python, lists are mutable, allowing modification of elements, whereas tuples are immutable, providing data integrity and optimization for performance as they cannot be altered after creation. Sets, while unordered and unique, allow modification through addition or removal of elements. These characteristics influence their use; lists are suitable for dynamic data storage, tuples for constant collections to ensure data reliability and speed, and sets for scenarios requiring mathematical operations and uniqueness without duplicates .

Anaconda is a distribution tailored for data science, integrating with Python to streamline tasks through pre-packaged and optimized libraries such as pandas and numpy for data manipulation, and scikit-learn for machine learning. It includes IDEs like Jupyter Notebook and Spyder, which offer robust environments for coding, visualizations, and data exploration. This ecosystem accelerates setup and execution of data science workflows, promoting efficiency and integration .

Python uses the 'in' keyword to test for membership within data structures such as lists, tuples, and sets. This allows for concise and intuitive checks for the presence of elements. Additionally, sets offer fast membership testing due to their underlying hash table implementation, enhancing performance significantly over other data types where a linear search would be required .

String immutability in Python guarantees that once a string is created, its contents cannot be altered, improving memory efficiency and security, and ensuring reliable references. Conversely, lists, as mutable sequences, permit in-place modification, enabling dynamic data alterations. This distinction critically impacts performance and functionality; immutable strings foster consistent string management and caching, while mutable lists offer flexibility in data handling, key for operations like appending or removing elements dynamically .

Identity operators in Python, 'is' and 'is not', compare memory addresses to verify if two variables point to the same object, emphasizing object identity rather than value equivalence. Membership operators ('in', 'not in') check the presence of elements within iterable objects, focusing on containment, while logical operators ('and', 'or', 'not') evaluate expression truth values. These variations distinctly influence code design; identity operators ensure reference equality, critical in object management, while membership and logical operators manage data presence and expression evaluation, respectively .

Arithmetic operators in Python perform mathematical operations like addition and subtraction, fundamentally modifying numeric data values. In contrast, relational operators compare values, yielding boolean results which are crucial for control flow and logical decisions within Python programs. The ability to directly evaluate expressions using relational operators facilitates conditional logic implementation, essential in tasks requiring decision-making structures .

List slicing in Python provides a mechanism for extracting and manipulating sublists using a compact syntax that supports starting index, end index, and step parameters to define sequences. This flexible method allows for efficient data manipulation such as reversing lists, selecting every nth element, and subsetting data for statistical analysis. Advanced use cases include creating derived datasets for machine learning models and simplifying complex reshaping operations in data transformation processes .

Boolean operators ('and', 'or', 'not') are fundamental in Python for controlling a program’s logical flow, determining how conditional statements are evaluated. They allow the combination and inversion of boolean values, enhancing the complexity and nuance of conditions under which decisions are made. Their interaction with 'if', 'else', and 'elif' statements decides the execution path, enabling the construction of multi-faceted and layered logical flows within a program .

Python's clear and expressive syntax allows rapid prototyping, making it ideal for web development frameworks like Django and Flask that expedite web application deployment. Its extensive libraries and community support enhance data manipulation in data science with pandas and numpy, while scikit-learn provides tools for implementing standard machine learning algorithms. This combination of readability, library support, and versatility in handling scientific tools positions Python as a strong choice in these fields, promoting efficient development cycles .

Python natively supports complex numbers using the 'j' suffix to denote the imaginary part, facilitating operations in domains involving complex arithmetic such as electrical engineering and quantum physics. Fractions are implemented using the 'Fraction' class for precise rational arithmetic, crucial in applications demanding exact values over floating-point approximations, such as in financial calculations or mathematical computations that benefit from rational representations .

You might also like