Variable Types

• 2.2. I/O Operations
• 2.4. Mathematical Operations
• 2.5. Dealing with Errors
• 7.4. Sequence Operations
• 7.6. Copying Data Structures

2.1. Variables and Data Types

In this section, we're going to look at one of the most fundamental concept of programming, variables and data types.

Introduction to Variables

Simply put, variables are containers that store a specific value. Each variable has a name and a value. We can store any value to variable and when we want to access that value again, we can simply reference that variable with its name.

For example, if we want to store the age of user, we can simply write: age = 20 This is the syntax of creating variables. Here, left hand side of the = symbol represents the name of variable while the right hand side is the value assigned to variable.

20 = age is not a valid syntax. Left side is always the variable name with right side being the value to store.

When we need the information, we can simply access it by referencing variable name:

Variable types

If you are coming from another language, you might be used to mentioning the type of variable when declaring it. In Python, the type is inferred automatically.

Rules for variable name

There are a few rules for the name of a variable which must be followed:

• Variable name can only contain letters, numbers or underscore.
• Variable names are case-sensitive. (e.g. age and Age are two different variables)

Updating a variable

As the name suggest, variables value can be varied too. For example, in below snippet of code we are first assigning the value 20 to age and after printing that, we're updating the age variable to hold the value 30.

When updating a variable, you can use the previous value too. For example, incrementing the previous age by one:

In programming, we tend to deal with different kinds of data e.g. numbers, text, decimal numbers, dates etc.

To categorize the data, we have data types in programming. Data types are used to represent the type or kind of data. In Python, we have four basic data types:

• str (string) for textual data
• int for integers or whole numbers
• float for floating point (decimal) numbers
• bool (boolean) for boolean values ( True or False )

The string type, str , is used to represent arbitrary textual values. In order to represent a string, we enclose the given text in quotes.

type() function

When we call the type(X) function, it returns the type of X .

Strings are used when we want to represent any textual value. It is important that we enclose strings in quotes, either double quotes or single quotes.

In this case, both name and name2 are same. Worth noting that we cannot mix double and single quotes. If you start a string with double quote, you must end it with a double quote too and vice versa.

This code will raise an error because quotes are not consistent: name = "Harry Potter'

When we want to represent integers i.e whole numbers, we use the int data type. To represent numbers, we simply write the number as is. There is no need of enclosing them in quotes.

A common pitfall is to enclose the number in quotes which makes it of str data type instead of int data type.

Floating-point numbers

Floating-point numbers are simply decimal numbers. In Python, the data type to represent these numbers is called float .

Boolean values

Boolean value is simply either True or False . Boolean values are often used to represent ON/OFF state. For example, if you're developing a program to control the lights remotely, you might need a boolean value to represent the current state of lights.

In Python, we have bool type to represent boolean values. There are only two boolean literals, True and False .

Booleans are used in logical expressions and conditionals . These topics are covered in later sections.

Converting data types

In programming, it is important to ensure that each data is in its appropriate data type. This is done to ensure that proper operations can be performed on the data.

For example, if you have two numeric strings "20" and "30" , you cannot add these two until they are converted to integer type.

• The two strings are joined together instead of expected mathematical addition operation.

In order to convert a data into a different type, we can call that data type with the value that needs to be converted.

For example, we can convert a numeric string to integer:

Similar to this, a string can also be converted to float and bool . Note that conversion can only occur successfully if the string is convertable to the given type. That is, in case of integers, all characters in a string are numbers.

• Raises an error as x cannot be converted to integer.

For each scenario, think of an appropriate Python data type that can be used.

• To store the address of a user.
• To store the phone number of a user.
• To store the height of user.
• To store whether the user is over 18 or not.
• To store the address of a user: str

Because address is a text, we must use a string to store it.

• To store the phone number of a user: str

Phone numbers are a set of digits and could also include dashes or plus symbols, so a string.

• To store the height of user: float

Heights can vary in decimals so floating point number is appropriate to use here.

• To store whether the user is over 18 or not: bool

Since there are only two possible cases here: over 18 or not over 18, we can use simply use a boolean value which if True, represents that user is over 18 and vice versa.

If you've used another statically typed programming language, you may be aware that variables can have fixed types and once declared, they cannot change type. This isn't the case in Python. Python is a dynamically typed language which means type can change at runtime.

For example, in this case, we first assign age an int but we can update it afterwards to hold a str type value. This code would execute without any errors.

In short, the type of variable isn't fixed and can change during the execution of program.

Variable Assignment

Variable types in python, object references, object identity, variable names, reserved words (keywords).

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Variables in Python

In the previous tutorial on Basic Data Types in Python , you saw how values of various Python data types can be created. But so far, all the values shown have been literal or constant values:

If you’re writing more complex code, your program will need data that can change as program execution proceeds.

Here’s what you’ll learn in this tutorial: You will learn how every item of data in a Python program can be described by the abstract term object , and you’ll learn how to manipulate objects using symbolic names called variables .

Interactive Quiz

Test your understanding of Python variables and object references.

Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign ( = ):

This is read or interpreted as “ n is assigned the value 300 .” Once this is done, n can be used in a statement or expression, and its value will be substituted:

Just as a literal value can be displayed directly from the interpreter prompt in a REPL session without the need for print() , so can a variable:

Later, if you change the value of n and use it again, the new value will be substituted instead:

Python also allows chained assignment, which makes it possible to assign the same value to several variables simultaneously:

The chained assignment above assigns 300 to the variables a , b , and c simultaneously.

In many programming languages, variables are statically typed. That means a variable is initially declared to have a specific data type, and any value assigned to it during its lifetime must always have that type.

Variables in Python are not subject to this restriction. In Python, a variable may be assigned a value of one type and then later re-assigned a value of a different type:

What is actually happening when you make a variable assignment? This is an important question in Python, because the answer differs somewhat from what you’d find in many other programming languages.

Python is a highly object-oriented language . In fact, virtually every item of data in a Python program is an object of a specific type or class. (This point will be reiterated many times over the course of these tutorials.)

Consider this code:

When presented with the statement print(300) , the interpreter does the following:

• Creates an integer object
• Gives it the value 300
• Displays it to the console

You can see that an integer object is created using the built-in type() function:

A Python variable is a symbolic name that is a reference or pointer to an object. Once an object is assigned to a variable, you can refer to the object by that name. But the data itself is still contained within the object.

For example:

This assignment creates an integer object with the value 300 and assigns the variable n to point to that object.

The following code verifies that n points to an integer object:

Now consider the following statement:

What happens when it is executed? Python does not create another object. It simply creates a new symbolic name or reference, m , which points to the same object that n points to.

Next, suppose you do this:

Now Python creates a new integer object with the value 400 , and m becomes a reference to it.

Lastly, suppose this statement is executed next:

Now Python creates a string object with the value "foo" and makes n reference that.

There is no longer any reference to the integer object 300 . It is orphaned, and there is no way to access it.

Tutorials in this series will occasionally refer to the lifetime of an object. An object’s life begins when it is created, at which time at least one reference to it is created. During an object’s lifetime, additional references to it may be created, as you saw above, and references to it may be deleted as well. An object stays alive, as it were, so long as there is at least one reference to it.

When the number of references to an object drops to zero, it is no longer accessible. At that point, its lifetime is over. Python will eventually notice that it is inaccessible and reclaim the allocated memory so it can be used for something else. In computer lingo, this process is referred to as garbage collection .

In Python, every object that is created is given a number that uniquely identifies it. It is guaranteed that no two objects will have the same identifier during any period in which their lifetimes overlap. Once an object’s reference count drops to zero and it is garbage collected, as happened to the 300 object above, then its identifying number becomes available and may be used again.

The built-in Python function id() returns an object’s integer identifier. Using the id() function, you can verify that two variables indeed point to the same object:

After the assignment m = n , m and n both point to the same object, confirmed by the fact that id(m) and id(n) return the same number. Once m is reassigned to 400 , m and n point to different objects with different identities.

Deep Dive: Caching Small Integer Values From what you now know about variable assignment and object references in Python, the following probably won’t surprise you: Python >>> m = 300 >>> n = 300 >>> id ( m ) 60062304 >>> id ( n ) 60062896 Copied! With the statement m = 300 , Python creates an integer object with the value 300 and sets m as a reference to it. n is then similarly assigned to an integer object with value 300 —but not the same object. Thus, they have different identities, which you can verify from the values returned by id() . But consider this: Python >>> m = 30 >>> n = 30 >>> id ( m ) 1405569120 >>> id ( n ) 1405569120 Copied! Here, m and n are separately assigned to integer objects having value 30 . But in this case, id(m) and id(n) are identical! For purposes of optimization, the interpreter creates objects for the integers in the range [-5, 256] at startup, and then reuses them during program execution. Thus, when you assign separate variables to an integer value in this range, they will actually reference the same object.

The examples you have seen so far have used short, terse variable names like m and n . But variable names can be more verbose. In fact, it is usually beneficial if they are because it makes the purpose of the variable more evident at first glance.

