Module 2 - Variables and Basic Data Types Header

Module 2 - Variables and Basic Data Types

Comments in Python

Before we get into actual coding, let's take a look at something that is very, very useful to know. Ironically, it's a way to type something in a Python program that results in – NOTHING – happening. Why would we need that? That's a great question.

This trick, called “commentsA way to type something in a Python program that results in nothing happening. Used for making notes in code.”, is useful precisely because it doesn't do anything, because it gives us the ability to make notes in our code without having to worry about what or how we write them.  These notes can be to ourselves, someone else we are working with on a coding project, or even to some person you don't know who could read your code in the future.  If you are reading this as part of a class, then you might want to use commentsA way to type something in a Python program that results in nothing happening. Used for making notes in code. to communicate to your teacher, so that they can understand the intent of what you are writing in your code.

Another reason to use commentsA way to type something in a Python program that results in nothing happening. Used for making notes in code. is in the early stages of writing a more complicated piece of code. In this case, you might use commentsA way to type something in a Python program that results in nothing happening. Used for making notes in code. to help you plan the structure of what you want to do.  This method is something I will cover later in the class lectures that accompany this text.

To write a comment in Python, just start your line of code with the hashtag or number symbol (#). Everything after that on the same line will be ignored when you run your code.

Here are a few examples:

# This is a comment.
# Python will ignore this whole line, no matter what I write.

I highly encourage you to make a habit of leaving commentsA way to type something in a Python program that results in nothing happening. Used for making notes in code. in your code.  You'll thank yourself later!



What's a Variable?

A variable in programming is a named location in memory that can be used to store a value. In other words, a variable is a set of characters or words that are used to store something else.  Think of it like a container for storing data, so that it can be used later in the program. For example, you could use a variable to store the user's name, the number of items in a shopping cart, or the current time. You can also change what's in the container.

To declare a variable in Python, you use the var_name = value syntax. For example, to declare a variable named name and store the value John Doe in it, you would use the following code:

name = “John Doe”


Once you have declared a variable, you can use it to store data and retrieve it later. For example, to print the value of the name variable, you would use the following code:

print(name)


This would print the following output to the console:

John Doe


Variables can be used to store any type of data, including numbers, strings, lists, and dictionaries. You can also use variables to store functions and objects.

Variables are a powerful tool that can be used to store data and make your programs more efficient. If you are new to programming, I encourage you to learn more about variables and how to use them.

Here are some additional tips for using variables:

  • Choose meaningful names for your variables. This will make your code easier to read and understand.
  • Use descriptive variable names. This will help you remember what each variable is used for.
  • Avoid using single-letter variable names. These can be difficult to read and understand.
  • Don't use reserved words as variable names. Reserved words are words that have a special meaning in the programming language.
  • Use constants for values that will not change. This will make your code more readable and maintainable.
  • It's also a good idea to indicate what type of data your variable contains.  More on this in the next section.


What are Data Types?

In Python, data types define the categories of the different kinds of data that can be stored in a variable. This is important, because the data type of a variable limits what can be done with it. Python provides several built-in data types, each with its own characteristics and usage. Let's explore each data type in detail and provide examples of their usage, starting with the basics. Later on, we will introduce a few other types:

Integer ('int')

Integers represent whole numbers without decimal points. They can be positive or negative. Here are some examples of how you can use integers in Python:

  • You can use integers to store the number of items in a list.
  • You can use integers to store the price of an item.
  • You can use integers to store the age of a person.

Here's how an integer is typically defined or assigned in Python:

x = 10
y = -5

 

Note about Integer variables:  I like to prefix Integer variables with the letters “int” so I can easily see what data type the variable is.

 

Float ('float')

Float (float): Floats are numbers with decimal points. They can be represented by digits with a decimal point. For example, 1.0, 2.5, -3.14 are all floats. Here are some examples of how you can use floats in Python:

  • You can use floats to store the price of an item.
  • You can use floats to store the weight of an object.
  • You can use floats to store the temperature of a room.

Here's how a float is typically defined or assigned in Python:

pi = 3.14
temperature = -12.5

 

Note about float variables:  I like to prefix float variables with the letters “float” so I can easily see what data type the variable is.

 

String ('str')

String (str): Strings are sequences of characters. They can be enclosed in single quotes or double quotes. Here are some examples of how you can use strings in Python:

  • You can use strings to store the name of a person.
  • You can use strings to store the title of a book.
  • You can use strings to store the lyrics of a song.

Here's how a string is typically defined or assigned in Python:

message = "Hello, world!"
firstName = 'Bill'

 

Note about string variables:  I like to prefix string variables with the letters “str” so I can easily see what data type the variable is.

 

Boolean ('bool')

Booleans are values that can be either True or False. They are often used to represent the outcome of a test or condition. For example, True and False are both Booleans.Here are some examples of how you can use Booleans in Python:

  • You can use Booleans to test whether or not a number is even.
  • You can use Booleans to test whether or not a string is empty.
  • You can use Booleans to test whether or not a list is empty.

Here's how a boolean is typically defined or assigned in Python:

is_raining = True
is_sunny = False

 

Note about boolean variables:  I like to prefix boolean variables with the letters “bool” so I can easily see what data type the variable is.

 

None ('NoneType')

The None type represents the absence of a value or a null value. It can be used as a placeholder, or to clear an existing value from a variable.  There are no examples of what kind of data it can be used to represent, because it literally means “nothing”

Here's how a none type is typically defined or assigned in Python:

result = None

 

Python supports other data types, and we will explore those later in this course.  However, we will stick with these 5 for now, so nobody gets overwhelmed with too much information too quickly.



String Type Limitations

Strings can do many things, but here are a few things they can't do: 
(Don't worry if some of these don't make sense right now - You might find yourself coming back to this page later)

  • You can't change individual letters in a string directly. For example, you can't turn "Hello" into "Hxllo" by changing the second letter.
  • If you want to combine a string with a number or a list, you need to convert the non-string item to a string first. For example, to combine the string "Hello" with the number 42, you would need to convert 42 to a string: "Hello" + str(42).
  • Slicing a string allows you to extract parts of it, but you can't modify the original string using slicing. For example, you can extract a substring from "Hello" using "Hello"[1:3], but you can't change "Hello" to "Hi" using slicing.
  • You can't perform mathematical operations directly on strings. For instance, you can't add or subtract strings like "5" + "2" or "10" - "3". If you want to do calculations with numbers represented as strings, you need to convert them to actual numbers first using functions like int() or float().
  • You can't delete characters or parts of a string directly. If you want to remove characters or substrings, you need to create a new string without those elements.
  • Changing the capitalization of characters in a string cannot be done directly. To convert a string to uppercase or lowercase, you need to create a new string with the desired capitalization using methods like upper() or lower().

Python provides many other string manipulation methods and functions that allow you to perform various operations efficiently.



Numeric Type Limitations

Overflow and Underflow: Numeric types like int and float have a finite range of values they can represent. If you perform arithmetic operations that result in a value exceeding the maximum limit (overflow) or going below the minimum limit (underflow), Python will raise an exception.

x = 2 ** 1000  # Overflow for integers
y = 1e-1000   # Underflow for floats


Precision Limitations: Floating-point numbers (float) in Python have a limited precision. This can lead to small errors in calculations that involve decimal values.

result = 0.1 + 0.2  # Expected: 0.3, Actual: 0.30000000000000004


Rounding Errors: Due to the way floating-point numbers are stored, rounding errors can occur in certain arithmetic operations. This can lead to unexpected results, especially when comparing floating-point values for equality.

x = 1.1
y = 2.2
z = 3.3
print(x + y == z)  # False (due to rounding error)


Limited Precision for Integers Used in Float Operations: When integers are involved in arithmetic operations with floating-point numbers, the result is automatically converted to a float, potentially losing some precision.

result = 1 + 0.1  # Result is a float, not an integer


Division Precision: Division of integers in Python 2.x performs integer division by default, resulting in a truncated integer value. In Python 3.x, division between integers using the / operator results in a float. To perform integer division in Python 3.x, you can use the // operator.

x = 5 / 2    # Python 3.x: 2.5, Python 2.x: 2 (integer division)
y = 5 // 2   # Python 3.x and 2.x: 2 (integer division)


It's important to be aware of these limitations when working with numeric types in Python to ensure accurate calculations and handle potential issues effectively.  Again, this isn't the sort of information that you need to memorize at this point, but if you are getting weird errors when working with numbers, this might be a good section to remember.



Python Functions

Standard Python functions are functions that are built into the Python language. They are available to all Python programs without any add-ons or special commands. You can think of a function as a command that tells Python to do something. All functions require parenthesis after the function name – even if there is nothing inside them.

Parameters are variables that are passed into a function, and are placed inside the parentheses when they are used. When you call a function, you can pass it any number of parameters. The function will then use those parameters to perform its task.

For example, the print() function can be used to print text to the console. The print() function has one parameter, which is the text that you want to print. For example, the following code prints the text "Hello, world!" to the console:

print("Hello, world!")


In this example, the print() function is called with one parameter, which is the string "Hello, world!". The print() function will then print the string to the console.

Parameters can be any type of variable, including strings, numbers, and other data types. 



The type() Function

The type() function in Python is used to get the type of an object. When you call the type() function, it will return the type of the object that you pass it.

For example, the following code gets the type of the variable name:

name = “John Doe”
print(type(name))

 

In this example, the type() function is called with the variable name. The type() function will then return the type of the variable name, which is str.

The type() function can be used to get the type of any object in Python. This can be useful for debugging or for understanding how an object works.

The type() function is a very simple function, but it can be very useful. By learning how to use the type() function, you can gain a better understanding of how Python works.

Here are some examples of how the type() function can be used:

To get the type of a variable:

name = "John Doe"
age = 47
print(type(name))
print(type(age))


The input() Function

The input() function in Python is used to get input from the user. When you call the input() function, it will prompt the user to enter some text. The text that the user enters will be returned by the input() function.

For example, the following code prompts the user to enter their name and then prints the name to the console:

name = input("What is your name? ")
print("Hello, " + name + "!")


In this example, the input() function is called with a parameter for the prompt. The prompt is the text that will be displayed to the user. The input() function will then return the text that the user enters.

The input() function can be used to get input from the user for any purpose. For example, you could use the input() function to get input from the user for a password, a number, or a choice of options.

The input() function is a very versatile function that can be used in many different ways. By learning how to use the input() function, you can make your Python programs more interactive.

Look at you go! Just like that, you know 3 functions!



String Methods

What's a Method?

 

String Information Methods

String Modification Methods



Formatting Strings

You might notice that above, a variable was added to a string inside the print function using the following syntax:

strName = “Bill”
print("My name is" + strName)


While this generally works fine in simpler applications, you could run into errors if you try this with a variable that isn't a string.  It can also get a bit messy and confusing if you have a lot of variables that you want to splice into a string.  A better way to do this in Python is through the use of formatted strings.

In Python, there are two ways to print formatted strings: f-strings and the string.format() method.

String.format() Method

The string.format() method is a more traditional way to format strings in Python. To use the string.format() method, you pass the string to the string.format() function and then use curly braces ({}) to specify the locations where expressions should be inserted. The expressions will be evaluated and replaced with their values when the string is formatted.

For example, the following code prints the string "Hello, {strName}!", where the value of the variable name is substituted for the placeholder {strName}:

strName = "John Doe"
print("Hello, {}".format(name))

F-strings

F-strings are a new feature in Python 3.6 that allow you to embed expressions in strings. F-strings are more concise and readable than the string.format() method, and they are also more efficient.

To use an f-string, simply prepend the string with the letter f. Then, you can embed expressions in the string by using curly braces ({}). The expressions will be evaluated and replaced with their values when the string is printed.

For example, the following code prints the string "Hello, {strName}!", where the value of the variable name is substituted for the placeholder {strName}:

strName = "John Doe"
print(f"Hello, {strName}!")

Which Method Should You Use?

In general, you should use f-strings whenever possible. F-strings are more concise, readable, and efficient than the string.format() method. However, if you need to support Python versions older than 3.6, you will need to use the string.format() method.

Here is a table that summarizes the differences between f-strings and the string.format() method:

FeatureF-stringsstring.format() method
SyntaxSimpler, more conciseMore complex
ReadabilityMore readableLess readable
EfficiencyMore efficientLess efficient
SupportPython 3.6+Python 2.6+


Try It: Printing Basics

Let's try some things with formatted strings in the code editor below:

First, type the following lines of code, pressing enter after each one:

strName = “Sally”
strColor = “Purple”
intAge = 42

Now, let's use a couple of these in an f-string by typing the following. Press shift-enter to run the code:

print(f"My name is {strName} and I am {intAge} years old.")


 

 

Try some of the following challenges on your own:

  1. Can you make up a sentence using the color and another variableA named location in memory used to store a value in programming.?
  2. Can you make it work using print.format() instead of an f-string?

Videos for Module 2 - Variables and Basic Data Types

2-1: About Python (17:31)

2-2: Introducing Variables in Python (4:49)

2-3: Introducing Data Types in Python (6:14)

2-4: Basic Python Functions (8:46)

2-5: The Input Function (5:30)

2-6: Sandbox 2 Explanation (12:35)

2-7: Introducing String Methods (1:28)

2-8: Transforming Strings (8:32)

2-9: String.replace( ) Function (4:44)

2-10: String.format( ) Method (7:41)

2-11: Formatted Strings in Python (5:28)

2-12: A2 Explanation (12:05)

Key Terms for Module 2 - Variables and Basic Data Types


Comments A way to type something in a Python program that results in nothing happening. Used for making notes in code.
Data Types Categories defining the kinds of data that can be stored in a variable.
F-strings A feature in Python 3.6 and later for formatting strings, allowing expressions to be embedded in strings.
Formatting Strings Techniques for formatting strings in Python, including f-strings and the string.format() method.
Input() Function A function in Python used to get input from the user.
Numeric Type Limitations Limitations of numeric types like int and float in Python, including overflow, underflow, precision limitations, rounding errors, and division precision.
Python Functions Built-in functions available in Python for various tasks. Examples: print(), type(), input().
String Methods Functions that can be applied to strings in Python for information and modification. Examples: String Information Methods, String Modification Methods.
String Type Limitations Things strings can't do directly in Python, such as changing individual letters, performing mathematical operations, or deleting characters.
String.format() Method A method in Python for formatting strings, using curly braces to specify locations for expression insertion.
Type() Function A function in Python used to get the type of an object.
Variable A named location in memory used to store a value in programming.

Quiz Yourself - Module 2 - Variables and Basic Data Types

Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.

Skip to the Next Question