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

Python Basics Notes for interns

This document provides an overview of fundamental Python concepts including variables, data types, operators, built-in functions, conditional statements, loops, and functions, with examples for each topic. It explains dynamic typing, primitive and non-primitive data types, various operators, and control flow structures. Additionally, it covers user-defined and lambda functions, as well as the use of *args and **kwargs in function definitions.
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 views13 pages

Python Basics Notes for interns

This document provides an overview of fundamental Python concepts including variables, data types, operators, built-in functions, conditional statements, loops, and functions, with examples for each topic. It explains dynamic typing, primitive and non-primitive data types, various operators, and control flow structures. Additionally, it covers user-defined and lambda functions, as well as the use of *args and **kwargs in function definitions.
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/ 13

Python Basics Notes

This document covers fundamental Python concepts: variables, data types, operators, built-
in functions, conditional statements, loops, and functions, with simple examples for each.

1. Variables

Variables in Python are used to store data. Python is dynamically typed, meaning you don’t
need to explicitly declare the type of a variable.

1.1 Variable Declaration

 Variables can be declared without keywords like var, let, or const (unlike JavaScript).

 Simply assign a value using =.

 Variable names are case-sensitive and should follow naming conventions (e.g.,
lowercase with underscores for multi-word names).

Example:

name = "Alice"

age = 25

print(name, age) # Output: Alice 25

1.2 Dynamic Typing

 Python automatically determines the data type based on the assigned value.

 The same variable can hold different types at different times.

Example:

x = 10 # x is an integer

print(x) # Output: 10

x = "Hello" # x is now a string

print(x) # Output: Hello

2. Data Types

Python has two categories of data types: primitive and non-primitive.

2.1 Primitive Data Types

 Simple, immutable data types stored directly in memory.


 Types:

o int: Whole numbers (e.g., 5, -10).

o float: Decimal numbers (e.g., 3.14, -0.5).

o str: Sequence of characters (e.g., "Hello").

o bool: True or False.

o NoneType: Represents the absence of a value (None).

Example:

num = 42 # int

price = 19.99 # float

text = "Python" # str

is_active = True # bool

nothing = None # NoneType

print(num, price, text, is_active, nothing)

# Output: 42 19.99 Python True None

2.2 Non-Primitive Data Types

 Complex, mutable data types stored as references.

 Types:

o list: Ordered, mutable collection (e.g., [1, 2, 3]).

o tuple: Ordered, immutable collection (e.g., (1, 2, 3)).

o set: Unordered, mutable collection of unique elements (e.g., {1, 2, 3}).

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

Example:

my_list = [1, 2, 3] # list

my_tuple = (4, 5, 6) # tuple

my_set = {7, 8, 9} # set

my_dict = {"name": "Bob", "age": 30} # dict


print(my_list, my_tuple, my_set, my_dict)

# Output: [1, 2, 3] (4, 5, 6) {8, 9, 7} {'name': 'Bob', 'age': 30}

3. Operators

Operators perform operations on variables and values.

3.1 Arithmetic Operators

 Perform mathematical calculations.

 Operators: + (addition), - (subtraction), * (multiplication), / (division), // (floor


division), % (modulus), ** (exponentiation).

Example:

a, b = 10, 3

print(a + b) # Output: 13

print(a - b) # Output: 7

print(a * b) # Output: 30

print(a / b) # Output: 3.333...

print(a // b) # Output: 3 (integer division)

print(a % b) # Output: 1 (remainder)

print(a ** 2) # Output: 100 (10^2)

3.2 Assignment Operators

 Assign values to variables.

 Operators: = (assign), +=, -=, *=, /=, //=, %=, **=.

Example:

x=5

x += 3 # x = x + 3

print(x) # Output: 8

x *= 2 # x = x * 2

print(x) # Output: 16

3.3 Comparison Operators


 Compare values and return a boolean.

 Operators: == (equal), != (not equal), <, >, <=, >=.

Example:

a, b = 5, 3

print(a == b) # Output: False

print(a != b) # Output: True

print(a > b) # Output: True

print(a <= b) # Output: False

3.4 Logical Operators

 Combine or manipulate boolean values.

 Operators: and, or, not.

Example:

is_adult = True

has_ticket = False

print(is_adult and has_ticket) # Output: False (both must be True)

print(is_adult or has_ticket) # Output: True (at least one is True)

print(not is_adult) # Output: False (negates True)

3.5 Bitwise Operators

 Operate on binary representations of numbers.

 Operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).

Example:

a, b = 5, 3 # 5 = 0101, 3 = 0011

print(a & b) # Output: 1 (0101 & 0011 = 0001)

print(a | b) # Output: 7 (0101 | 0011 = 0111)

print(a ^ b) # Output: 6 (0101 ^ 0011 = 0110)

4. Built-in Functions/Methods

Python provides many built-in functions to simplify common tasks.


Examples:

# print() - Prints to console

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

# len() - Returns length

my_list = [1, 2, 3]

print(len(my_list)) # Output: 3

# type() - Returns data type

x = 42

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

# input() - Takes user input (as string)

name = input("Enter your name: ") # User enters "Alice"

print(name) # Output: Alice

# int(), float(), str() - Type conversion

