Tt
Click this widget to change the font size.
CC
Click this widget to change contrast.

Home Page 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Links | Search | Bio |

Guide to Python (University at Buffalo Version)


Chapter 2: Python Variables and Arrays

Python Variables

Python is a strongly typed language. This means you do not have to declare a specific type (string, int, etc.) when creating a variable (unlike other languages such as Java). Python variables and variable names must start with a letter or an underscore and can contain any number of letters, numbers, or underscores.

You can assign values to variables using the equals sign (=).

You can use the date object with the datetime.now method to obtain the durrent date and time. Python provides many format codes to forat the date and time.

# date_now.py

import datetime

# get the current date and time
today = datetime.datetime.now()
print('The date and time now is', today)
# format the date
formatted_date = today.strftime("%B %d, %Y")
print('Today formatted is:', formatted_date)
Figure 2-1: Python Variables Code
The date and time now is 2025-02-10 09:55:08.508134
Today formatted is: February 10, 2025
Figure 2-2: Print Variables Output

Assigning Values to a String Variable

You can assign a long string to a variable using different methods. You could simply type the long string. You could also use string concatenaton. Or, you can use the Python """ method. The """ method uses three (3) double quote than characters around the string. Here are some examples:

# string_assign.py

firstName = "D'arcy"
lastName = 'O\'Brien'
fullName = firstName + " " + lastName
myAddress = """
123 Mian Street
Pike's Peak, UT
12345
"""

print("First: " + firstName
+ "\nLast: " + lastName + "\nFull Name: " + fullName
+ "\nAddress: " + myAddress)
   
Figure 2-3: Python String Variables Code
First: D'arcy
Last: O'Brien
Full Name: D'arcy O'Brien
Address:
123 Mian Street
Pike's Peak, UT
12345
Figure 2-4: Print String Variables Output

Casting a String to an Integer or Floating Point Variable

When you use the input() method to get data from the user, that data is stored in a string variable by default. Often, you need to convert (cast) that data to an integer or a floating point number. You can us the int() or float() methods to convert a string. Likewise, you cna use the str() method to convert a number to a string. Here are some examples:

# casting.py

firstName = input('Enter your first name: ')
age = int(input('Enter your age: '))
textCost = float(input('Enter the cost of your textbook: '))

print(f'Hello {firstName}!')

if age >= 18:
    print(f'You are old enough to vote!')

if textCost > 0:
    print(f'And your textbook cost was {textCost:.2f}.')
   
Figure 2-5: Using the float, Int(), and str() Methods Code
Enter your first name: Jim
Enter your age: 74
Enter the cost of your textbook: 59.95
Hello Jim!
You are old enough to vote!
And your textbook cost was $59.95.
Figure 2-6: Using the float, Int(), and str() Methods Output

Python Constants

Python constants should be writtren in ALL UPPERCASE.

TEMP = 98.6
  
Figure 2-7: A Python Constant

Python Arrays

Like most languages, Python provides arrays to store multiple values in a single array variable.

An array in Python is actually a list with restrictions on the data types. Aarray is an object that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional (nested) arrays are also possible. The first element of an array is referenced as the zero (0) element. For example:

# arrays.py
  
coursesArray = ["cis101", "cis121", "cis141", "cis151"]

print(coursesArray[0])
  
Figure 2-8: A Python Array Code
cis101
Figure 2-9: Print Array Output

An associative array allows you to access the array elements using a keyword/value pair. Note, the statements that are part of the for loop must begin with a tab character. For example:

# arrays.py

facultyArray = [("firstName", "Jim"),("lastName", "Gerland")]
for Key,Value in facultyArray: 
    print(Key, "=", Value)
Figure 2-10: A Python Associative Array Code
firstName = Jim
lastName = Gerland
Figure 2-11: Print Associative Array Output

Populating Python Arrays

You can use the append() method to populate an array.

# append_array.py

jimArray = []
jimArray.append(1)
jimArray.append(2)
jimArray.append(3)

print("In the jimArray, element [0] contains:", jimArray[0])
print("In the jimArray, element [1] contains:", jimArray[1])
print("In the jimArray, element [2] contains:", jimArray[2])  
Figure 2-12: Using the append() Method Code
In the jimArray, element [0] contains: 1
In the jimArray, element [1] contains: 2
In the jimArray, element [2] contains: 3
Figure 2-13: Using the append() Method Output

