Python Beginner Examples: Numbers, Strings, Lists, and Dictionaries

This content contains beginner-friendly Python code examples focused on working with basic data types: numbers, strings, lists, and dictionaries. These examples emphasize fundamental operations and Pythonic patterns.

How to Use These Examples

  1. Start with basic operations - Understand how Python handles numbers and strings
  2. Follow data manipulation - See how to process and transform data
  3. Notice Python patterns - Learn Python’s dynamic typing and built-in methods
  4. Practice reading collections - Understand list and dictionary operations
  5. Trace through examples - Follow the step-by-step execution

Example 1: Number Operations and Calculations

Code to Read:

 1def process_shopping_data():
 2    """Demonstrate Python number operations with shopping cart calculations."""
 3    
 4    # Basic number types and operations
 5    item_count = 12
 6    unit_price = 15.99
 7    tax_rate = 0.08
 8    shipping_threshold = 50.0
 9    
10    print("=== Shopping Cart Calculation ===")
11    print(f"Items: {item_count}")
12    print(f"Unit price: ${unit_price}")
13    print(f"Tax rate: {tax_rate * 100}%")
14    
15    # Mathematical calculations
16    subtotal = unit_price * item_count
17    tax_amount = subtotal * tax_rate
18    total_before_shipping = subtotal + tax_amount
19    
20    # Conditional shipping calculation
21    if total_before_shipping >= shipping_threshold:
22        shipping_cost = 0.0
23        shipping_message = "Free shipping!"
24    else:
25        shipping_cost = 8.99
26        needed_for_free = shipping_threshold - total_before_shipping
27        shipping_message = f"Add ${needed_for_free:.2f} for free shipping"
28    
29    final_total = total_before_shipping + shipping_cost
30    
31    print(f"\n=== Price Breakdown ===")
32    print(f"Subtotal: ${subtotal:.2f}")
33    print(f"Tax: ${tax_amount:.2f}")
34    print(f"Shipping: ${shipping_cost:.2f}")
35    print(f"Final total: ${final_total:.2f}")
36    print(f"Shipping note: {shipping_message}")
37    
38    # Number formatting and rounding
39    rounded_total = round(final_total, 2)
40    whole_dollars = int(final_total)
41    cents = final_total - whole_dollars
42    
43    print(f"\n=== Detailed Analysis ===")
44    print(f"Rounded total: ${rounded_total}")
45    print(f"Whole dollars: ${whole_dollars}")
46    print(f"Cents portion: {cents:.2f}")
47
48# Call the function
49if __name__ == "__main__":
50    process_shopping_data()

What to Notice:

  • Dynamic Typing: No need to declare variable types explicitly
  • F-strings: f"Text {variable}" for clean string formatting
  • Built-in Functions: round(), int(), max(), min() work directly
  • Docstrings: Triple-quoted strings document function purpose
  • Conditional Expressions: Clean if/else logic for business rules
  • Decimal Formatting: :.2f controls decimal places in f-strings

Trace Through Example:

 1item_count = 12
 2unit_price = 15.99
 3tax_rate = 0.08
 4
 5# Calculations:
 6subtotal = 15.99 * 12 = 191.88
 7tax_amount = 191.88 * 0.08 = 15.3504
 8total_before_shipping = 191.88 + 15.3504 = 207.2304
 9
10# Since 207.23 >= 50.0, shipping_cost = 0.0
11final_total = 207.2304 + 0.0 = 207.2304

Example 2: String Processing and Text Analysis

Code to Read:

 1def analyze_customer_feedback():
 2    """Process and analyze customer feedback text."""
 3    
 4    # Sample customer feedback
 5    feedback = "The product quality is EXCELLENT! Fast shipping, great customer service."
 6    customer_name = "Alice Johnson"
 7    rating = "5 stars"
 8    
 9    print("=== Customer Feedback Analysis ===")
