Introduction to Python¶

BUSI 520: Python for Business Research¶

Kerry Back, JGSB, Rice University¶

1. What is Python?¶

Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than might be possible in other languages, such as C++ or Java.

Python is versatile and can be used for a wide range of applications, including web development, data analysis, artificial intelligence, scientific computing, and more. It has a large and active community, which means there are plenty of resources, libraries, and frameworks available to help you with your projects.

2. Python Syntax Basics¶

Python is known for its clean and straightforward syntax, which is one of the reasons it's a great language for beginners. Let's go over some of the basic syntax rules:

  • Indentation: Unlike many other languages, Python uses whitespace (indentation) to delimit blocks of code. This means that the amount of whitespace before a line of code is important.
  • Comments: In Python, comments start with the # symbol. Comments are ignored by the Python interpreter and are used to provide notes or explanations within the code.
  • Statements: A statement is a unit of code that the Python interpreter can execute. For example, a = 1 is an assignment statement.
  • Line Continuation: If a statement is too long, you can break it into multiple lines using the \ character or by enclosing the expression in parentheses.

Let's see some of these in action.

In [18]:
# This is a comment and will be ignored by Python

# Let's declare a variable and assign a value to it
a = 5
print(a)

# Line continuation example
b = 1 + 2 + 3 + \
    4 + 5
print(b)

# Another way to continue a long line
c = (1 + 2 + 3 +
     4 + 5)
print(c)
5
15
15

3. Variables and Data Types¶

In Python, variables are used to store data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

Python supports various data types, including:

  • Integers (int): Whole numbers, e.g., 5, -3, 42
  • Floating point (float): Decimal numbers, e.g., 3.14, -0.001, 5.0
  • Strings (str): Sequence of characters, e.g., 'hello', 'Python123', ' '
  • Booleans (bool): Represents truth values, True or False

Let's explore these data types with some examples.

In [19]:
# Integer variable
x = 10
print(type(x), x)

# Float variable
y = 20.5
print(type(y), y)

# String variable
name = 'Python'
print(type(name), name)

# Boolean variable
is_active = True
print(type(is_active), is_active)
<class 'int'> 10
<class 'float'> 20.5
<class 'str'> Python
<class 'bool'> True

4. Basic Operators¶

Operators are used to perform operations on variables and values. Python has several types of operators:

  • Arithmetic Operators: Used to perform mathematical operations.
  • Comparison Operators: Used to compare two values.
  • Logical Operators: Used to combine conditional statements.
  • Assignment Operators: Used to assign values to variables.

Let's explore some of these operators with examples.

In [20]:
# Arithmetic Operators
a = 10
b = 3
print('a + b =', a + b)  # Addition
print('a - b =', a - b)  # Subtraction
print('a * b =', a * b)  # Multiplication
print('a / b =', a / b)  # Division
print('a % b =', a % b)  # Modulus (remainder)
print('a ** b =', a ** b)  # Exponentiation

# Comparison Operators
print('a == b:', a == b)  # Equal to
print('a != b:', a != b)  # Not equal to
print('a > b:', a > b)   # Greater than
print('a < b:', a < b)   # Less than
a + b = 13
a - b = 7
a * b = 30
a / b = 3.3333333333333335
a % b = 1
a ** b = 1000
a == b: False
a != b: True
a > b: True
a < b: False
In [21]:
# Logical Operators
x = True
y = False
print('x and y:', x and y)  # Logical AND
print('x or y:', x or y)    # Logical OR
print('not x:', not x)      # Logical NOT
x and y: False
x or y: True
not x: False

5. Control Structures¶

Control structures allow you to control the flow of your program's execution based on certain conditions or loops. The primary control structures in Python are:

  • if, elif, and else statements: Used for conditional execution.
  • for loops: Used to iterate over a sequence (like a list or a string) or other iterable objects.
  • while loops: Used to execute a set of statements as long as a condition is true.

Let's see some examples of these control structures.

In [22]:
# if, elif, and else statements
age = 18
if age < 13:
    print('Child')
elif age < 20:
    print('Teenager')
else:
    print('Adult')

# for loop
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

# while loop
count = 0
while count < 3:
    print('Count:', count)
    count += 1
Teenager
apple
banana
cherry
Count: 0
Count: 1
Count: 2

6. Functions¶

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

In Python, you can define a function using the def keyword. Functions can take parameters and return a value.

Let's see some examples of defining and using functions.

In [23]:
# Defining a simple function
def greet():
    return 'Hello, World!'

# Calling the function
print(greet())

# Function with parameters
def add_numbers(a, b):
    return a + b