Officially, variable names in Python can be any length and can consist of uppercase and lowercase letters ( A-Z , a-z ), digits ( 0-9 ), and the underscore character ( _ ). An additional restriction is that, although a variable name can contain digits, the first character of a variable name cannot be a digit.

Note: One of the additions to Python 3 was full Unicode support , which allows for Unicode characters in a variable name as well. You will learn about Unicode in greater depth in a future tutorial.

For example, all of the following are valid variable names:

But this one is not, because a variable name can’t begin with a digit:

Note that case is significant. Lowercase and uppercase letters are not the same. Use of the underscore character is significant as well. Each of the following defines a different variable:

There is nothing stopping you from creating two different variables in the same program called age and Age , or for that matter agE . But it is probably ill-advised. It would certainly be likely to confuse anyone trying to read your code, and even you yourself, after you’d been away from it awhile.

It is worthwhile to give a variable a name that is descriptive enough to make clear what it is being used for. For example, suppose you are tallying the number of people who have graduated college. You could conceivably choose any of the following:

All of them are probably better choices than n , or ncg , or the like. At least you can tell from the name what the value of the variable is supposed to represent.

On the other hand, they aren’t all necessarily equally legible. As with many things, it is a matter of personal preference, but most people would find the first two examples, where the letters are all shoved together, to be harder to read, particularly the one in all capital letters. The most commonly used methods of constructing a multi-word variable name are the last three examples:

Programmers debate hotly, with surprising fervor, which of these is preferable. Decent arguments can be made for all of them. Use whichever of the three is most visually appealing to you. Pick one and use it consistently.

You will see later that variables aren’t the only things that can be given names. You can also name functions, classes, modules, and so on. The rules that apply to variable names also apply to identifiers, the more general term for names given to program objects.

The Style Guide for Python Code , also known as PEP 8 , contains Naming Conventions that list suggested standards for names of different object types. PEP 8 includes the following recommendations:

• Snake Case should be used for functions and variable names.
• Pascal Case should be used for class names. (PEP 8 refers to this as the “CapWords” convention.)

There is one more restriction on identifier names. The Python language reserves a small set of keywords that designate special language functionality. No object can have the same name as a reserved word.

In Python 3.6, there are 33 reserved keywords:

Python
Keywords

You can see this list any time by typing help("keywords") to the Python interpreter. Reserved words are case-sensitive and must be used exactly as shown. They are all entirely lowercase, except for False , None , and True .

Trying to create a variable with the same name as any reserved word results in an error:

This tutorial covered the basics of Python variables , including object references and identity, and naming of Python identifiers.

You now have a good understanding of some of Python’s data types and know how to create variables that reference objects of those types.

Next, you will see how to combine data objects into expressions involving various operations .

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

John is an avid Pythonista and a member of the Real Python tutorial team.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: basics python

Recommended Video Course: Variables in Python

Almost there! Complete this form and click the button below to gain instant access:

Python 3 Cheat Sheet (PDF)

🔒 No spam. We take your privacy seriously.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

• Get Started With Python

Python Fundamentals

• Python Variables and Literals
• Python Type Conversion
• Python Basic Input and Output
• Python Operators

Python Flow Control

• Python if...else Statement
• Python for Loop
• Python while Loop
• Python break and continue
• Python pass Statement

Python Data types

• Python Numbers and Mathematics
• Python List

Python Tuple

• Python String

Python Sets

Python Dictionary

• Python Functions
• Python Function Arguments
• Python Variable Scope
• Python Global Keyword
• Python Recursion
• Python Modules
• Python Package
• Python Main function

Python Files

• Python Directory and Files Management
• Python CSV: Read and Write CSV files
• Reading CSV files in Python
• Writing CSV files in Python
• Python Exception Handling
• Python Exceptions
• Python Custom Exceptions

Python Object & Class

• Python Objects and Classes
• Python Inheritance
• Python Multiple Inheritance
• Polymorphism in Python

• List comprehension
• Python Lambda/Anonymous Function
• Python Iterators
• Python Generators
• Python Namespace and Scope
• Python Closures
• Python Decorators
• Python @property decorator
• Python RegEx

Python Date and Time

• Python datetime
• Python strftime()
• Python strptime()
• How to get current date and time in Python?
• Python Get Current Time
• Python timestamp to datetime and vice-versa
• Python time Module
• Python sleep()

• Precedence and Associativity of Operators in Python
• Python Keywords and Identifiers
• Python Asserts
• Python Json
• Python *args and **kwargs

Python Tutorials

Python Numbers, Type Conversion and Mathematics

• Python Dictionary items()
• Python List extend()
• Python Data Types

In computer programming, data types specify the type of data that can be stored inside a variable. For example,

Here, 24 (an integer) is assigned to the num variable. So the data type of num is of the int class.

Data Types Classes Description
Numeric int, float, complex holds numeric values
String str holds sequence of characters
Sequence list, tuple, range holds collection of items
Mapping dict holds data in key-value pair form
Boolean bool holds either or
Set set, frozenset hold collection of unique items

Since everything is an object in Python programming, data types are actually classes and variables are instances(object) of these classes.

• Python Numeric Data type

In Python, numeric data type is used to hold numeric values.

Integers, floating-point numbers and complex numbers fall under Python numbers category. They are defined as int , float and complex classes in Python.

• int - holds signed integers of non-limited length.
• float - holds floating decimal points and it's accurate up to 15 decimal places.
• complex - holds complex numbers.

We can use the type() function to know which class a variable or a value belongs to.

Let's see an example,

In the above example, we have created three variables named num1 , num2 and num3 with values 5 , 5.0 , and 1+2j respectively.

We have also used the type() function to know which class a certain variable belongs to.

• 5 is an integer value, type() returns int as the class of num1 i.e <class 'int'>
• 2.0 is a floating value, type() returns float as the class of num2 i.e <class 'float'>
• 1 + 2j is a complex number, type() returns complex as the class of num3 i.e <class 'complex'>
• Python List Data Type

List is an ordered collection of similar or different types of items separated by commas and enclosed within brackets [ ] . For example,

Here, we have created a list named languages with 3 string values inside it.

Access List Items

To access items from a list, we use the index number (0, 1, 2 ...) . For example,

In the above example, we have used the index values to access items from the languages list.

• languages[0] - access first item from languages i.e. Swift
• languages[2] - access third item from languages i.e. Python

• Python Tuple Data Type

Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.

In Python, we use the parentheses () to store items of a tuple. For example,

Here, product is a tuple with a string value Xbox and integer value 499.99 .

Access Tuple Items

Similar to lists, we use the index number to access tuple items in Python . For example,

• Python String Data Type

String is a sequence of characters represented by either single or double quotes. For example,

In the above example, we have created string-type variables: name and message with values 'Python' and 'Python for beginners' respectively.

• Python Set Data Type

Set is an unordered collection of unique items. Set is defined by values separated by commas inside braces { } . For example,

Here, we have created a set named student_info with 5 integer values.

Since sets are unordered collections, indexing has no meaning. Hence, the slicing operator [] does not work.

• Python Dictionary Data Type

Python dictionary is an ordered collection of items. It stores elements in key/value pairs.

Here, keys are unique identifiers that are associated with each value.

In the above example, we have created a dictionary named capital_city . Here,

• Keys are 'Nepal' , 'Italy' , 'England'
• Values are 'Kathmandu' , 'Rome' , 'London'

Access Dictionary Values Using Keys

We use keys to retrieve the respective value . But not the other way around. For example,

Here, we have accessed values using keys from the capital_city dictionary.

Since 'Nepal' is key, capital_city['Nepal'] accesses its respective value i.e. Kathmandu

However, 'Kathmandu' is the value for the 'Nepal' key, so capital_city['Kathmandu'] throws an error message.

• Introduction

Python Tutorial

previous episode

Python for absolute beginners, next episode, variables and assignment.

Overview Teaching: 15 min Exercises: 15 min Questions How can I store data in programs? Objectives Write scripts that assign values to variables and perform calculations with those values. Correctly trace value changes in scripts that use assignment.

Use variables to store values

Variables are one of the fundamental building blocks of Python. A variable is like a tiny container where you store values and data, such as filenames, words, numbers, collections of words and numbers, and more.

The variable name will point to a value that you “assign” it. You might think about variable assignment like putting a value “into” the variable, as if the variable is a little box 🎁

(In fact, a variable is not a container as such but more like an adress label that points to a container with a given value. This difference will become relevant once we start talking about lists and mutable data types.)

You assign variables with an equals sign ( = ). In Python, a single equals sign = is the “assignment operator.” (A double equals sign == is the “real” equals sign.)

• Variables are names for values.
• In Python the = symbol assigns the value on the right to the name on the left.
• The variable is created when a value is assigned to it.
• Here, Python assigns an age to a variable age and a name in quotation marks to a variable first_name :

Variable names

Variable names can be as long or as short as you want, but there are certain rules you must follow.

• Cannot contain spaces, quotation marks, or other punctuation.
• May contain an underscore (typically used to separate words in long variable names).
• Having an underscore at the beginning of a variable name like _alistairs_real_age has a special meaning. So we won’t do that until we understand the convention.
• The standard naming convention for variable names in Python is the so-called “snake case”, where each word is separated by an underscore. For example my_first_variable . You can read more about naming conventions in Python here .

