avatarAyşe Kübra Kuyucu

Summary

This tutorial provides a comprehensive guide on Python syntax basics, covering the declaration and use of variables, as well as an overview of different data types in Python, including numbers, strings, booleans, lists, tuples, dictionaries, and sets.

Abstract

The Python Tutorial 3 is designed to introduce learners to the fundamental concepts of Python programming, focusing on variables and data types. It begins with an introduction to variables as containers for data, explaining how to declare and manipulate them in Python. The tutorial then delves into the various data types available in Python, illustrating their usage with examples and detailing the operations and manipulations that can be performed on them. The author emphasizes the importance of understanding these basics for writing complex and dynamic programs, and for handling data analysis tasks effectively. The tutorial caters to individuals with a basic understanding of Python and data analysis, providing resources for further learning and practice exercises to reinforce the concepts covered.

Opinions

  • The author believes that variables are essential building blocks for programming in Python, enabling the storage and manipulation of data.
  • Variables in Python are dynamic and can have their values changed after declaration, reflecting the language's flexibility.
  • The tutorial suggests that Python's automatic type inference for variables simplifies the programming process.
  • The author advocates for descriptive and meaningful variable names in line with PEP 8 style guidelines for better code readability and maintainability.
  • Python's rich set of data types is presented as a powerful feature for data manipulation and analysis.
  • The tutorial encourages the use of Python's built-in functions and methods to perform operations on different data types, showcasing Python's intuitive and expressive syntax.
  • The author promotes the In Plain English community, inviting readers to engage further by clapping, following, writing, and exploring other platforms associated with the community.

Python Tutorial 3 — Python Syntax Basics: Variables, Data Types

Learn how to declare variables and use different data types.

AI-Generated Image by Author

Table of Contents 1. Introduction 2. What are Variables? 3. How to Declare Variables in Python? 4. What are Data Types? 5. How to Use Different Data Types in Python? 6. Conclusion

Subscribe for FREE to get your 42 pages e-book: Data Science | The Comprehensive Handbook

Get step-by-step e-books on Python, ML, DL, and LLMs.

1. Introduction

Welcome to this tutorial on Python syntax basics. In this tutorial, you will learn how to declare variables and use different data types in Python. Variables are the building blocks of any programming language, and data types are the categories of values that variables can store. By the end of this tutorial, you will be able to:

  • Understand what variables are and how they work in Python
  • Declare and assign values to variables using different methods
  • Use different data types in Python, such as numbers, strings, booleans, lists, tuples, dictionaries, and sets
  • Perform basic operations and manipulations on different data types

This tutorial assumes that you have a basic understanding of Python and data analysis. If you need a refresher, you can check out this [Python for Data Analysis] course. You will also need a Python interpreter or an online code editor to run the code examples in this tutorial. You can use this [online Python editor] or any other tool of your choice.

Ready to start? Let’s dive into Python syntax basics!

2. What are Variables?

Variables are one of the most fundamental concepts in any programming language. A variable is a name that refers to a value stored in the computer’s memory. You can think of a variable as a container that holds a piece of data that you can use in your program. For example, you can create a variable called name and assign it the value “Alice”. Then, you can use the variable name to access the value “Alice” in your program.

# Create a variable called name and assign it the value "Alice"
    name = "Alice"

    # Print the value of the variable name
    print(name)

The output of this code is:

Alice

Variables are useful because they allow you to store and manipulate data in your program without having to remember the actual values. You can also change the value of a variable at any time, and the new value will replace the old one in the memory. For example, you can change the value of the variable name from “Alice” to “Bob” by assigning it a new value.

# Change the value of the variable name from "Alice" to "Bob"
    name = "Bob"

    # Print the value of the variable name
    print(name)

The output of this code is:

Bob

Variables are essential for writing complex and dynamic programs that can handle different types of data and perform various operations on them. In the next section, you will learn how to declare variables in Python using different methods.

3. How to Declare Variables in Python?

In Python, declaring variables is very easy and simple. You don’t need to specify the type of the variable or use any special keywords. You just need to use the assignment operator = to assign a value to a variable name. For example, you can create a variable called age and assign it the value 25 by writing:

# Create a variable called age and assign it the value 25
    age = 25