Sorting Python Arrays

Python provides a two (2) functons for sorting arrays. The sort() function sorts an array in ascending order and the reverse() function sorts an array in reverse order.

# sort_array.py

statesArray = ["North Dakota",
 "Nebraska", "New Hampshire", "Alaska", "Alabama", "Arkansas", "American Samoa",
 "Arizona", "California", "Colorado", "Connecticut", "District of Columbia", 
 "Delaware", "Florida", "Georgia", "Guam", "Hawaii", "Iowa", "Idaho", "Illinois", 
 "Indiana", "Kansas", "Kentucky", "Louisiana", "Massachusetts", "Maryland",
 "Maine", "Michigan", "Minnesota", "Missouri", "Mississippi", "Montana", 
 "North Carolina", "New Jersey", "New Mexico", "Nevada", "New York", "Ohio",
 "Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", 
 "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Virginia", 
 "Virgin Islands", "Vermont", "Washington", "Wisconsin", "West Virginia", 
 "Wyoming"]

print('Before sort:')
print(statesArray)
print()
statesArray.sort()
print('After sort:')
print(statesArray)
print()
statesArray.reverse()
print('After reverse sort:')
print(statesArray)
Figure 2-14: Using sort() to Sort an Array
Before sort:
["North Dakota", "Nebraska", "New Hampshire", "Alaska", "Alabama", "Arkansas", "American Samoa",
 "Arizona", "California", "Colorado", "Connecticut", "District of Columbia", 
 "Delaware", "Florida", "Georgia", "Guam", "Hawaii", "Iowa", "Idaho", "Illinois", 
 "Indiana", "Kansas", "Kentucky", "Louisiana", "Massachusetts", "Maryland",
 "Maine", "Michigan", "Minnesota", "Missouri", "Mississippi", "Montana", 
 "North Carolina", "New Jersey", "New Mexico", "Nevada", "New York", "Ohio",
 "Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", 
 "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Virginia", 
 "Virgin Islands", "Vermont", "Washington", "Wisconsin", "West Virginia", 
 "Wyoming"]
 
After sort:
["Alaska", "Alabama", "Arkansas", "American Samoa",
 "Arizona", "California", "Colorado", "Connecticut", "District of Columbia", 
 "Delaware", "Florida", "Georgia", "Guam", "Hawaii", "Iowa", "Idaho", "Illinois", 
 "Indiana", "Kansas", "Kentucky", "Louisiana", "Massachusetts", "Maryland",
 "Maine", "Michigan", "Minnesota", "Missouri", "Mississippi", "Montana", 
 "North Carolina", "North Dakota",
 "Nebraska", "New Hampshire", "New Jersey", "New Mexico", "Nevada", "New York", "Ohio",
 "Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", 
 "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Virginia", 
 "Virgin Islands", "Vermont", "Washington", "Wisconsin", "West Virginia", 
 "Wyoming"]
 
Figure 2-15: Sort an Array Output
After reverse:
['Wyoming', 'Wisconsin', 'West Virginia', 'Washington', 'Virginia', 'Virgin Islands', 
'Vermont', 'Utah', 'Texas', 'Tennessee', 'South Dakota', 'South Carolina', 
'Rhode Island', 'Puerto Rico', 'Pennsylvania', 'Oregon', 'Oklahoma', 'Ohio', 
'North Dakota', 'North Carolina', 'New York', 'New Mexico', 'New Jersey', 
'New Hampshire', 'Nevada', 'Nebraska', 'Montana', 'Missouri', 'Mississippi', 
'Minnesota', 'Michigan', 'Massachusetts', 'Maryland', 'Maine', 'Louisiana', 
'Kentucky', 'Kansas', 'Iowa', 'Indiana', 'Illinois', 'Idaho', 'Hawaii', 
'Guam', 'Georgia', 'Florida', 'District of Columbia', 'Delaware', 
'Connecticut', 'Colorado', 'California', 'Arkansas', 'Arizona', 'American Samoa', 
'Alaska', 'Alabama']
Figure 2-16: Using reverse() to Reverse Sort an Array

Help contribute to my OER Resources. Donate with PayPal button via my PayPal account.
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2016-2025 Jim Gerland