Use meaningful variable names

Python doesn’t care what you call variables as long as they obey the rules (alphanumeric characters and the underscore). As you start to code, you will almost certainly be tempted to use extremely short variables names like f . Your fingers will get tired. Your coffee will wear off. You will see other people using variables like f . You’ll promise yourself that you’ll definitely remember what f means. But you probably won’t.

So, resist the temptation of bad variable names! Clear and precisely-named variables will:

• Reinforce your understanding of Python and what’s happening in the code.
• Clarify and strengthen your thinking.

Use meaningful variable names to help other people understand what the program does. The most important “other person” is your future self!

Python is case-sensitive

Python thinks that upper- and lower-case letters are different, so Name and name are different variables. There are conventions for using upper-case letters at the start of variable names so we will use lower-case letters for now.

Off-Limits Names

The only variable names that are off-limits are names that are reserved by, or built into, the Python programming language itself — such as print , True , and list . Some of these you can overwrite into variable names (not ideal!), but Jupyter Lab (and many other environments and editors) will catch this by colour coding your variable. If your would-be variable is colour-coded green, rethink your name choice. This is not something to worry too much about. You can get the object back by resetting your kernel.

Use print() to display values

We can check to see what’s “inside” variables by running a cell with the variable’s name. This is one of the handiest features of a Jupyter notebook. Outside the Jupyter environment, you would need to use the print() function to display the variable.

You can run the print() function inside the Jupyter environment, too. This is sometimes useful because Jupyter will only display the last variable in a cell, while print() can display multiple variables. Additionally, Jupyter will display text with \n characters (which means “new line”), while print() will display the text appropriately formatted with new lines.

• Python has a built-in function called print() that prints things as text.
• Provide values to the function (i.e., the things to print) in parentheses.
• To add a string to the printout, wrap the string in single or double quotations.
• The values passed to the function are called ‘arguments’ and are separated by commas.
• When using the print() function, we can also separate with a ‘+’ sign. However, when using ‘+’ we have to add spaces in between manually.
• print() automatically puts a single space between items to separate them.
• And wraps around to a new line at the end.

Variables must be created before they are used

If a variable doesn’t exist yet, or if the name has been misspelled, Python reports an error (unlike some languages, which “guess” a default value).

The last line of an error message is usually the most informative. This message lets us know that there is no variable called eye_color in the script.

Variables Persist Between Cells Variables defined in one cell exist in all other cells once executed, so the relative location of cells in the notebook do not matter (i.e., cells lower down can still affect those above). Notice the number in the square brackets [ ] to the left of the cell. These numbers indicate the order, in which the cells have been executed. Cells with lower numbers will affect cells with higher numbers as Python runs the cells chronologically. As a best practice, we recommend you keep your notebook in chronological order so that it is easier for the human eye to read and make sense of, as well as to avoid any errors if you close and reopen your project, and then rerun what you have done. Remember: Notebook cells are just a way to organize a program! As far as Python is concerned, all of the source code is one long set of instructions.

Variables can be used in calculations

• We can use variables in calculations just as if they were values. Remember, we assigned 42 to age a few lines ago.

This code works in the following way. We are reassigning the value of the variable age by taking its previous value (42) and adding 3, thus getting our new value of 45.

Use an index to get a single character from a string

• The characters (individual letters, numbers, and so on) in a string are ordered. For example, the string ‘AB’ is not the same as ‘BA’. Because of this ordering, we can treat the string as a list of characters.
• Each position in the string (first, second, etc.) is given a number. This number is called an index or sometimes a subscript.
• Indices are numbered from 0 rather than 1.
• Use the position’s index in square brackets to get the character at that position.

Use a slice to get a substring

A part of a string is called a substring. A substring can be as short as a single character. A slice is a part of a string (or, more generally, any list-like thing). We take a slice by using [start:stop] , where start is replaced with the index of the first element we want and stop is replaced with the index of the element just after the last element we want. Mathematically, you might say that a slice selects [start:stop] . The difference between stop and start is the slice’s length. Taking a slice does not change the contents of the original string. Instead, the slice is a copy of part of the original string.

Use the built-in function len() to find the length of a string

The built-in function len() is used to find the length of a string (and later, of other data types, too).

Note that the result is 6 and not 7. This is because it is the length of the value of the variable (i.e. 'helium' ) that is being counted and not the name of the variable (i.e. element )

Also note that nested functions are evaluated from the inside out, just like in mathematics. Thus, Python first reads the len() function, then the print() function.

Choosing a Name Which is a better variable name, m , min , or minutes ? Why? Hint: think about which code you would rather inherit from someone who is leaving the library: ts = m * 60 + s tot_sec = min * 60 + sec total_seconds = minutes * 60 + seconds Solution minutes is better because min might mean something like “minimum” (and actually does in Python, but we haven’t seen that yet).
Swapping Values Draw a table showing the values of the variables in this program after each statement is executed. In simple terms, what do the last three lines of this program do? x = 1.0 y = 3.0 swap = x x = y y = swap Solution swap = x # x->1.0 y->3.0 swap->1.0 x = y # x->3.0 y->3.0 swap->1.0 y = swap # x->3.0 y->1.0 swap->1.0 These three lines exchange the values in x and y using the swap variable for temporary storage. This is a fairly common programming idiom.
Predicting Values What is the final value of position in the program below? (Try to predict the value without running the program, then check your prediction.) initial = "left" position = initial initial = "right" Solution initial = "left" # Initial is assigned the string "left" position = initial # Position is assigned the variable initial, currently "left" initial = "right" # Initial is assigned the string "right" print(position) left The last assignment to position was “left”
Can you slice integers? If you assign a = 123 , what happens if you try to get the second digit of a ? Solution Numbers are not stored in the written representation, so they can’t be treated like strings. a = 123 print(a[1]) TypeError: 'int' object is not subscriptable
Slicing What does the following program print? library_name = 'social sciences' print('library_name[1:3] is:', library_name[1:3]) If thing is a variable name, low is a low number, and high is a high number: What does thing[low:high] do? What does thing[low:] (without a value after the colon) do? What does thing[:high] (without a value before the colon) do? What does thing[:] (just a colon) do? What does thing[number:negative-number] do? Solution library_name[1:3] is: oc It will slice the string, starting at the low index and ending an element before the high index It will slice the string, starting at the low index and stopping at the end of the string It will slice the string, starting at the beginning on the string, and ending an element before the high index It will print the entire string It will slice the string, starting the number index, and ending a distance of the absolute value of negative-number elements from the end of the string
Key Points Use variables to store values. Use meaningful variable names. Python is case-sensitive. Use print() to display values. Variables must be created before they are used. Variables persist between cells. Variables can be used in calculations. Use an index to get a single character from a string. Use a slice to get a substring. Use the built-in function len to find the length of a string.

Leon Lovett

Python Variables – A Guide to Variable Assignment and Naming

In Python, variables are essential elements that allow developers to store and manipulate data. When writing Python code, understanding variable assignment and naming conventions is crucial for effective programming.

Python variables provide a way to assign a name to a value and use that name to reference the value later in the code. Variables can be used to store various types of data, including numbers, strings, and lists.

In this article, we will explore the basics of Python variables, including variable assignment and naming conventions. We will also dive into the different variable types available in Python and how to use them effectively.

Key Takeaways

• Python variables are used to store and manipulate data in code.
• Variable assignment allows developers to assign a name to a value and reference it later.
• Proper variable naming conventions are essential for effective programming.
• Python supports different variable types, including integers, floats, strings, and lists.

Variable Assignment in Python

Python variables are created when a value is assigned to them using the equals sign (=) operator. For example, the following code snippet assigns the integer value 5 to the variable x :

From this point forward, whenever x is referenced in the code, it will have the value 5.

Variables can also be assigned using other variables or expressions. For example, the following code snippet assigns the value of x plus 2 to the variable y :

It is important to note that variables in Python are dynamically typed, meaning that their type can change as the program runs. For example, the following code snippet assigns a string value to the variable x , then later reassigns it to an integer value:

x = "hello" x = 7

Common Mistakes in Variable Assignment

One common mistake is trying to reference a variable before it has been assigned a value. This will result in a NameError being raised. For example:

print(variable_name) NameError: name ‘variable_name’ is not defined

Another common mistake is assigning a value to the wrong variable name. For example, the following code snippet assigns the value 5 to the variable y instead of x :

y = 5 print(x) NameError: name ‘x’ is not defined

To avoid these mistakes, it is important to carefully review code and double-check variable names and values.

Using Variables in Python

Variables are used extensively in Python code for a variety of purposes, from storing user input to performing complex calculations. The following code snippet demonstrates the basic usage of variables in a simple addition program:

number1 = input("Enter the first number: ") number2 = input("Enter the second number: ") sum = float(number1) + float(number2) print("The sum of", number1, "and", number2, "is", sum)

This program prompts the user to enter two numbers, converts them to floats using the float() function, adds them together, and prints the result using the print() function.