Python will automatically infer the type of the variable based on the value you assign to it. In this case, the variable age will have the type int, which stands for integer. You can check the type of any variable using the built-in function type(). For example, you can write:

# Check the type of the variable age
    print(type(age))

The output of this code is:

You can also declare multiple variables in one line by separating them with commas. For example, you can create three variables called name, city, and country and assign them the values “Alice”, “New York”, and “USA” respectively by writing:

# Create three variables in one line
    name, city, country = "Alice", "New York", "USA"

Python will assign the values to the variables in the same order as they appear in the line. You can check the values and types of the variables by printing them. For example, you can write:

# Print the values and types of the variables
    print(name, type(name))
    print(city, type(city))
    print(country, type(country))

The output of this code is:

Alice 
    New York 
    USA

As you can see, the variables name, city, and country have the type str, which stands for string. A string is a sequence of characters enclosed in quotation marks. You can use either single quotes (‘ ‘) or double quotes (“ “) to create a string in Python. For example, ‘Hello’ and “Hello” are both valid strings.

When you declare variables in Python, there are some rules and conventions that you need to follow. These are:

  • The variable name must start with a letter or an underscore (_). It cannot start with a number or any other symbol.
  • The variable name can only contain letters, numbers, and underscores. It cannot contain spaces or any other characters.
  • The variable name is case-sensitive, which means that name and Name are different variables.
  • The variable name should be descriptive and meaningful, but not too long. It should also follow the [PEP 8] style guide, which recommends using lowercase letters and underscores to separate words. For example, first_name is a good variable name, but FirstName or first-name are not.
  • The variable name should not be a reserved word in Python, which are keywords that have a special meaning and function in the language. For example, you cannot use if, for, print, or def as variable names, because they are reserved words. You can find the full list of reserved words in Python [here].

By following these rules and conventions, you can avoid errors and confusion when declaring variables in Python. In the next section, you will learn about the different data types that variables can store in Python.

4. What are Data Types?

Data types are the categories of values that variables can store in Python. Data types determine the characteristics and behavior of the values, such as how they are represented, stored, manipulated, and operated on. Python has many built-in data types, but in this tutorial, we will focus on the most common and basic ones. These are:

  • Numbers: These are numeric values that can be integers, floats, or complex numbers. Integers are whole numbers, such as 1, -5, or 42. Floats are decimal numbers, such as 3.14, -2.5, or 6.02e23. Complex numbers are numbers that have a real and an imaginary part, such as 2+3j, -1–4j, or 0+1j.
  • Strings: These are sequences of characters enclosed in quotation marks, such as “Hello”, ‘Python’, or “3.14”. Strings can contain letters, numbers, symbols, spaces, or any other characters. Strings can also be empty, such as “” or ‘’.
  • Booleans: These are logical values that can be either True or False. Booleans are used to represent the truth value of a condition or expression. For example, 2 > 1 is a boolean expression that evaluates to True, while 2 < 1 evaluates to False.
  • Lists: These are ordered collections of values that can be of any data type. Lists are created by enclosing the values in square brackets, such as [1, 2, 3], [“a”, “b”, “c”], or [True, False, None]. Lists can also be empty, such as []. Lists are mutable, which means that you can change their elements, add new elements, or remove existing elements.
  • Tuples: These are ordered collections of values that can be of any data type. Tuples are similar to lists, but they are created by enclosing the values in parentheses, such as (1, 2, 3), (“a”, “b”, “c”), or (True, False, None). Tuples can also be empty, such as (). Tuples are immutable, which means that you cannot change their elements, add new elements, or remove existing elements.
  • Dictionaries: These are unordered collections of key-value pairs that can be of any data type. Dictionaries are created by enclosing the key-value pairs in curly braces, such as {‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}, {1: ‘one’, 2: ‘two’, 3: ‘three’}, or {True: ‘yes’, False: ‘no’, None: ‘maybe’}. Dictionaries can also be empty, such as {}. Dictionaries are mutable, which means that you can change their values, add new pairs, or remove existing pairs.
  • Sets: These are unordered collections of unique values that can be of any data type. Sets are created by enclosing the values in curly braces, such as {1, 2, 3}, {‘a’, ‘b’, ‘c’}, or {True, False, None}. Sets can also be empty, such as set(). Sets are mutable, which means that you can add new elements or remove existing elements.