10    print(f"Customer: {customer_name}")
11    print(f"Rating: {rating}")
12    print(f"Feedback: {feedback}")
13    
14    # Basic string properties
15    feedback_length = len(feedback)
16    word_count = len(feedback.split())
17    has_exclamation = "!" in feedback
18    is_positive = "excellent" in feedback.lower()
19    
20    print(f"\n=== Text Properties ===")
21    print(f"Character count: {feedback_length}")
22    print(f"Word count: {word_count}")
23    print(f"Contains exclamation: {has_exclamation}")
24    print(f"Appears positive: {is_positive}")
25    
26    # String transformations
27    clean_feedback = feedback.lower().strip()
28    words = feedback.split()
29    first_three_words = " ".join(words[:3])
30    last_word = words[-1]
31    
32    print(f"\n=== Text Processing ===")
33    print(f"Cleaned feedback: {clean_feedback}")
34    print(f"First three words: {first_three_words}")
35    print(f"Last word: {last_word}")
36    
37    # Extract specific information
38    positive_words = ["excellent", "great", "fast", "good", "amazing"]
39    found_positive_words = []
40    
41    for word in words:
42        clean_word = word.lower().strip(".,!?")
43        if clean_word in positive_words:
44            found_positive_words.append(clean_word)
45    
46    print(f"\n=== Sentiment Analysis ===")
47    print(f"Positive words found: {found_positive_words}")
48    print(f"Positive word count: {len(found_positive_words)}")
49    
50    # Customer name processing
51    name_parts = customer_name.split()
52    first_name = name_parts[0]
53    last_name = name_parts[1] if len(name_parts) > 1 else ""
54    initials = first_name[0] + (last_name[0] if last_name else "")
55    
56    print(f"\n=== Customer Info ===")
57    print(f"First name: {first_name}")
58    print(f"Last name: {last_name}")
59    print(f"Initials: {initials}")
60
61# Call the function
62if __name__ == "__main__":
63    analyze_customer_feedback()

What to Notice:

  • String Methods: .lower(), .strip(), .split() transform strings
  • List Slicing: words[:3] gets first three elements, words[-1] gets last
  • String Membership: "text" in string checks if substring exists
  • List Comprehension Alternative: Traditional loop to build list of matches
  • String Cleaning: Removing punctuation with .strip(".,!?")
  • Conditional Assignment: Safe handling of optional last name

Trace Through Example:

 1feedback = "The product quality is EXCELLENT! Fast shipping, great customer service."
 2words = feedback.split()
 3# words = ["The", "product", "quality", "is", "EXCELLENT!", "Fast", "shipping,", "great", "customer", "service."]
 4
 5first_three_words = " ".join(words[:3])
 6# first_three_words = "The product quality"
 7
 8# For positive word detection:
 9for word in ["The", "product", "quality", ...]:
10    clean_word = word.lower().strip(".,!?")
11    # "EXCELLENT!" becomes "excellent", which is in positive_words
12    # found_positive_words = ["excellent", "fast", "great"]

Example 3: List Operations and Data Management

Code to Read:

 1def manage_playlist():
 2    """Demonstrate list operations with a music playlist."""
 3    
 4    # Initial playlist setup
 5    playlist = ["Bohemian Rhapsody", "Hotel California", "Imagine", "Sweet Child O' Mine"]
 6    genres = ["Rock", "Rock", "Pop", "Rock"]
 7    durations = [355, 391, 183, 356]  # in seconds
 8    
 9    print("=== Original Playlist ===")