Variables can also be used in more complex operations, such as string concatenation and list manipulation. The following code snippet demonstrates how variables can be used to combine two strings:

greeting = "Hello" name = "Alice" message = greeting + ", " + name + "!" print(message)

This program defines two variables containing a greeting and a name, concatenates them using the plus (+) operator, and prints the result.

Variable Naming Conventions in Python

In Python, proper variable naming conventions are crucial for writing clear and maintainable code. Consistently following naming conventions makes code more readable and easier to understand, especially when working on large projects with many collaborators. Here are some commonly accepted conventions:

ConventionExample
Lowercasefirst_name
UppercaseLAST_NAME
Camel CasefirstName
Snake Casefirst_name

It’s recommended to use lowercase or snake case for variable names as they are easier to read and more commonly used in Python. Camel case is common in other programming languages, but can make Python code harder to read.

Variable names should be descriptive and meaningful. Avoid using abbreviations or single letters, unless they are commonly understood, like “i” for an iterative variable in a loop. Using descriptive names will make your code easier to understand and maintain by you and others.

Lastly, it’s a good practice to avoid naming variables with reserved words in Python such as “and”, “or”, and “not”. Using reserved words can cause errors in your code, making it hard to debug.

Scope of Variables in Python

Variables in Python have a scope, which dictates where they can be accessed and used within a code block. Understanding variable scope is important for writing efficient and effective code.

Local Variables in Python

A local variable is created within a particular code block, such as a function. It can only be accessed within that block and is destroyed when the block is exited. Local variables can be defined using the same Python variable assignment syntax as any other variable.

Example: def my_function():     x = 10     print(“Value inside function:”, x) my_function() print(“Value outside function:”, x) Output: Value inside function: 10 NameError: name ‘x’ is not defined

In the above example, the variable ‘x’ is a local variable that is defined within the function ‘my_function()’. It cannot be accessed outside of that function, which is why the second print statement results in an error.

Global Variables in Python

A global variable is a variable that can be accessed from anywhere within a program. These variables are typically defined outside of any code block, at the top level of the program. They can be accessed and modified from any code block within the program.

Example: x = 10 def my_function():     print(“Value inside function:”, x) my_function() print(“Value outside function:”, x) Output: Value inside function: 10 Value outside function: 10

In the above example, the variable ‘x’ is a global variable that is defined outside of any function. It can be accessed from within the ‘my_function()’ as well as from outside it.

When defining a function, it is possible to access and modify a global variable from within the function using the ‘global’ keyword.

Example: x = 10 def my_function():     global x     x = 20 my_function() print(x) Output: 20

In the above example, the ‘global’ keyword is used to indicate that the variable ‘x’ inside the function is the same as the global variable ‘x’. The function modifies the global variable, causing the final print statement to output ’20’ instead of ’10’.

One of the most fundamental concepts in programming is the use of variables. In Python, variables allow us to store and manipulate data efficiently. Here are some practical examples of how to use variables in Python:

Mathematical Calculations

Variables are often used to perform mathematical calculations in Python. For instance, we can assign numbers to variables and then perform operations on those variables. Here’s an example:

x = 5 y = 10 z = x + y print(z) # Output: 15

In this code, we have assigned the value 5 to the variable x and the value 10 to the variable y. We then create a new variable z by adding x and y together. Finally, we print the value of z, which is 15.

String Manipulation

Variables can also be used to manipulate strings in Python. Here is an example:

first_name = “John” last_name = “Doe” full_name = first_name + ” ” + last_name print(full_name) # Output: John Doe

In this code, we have assigned the strings “John” and “Doe” to the variables first_name and last_name respectively. We then create a new variable full_name by combining the values of first_name and last_name with a space in between. Finally, we print the value of full_name, which is “John Doe”.

Working with Data Structures

Variables are also essential when working with data structures such as lists and dictionaries in Python. Here’s an example:

numbers = [1, 2, 3, 4, 5] sum = 0 for num in numbers:     sum += num print(sum) # Output: 15

In this code, we have assigned a list of numbers to the variable numbers. We then create a new variable sum and initialize it to 0. We use a for loop to iterate over each number in the list, adding it to the sum variable. Finally, we print the value of sum, which is 15.

As you can see, variables are an essential tool in Python programming. By using them effectively, you can manipulate data and perform complex operations with ease.

Variable Types in Python

Python is a dynamically typed language, which means that variables can be assigned values of different types without explicit type declaration. Python supports a wide range of variable types, each with its own unique characteristics and uses.

Numeric Types:

Python supports several numeric types, including integers, floats, and complex numbers. Integers are whole numbers without decimal points, while floats are numbers with decimal points. Complex numbers consist of a real and imaginary part, expressed as a+bi.

TypeExampleDescription
int42Represent whole numbers
float3.14Represent decimal numbers
complex1+2jRepresent numbers with real and imaginary parts

Sequence Types:

Python supports several sequence types, including strings, lists, tuples, and range objects. Strings are sequences of characters, while lists and tuples are sequences of values of any type. Range objects are used to represent sequences of numbers.

TypeExampleDescription
str‘hello’Represents text strings
list[1, 2, 3]Represents ordered collections of values
tuple(1, 2, 3)Represents immutable ordered collections of values
rangerange(0, 10)Represents a range of numbers

Mapping Types:

Python supports mapping types, which are used to store key-value pairs. The most commonly used mapping type is the dictionary, which supports efficient lookup of values based on their associated keys.

TypeExampleDescription
dict{‘name’: ‘John’, ‘age’: 30}Represents a collection of key-value pairs

Boolean Type:

Python supports a Boolean type, which is used to represent truth values. The Boolean type has two possible values: True and False.

Python has a special value called None, which represents the absence of a value. This type is often used to indicate the result of functions that do not return a value.

Understanding the different variable types available in Python is essential for effective coding. Each type has its own unique properties and uses, and choosing the right type for a given task can help improve code clarity, efficiency, and maintainability.

Python variables are a fundamental concept that every aspiring Python programmer must understand. In this article, we have covered the basics of variable assignment and naming conventions in Python. We have also explored the scope of variables and their different types.

It is important to remember that variables play a crucial role in programming, and their effective use can make your code more efficient and easier to read. Proper naming conventions and good coding practices can also help prevent errors and improve maintainability.

As you continue to explore the vast possibilities of Python programming, we encourage you to practice using variables in your code. With a solid understanding of Python variables, you will be well on your way to becoming a proficient Python programmer.

Exception Handling in Python – A Tutorial

Python is a powerful and versatile programming language used in a wide range of applications. However, even the most skilled Python developers encounter errors and bugs in their code. That’s where exception handling comes in – it is a crucial aspect of Python programming that helps prevent errors and ensure smooth code execution. Exception handling…

Understanding Scope and Namespace in Python

Python is a high-level programming language that provides powerful tools for developers to create efficient and effective code. Understanding the scope and namespace in Python is crucial for writing programs that work as intended. Python scope refers to the area of a program where a variable or function is accessible. This scope can be local…

Object Oriented Programming in Python – A Beginner’s Guide

Python is a versatile programming language that offers support for object-oriented programming (OOP). OOP is a programming paradigm that provides a modular and reusable way to design software. In this article, we will provide a beginner’s guide to object-oriented programming in Python with a focus on Python classes. Python classes are the building blocks of…

Demystifying the Python __init__ Method

Python is one of the most widely used programming languages in the world, known for its simplicity and ease of use. One of the key features of Python is the __init__ method, which plays a critical role in object-oriented programming. In this article, we will explore the __init__ method in depth, starting with its syntax…

Python decorators are a powerful language feature that allow developers to modify the behavior of functions and classes in a non-intrusive way. By wrapping code in another function, decorators provide a convenient mechanism for adding functionality to existing code without modifying it directly. In this article, we will provide a deep dive into Python decorators,…

A Guide to Python’s String Methods

Python is a powerful programming language for text processing, thanks to its rich set of string methods. Python string methods are built-in functions that allow you to manipulate and transform text data in various ways. In this article, we will explore Python’s string methods in depth, discussing their functionalities and demonstrating their usage with examples….

• suggest edit

Variables, Expressions, and Assignments

Variables, expressions, and assignments 1 #, introduction #.

In this chapter, we introduce some of the main building blocks needed to create programs–that is, variables, expressions, and assignments. Programming related variables can be intepret in the same way that we interpret mathematical variables, as elements that store values that can later be changed. Usually, variables and values are used within the so-called expressions. Once again, just as in mathematics, an expression is a construct of values and variables connected with operators that result in a new value. Lastly, an assignment is a language construct know as an statement that assign a value (either as a constant or expression) to a variable. The rest of this notebook will dive into the main concepts that we need to fully understand these three language constructs.

Values and Types #

A value is the basic unit used in a program. It may be, for instance, a number respresenting temperature. It may be a string representing a word. Some values are 42, 42.0, and ‘Hello, Data Scientists!’.

Each value has its own type : 42 is an integer ( int in Python), 42.0 is a floating-point number ( float in Python), and ‘Hello, Data Scientists!’ is a string ( str in Python).

The Python interpreter can tell you the type of a value: the function type takes a value as argument and returns its corresponding type.

