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)
The date and time now is 2025-02-10 09:55:08.508134 Today formatted is: February 10, 2025
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
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()
, andstr()
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.
float
, Int()
, and str()
Methods OutputPython Constants
Python constants should be writtren in ALL UPPERCASE.
TEMP = 98.6
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])
cis101
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)
firstName = Jim lastName = Gerland
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])
append()
Method CodeIn the jimArray, element [0] contains: 1 In the jimArray, element [1] contains: 2 In the jimArray, element [2] contains: 3
append()
Method OutputSorting 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)
sort()
to Sort an ArrayBefore 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"]
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']
reverse()
to Reverse Sort an Array