num_str = "123"

num = int(num_str)

print(num + 1) # Output: 124

print(float(num_str)) # Output: 123.0

print(str(num)) # Output: 123

# range() - Generates sequence

for i in range(3):

print(i) # Output: 0, 1, 2

# list(), tuple(), set(), dict() - Type casting/creation


nums = [1, 2, 2, 3]

print(set(nums)) # Output: {1, 2, 3}

print(tuple(nums)) # Output: (1, 2, 2, 3)

# sum(), max(), min() - Aggregate functions

numbers = [1, 2, 3, 4]

print(sum(numbers)) # Output: 10

print(max(numbers)) # Output: 4

print(min(numbers)) # Output: 1

# sorted(), reversed() - Sorting/reversing

print(sorted([3, 1, 2])) # Output: [1, 2, 3]

print(list(reversed([1, 2, 3]))) # Output: [3, 2, 1]

# enumerate() - Index-value pairs

fruits = ["apple", "banana"]

for index, value in enumerate(fruits):

print(index, value)

# Output:

# 0 apple

# 1 banana

# zip() - Combines iterables

names = ["Alice", "Bob"]

ages = [25, 30]

print(list(zip(names, ages))) # Output: [('Alice', 25), ('Bob', 30)]

# map() - Apply function to items


nums = [1, 2, 3]

squared = list(map(lambda x: x**2, nums))

print(squared) # Output: [1, 4, 9]

# filter() - Filter items

evens = list(filter(lambda x: x % 2 == 0, nums))

print(evens) # Output: [2]

# any(), all() - Check truthy values

bools = [True, False, True]

print(any(bools)) # Output: True

print(all(bools)) # Output: False

# abs(), round(), pow() - Numeric functions

print(abs(-5)) # Output: 5

print(round(3.14159, 2)) # Output: 3.14

print(pow(2, 3)) # Output: 8

# id() - Memory address

x = 42

print(id(x)) # Output: Memory address (varies)

# isinstance() - Check type

print(isinstance(42, int)) # Output: True

# eval() - Evaluate string expression

print(eval("2 + 3")) # Output: 5


# chr(), ord() - ASCII conversion

print(chr(65)) # Output: A

print(ord("A")) # Output: 65

# help() - Documentation

help(print) # Opens documentation for print function

5. Conditional Statements

Conditional statements control the flow of execution based on conditions.

5.1 If Statement

 Executes code if a condition is True.

Example:

age = 18

if age >= 18:

print("You are an adult.")

# Output: You are an adult.

5.2 If-Else Statement

 Executes one block if the condition is True, another if False.

Example:

age = 16

if age >= 18:

print("You are an adult.")

else:

print("You are a minor.")

# Output: You are a minor.

5.3 If-Elif-Else Statement

 Checks multiple conditions sequentially.

Example:
score = 85

if score >= 90:

print("Grade: A")

elif score >= 80:

print("Grade: B")

elif score >= 70:

print("Grade: C")

else:

print("Grade: D or F")

# Output: Grade: B

6. Loops

Loops execute a block of code repeatedly.

6.1 For Loop

 Iterates over a sequence (e.g., list, range).

Example:

for i in range(1, 6):

print(i)

# Output:

#1

#2

#3

#4

#5

6.2 While Loop

 Runs as long as a condition is True.

Example:

count = 1
while count <= 5:

print(count)

count += 1

# Output:

#1

#2

#3

#4

#5

6.3 Nested Loops

 A loop inside another loop.

Example:

for i in range(1, 3):

for j in range(1, 3):

print(i, j)

# Output:

#11

#12

#21

#22

6.4 Break, Continue, Pass

 break: Exits the loop.

 continue: Skips to the next iteration.

 pass: Does nothing (placeholder).

Example:

for i in range(1, 6):

if i == 3:

break # Exit loop


print(i)

# Output: 1, 2

for i in range(1, 6):

if i == 3:

continue # Skip 3

print(i)

# Output: 1, 2, 4, 5

for i in range(1, 6):

if i == 3:

pass # Placeholder

print(i)

# Output: 1, 2, 3, 4, 5

7. Functions

Functions are reusable blocks of code that perform a specific task.

7.1 User-Defined Functions

 Defined using the def keyword.

 Can have parameters and return values.

Example:

def add(a, b):

return a + b

result = add(3, 4)

print(result) # Output: 7

def greet(name):
print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!

7.2 Lambda Functions

 Anonymous, single-expression functions created with lambda.

 Useful for short, one-off operations.

Example:

square = lambda x: x * x

print(square(5)) # Output: 25

# Lambda with map

nums = [1, 2, 3]

squared = list(map(lambda x: x**2, nums))

print(squared) # Output: [1, 4, 9]

7.3 *args and **kwargs

 *args: Allows a function to accept any number of positional arguments.

 **kwargs: Allows a function to accept any number of keyword arguments.

Example:

def sum_numbers(*args):

return sum(args)

print(sum_numbers(1, 2, 3)) # Output: 6

print(sum_numbers(10, 20, 30, 40)) # Output: 100

def print_info(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")
print_info(name="Alice", age=25)

# Output:

# name: Alice

# age: 25

You might also like