☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 2 : Data (Input) : Variables

Variables

Subscribe Contact


Contents

Overview

Variables in Python are labels (names) that we assign to represent datum elements. As programmers, we choose what we want to use as variable names, within some constraints based on rules (see the list below). Variable naming is often based on naming standards within a course or company where you're working. Generally speaking, variable naming is based on clear connections between the datum value and the concept it represents. Continuing the example of age, the ideal variable name to store an age is age. We could use any variable name for that value, however using something like x to store age, while valid, is less understandable for those reading or maintaining our code.

Concept: Variable
Full Concepts List: Alphabetical  or By Chapter 

In programming, a variable is a fundamental concept that acts as a storage location in a computer's memory, holding data that can be accessed and manipulated by a program. Variables are named entities, and their names are used to refer to the stored data. The name of a variable acts as a symbolic representation of the data it contains. The type of data a variable can hold (such as integers, strings, objects) is determined by its data type. Variables are mutable, meaning their values can change throughout the execution of a program. They allow programmers to store temporary data and manipulate it, making programs dynamic and flexible. The declaration and naming of variables typically follow specific rules and conventions of the programming language being used. Proper use of variables is crucial for creating readable and maintainable code, allowing programmers to express operations in a clear and logical manner.

Note: The discussion on this page includes a few highlights from the Style Guide for Python Code which contains more extensive coverage of coding conventions for Python code.

Variable Name Rules in Python

Variable Value Assignment

Once we have a datum and have decided on a variable name to use to attach to it, we assign the datum value to the variable using the assignment operator, which in Python is the equal sign. The variable appears first, then the assignment operator, and then the value, as shown here ...



Variables & Memory

When we assign a value to a variable, the value is stored in the computer's memory (RAM). The location in memory is assigned a memory address by the operating system. Our variable is the label for the memory location, which is much easier for us to read and remember than a raw memory address value such as 0x1b1271b6c30. Here is a diagram that depicts this scenario. We have declared the age variable in our Python program and assigned the value 25 to it. In memory, 25 is stored in a memory cell and our age variable is used as the label for that memory location.



Python is a Dynamically Typed Language

It is important to be aware that Python is dynamically typed. What does this mean? In some programming languages to assign a value to a variable, we must first declare the data type of that variable. That is called static typing, which is also often called safe typing. With this safety in place, if I declare a variable as an int then I cannot assign a value of another data type to that variable.

Concept: Dynamically Typed
Full Concepts List: Alphabetical  or By Chapter 

Python is often described as a dynamically typed language, which means that the type (like integer, string, list) of a variable is decided at runtime rather than in advance. In dynamically typed languages, you don't have to declare the type of a variable when you write the code. Python interprets the type based on the value it is assigned at execution time. For instance, if you assign a = 5, Python automatically understands a to be an integer. If later you assign a = "Hello", a becomes a string. This flexibility allows for faster and more concise coding, as it reduces the need for verbose type declarations and can make the code more readable and adaptable. However, it also requires careful programming, as errors related to unexpected data types might only become evident at runtime. Dynamically typed languages like Python are contrasted with statically typed languages, where the data type of each variable must be explicitly declared and does not change, such as in Java or C++.

In Python, on the other hand, we do not declare the data type of our variables. Python dynamically recognizes the data type based on the value we are assigning to the variable. So in our example above, writing age = 25 is interpreted by Python to mean that the variable age is of type integer. This is convenient, but it can be potentially problematic if later in the program we write age = "Young". In a strict-typed language, this would produce an error. This is not an error in Python, age would now contain "Young" as its value and its data type would now be a string. If we did not mean to change the data type of age, we could run into a problem with this reassignment. Here's what this would look like in PyCharm:




Let's take a look at an example of variable assignments for our data entry screen example from the previous page about Data & Data Types. The image below depicts our data entry form filled in by Bob Smith. Also, in my Python code file (Demo.py) I've written out variables to show how that data could be set to variables:




Note the following about the Python code in the Demo.py file shown above:

Multiple Variable Assignments

Python supports assigning the same value to more than one variable, like this:

x = y = z = 0
print(x)
print(y)
print(z)
person1, person2, person3 = "Bob", "Sally", "Joe"
print(person1)
print(person2)
print(person3)

The output of the above example would look like this:


0
0
0
Bob
Sally
Joe

Based on the example above, answer the following question...

Question 1

Explain why the output shown above looks the way it does.


Checking a Variable's Data Type

Since Python is dynamically typed, there are times when we may not be sure what data type a particular variable is at any given point in a program. Python has a function called type() that we can use to check the type of a variable. Here is an example of Python's dynamic typing and using the type() function:

x = 10
print(type(x))
x = "Bob"
print(type(x))
x = 3.14
print(type(x))

The output of the above example would look like this:


class 'int'
class 'str'
class 'float'

Note that we dynamically changed the data type of the variable x three times, and each print statement of type(x) demonstrated that x changes each time we assign a value.

Based on the example above, answer the following question...

Question 2

What is the output of the following code?

a = 3000
b = 10.6
a = "Three Thousand"
a = True
a = b
print(type(a))


Variable Case

As indicated previously, Python is case-sensitive. When we are creating variables for data values we have some choices on how we decide to apply the case to those variables. For example, we have used age as a variable several times now, which is a simple and clear variable name. What if we wanted to create a variable like aggregatemonthlysales? It is a descriptive variable name but can be hard to read. There are a few ways to help the readability of variables like this multi-word variable. Each of these approaches has names:

Name Example Description
Camel Case aggregateMonthlySales Camel case is structured so that the first word of a multi-word variable name is lower-case, then the first letter of each subsequent word in the name is upper-case. Other examples: firstName, maxBudget, hitPoints.
Pascal Case AggregateMonthlySales Pascal case is structured with every word in a multi-word name has its first letter upper-case. Other examples: FirstName, MaxBudget, HitPoints.
Snake Case aggregate_monthly_sales Snake case is structured with each word lower-case and separated by underscores. Other examples: first_name, max_budget, hit_points. According to the Style Guide for Python Code, Snake Case is the standard for variable names in Python.

Python Reserved Words

The Python language has a set of reserved words which are used strictly by the language. When we create variables, we cannot use any of these reserved words. The following table provides a list of these reserved words (current as of Python 3.9):

and as assert async await break
class continue def del elif else
except False finally for from global
if import in is lambda None
nonlocal not or pass raise return
True try while with yield __peg_parser__

Practice Problem

Problem 1

Write a Python program that creates variables and assigns values that fulfill the following description. You will need to interpret the English description into the appropriate datum and data types, and then create variables with descriptive names:

Scenario: In a game system users create a game character with specific attributes. The user is prompted for information about themselves and asks them to choose player attributes from lists of choices. The user information the system asks for includes their first name, age, city, state, and country. The game player attributes include player name, player type (such as Warrior, Wizard, Elf, etc.), player age, player gender, and primary weapon. Based on the user's choices, we will also need variables for hit points (a decimal number), strength (a whole number), and experience points (a whole number) and we will also track if they are actively playing the game (yes or no).

Note: For this problem, we are only focused on creating variables and making data assignments to those variables (you can create the values as you wish). We are not trying to code anything further, yet. We will build upon this as we progress in the book.



 





© 2023 John Gordon
Cascade Street Publishing, LLC