10    for i, song in enumerate(playlist):
11        minutes = durations[i] // 60
12        seconds = durations[i] % 60
13        print(f"{i+1}. {song} ({genres[i]}) - {minutes}:{seconds:02d}")
14    
15    # List operations
16    playlist_length = len(playlist)
17    total_duration = sum(durations)
18    average_duration = total_duration / playlist_length
19    
20    print(f"\n=== Playlist Statistics ===")
21    print(f"Number of songs: {playlist_length}")
22    print(f"Total duration: {total_duration // 60}:{total_duration % 60:02d}")
23    print(f"Average duration: {average_duration:.1f} seconds")
24    
25    # Adding new songs
26    new_songs = ["Stairway to Heaven", "Purple Haze"]
27    new_genres = ["Rock", "Rock"]
28    new_durations = [482, 167]
29    
30    # Extend lists with new data
31    playlist.extend(new_songs)
32    genres.extend(new_genres)
33    durations.extend(new_durations)
34    
35    print(f"\n=== After Adding Songs ===")
36    print(f"Updated playlist length: {len(playlist)}")
37    print(f"Last song: {playlist[-1]}")
38    
39    # Searching and filtering
40    rock_songs = []
41    rock_indices = []
42    
43    for i, genre in enumerate(genres):
44        if genre == "Rock":
45            rock_songs.append(playlist[i])
46            rock_indices.append(i)
47    
48    print(f"\n=== Rock Songs ===")
49    print(f"Rock songs: {rock_songs}")
50    print(f"Count: {len(rock_songs)}")
51    
52    # List slicing and manipulation
53    first_three = playlist[:3]
54    last_two = playlist[-2:]
55    middle_songs = playlist[2:4]
56    
57    print(f"\n=== Playlist Segments ===")
58    print(f"First three: {first_three}")
59    print(f"Last two: {last_two}")
60    print(f"Middle songs: {middle_songs}")
61    
62    # Sort by duration (create new sorted list)
63    song_duration_pairs = list(zip(playlist, durations))
64    sorted_by_duration = sorted(song_duration_pairs, key=lambda x: x[1])
65    
66    print(f"\n=== Sorted by Duration ===")
67    for song, duration in sorted_by_duration[:3]:  # Show shortest 3
68        minutes = duration // 60
69        seconds = duration % 60
70        print(f"{song}: {minutes}:{seconds:02d}")
71
72# Call the function
73if __name__ == "__main__":
74    manage_playlist()

What to Notice:

  • List Indexing: Access elements with [index], negative indices count from end
  • List Methods: .extend() adds multiple elements, .append() adds one
  • Enumerate: enumerate(list) provides both index and value in loops
  • List Slicing: [:3] first three, [-2:] last two, [2:4] middle range
  • Zip Function: zip() combines multiple lists element-wise
  • Lambda Functions: Anonymous functions for sorting criteria
  • List Building: Traditional loop to build filtered lists

Trace Through Example:

 1playlist = ["Bohemian Rhapsody", "Hotel California", "Imagine", "Sweet Child O' Mine"]
 2durations = [355, 391, 183, 356]
 3
 4# Statistics:
 5playlist_length = len(playlist) = 4
 6total_duration = sum(durations) = 355 + 391 + 183 + 356 = 1285
 7average_duration = 1285 / 4 = 321.25
 8
 9# After extending:
10playlist.extend(["Stairway to Heaven", "Purple Haze"])
11# playlist = ["Bohemian Rhapsody", "Hotel California", "Imagine", "Sweet Child O' Mine", "Stairway to Heaven", "Purple Haze"]

Example: Python Variables, Types, and Basic Operations

Code to Read:

 1def process_student_info():
 2    """Demonstrate Python's built-in types and variable handling."""
 3    
 4    # Different variable types - Python infers the type
 5    student_name = "Alice Johnson"          # str
 6    age = 20                               # int
 7    gpa = 3.85                            # float
 8    is_enrolled = True                     # bool
 9    courses = ["Math", "Physics", "CS"]    # list
