Python’s Data Types and Variables

Python variables:

x = 5

someString = “hello”

print(x)

Python constants:

There are no constants in Python. However, it’s common practice to use all capitals for names of things you want to stay the same, even if the language doesn’t actually enforce it.

For example:

def main():

FINAL_FILENAME = “example.txt”

print(FINAL_FILENAME)

Some features that other languages have, like constructor overloading, access modifiers, constants, or switch/case, simply don’t exist in Python, so you’ll have to either do without them, or come up with your own pseudo-workarounds to achieve similar results. You could also technically use a single-element tuple, as tuples are immutable data structures. Or you can just accept that Python doesn’t really do constants.

Python type conversion:

someInt = 5

print(“someInt is ” + str(someInt))

someString = “5”

print(5 + int(someString))

Python lists:

#!/usr/bin/env python3

import sys

def main():

coolCars = [‘Silvia’, ‘Miata’, ‘RX-7’, ‘MR2’, ‘Supra’]

coolCars.append(‘NSX’)

coolCars.remove(‘Silvia’)

print(coolCars)

for car in coolCars:

print(car + ” is a type of cool car”)

print(coolCars[0] + ” is the first in the list”)

if ‘RX-7’ in coolCars:

print(“Rotary engines are cool”)

if __name__ == ‘__main__’:

try:

main()

except KeyboardInterrupt:

print(“\nQuitting. Goodbye.”)

sys.exit()

Python tuples:

carTuple = (“Lancia Stratos”, “360 Modena”, “DeTomaso Pantera”)

print(carTuple)

print(carTuple[0])

for car in carTuple:

print(car)

print(“unlike lists, tuples can’t be changed”)

print(len(carTuple))

Python dictionaries:

productDict = {

“name”: “x5000 laptop”,

“brand”: “super cool computers”,

“price”: 799.99,

“product_id”: 12346,

“sold_yet” : False

}

#dictionaries look very similar to JSON

print(productDict[“name”])

salesTax = 0.10 # 10%

shipping = 20

finalPrice = (productDict[“price”] * (1 + salesTax)) + shipping

productDict[“sold_yet”] = True

print(“Final price: %1.2f” % finalPrice)

print(productDict)

Python split():

def main():

stringExample = “here are some words”

someList = stringExample.split()

for item in someList:

print(item)

Python string slicing:

stringExample = “grasshopper”

print(stringExample[4:11])

← Previous | Next →

Python Topic List

Main Topic List

Leave a Reply

Your email address will not be published. Required fields are marked *