How do you call a variable in python?


Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.

This tutorial will go over a few basic types of variables.

Numbers

Python supports two types of numbers - integers(whole numbers) and floating point numbers(decimals). (It also supports complex numbers, which will not be explained in this tutorial).

To define an integer, use the following syntax:

myint = 7
print(myint)

To define a floating point number, you may use one of the following notations:

myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)

Strings

Strings are defined either with a single quote or a double quotes.

mystring = 'hello'
print(mystring)
mystring = "hello"
print(mystring)

The difference between the two is that using double quotes makes it easy to include apostrophes (whereas these would terminate the string if using single quotes)

mystring = "Don't worry about apostrophes"
print(mystring)

There are additional variations on defining strings that make it easier to include things such as carriage returns, backslashes and Unicode characters. These are beyond the scope of this tutorial, but are covered in the Python documentation.

Simple operators can be executed on numbers and strings:

one = 1
two = 2
three = one + two
print(three)

hello = "hello"
world = "world"
helloworld = hello + " " + world
print(helloworld)

Assignments can be done on more than one variable "simultaneously" on the same line like this

a, b = 3, 4
print(a, b)

Mixing operators between numbers and strings is not supported:

# This will not work!
one = 1
two = 2
hello = "hello"

print(one + two + hello)

Exercise

The target of this exercise is to create a string, an integer, and a floating point number. The string should be named mystring and should contain the word "hello". The floating point number should be named myfloat and should contain the number 10.0, and the integer should be named myint and should contain the number 20.

# change this code mystring = None myfloat = None myint = None # testing code if mystring == "hello": print("String: %s" % mystring) if isinstance(myfloat, float) and myfloat == 10.0: print("Float: %f" % myfloat) if isinstance(myint, int) and myint == 20: print("Integer: %d" % myint) # change this code mystring = "hello" myfloat = 10.0 myint = 20 # testing code if mystring == "hello": print("String: %s" % mystring) if isinstance(myfloat, float) and myfloat == 10.0: print("Float: %f" % myfloat) if isinstance(myint, int) and myint == 20: print("Integer: %d" % myint) test_object('mystring', incorrect_msg="Don't forget to change `mystring` to the correct value from the exercise description.") test_object('myfloat', incorrect_msg="Don't forget to change `myfloat` to the correct value from the exercise description.") test_object('myint', incorrect_msg="Don't forget to change `myint` to the correct value from the exercise description.") test_output_contains("String: hello",no_output_msg= "Make sure your string matches exactly to the exercise desciption.") test_output_contains("Float: 10.000000",no_output_msg= "Make sure your float matches exactly to the exercise desciption.") test_output_contains("Integer: 20",no_output_msg= "Make sure your integer matches exactly to the exercise desciption.") success_msg("Great job!")

  • Code of Conduct
  • Setup
  • Episodes
  • Extras
  • License
  • Improve this page

Overview

Teaching: 10 min
Exercises: 10 min

Questions

  • How can I store data in programs?

Objectives

  • Write programs that assign values to variables and perform calculations with those values.

  • Correctly trace value changes in programs that use assignment.

Use variables to store values.

  • 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.

age = 42
first_name = 'Ahmed'

  • Variable names:
    • cannot start with a digit
    • cannot contain spaces, quotation marks, or other punctuation
    • may contain an underscore (typically used to separate words in long variable names)
  • Underscores at the start like __alistairs_real_age have a special meaning so we won’t do that until we understand the convention.

Use print to display values.

  • Python has a built-in function called print that prints things as text.
  • Call the function (i.e., tell Python to run it) by using its name.
  • 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 quotations.
  • The values passed to the function are called ‘arguments’

print(first_name, 'is', age, 'years old')

  • 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 mis-spelled, Python reports an error.
    • Unlike some languages, which “guess” a default value.

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-c1fbb4e96102> in <module>()
----> 1 print(eye_color)

NameError: name 'eye_color' is not defined

  • The last line of an error message is usually the most informative.
  • We will look at error messages in detail later.

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). 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.

age = age + 3
print('Age in three years:', age)

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.

element = 'helium'
print(element[0])

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.
  • An item in a list is called an element. Whenever we treat a string as if it were a list, the string’s elements are its individual characters.
  • 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.

element = 'sodium'
print(element[0:3])

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

  • Nested functions are evaluated from the inside out, just like in mathematics.

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.

Use meaningful variable names.

  • Python doesn’t care what you call variables as long as they obey the rules (alphanumeric characters and the underscore).

flabadab = 42
ewr_422_yY = 'Ahmed'
print(ewr_422_yY, 'is', flabadab, 'years old')

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

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)

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.

TypeError: 'int' object is not subscriptable

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:

  1. ts = m * 60 + s
  2. tot_sec = min * 60 + sec
  3. 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).

Slicing

What does the following program print?

library_name = 'social sciences'
print('library_name[1:3] is:', library_name[1:3])

  1. What does thing[low:high] do?
  2. What does thing[low:] (without a value after the colon) do?
  3. What does thing[:high] (without a value before the colon) do?
  4. What does thing[:] (just a colon) do?
  5. What does thing[number:negative-number] do?

Solution

  1. It will slice the string, starting at the low index and ending an element before the high index
  2. It will slice the string, starting at the low index and stopping at the end of the string
  3. It will slice the string, starting at the beginning on the string, and ending an element before the high index
  4. It will print the entire string
  5. 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 print to display values.

  • Variables persist between cells.

  • Variables must be created before they are used.

  • 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.

  • Python is case-sensitive.

  • Use meaningful variable names.

What do you call a variable in Python?

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.

How do you run a variable in Python?

If you want to execute Python statements, you can use exec(string). For example, >>> my_code = 'print "Hello World!"' >>> exec(my_code) Hello World!

How do you call variable names?

To call a variable from a data set, you have two options:.
You can call var1 by first specifying the name of the data set (e.g., mydata ): > mydata$var1 > mydata[,"var1"].
Alternatively, use the function attach() , which attaches the data set to the R search path. You can now refer to variables by name..

What is $_ in Python?

According to Python doc, the special identifier _ is used in the interactive interpreter to store the result of the last evaluation. It is stored in the builtin module.