2.2 Variables and Assignment Statements

2.2 Variables and Assignment Statements (1 of 2)

In [1]:
45 + 72
Out[1]:
117
In [2]:
x = 7

2.2 Variables and Assignment Statements (2 of 2)

  • Preceding snippet is a statement.
  • Specifies a task to perform.
  • Preceding statement creates x and uses the assignment symbol (=) to give x a value.
In [3]:
y = 3

Adding Variable Values and Viewing the Result

In [4]:
x + y
Out[4]:
10

Calculations in Assignment Statements

In [5]:
total = x + y
  • assignment symbol (=) is not an operator
In [6]:
total
Out[6]:
10

Python Style

  • The Style Guide for Python Code helps you write code that conforms to Python’s coding conventions.
  • Recommends inserting one space on each side of the assignment symbol = and binary operators like + to make programs more readable.

Variable Names

  • A variable name is an identifier.
  • May consist of letters, digits and underscores (_) but may not begin with a digit.
  • Python is case sensitive.

Types (1 of 2)

  • Each value in Python has a type that indicates the kind of data the value represents.
  • You can view a value’s type, with the type built-in function.
In [7]:
type(x)
Out[7]:
int
In [8]:
type(10.5)
Out[8]:
float

Types (2 of 2)

  • A function performs a task when you call it by writing its name, followed by parentheses, ().
  • The parentheses contain the function’s argument—the data that the type function needs to perform its task.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 2 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.