Observe the difference between type(42) and type('42') !

Expressions and Statements #

On the one hand, an expression is a combination of values, variables, and operators.

A value all by itself is considered an expression, and so is a variable.

When you type an expression at the prompt, the interpreter evaluates it, which means that it calculates the value of the expression and displays it.

In boxes above, m has the value 27 and m + 25 has the value 52 . m + 25 is said to be an expression.

On the other hand, a statement is an instruction that has an effect, like creating a variable or displaying a value.

The first statement initializes the variable n with the value 17 , this is a so-called assignment statement .

The second statement is a print statement that prints the value of the variable n .

The effect is not always visible. Assigning a value to a variable is not visible, but printing the value of a variable is.

Assignment Statements #

We have already seen that Python allows you to evaluate expressions, for instance 40 + 2 . It is very convenient if we are able to store the calculated value in some variable for future use. The latter can be done via an assignment statement. An assignment statement creates a new variable with a given name and assigns it a value.

The example in the previous code contains three assignments. The first one assigns the value of the expression 40 + 2 to a new variable called magicnumber ; the second one assigns the value of π to the variable pi , and; the last assignment assigns the string value 'Data is eatig the world' to the variable message .

Programmers generally choose names for their variables that are meaningful. In this way, they document what the variable is used for.

Do It Yourself!

Let’s compute the volume of a cube with side \(s = 5\) . Remember that the volume of a cube is defined as \(v = s^3\) . Assign the value to a variable called volume .

Well done! Now, why don’t you print the result in a message? It can say something like “The volume of the cube with side 5 is \(volume\) ”.

Beware that there is no checking of types ( type checking ) in Python, so a variable to which you have assigned an integer may be re-used as a float, even if we provide type-hints .

Names and Keywords #

Names of variable and other language constructs such as functions (we will cover this topic later), should be meaningful and reflect the purpose of the construct.

In general, Python names should adhere to the following rules:

It must only contain alpha-numeric (i.e., letters a-z A-Z and digits 0-9) characters and underscores.

They cannot share the name of a Python keyword.

If you use illegal variable names you will get a syntax error.

By choosing the right variables names you make the code self-documenting, what is better the variable v or velocity ?

The following are examples of invalid variable names.

These basic development principles are sometimes called architectural rules . By defining and agreeing upon architectural rules you make it easier for you and your fellow developers to understand and modify your code.

If you want to read more on this, please have a look at Code complete a book by Steven McConnell [ McC04 ] .

Every programming language has a collection of reserved keywords . They are used in predefined language constructs, such as loops and conditionals . These language concepts and their usage will be explained later.

The interpreter uses keywords to recognize these language constructs in a program. Python 3 has the following keywords:

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass break

except in raise

Reassignments #

It is allowed to assign a new value to an existing variable. This process is called reassignment . As soon as you assign a value to a variable, the old value is lost.

The assignment of a variable to another variable, for instance b = a does not imply that if a is reassigned then b changes as well.

You have a variable salary that shows the weekly salary of an employee. However, you want to compute the monthly salary. Can you reassign the value to the salary variable according to the instruction?

Updating Variables #

A frequently used reassignment is for updating puposes: the value of a variable depends on the previous value of the variable.

This statement expresses “get the current value of x , add one, and then update x with the new value.”

Beware, that the variable should be initialized first, usually with a simple assignment.

Do you remember the salary excercise of the previous section (cf. 13. Reassignments)? Well, if you have not done it yet, update the salary variable by using its previous value.

Updating a variable by adding 1 is called an increment ; subtracting 1 is called a decrement . A shorthand way of doing is using += and -= , which stands for x = x + ... and x = x - ... respectively.

Order of Operations #

Expressions may contain multiple operators. The order of evaluation depends on the priorities of the operators also known as rules of precedence .

For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3 - 1) is 4 , and (1 + 1)**(5 - 2) is 8 . You can also use parentheses to make an expression easier to read, even if it does not change the result.

Exponentiation has the next highest precedence, so 1 + 2**3 is 9 , not 27 , and 2 * 3**2 is 18 , not 36 .

Multiplication and division have higher precedence than addition and subtraction . So 2 * 3 - 1 is 5 , not 4 , and 6 + 4 / 2 is 8 , not 5 .

Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi , the division happens first and the result is multiplied by pi . To divide by 2π, you can use parentheses or write: degrees / 2 / pi .

In case of doubt, use parentheses!

Let’s see what happens when we evaluate the following expressions. Just run the cell to check the resulting value.

Floor Division and Modulus Operators #

The floor division operator // divides two numbers and rounds down to an integer.

For example, suppose that driving to the south of France takes 555 minutes. You might want to know how long that is in hours.

Conventional division returns a floating-point number.

Hours are normally not represented with decimal points. Floor division returns the integer number of hours, dropping the fraction part.