# Calling the function with arguments
result = add_numbers(5, 3)
print('5 + 3 =', result)
Hello, World!
5 + 3 = 8

7. Lists and Dictionaries¶

Lists and dictionaries are two of the most frequently used data structures in Python.

  • List: A list is an ordered collection of items. Lists are mutable, which means you can modify their content. Lists are defined by enclosing a comma-separated sequence of items in square brackets [].

  • Dictionary: A dictionary is an unordered collection of data in a key:value pair form. Here, keys are unique and used to access the corresponding value. Dictionaries are defined by enclosing a comma-separated list of key:value pairs in curly braces {}.

Let's explore these data structures with some examples.

In [24]:
# Lists
fruits = ['apple', 'banana', 'cherry', 'date']
print('Original List:', fruits)

# Accessing elements
print('First Fruit:', fruits[0])
print('Last Fruit:', fruits[-1])

# Modifying a list
fruits[1] = 'blueberry'
print('Modified List:', fruits)

# Adding to a list
fruits.append('elderberry')
print('Appended List:', fruits)
Original List: ['apple', 'banana', 'cherry', 'date']
First Fruit: apple
Last Fruit: date
Modified List: ['apple', 'blueberry', 'cherry', 'date']
Appended List: ['apple', 'blueberry', 'cherry', 'date', 'elderberry']
In [25]:
# Dictionaries
person = {
    'name': 'John',
    'age': 30,
    'is_student': False
}
print('Person Dictionary:', person)

# Accessing dictionary values
print('Name:', person['name'])
print('Age:', person.get('age'))

# Modifying a dictionary
person['age'] = 31
print('Updated Age:', person['age'])
Person Dictionary: {'name': 'John', 'age': 30, 'is_student': False}
Name: John
Age: 30
Updated Age: 31

8. Ternary Operator¶

The ternary operator provides a shorthand way to write conditional statements. It's a concise way to evaluate expressions based on a condition.

The syntax for the ternary operator is:

value_if_true if condition else value_if_false

Let's see some examples of the ternary operator in action.

In [26]:
# Using the ternary operator
age = 18
status = 'Adult' if age >= 18 else 'Minor'
print(status)

# Another example
score = 85
result = 'Pass' if score >= 50 else 'Fail'
print(result)
Adult
Pass

9. Classes in Python¶

Python is an object-oriented programming language. This means that almost everything in Python is an object, with its properties and methods. A class is like an object constructor or a blueprint for creating objects.

Classes encapsulate data for the object and methods to manipulate that data. Let's understand classes with a simple example.

In [27]:
# Defining a simple class
class Dog:
    # A class attribute
    species = 'Canis familiaris'

    # Initializer / Constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Method to describe the dog
    def description(self):
        return f'{self.name} is {self.age} years old'

    # Method to make the dog bark
    def speak(self, sound):
        return f'{self.name} says {sound}'

# Creating instances of the Dog class
dog1 = Dog('Buddy', 3)
dog2 = Dog('Rex', 5)

# Accessing attributes and methods
print(dog1.description())
print(dog2.speak('Woof'))
Buddy is 3 years old
Rex says Woof

10. Enumerate and zip¶

In Python, the enumerate() function is used to loop through a list (or any iterable) and retrieve both the index and the value of each item in the list. This can be particularly useful when you want to know the position of an item in the list.

The zip function zips two lists together and creates a list of tuples. This is often useful in loops.

In [28]:
# List of fruits
fruits = ['apple', 'banana', 'cherry', 'date']

# Using enumerate to loop through the list with index and value
for index, fruit in enumerate(fruits):
    print(f'Index: {index}, Fruit: {fruit}')

# Using zip to zip a range object and a list

for index, fruit in zip(range(len(fruits)), fruits):
    print(f'Index: {index}, Fruit: {fruit}')
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Index: 3, Fruit: date
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Index: 3, Fruit: date

11. List and dictionary comprehensions.¶

List Comprehensions¶

List comprehensions provide a concise way to create lists. The syntax is:

[expression for item in iterable if condition]

Dictionary Comprehensions¶

Similar to list comprehensions, dictionary comprehensions provide a concise way to create dictionaries. The syntax is:

{key: value for item in iterable if condition}

Let's see some examples.

In [29]:
# List comprehension to create a list of squares
squares = [x**2 for x in range(5)]
print('Squares:', squares)

# List comprehension with condition
even_squares = [x**2 for x in range(5) if x % 2 == 0]
print('Even Squares:', even_squares)

# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
print('Squares Dictionary:', squares_dict)