These are the main data types that you will encounter in Python programming. Each data type has its own methods and functions that you can use to manipulate and operate on the values. In the next section, you will learn how to use different data types in Python and perform some basic operations and manipulations on them.

5. How to Use Different Data Types in Python?

In this section, you will learn how to use different data types in Python and perform some basic operations and manipulations on them. You will also see some examples of code that demonstrate how to use each data type. Let’s start with numbers.

Numbers

Numbers are one of the most common and basic data types in Python. You can use numbers to perform arithmetic operations, such as addition, subtraction, multiplication, division, exponentiation, and more. You can also use numbers to compare values, such as greater than, less than, equal to, and more. Here are some examples of how to use numbers in Python:

# Create some numbers
    x = 10 # an integer
    y = 3.14 # a float
    z = 2+5j # a complex number

    # Print the numbers and their types
    print(x, type(x))
    print(y, type(y))
    print(z, type(z))

    # Perform some arithmetic operations
    print(x + y) # addition
    print(x - y) # subtraction
    print(x * y) # multiplication
    print(x / y) # division
    print(x ** y) # exponentiation

    # Perform some comparisons
    print(x > y) # greater than
    print(x < y) # less than
    print(x == y) # equal to
    print(x != y) # not equal to

The output of this code is:

10 
    3.14 
    (2+5j) 
    13.14
    6.86
    31.4
    3.184713375796178
    1385.4557313670107
    True
    False
    False
    True

As you can see, Python can handle different types of numbers and perform various operations on them. You can also use parentheses to change the order of operations, as in mathematics. For example, (x + y) * z will give a different result than x + (y * z).

Strings

Strings are sequences of characters enclosed in quotation marks. You can use strings to store and manipulate text data, such as names, messages, titles, and more. You can also use strings to format and display data in a readable way. Here are some examples of how to use strings in Python:

# Create some strings
    s1 = "Hello" # a string with double quotes
    s2 = 'Python' # a string with single quotes
    s3 = "" # an empty string
    s4 = "3.14" # a string that looks like a number

    # Print the strings and their types
    print(s1, type(s1))
    print(s2, type(s2))
    print(s3, type(s3))
    print(s4, type(s4))

    # Perform some string operations
    print(s1 + s2) # concatenation
    print(s1 * 3) # repetition
    print(s1[0]) # indexing
    print(s1[1:3]) # slicing
    print(len(s1)) # length
    print(s1.upper()) # upper case
    print(s2.lower()) # lower case
    print(s1.replace("l", "r")) # replacement
    print(s4.isdigit()) # check if string is a digit

The output of this code is:

Hello 
    Python 

    
    3.14 
    HelloPython
    HelloHelloHello
    H
    el
    5
    HELLO
    python
    Herro
    False

As you can see, Python can handle different types of strings and perform various operations on them. You can also use some special characters in strings, such as \n for a new line, \t for a tab, or \’ for a single quote. For example, “Hello\nWorld” will print as:

Hello
    World

You can also use the format() method to insert values into a string using placeholders. For example, “Hello, {}. You are {} years old.” .format(“Alice”, 25) will print as:

Hello, Alice. You are 25 years old.

6. Conclusion

In this tutorial, you have learned how to declare variables and use different data types in Python. You have seen how to create and manipulate numbers, strings, booleans, lists, tuples, dictionaries, and sets. You have also learned some basic operations and functions that you can use on each data type. You have also seen some examples of code that demonstrate how to use each data type.

By learning these concepts, you have gained a solid foundation for Python programming and data analysis. You can now use variables and data types to store and manipulate data in your programs. You can also use them to format and display data in a readable way. You can also use them to perform calculations, comparisons, and logical operations.

We hope that you have enjoyed this tutorial and learned something new and useful. If you want to learn more about Python syntax and data types, you can check out these [resources]. If you want to practice what you have learned, you can try these [exercises]. If you have any questions or feedback, you can leave a comment below. Thank you for reading and happy coding!

Subscribe for FREE to get your 42 pages e-book: Data Science | The Comprehensive Handbook

Get step-by-step e-books on Python, ML, DL, and LLMs.

PlainEnglish.io 🚀

Thank you for being a part of the In Plain English community! Before you go:

Python
Syntax
Variables
Data Types
Programming
Recommended from ReadMedium