Back to Python
2026-02-115 min read

R Examples (Python Programming)

Learn R Examples (Python Programming) step by step with clear examples and exercises.

Title: Mastering Python Programming with Practical Examples

Why This Matters

Python is a versatile and popular programming language used across various fields such as data analysis, machine learning, web development, and more. Understanding its practical applications can help you excel in your projects, interviews, and even real-world bug fixing scenarios. In this lesson, we will delve into some essential Python examples that every programmer should know.

Prerequisites

To follow along with the examples, it is assumed that you have a basic understanding of Python syntax, variables, data types, functions, and control structures like loops and conditional statements. If you are new to Python, we recommend brushing up on these concepts before moving forward.

Core Concept

Python Built-in Functions

Python provides a rich set of built-in functions that make programming easier and more efficient. Here are some commonly used built-in functions:

  1. print() - prints the specified output to the console
  2. input() - reads user input from the console
  3. len() - returns the length of an object (e.g., a list, string, or tuple)
  4. type() - returns the type of an object
  5. range() - generates a sequence of numbers within a specified range
  6. sum() - calculates the sum of elements in an iterable (e.g., a list or a tuple)
  7. max() and min() - return the maximum and minimum values from an iterable, respectively

Python Lists

Lists are one of the most commonly used data structures in Python. They allow you to store multiple items of different data types within a single variable. Here's how to create and manipulate lists:

  1. Creating a list - my_list = [1, 2, 3, "apple", True]
  2. Accessing elements - my_list[0] accesses the first element, while my_list[-1] accesses the last element
  3. Adding an element - my_list.append(4) adds a new element to the end of the list
  4. Removing an element - my_list.remove(2) removes the first occurrence of the specified value
  5. Sorting a list - my_list.sort() sorts the elements in ascending order
  6. Reversing a list - my_list.reverse() reverses the order of the elements
  7. Concatenating lists - combined_list = my_list + another_list combines two lists

Python Dictionaries

Dictionaries are used to store key-value pairs, where each key is unique and maps to a corresponding value. Here's how to create and manipulate dictionaries:

  1. Creating a dictionary - my_dict = {"name": "John", "age": 30}
  2. Accessing values - my_dict["name"] accesses the value associated with the specified key
  3. Adding a key-value pair - my_dict["job"] = "engineer" adds a new key-value pair to the dictionary
  4. Removing a key-value pair - del my_dict["age"] removes the specified key and its associated value
  5. Iterating through keys or values - You can iterate through the keys or values using loops, e.g., for key in my_dict.keys():, or for value in my_dict.values():

Python Strings

Strings are sequences of characters and are defined using single or double quotes. Here's how to manipulate strings:

  1. Concatenating strings - message = "Hello, " + "World!" concatenates two strings
  2. Accessing individual characters - message[0] accesses the first character in a string
  3. Slicing strings - message[1:5] returns the substring starting from the second character and ending before the fifth character (exclusive)
  4. Replacing substrings - new_message = message.replace("World", "Universe") replaces all occurrences of "World" with "Universe"

Worked Example

Let's write a simple Python program that calculates the factorial of a number using recursion and loops, demonstrating both built-in functions and control structures.

def factorial_recursive(n):
if n == 0:
return 1
else:
return n * factorial_recursive(n - 1)

def factorial_loop(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

number = int(input("Enter a number: "))
print("Factorial using recursion:", factorial_recursive(number))
print("Factorial using loop:", factorial_loop(number))

Common Mistakes

  1. Forgetting to close the parentheses or brackets in function calls, e.g., print(hello) instead of print("hello")
  2. Using an uninitialized variable, e.g., x = 5; print(y) where y has not been defined yet
  3. Misusing the assignment operator (=) instead of comparison operators (==), e.g., if x = 5: instead of if x == 5:
  4. Not handling edge cases, such as checking for zero before calculating the factorial recursively
  5. Using a loop when a built-in function like sum() or max() would be more efficient, e.g., calculating the sum of elements in a list using a loop instead of sum(my_list)

Practice Questions

  1. Write a Python program that takes two lists as input and returns their intersection (i.e., the elements common to both lists).
  2. Write a Python program that defines a function to find the second-highest value in a list of numbers without using built-in functions like max().
  3. Write a Python program that defines a function to reverse a string without using built-in functions like reverse().
  4. Write a Python program that defines a function to check if a given number is prime or not.
  5. Write a Python program that defines a function to find the Fibonacci sequence up to a specified number.

FAQ

--

Q: What's the difference between lists and tuples in Python?

A: Lists are mutable, meaning their elements can be changed, while tuples are immutable, meaning their elements cannot be changed.

Q: How do I handle exceptions in Python?

A: You can use a try-except block to catch and handle exceptions. For example:

try:

code that might raise an exception

except ExceptionType:

code to handle the exception


3. Q: How do I sort a list of dictionaries in Python?
A: You can use the `sorted()` function and specify a key parameter, which defines the field to be sorted by. For example:

data = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}, {"name": "Charlie", "age": 20}]

sorted_data = sorted(data, key=lambda x: x["age"])

R Examples (Python Programming) | Python | XQA Learn