You spend around 225 minutes every week on programming activities. You want to know around how many hours you invest to this activity during a month. Use the \(//\) operator to give the answer.

The modulus operator % works on integer values. It computes the remainder when dividing the first integer by the second one.

The modulus operator is more useful than it seems.

For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y .

String Operations #

In general, you cannot perform mathematical operations on strings, even if the strings look like numbers, so the following operations are illegal: '2'-'1' 'eggs'/'easy' 'third'*'a charm'

But there are two exceptions, + and * .

The + operator performs string concatenation, which means it joins the strings by linking them end-to-end.

The * operator also works on strings; it performs repetition.

Speedy Gonzales is a cartoon known to be the fastest mouse in all Mexico . He is also famous for saying “Arriba Arriba Andale Arriba Arriba Yepa”. Can you use the following variables, namely arriba , andale and yepa to print the mentioned expression? Don’t forget to use the string operators.

Asking the User for Input #

The programs we have written so far accept no input from the user.

To get data from the user through the Python prompt, we can use the built-in function input .

When input is called your whole program stops and waits for the user to enter the required data. Once the user types the value and presses Return or Enter , the function returns the input value as a string and the program continues with its execution.

Try it out!

You can also print a message to clarify the purpose of the required input as follows.

The resulting string can later be translated to a different type, like an integer or a float. To do so, you use the functions int and float , respectively. But be careful, the user might introduce a value that cannot be converted to the type you required.

We want to know the name of a user so we can display a welcome message in our program. The message should say something like “Hello \(name\) , welcome to our hello world program!”.

Script Mode #

So far we have run Python in interactive mode in these Jupyter notebooks, which means that you interact directly with the interpreter in the code cells . The interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy. The alternative is to save code in a file called a script and then run the interpreter in script mode to execute the script. By convention, Python scripts have names that end with .py .

Use the PyCharm icon in Anaconda Navigator to create and execute stand-alone Python scripts. Later in the course, you will have to work with Python projects for the assignments, in order to get acquainted with another way of interacing with Python code.

This Jupyter Notebook is based on Chapter 2 of the books Python for Everybody [ Sev16 ] and Think Python (Sections 5.1, 7.1, 7.2, and 5.12) [ Dow15 ] .

Variables and data types ¶

In the introductory lesson , we learned how to assign some data into a variable . Below are a few examples. We will use these variables in the remainder of this lesson.

We have also learned about the important distinction between variables that store text (termed strings and abbreviated to str ) and variables that store numbers. The form of the data stored in a variable (text, number, something else) is called its type .

In the examples above, the variables name , street , and street_number are of type string. We can see this from the way that they are written. The syntax for creating a string is simply to enclose the text of the string in quote marks ( '' ). Quote marks distinguish strings (i.e. literal text) from other things such as numbers, the names of other variables, or Python commands, all of which are written without quote marks. This is similar to the use of quote marks in everyday English. Think of the lyrics to the song Say My Name by Destiny’s Child. When Beyoncé issues the instruction say my name , she intends my name to be replaced by her actual name when the instructions are carried out. This is equivalent to the following short Python program, albeit with print() in place of say , since Python has no say() function:

What if the lyrics to the song were subtly different and included quote marks around ‘ my name ’ (i.e. say ‘my name’ )? One use of quote marks in English is to clarify that a piece of text is to be interpreted literally, and not replaced with whatever the text refers to. So this version of the song would be equivalent to the following short Python program:

When it comes to data types, appearances can occasionally be deceptive. For example, the street_number variable that we created above is a string that happens to contain digits. These can occur from time to time in programming, in cases where the digits do not really represent a mathematical quantity or might sometimes need to have extra non-number characters added to them (for example, Sherlock Holmes lives at house number 221b, which we can’t represent and manipulate as an actual number).

If we are unsure what type of data is stored in a variable, we can check at the console using the built-in Python function type() :

Python is fairly strict about what we can and cannot do with various types. If we try to get Python to evaluate a mathematical expression that contains a string variable, we will encounter an error .

However, some Python functions and operators are somewhat flexible, and may instead do different things depending on the type of the variable that they are applied to. For example, the multiplication operator * performs normal math multiplication for variables that store numbers, but for strings it instead repeats their contents.

Python’s occasional flexibility about data types is a double-edged sword. On the one hand, it allows for some concise intuitive commands, such as using + to combine strings or * to repeat them. But on the other hand, it means that we can occasionally make some big mistakes in our programs without immediately becoming aware of it. For example, if we found that street_number had been entered incorrectly and in fact needed an extra zero adding to it, then we might be tempted to multiply it by 10 in order to achieve this. Python would give no warning and would go ahead with what we asked even though the result is not what we want. In this case, our program might end up sending somebody’s automated delivery a lot further down the street than we intended.

A correct way to add an extra 0 to a string would be to add another string containing the '0' character .

Assignment and immutability ¶

‘Assignment and immutability’ is of course the title of a novel by Jane Austen. But it also refers to two important concepts in Python programming. We learned about assignment earlier; when we assign some value to a variable, we store that value under the name of the variable, and can retrieve it using that name.

To understand immutability, let’s remind ourselves of something. Take a look at the value of the street_number variable after everything that we have been doing with it above.

It hasn’t changed since its original assignment. Although we have been performing various operations with the variable, we have merely been testing out and looking at the results of these operations. The value of the variable has remained unchanged. The value of a string variable will always remain the same unless we overwrite it by assigning it again. If we want to change or update the value of a variable with the result of some calculation, then we must assign that result back into the same variable name.

For example if we want to add a 'b' to the street_number string (and then print it out to check its new value):

The opposite of immutability is ‘mutability’. As it turns out, there are some data types that are mutable. That is, their contents can change without us having to overwrite them. We will meet one of these at the end of this lesson. But all the simple data types, such as strings and numbers, are immutable; string and numeric variables will only ever change their contents if there is an = somewhere in our program that overwrites them.

Although this behavior can occasionally be a source of frustration, for example if we perform some calculations but forget to store the result in the relevant variable, in general immutability is a good thing. It would be annoying if every time we wanted to calculate something with our variables, this also overwrote their contents. For example, we might want to just print out the result of adding one year to somebody’s age, without actually changing it.

Of course if we want to keep both the original value of a variable and store an updated one, we can just assign the updated value into a new variable. In such cases it is a good idea to choose an expressive variable name that says something about what the changed value means. For example:

Numeric data ¶

So far most of our examples have concerned the behavior of the string data type. Let’s now consider how Python manages numbers.

Python distinguishes between two different ways of representing numbers. Numbers can be stored either as whole numbers ( 1 , 2 , 3 , etc.) or as non-whole numbers (for example 1.618 , 2.718 , or 3.142 ). Whole numbers are called integers (abbreviated to int ), and non-whole numbers are called floating point numbers (abbreviated to float ). Just as there is a particular syntactical rule for creating a string, namely the use of quote marks, so there are syntactical rules for creating integers and floats. The presence of a decimal point ( . ) indicates a float, and its absence indicates an integer.

Take a look back at the age and height variables that we defined above. We can see that Python has stored these as two different types.

Note that even if the number represented is a whole number, if we include a decimal point its type will still be float.

For historical reasons, the syntax of programming languages (along with many other conventions in computing in general) is heavily influenced by British and US English. If you come from a part of the world where the comma is used as a decimal separator instead of the point, for example Germany, then beware that Python does not interpret it this way. If you try to create a float using the comma, the result will not be as expected. Surprisingly, however, you will not see an error message either. Instead, Python interprets commas as separating two different things, and so will store the two numbers together in a new kind of variable (called a tuple ) that can contain more than one value.

How should we decide whether to store a number as integer or float? If we want to store a non-whole number, the decision is easy; it has to be a float. But what about something like somebody’s age? Here, we have to think about what concept the number is supposed to represent in the real world, and consider whether we want to treat the units of that concept as atomic or as divisible into parts. For example, we can think of someone’s age as being a count of the number of whole years that they have survived. But we can also think of it as a continuous measure of how much time they have survived. Children in particular often like to give their age as a continuous quantity like ‘six-and-three-quarters’.

As it turns out, there are many cases in which the difference between integers and floats does not actually matter for the functioning of our program. Python is quite flexible with number types.

It allows us to mix integer and float numbers in the same mathematical expression:

The result of a mathematical expression containing a mixture of integers and floats is always a float, even if the resulting quantity is a whole number:

A calculation that involves only integers and that results in a whole number will produce an integer:

If a calculation with integers results in a non-whole number then Python does the reasonable thing and nonetheless stores the result as a float instead of rounding it off:

Indeed, any calculation involving division will result in a float, even if the result is a whole number (you might find this rule a little less intuitive):

If we are dividing integers and we would like to insist that the result also be an integer, then we can use a double slash // for so-called ‘floor division’. The result is ‘rounded down’:

A previous version of Python, Python 2, was slightly less flexible about numeric data types. The result of division with integers in Python 2 was always an integer, with the non-whole part discarded. This could produce some surprises for the unwary, such as the result of 1 / 2 being 0 .

We are learning to program with Python 3, and almost all new Python software is written for Python 3, so you do not need to worry about this. Just be aware of it if you see some older Python examples or programs when searching online.

Type conversion ¶

What if we have data of one type, but we need it to be of another? For example, we have stored the house number of an address as a string because we might need to append letters to it, but now in another part of our program we need to do some math with it, perhaps in order to find out the address of a next-door neighbor.

Python has functions that convert one data type into another. Each of these functions has the same name as the abbreviated name of the data type that we are converting to. So for example str() converts to string, and int() to integer.

We can apply these functions to variables within a calculation that would otherwise result in an error:

And here is a similar example but imagining we had first stored the house number as an integer:

Remind yourself one more time that the values of string and numeric variables are not changed unless we overwrite them with an = assignment. Forgetting that this principle also applies to type conversion can lead to a common beginners’ mistake.

Line 2 in this example has no effect on the type of the number_beast variable because it is not assigned anywhere:

Here the problem is fixed:

We saw above that Python handles the two numeric data types integer and float fairly flexibly and intuitively if we mix them in mathematical expressions. For this reason it is not so often necessary to convert variables between these two types.

(The most common case in which we do want to do this is in order to convert float to integer. We will later encounter some situations in which we definitely need integers.)

User input ¶

Let’s take a look at a common situation in which type conversion from string to numeric is necessary. In one of our first example programs, greeting_personal.py , we used the input() function in order to prompt the user to type something in at the console.

The input() function always returns a string, even if the user types in a valid number. If we try to do math with the result, we will encounter an error:

Python has no way of knowing what type of data we want to get from the user. So in order to ‘play it safe’ and always be consistent, Python makes it a string and leaves it up to us to convert the contents of the string if necessary.

So if we want to get numbers from the user, we must first convert the result of input() :

The example program age_next_year.py shows how to use this pattern of Python commands in a simple program. If you would like to explore type conversion a little more, open up the file in Spyder, save a new copy of it, for example under the name age_next_year_v2.py , and try out a few changes:

Does it matter for the workings of the program if you convert the user input to float instead of integer?

Why is it necessary to use the str() type conversion function on line 14 ? What happens if you remove it?

What happens if the user enters a non-whole number for their age, such as 6.75 ?

Python 2 again ¶

One of the other most noticeable differences in the previous version of Python was the behavior of the input() function. Confusingly, in Python 2 this function treated the user’s input not as a string, nor even as a number, but as a Python command , which Python 2 would then evaluate . In theory this allowed malicious or just clumsy users to completely mess up the workings of a program by entering their own Python commands at the console while the program was running. So Python 3 takes the much safer option of just treating all user inputs as strings.

Again, you do not need to worry about this since we will always be working with Python 3. Just be aware of it if you encounter old Python examples on the internet.

As we have seen, Python’s type system lays down some (mostly) sensible rules about what we can and cannot do with various types of data. For example, we can perform division with integers and floats but not with strings. How does this work ‘behind the scenes’? It turns out that for any variable we can access a list of the things that it is possible to do with a variable of that type. Along with the actual data stored in a variable, Python stores various links to the operations that it is possible to carry out with that type of data.

The dir() function returns this list of possibilities for a certain variable. Let’s try it for our name variable. Since this variable is a string, dir() tells us what it is possible to do with strings.

(Note that it is only very rarely that we will need to use the dir() function in an actual program. It is instead a useful function to enter at the console when we are experimenting and checking Python’s behavior. It can be particularly useful when we encounter a new type and want an overview of the sorts of things that it can do.)

In the output from dir() we see various things enclosed in double underscores __ __ . We do not need to concern ourselves with these for the moment. They define the behavior of strings when they appear in various Python commands. For example, the __add__ entry refers to the behavior of strings when we combine them with the + operator.

The entries that interest us for the moment are those without underscores. These are the names of functions that can be applied to strings. Functions that are defined especially for one data type and can be accessed through variables of that type are called ‘ methods ’ for that data type. For example, the penultimate entry in the list of string methods above is a method called upper . This method returns an all UPPERCASE version of the string. This method is special to strings; it wouldn’t make any sense for other data types.

The syntax for calling a method has a lot in common with the syntax for calling any other function:

place parentheses after the name of the method

(optionally) place any input arguments for the method inside the parentheses

But there is an important difference. We first ‘go into’ the variable that we want to apply the method to, and get the method from there. To go into a variable like this in Python, we place a dot ( . ) after its name.

So to call the upper() method on our string variable name :

Note that we do not also need to put the variable inside the parentheses, as we do with functions. Because we have accessed the method by first going into a particular variable, Python already understands that we wish to apply the method to that same variable.

Indeed, if we make this mistake, we may get an error message telling us that we have given too many input arguments :

And remember once again that strings are immutable . Calling a method of a string variable does not change the string, it merely returns the result.

Some methods require additional input arguments . For example the string method count() counts how many times a particular ‘substring’ appears inside a string variable. The input argument is the substring to count:

Note that Python strings are ‘case-sensitive’. UPPERCASE characters are not considered the same as their lowercase counterparts:

Python syntax allows methods to be applied one after another within the same command. Immediately after calling one method, we can use the . syntax again to call another method on the result of calling the first method.

For example, to first get a lowercase version of a string and then count the occurrences of a particular character in that lowercase version:

A common pattern when dealing with user input is to apply a few string methods to the input in order to ‘clean’ it. If we would like to make our program a little more robust to variations in user behavior, we can for example strip away any surrounding spaces that they typed by accident (with the strip() method), and then convert the result to lowercase (with the lower() method).

For example to allow the user to type 'yes' , 'Yes' , 'YES' , or even '       yEs' and make all these inputs equivalent to 'yes' :

Now would be a good moment to turn to the console in Spyder and explore some of the other string methods. In the console, create yourself a string variable (for example by entering a command like word = 'floccinaucinihilipilification' ), then use the dir() function to view its available methods, then try to apply some of them to see what they do.

Some string methods are a bit too complex for us at this stage. Try the following ones:

capitalize()

index() (Note the subtle difference from find() .)

startswith()

If you are feeling adventurous you can just try these out and see whether you can work out what they do. If so, make sure to test them with a variety of different strings to check that you have really understood their behavior. If you would like to check or need some help with examples, you can search online for Python string method x or you can read the official documentation for all of Python’s string methods here .

You might be wondering whether the two numeric data types that we have learned about also have methods. They do. But because we tend to work with numbers primarily using mathematical operators , we rarely need to work directly with their methods as we do for strings.

String formatting ¶

We will look now at just one more string method together, because it is a very useful one, but whose use is not completely straightforward. The format() method inserts the values of other variables into certain positions in a string. This is particularly useful for preparing neat printouts for the users of our programs.

To use format() , our string must contain the characters {} in the positions where we would like to insert something. These positions are termed ‘replacement fields’, and they will be replaced by the values from the variables that we give as arguments to the format() method.

Let’s see an example using format() to print out a few different pieces of information contained in the variables we created at the beginning of this lesson:

We can see that if we have multiple {} replacement fields, these are replaced with the values of the variables that we give to format() in the order that we enter them. Notice also that we did not have to use the str() type conversion function to convert the two numeric variables age and height into strings; format() handles variables of different types automatically.

There is a little bit more to the format() method than this. For example, we can also specify how many decimal places of a float to insert into the string, and other details. But this is enough for now about format() , and about string methods in general. If you would like to see an example of a program that makes use of a few string methods, take a look at name_trivia.py .

Other types ¶

Are there other data types in Python? Is there anything in the world worth talking about other than words and numbers?

Yes. In fact there are lots more. We will finish this lesson with a quick overview of a few more types. We will learn about these in more detail in the lessons that follow.

Variables of boolean type are very simple. They store one of only two possible values: True or False . Boolean values can be the result of various Python commands whose purpose is to check whether or not something is the case. For example, the string method startswith() returns a boolean value, True if the string starts with a particular substring, and False otherwise:

(If you were expecting True above, remember that strings are case-sensitive.)

Occasionally, the status of some piece of information in our program is neither true nor false nor a string nor a number nor anything, it is instead simply undefined. There is an ‘empty’ type called None for this eventuality. We might occasionally assign None into a variable as a default starting value, anticipating that this value might be changed later on in our program.

We can also sometimes get a None value if we try to assign the result of a function that actually does not return anything. For example, although the print() function serves to display output for the user of our program, it does not actually return any value that can be assigned. By default, a function that does not return anything returns None .

We briefly encountered the tuple by mistake earlier, when we tried to create a float using a comma for the decimal separator instead of a point. The comma is not the correct Python syntax for the decimal separator, but it turns out that it is the correct syntax for something else: separating multiple values in a sequence. The result is a data type that does exactly that; it stores multiple values in a sequence. Although not an absolutely necessary aspect of the syntax, it is an extremely common convention to also place parentheses around the sequence of values when creating a tuple, as this makes our program clearer.

Here is an example of creating a tuple:

We can refer to the values in a tuple using their indices , their numbered positions in the sequence. We place the index in square parentheses [] after the name of the tuple variable.

Beware that Python’s numbering system for sequences begins at zero. So the first value in a tuple has index 0 , the second value has index 1 , and so on.

We cannot change individual values in a tuple. Here is what happens if we try:

Like all the data types we have encountered so far, tuples are immutable . If we want to change the contents of a tuple variable, we must overwrite the whole thing by assigning it anew with = .

Not being able to change individual values in a tuple seems like a very onerous restriction. What if we are working with data that need to be updated or added to as our program runs? Lists , the final data type that we will learn about in this lesson, provide just this ability. A list is an ordered sequence of values, just like a tuple, but it is mutable ; we can change one item in a list without having to re-assign the whole thing.

The syntax for creating a list is the same as for creating a tuple, except with square parentheses in place of round ones:

Python allows us to change individual values in a list:

There are also list methods , like the string methods we learned about above. For example, there is a list method called append() for adding a new value to the end of the list:

Notice what just happened. The append() method changed the list without our having to assign the result back into the list variable with = . This is different from the behavior of string methods. As we learned above, string methods always just return the result of whatever it is that they do with the string, but they do not change the string while doing so. List methods just go ahead and change the list.

This distinction is important, and forgetting it can lead to some frustrating mistakes. Let’s see what happens if we try to use a list method as if it were a string method, and assign its return value back into the original list variable:

The print() function suddenly seems to have no effect, and prints nothing. This is because our list has gone. List methods do not do their work by outputting a return value as string methods do. Most list methods do not output anything. As we learned a moment ago, the output of a function that does not have any defined output is the None value. So our list has become just None .

So beware. If you want to change a list, it is enough to just use the list method. Don’t assign the result back into the list variable.

As you did for string methods above, take a moment to go to the console in Spyder and explore the behavior of some of the list methods. Try to discover what the following methods do:

Because list methods just change the contents of the list behind the scenes and do not produce output, you will need to print() your list after applying each method to see what change has taken place.

Exercises ¶

A good way to strengthen your understanding of how Python works is to test that understanding regularly. When you test out a command in the console, try first to predict what the result will be, and only then type it in to check whether you were right. What is the result of each of the following short programs?

The ‘half-your-age-plus-seven’ rule is a folk rule of thumb used to calculate the minimum socially acceptable age of your dating partners, given your age. The rule asserts that if your age is \(x\) , then the minimum socially acceptable age for your partner is:

Write a program that asks the user for their age, and then tells them the result of applying this rule of thumb.

Python Programming

Python Variables and Data Types Quiz

Updated on:  February 24, 2024 | 62 Comments

This Python Variables and Data Types Quiz provide Multiple Choice Questions(MCQ) to get familiar with different data types of variables. This online quiz will help you to improve your understanding of Python variable assignment and casting.

Also, Solve Python Basic Exercise for Beginners .

• The quiz contains 13 Questions . Solve 8 correct to pass the test.

Read Variables in Python and  Python Data Types to solve this quiz.

1. What is the output of the following code?

2. What is the output of the following variable assignment?

Refer Variables in Python .

3. What is the data type of print(type(0xFF))

4. Select all the right ways to create a string literal Ault'Kelly

5. What is the data type of the following

• Python Data types
• tuples in Python

6. What is the output of the following code

print(bool(0), bool(3.14159), bool(-3), bool(1.0+1j))

7. What is the output of the following code

8. What is the output of print(type({}) is set)

9. Please select the correct expression to reassign a global variable “ x ” to 20 inside a function fun1()

global.x = 20

10. Select all the valid String creation in Python

• str1 = 'str1'
• str1 = "str1"
• str1 = '''str'''
• str1 = "str1""
• str1 = '''str1''

11. In Python 3, what is the output of type(range(5)) . (What data type it will return).

Hint : range() in Python

12. What is the data type of print(type(10))

13. What is the result of print(type([]) is list)

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

• 15+ Topic-specific Exercises and Quizzes
• Each Exercise contains 10 questions
• Each Quiz contains 12-15 MCQ

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

• Learn Python
• Python Basics
• Python Databases
• Python Exercises
• Python Quizzes
• Online Python Code Editor
• Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

Official websites use .gov

A .gov website belongs to an official government organization in the United States.

Secure .gov websites use HTTPS

A lock ( ) or https:// means you've safely connected to the .gov website. Share sensitive information only on official, secure websites.

National Electronic Health Records Survey (NEHRS) Restricted Variables

The restricted National Electronic Health Records Survey (NEHRS)  data files from the 2012, 2013, 2014, 2015, 2017, 2018, 2019, and 2021, formerly the National Ambulatory Medical Care Survey (NAMCS) Electronic Medical Records Supplement from 2008—2011, and the Physicians Experiences with Electronic Health Records Surveys (PEEHRS), are available for use by approved researchers in the NCHS Research Data Center (RDC). The RDC provides access to restricted survey data files for approved users and fees apply. To access any restricted NEHRS data, investigators must first submit requests in the Standard Application Process (SAP) portal. Instructions for preparing and submitting an application are available here . The SAP portal is available here .

Currently, NEHRS data dictionaries can be obtained as PDF files directly from the NEHRS website .

• National Center for Health Statistics
• U.S. Census Bureau, Center for Economic Studies

• The Centers for Disease Control and Prevention (CDC) cannot attest to the accuracy of a non-federal website.
• Linking to a non-federal website does not constitute an endorsement by CDC or any of its employees of the sponsors or the information and products presented on the website.
• CDC is not responsible for Section 508 compliance (accessibility) on other federal or private website.

Guidelines for Purging Oracle Learning Assignments

You can purge, or permanently delete, any types of learning assignments with a Deleted status from Oracle Learning. This means course, offering, specialization, legacy, noncatalog, and self-service learning.

Purging a Deleted assignment also purges any of this related data:

• Complete date-effective history.
• Event assignment profile, including request details and assignment rules data, when the assignment profile links to only the current learning assignment. If the assignment profile also links to other assignments, the assignment profile data isn't purged.
• Related offering assignments and related data are purged when you purge the corresponding course assignment. This happens only when the course and offering assignments are eligible for purge and have the Deleted status.

Course and Offering Assignment

When a course assignment links to multiple offering assignments, purging one of the offering assignments won't affect the other linked offering assignments, regardless of their statuses. Also, purging an offering assignment won't purge the corresponding course assignment. But purging a course assignment also recursively purges the linked offering assignments and their related data, as long as all offering assignments have a Deleted status. If even one offering assignment has a different status, the purge ends in error.

Learning Initiative Assignments

Purging a course or specialization assignment linked to a learning initiative doesn't affect other learning assignments linked to the initiative.

Sample .dat File

IMAGES

1. Variables, Assignment & Data Types

2. Python Variables and Data Types

3. Variables, Data Types and Assignment

4. PPT

5. PPT

6. Assignment Questions

VIDEO

1. OS-CIT A+ JAVA_Programming_Session2

2. 10. مقدمة في برمجة جافا

3. 10th Class Computer

4. Variable Insilization in C Language

5. 10th Class Computer

6. 10th Class Computer

1. 2.1. Variables and Data Types

Data Types. In programming, we tend to deal with different kinds of data e.g. numbers, text, decimal numbers, dates etc. To categorize the data, we have data types in programming. Data types are used to represent the type or kind of data. In Python, we have four basic data types: str (string) for textual data. int for integers or whole numbers.

2. Variables in Python

Variable Assignment. Think of a variable as a name attached to a particular object. In Python, variables need not be declared or defined in advance, as is the case in many other programming languages. ... You now have a good understanding of some of Python's data types and know how to create variables that reference objects of those types ...

3. Variables and Assignment

Variables and Assignment ... A data type is a classification of the type of information that is being stored in a variable. The basic data types that you will utilize throughout this book are boolean, int, float, string, list, tuple, dictionary, set. A formal description of these data types is given in the following sections.

4. Python Variables

You simply use the equal sign = as an assignment operator, followed by the value you want to assign to the variable. Here's an example: ... One of the best features of Python is its flexibility when it comes to handling various data types. Python variables can hold various data types, including integers, floats, strings, booleans, tuples and ...

5. Python Data Types (With Examples)

Python Numeric Data type. In Python, numeric data type is used to hold numeric values. Integers, floating-point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex classes in Python.. int - holds signed integers of non-limited length.; float - holds floating decimal points and it's accurate up to 15 decimal places.

6. Docs: data types, operators, and variables

A data type categorizes a value so that the computer knows how to interpret it. data type description example; integer: whole number: 5: float: decimal number: 12.4: string: text, enclosed in quotes "happy birthday" boolean: ... Variable assignment. An assignment statement stores a value in a variable. A variable associates a name with a ...

7. Data Types & Variable Assignment

Variables are instances of data saved to your system's memory. Variables are created to "store" data in human-readable text. Variables are nuclear (like string variables) and container (like dictionaries). Follow along to learn more about assigning data to variables. In this section, you will learn how to: Differentiate between common object ...

8. Variables and Assignment

In Python, a single equals sign = is the "assignment operator." (A double equals sign == is the "real" equals sign.) Variables are names for values. In Python the = symbol assigns the value on the right to the name on the left. The variable is created when a value is assigned to it. Here, Python assigns an age to a variable age and a ...

9. Python Variables

Python variables are used to store and manipulate data in code. Variable assignment allows developers to assign a name to a value and reference it later. Proper variable naming conventions are essential for effective programming. Python supports different variable types, including integers, floats, strings, and lists.

10. Python Variables

And the operand, which is the right side of the assignment operator, is the variable's value. <code>variable_name = variable_value</code> Code language: Python (python) ... But in Python, variables are dynamically typed and not subject to the data type restriction. A variable may be assigned to a value of one type, and then later, ...

11. Python Variables and Data types

Learn about Python variables and data types with this in-depth guide. Explore integers, floats, strings, lists, and more through clear explanations and hands-on examples.

12. Variables, Expressions, and Assignments

Variables, Expressions, and Assignments 1 # Introduction # In this chapter, we introduce some of the main building blocks needed to create programs-that is, variables, expressions, and assignments. ... When input is called your whole program stops and waits for the user to enter the required data. Once the user types the value and presses ...

13. Python Variables

Variables Assignment in Python. Here, we will define a variable in python. Here, clearly we have assigned a number, a floating point number, and a string to a variable such as age, salary, and name. ... Variable Types in Python. Data types are the classification or categorization of data items. It represents the kind of value that tells what ...

14. Variables and data types

Strings¶. We have also learned about the important distinction between variables that store text (termed strings and abbreviated to str) and variables that store numbers.The form of the data stored in a variable (text, number, something else) is called its type.. In the examples above, the variables name, street, and street_number are of type string. We can see this from the way that they are ...

15. Python Variables and Data Types Quiz [15 Quiz Questions]

The quiz contains 13 Questions. Solve 8 correct to pass the test. Read all the given answers and click over the correct answer. Read Variables in Python and Python Data Types to solve this quiz. 1. Select all the valid String creation in Python. str1 = 'str1'. str1 = "str1". str1 = '''str'''.

16. Variables and data types

The following four data types are the most basic in Python: 'Hello World!'. Function print() is a built-in function in Python that is used to print the specified message to the screen. The following examples show how to use the print() function. To show the data type of a variable, use the type() function. Cast a variable to a different data ...

17. 2. Variables, expressions and statements

2.1. Values and data types¶. A value is one of the fundamental things — like a letter or a number — that a program manipulates. The values we have seen so far are 4 (the result when we added 2 + 2), and "Hello, World!".. These values are classified into different classes, or data types: 4 is an integer, and "Hello, World!" is a string, so-called because it contains a string of letters.

18. Python Data Types

Each assignment replaces the previous value, making 'x ... Example: This code demonstrates how to determine the data type of variables in Python using the type() function. It prints the data types of three variables: a (integer), b (float), and c (complex). The output shows the respective data type Python for each variable.

19. PDF Python: Variables and Data Types

Variable Guidelines/Rules: pg. 1 . Data Types: pg. 2 . Different Data Types and What They are Used For: pg. 2 . Variable Guidelines/Rules. The process of creating variables with data is referred to as "assignment." A variable assignment usually consists of a name, followed by an equal sign (=), and the value assigned by the programmer.

20. PDF Variables, Constants, and Data Types

Useful string methods • Using a string method requires three things: 1) A reference to the string, such as a string literal or a variable 2) The method name, such as upper 3) The argument list, a pair of parentheses ()with a list of values inside. May be empty • Example: print ("Hello") → Hello print ("Hello".upper()) → HELLO print ("Hello".lower()) → hello

21. Variables and Data Types

Variables are the nouns of a programming language-that is, they are the entities (values and data) that act or are acted upon. A variable declaration always contains two components: the type of the variable and. its name. For example, " int count; " has type integer and name "count". All variables in the Java language must have a data type.

22. PDF Variables, Constants, and Data Types

variable • The equals sign is also the assignment operator • The expression on the right is evaluated and the result is stored as the value of the variable on the left • The value previously stored in totalis overwritten • You can only assign a value to a variable that is consistent with the variable's declared type

23. Variable Data Types Explained

A variable has a data type such as number, string (for text), date, and Boolean (for true or false). An array stores a set of data items, often of the same type. An object represents something in the website or app, like a pet, a customer, or a blog post. The object groups related properties holding the data for the object.

24. Variables, Assignments, and Data Types Flashcards

kl07gobertKirstenG. Top creator on Quizlet. Study with Quizlet and memorize flashcards containing terms like character, String, variable and more.

25. RDC