10    grades = {"Math": 95, "Physics": 88, "CS": 92}  # dict
11    
12    # String operations and formatting
13    first_name = student_name.split()[0]  # Split on whitespace, take first part
14    last_initial = student_name.split()[1][0]  # Get first letter of last name
15    
16    # String methods and formatting
17    display_name = f"{first_name} {last_initial}."  # f-string formatting
18    email = f"{first_name.lower()}.{student_name.split()[1].lower()}@university.edu"
19    
20    # Working with numbers
21    total_credits = len(courses) * 3  # Each course is 3 credits
22    next_year_age = age + 1
23    gpa_percentage = gpa / 4.0 * 100  # Convert 4.0 scale to percentage
24    
25    # Boolean operations
26    is_honor_student = gpa >= 3.5 and is_enrolled
27    needs_advising = gpa < 2.0 or total_credits < 12
28    is_senior = age >= 21 and total_credits > 90
29    
30    # List operations
31    course_count = len(courses)
32    has_math = "Math" in courses  # Membership testing
33    courses_upper = [course.upper() for course in courses]  # List comprehension
34    
35    # Dictionary operations
36    math_grade = grades.get("Math", 0)  # Safe dictionary access
37    average_grade = sum(grades.values()) / len(grades)  # Calculate average
38    passing_courses = [course for course, grade in grades.items() if grade >= 60]
39    
40    # Print information using different formatting methods
41    print("=== Student Information ===")
42    print(f"Name: {display_name}")
43    print(f"Age: {age} (will be {next_year_age} next year)")
44    print(f"Email: {email}")
45    print(f"GPA: {gpa} ({gpa_percentage:.1f}%)")
46    print(f"Enrolled: {'Yes' if is_enrolled else 'No'}")
47    
48    print(f"\n=== Academic Status ===")
49    print(f"Courses: {', '.join(courses)}")  # Join list into string
50    print(f"Total Credits: {total_credits}")
51    print(f"Average Grade: {average_grade:.1f}")
52    print(f"Honor Student: {'Yes' if is_honor_student else 'No'}")
53    print(f"Needs Advising: {'Yes' if needs_advising else 'No'}")
54    
55    # Return a summary dictionary
56    return {
57        'name': display_name,
58        'email': email,
59        'gpa': gpa,
60        'courses': courses,
61        'grades': grades,
62        'status': {
63            'honor_student': is_honor_student,
64            'needs_advising': needs_advising,
65            'is_senior': is_senior
66        }
67    }
68
69# Example usage
70if __name__ == "__main__":
71    student_data = process_student_info()
72    print(f"\nReturned data type: {type(student_data)}")
73    print(f"Number of keys in returned dict: {len(student_data)}")

What to Notice:

Python's Dynamic Type System
  • No type declarations needed: Python infers types automatically
  • Built-in data types: str, int, float, bool, list, dict
  • Type flexibility: Variables can be reassigned to different types
  • Runtime type checking: type() function reveals actual types
String Operations and F-strings
  • String methods: .split(), .lower(), .upper() for transformations
  • F-string formatting: f"{variable}" is modern, readable syntax
  • String slicing: student_name.split()[1][0] chains operations
  • Formatted numbers: {gpa_percentage:.1f} controls decimal places
List and Dictionary Operations
  • List comprehensions: [course.upper() for course in courses] - concise transformation
  • Membership testing: "Math" in courses - readable boolean operations
  • Dictionary methods:
    • .get("Math", 0) - safe access with default
    • .values() and .items() for iteration
    • .keys() for key access
Boolean Logic and Conditionals
  • Readable operators: and, or instead of &&, ||
  • Truthiness: Empty lists, None, 0 are “falsy”
  • Conditional expressions: 'Yes' if condition else 'No' (ternary operator)
  • Chained comparisons: 60 <= grade <= 100 more readable than grade >= 60 and grade <= 100

Trace Through Example:

 1# Initial assignments:
 2student_name = "Alice Johnson"
 3courses = ["Math", "Physics", "CS"]
 4grades = {"Math": 95, "Physics": 88, "CS": 92}
 5
 6# String processing:
 7first_name = "Alice Johnson".split()[0]  # → "Alice"
 8last_initial = "Alice Johnson".split()[1][0]  # → "J"
 9display_name = f"Alice J."  # → "Alice J."
10
11# List operations:
12course_count = len(["Math", "Physics", "CS"])  # → 3
13total_credits = 3 * 3  # → 9
14has_math = "Math" in ["Math", "Physics", "CS"]  # → True
15
16# Dictionary operations:
17math_grade = grades.get("Math", 0)  # → 95
18average_grade = sum([95, 88, 92]) / 3  # → 91.67
19passing_courses = ["Math", "Physics", "CS"]  # All >= 60
20
21# Boolean logic:
22is_honor_student = 3.85 >= 3.5 and True  # → True
23needs_advising = 3.85 < 2.0 or 9 < 12  # → False or True → True

Reading Practice Tips

After studying these Python examples:

  1. Notice dynamic typing: Python infers types automatically, no declarations needed
  2. Follow list operations: Understand how lists grow, shrink, and get processed
  3. Practice string formatting: Master f-strings and format specifiers
  4. Trace data flow: Follow how data moves through functions and transformations
  5. Experiment with code: Try modifying values and see how outputs change

These foundational Python patterns form the building blocks of most Python programs. Understanding them will help you read more complex Python code with confidence.