Programming Fundamentals

Understanding Data Types

Integer

Definition: Whole numbers, positive or negative, without decimals. Practical Use: Counting items, indexing arrays, loop counters.

age = 25

Real (Float/Double)

Definition: Numbers that contain fractional parts, represented with decimals. Practical Use: Calculations requiring precision, like scientific measurements.

temperature = 98.6

Boolean

Definition: Represents true or false values. Practical Use: Conditional statements, flags for control flow. Example: bool ;

isStudent = true

Character and String

Character:

  • Definition: Single alphanumeric character.
  • Practical Use: Handling individual characters.
grade = 'A'

String:

Definition: Sequence of characters. Practical Use: Storing and manipulating text.

name = "Alice"

Casting

Definition: Casting

Changing the data type of a value. Most often used when converting between types for calculations or data manipulation.

Integer to Float:

number = 12
result = float(number / 2) # will store 6.0 in result

String to Integer:

number = "12"
result = int(number) # will cast the string "12" into integer 12

Integer to String:

number = 12
result = str(number) # will cast the integer 12 into string "12"

Casting Inputs

The most common place you will use casting is during the use of input. Python inputs in particular are always stored as a string. So if you want to take input and then use mathematical operations on that input you need to convert, or cast, into a number.

example:

number1 = input("please enter the first number: ")
number2 = input("please enter a second number: ")

print(number1+number2)

as python treats these two numbers as strings the output for the following data entry would be treated as concatenation

  • "12"+"10" gives "1210"

to ensure that the numbers are treated as integers casting can be used, as follows

number1 = input("please enter the first number: ")
number2 = input("please enter a second number: ")

print(int(number1)+int(number2))

the use of int() in this case means they are now treated as integers and they will use the plus + operation rather than concatenation

  • 12+10 gives 22

You then might find though you want to concatenate the result with a message and so perhaps need to cast back to a string also

number1 = input("please enter the first number: ")
number2 = input("please enter a second number: ")

result = int(number1)+int(number2)

print("the total of your two numbers is "+str(result))
  • now the input "12" "10" will give us
  • "the total of your two numbers is 22"

If you didn't cast in these examples you would see an run time error that will usually identify an incorrect type.

Previous
Variables, constants, operators, inputs, outputs and assignments