# Dictionary comprehension with condition
even_squares_dict = {x: x**2 for x in range(5) if x % 2 == 0}
print('Even Squares Dictionary:', even_squares_dict)
Squares: [0, 1, 4, 9, 16]
Even Squares: [0, 4, 16]
Squares Dictionary: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Even Squares Dictionary: {0: 0, 2: 4, 4: 16}

12. Arguments with Default Values¶

In Python, you can define functions with default values for arguments. This means that if a value for a specific argument is not provided when the function is called, the default value will be used.

The syntax for defining a function with default argument values is:

def function_name(arg1=default_value1, arg2=default_value2, ...):
    # function body

Let's see an example.

In [30]:
# Defining a function with default argument values
def greet(name='World'):
    return f'Hello, {name}!'

# Calling the function without providing an argument
print(greet())

# Calling the function with an argument
print(greet('Alice'))
Hello, World!
Hello, Alice!

13. Keyword Arguments¶

In Python, you can call functions using variable names. This is known as passing arguments using keywords. It allows you to specify which argument value corresponds to which parameter, making the code more readable and allowing you to skip certain arguments or rearrange the order in which they are passed.

Let's see an example of calling a function using keyword arguments.

In [31]:
# Defining a function with multiple parameters
def display_info(name, age, is_student):
    return f'{name} is {age} years old. Student status: {is_student}'

# Calling the function using keyword arguments
info = display_info(age=25, name='Bob', is_student=True)
print(info)
Bob is 25 years old. Student status: True

14. Local vs. Global Variables¶

In Python, variables can be categorized as local or global based on their scope.

  • Local Variables: Variables declared inside a function or block are local to that function or block. They can be accessed only inside the function in which they are declared.
  • Global Variables: Variables declared outside a function or block are global variables. They can be accessed both inside and outside functions.

Let's understand the difference between local and global variables with an example.

In [32]:
# Global variable
global_var = 'I am a global variable'

def test_function():
    # Local variable
    local_var = 'I am a local variable'
    print(global_var)
    print(local_var)

test_function()

# This will raise an error as local_var is not accessible outside the function
# print(local_var)
I am a global variable
I am a local variable

15. Passing by Reference vs. Passing by Value¶

When passing parameters to functions in Python, it's crucial to understand the difference between passing by reference and passing by value.

  • Passing by Value: When you pass a value type (like an integer or a string) to a function, a copy of the original variable is created, and the function works with this copy. Changes made to the copy inside the function do not affect the original variable.

  • Passing by Reference: When you pass a reference type (like a list or a dictionary) to a function, the function works directly with the original variable. Changes made to the variable inside the function affect the original variable.

Let's see examples to understand the difference between the two.

In [33]:
# Passing by Value
def modify_value(x):
    x = x + 1
    return x

num = 5
print('Original Value:', num)
print('Modified Value:', modify_value(num))
print('Value after function call:', num)

# Passing by Reference
def modify_list(lst):
    lst.append(4)

numbers = [1, 2, 3]
print('\nOriginal List:', numbers)
modify_list(numbers)
print('List after function call:', numbers)
Original Value: 5
Modified Value: 6
Value after function call: 5

Original List: [1, 2, 3]
List after function call: [1, 2, 3, 4]

16. Importing Libraries and Objects from Libraries¶

In Python, a library (also known as a module) is a collection of functions and methods that allow you to perform various actions without writing your code. Python has a rich set of libraries that you can use to extend the functionality of your programs.

To use a library in your code, you need to import it. There are several ways to import libraries and specific objects from libraries:

  1. Importing an Entire Library:

    import library_name
    

    After importing, you can use the functions and objects from the library by prefixing them with the library name.

  2. Importing Specific Objects from a Library:

    from library_name import object_name
    

    This allows you to use the imported object directly without prefixing it with the library name.

  1. Importing All Objects from a Library:
    from library_name import *
    
    This imports all objects from the library, but it's generally not recommended as it can lead to naming conflicts and makes the code less readable.

Aliases¶

Aliases are alternative names given to libraries or objects when they are imported. This can make the code more concise and often follows community conventions. For example, the numpy library is commonly imported with the alias np.

The syntax for importing with an alias is:

import library_name as alias_name

Let's see some examples of importing libraries and using aliases.

In [34]:
# Importing the entire math library
import math
print('Square root of 16:', math.sqrt(16))

# Importing a specific object from the datetime library
from datetime import date
print("Today's date:", date.today())

# Importing a library with an alias
import datetime as dt
print('Current year:', dt.datetime.now().year)
Square root of 16: 4.0
Today's date: 2023-08-25
Current year: 2023