Python for AI and Machine Learning / Python Essentials

Values, types and strings

Lesson 3 of 30. Open to read. No account needed.

Data Arrives as Text

A sensor, a form or a file gives you text. The line D1:21.456 looks like a device name and a temperature, but to Python it is nine characters. Before you can compare the temperature with a limit or average it, you have to cut out the part you need and turn it into a number. Afterwards, you usually turn numbers back into readable text. This lesson covers the values involved and the conversions between them.

Values and Their Types

Every value in Python has a type, which decides what you can do with it:

TypeExample valuesUsed for
int3, -12, 1024Whole numbers and counts
float21.5, 0.1, -3.0Numbers with a fractional part
str"D1", 'north', ""Text, written in single or double quotes
boolTrue, FalseThe result of a comparison
NoneNone"No value", for example a reading that is missing

The built-in function type() tells you a value's type. These snippets show a line of code and, below it, what it prints; you can try each one by typing python in your active environment and entering the line, or by saving it in a file and running it. Type exit() to leave the interactive prompt.

print(type(3), type(3.0), type("3"), type(True), type(None))
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>

3, 3.0 and "3" are three different values: a whole number, a number with a fractional part and a one-character piece of text.

Numbers

The arithmetic operators are +, -, * and /, plus three you may not know: // divides and drops the fractional part, % gives the remainder and ** raises to a power.

print(7 / 2, 7 // 2, 7 % 2, 2 ** 10)
3.5 3 1 1024

/ always gives a float, even when the division is exact.

A float is stored in binary, so most decimal fractions are stored as the nearest value the computer can hold. Usually you never notice, but sometimes the difference shows:

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2), 0.1 + 0.2 == 0.3)
0.30000000000000004
0.3 False

This is not a bug in your program. Round results when you display them, and never test two floats for exact equality; later lessons show how to compare them with a tolerance.

Comparisons such as >, <, >=, <=, == (equal) and != (not equal) give a bool. Note the double ==: a single = assigns a value to a variable, a name that refers to a value, as in limit = 25.0.

Strings

A string is a sequence of characters. Each character has a position, called its index, starting from 0. Negative indexes count from the end.

The string "D1:21.456" has nine characters. Index 0 is D and index 8 is 6; counting from the end, index -1 is 6 and -9 is D. The slice line[:2] takes positions 0 and 1, giving "D1"; the slice line[3:] takes positions 3 to 8, giving "21.456". A slice includes its start and stops before its stop.

Read the diagram from top to bottom: the green numbers are the indexes you count from the start, the blue numbers are the ones you count from the end, and the brackets show two slices. A slice [start:stop] takes the characters from start up to, but not including, stop. Leaving out start means "from the beginning"; leaving out stop means "to the end".

line = "D1:21.456"
print(line[0], line[-1], line[:2], line[3:], len(line))
D 6 D1 21.456 9

len() gives the number of characters. Strings also have methods, functions that belong to a value and are called with a dot after it:

print("  north ".strip().title(), "D1:21.456".startswith("D1"), "a,b".split(","))
North True ['a', 'b']

strip() removes spaces at both ends, title() capitalises each word and startswith() tests the beginning. Methods can be chained: strip() returns a new string, and title() is called on that. split(",") cuts a string at each comma and returns a list of the pieces; the next lesson covers lists. Strings never change: every method returns a new string and leaves the original as it was.

Converting Between Types

int(), float() and str() convert a value to another type when they can:

print(int("42") + 1, float("2.5") * 2, str(7) + "%")
43 5.0 7%

When they cannot, Python stops with an error. Two you will meet often:

int("12.5")
ValueError: invalid literal for int() with base 10: '12.5'
print("total: " + 3)
TypeError: can only concatenate str (not "int") to str

int() accepts only text that looks like a whole number. And + means addition for numbers but joining for strings, so Python refuses to guess what "total: " + 3 should mean. Convert first, as in "total: " + str(3), or use an f-string.

When an error stops a program, Python prints several lines; read the last line first. It names the type of error and explains it. The lesson on errors explains the lines above it.

f-strings

An f-string is a string with f before the opening quote. Anything inside curly braces is evaluated and inserted. After a colon, a format specification controls how it looks:

SpecificationMeaningf"{26.95:...}" gives
.1fOne decimal place26.9
.3fThree decimal places26.950
,.2fThousands separator, two places26.95
.1%Multiply by 100, one place, add %2695.0%
value = 26.95
print(f"{value:.1f} {value:.3f} {1234567.891:,.2f}")
26.9 26.950 1,234,567.89

Why does 26.95 round down to 26.9? Because the float stored for 26.95 is very slightly less than 26.95 (26.9499999...), so the nearest value with one decimal place is 26.9. Rounding a decimal that ends in 5 can go either way for this reason.

Exercise: Format Raw Readings

You will turn four raw sensor lines into readable summaries. The fourth line is broken on purpose.

Starting state: the course environment from the setup lesson, active in your terminal.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/pyml-practice/reading-summary
    cd ~/pyml-practice/reading-summary
    

    Windows PowerShell:

    mkdir $HOME\pyml-practice\reading-summary
    cd $HOME\pyml-practice\reading-summary
    
  2. Save this as summary.py in that folder:

    """Turn raw sensor lines into formatted summaries."""
    limit = 25.0
    
    line = "D1:21.456"
    name = line[:2]
    reading = float(line[3:])
    print(f"{name}: {reading:.1f} degrees, above limit: {reading > limit}")
    
    line = "D2:19.04"
    name = line[:2]
    reading = float(line[3:])
    print(f"{name}: {reading:.1f} degrees, above limit: {reading > limit}")
    
    line = "D3:26.95"
    name = line[:2]
    reading = float(line[3:])
    print(f"{name}: {reading:.1f} degrees, above limit: {reading > limit}")
    
    line = "D4:error"
    name = line[:2]
    reading = float(line[3:])
    print(f"{name}: {reading:.1f} degrees, above limit: {reading > limit}")
    
  3. Predict what it prints, then run it:

    python summary.py
    

    Illustrative output:

    D1: 21.5 degrees, above limit: False
    D2: 19.0 degrees, above limit: False
    D3: 26.9 degrees, above limit: True
    Traceback (most recent call last):
      File "/home/you/pyml-practice/reading-summary/summary.py", line 21, in <module>
        reading = float(line[3:])
    ValueError: could not convert string to float: 'error'
    

    The file path differs on your computer, and some Python versions add a row of ^ marks under the failing line.

How the Script Works

limit = 25.0 creates a variable that every block uses. Each of the four blocks then does the same three things. line[:2] slices the device name, the first two characters. line[3:] slices everything after the colon, and float() converts it to a number. The f-string inserts the name, the reading rounded to one decimal place and the result of reading > limit, which is True or False.

The fourth block slices "error" after the colon, and float("error") cannot convert it, so Python stops with a ValueError and never reaches the last print. The line line 21 in the traceback is the line of summary.py that failed. Three blocks of almost identical code is clumsy; the lesson on loops shows how to write the steps once and repeat them.

If you changed limit = 25.0 to limit = 20.0, the first line would end in True as well, because 21.456 is greater than 20.

Success: the first three lines match the illustrative output exactly, and the last line of the error reads ValueError: could not convert string to float: 'error'.

If something differs:

What you seeLikely causeNext step
D3: 27.0 degreesThe value in the file is not exactly 26.95Compare line 14 with the lesson
{name}: {reading:.1f} printed literallyThe f before the opening quote is missingAdd f before the quote
A last line starting NameError: name 'limit' is not definedThe first assignment is missing or misspeltCheck line 2
No module named or python: command not foundThe environment is not activeActivate it as in the setup lesson

Independent task: change the four print lines so that each one shows the reading as a percentage of the limit instead of above limit, for example D1: 21.5 degrees, 85.8% of the limit. Use a format specification from the table above. Predict the third line before you run it.

  1. Clean up. macOS and Linux:

    cd ~/pyml-practice
    ls
    rm -rf reading-summary
    

    Windows PowerShell:

    cd $HOME\pyml-practice
    ls
    Remove-Item -Recurse reading-summary
    

    Check that ls shows reading-summary before you remove it. Keep .venv.

Check Your Understanding

Predict what each line does, then check with the reasoning:

  1. print(10 / 5)
  2. print("3" * 3)
  3. print(int("12.5"))
  4. print("total: " + 3)

Answer and Reasoning

Independent task

Each print line becomes:

print(f"{name}: {reading:.1f} degrees, {reading / limit:.1%} of the limit")

reading / limit is the reading as a fraction of the limit, and .1% multiplies it by 100, keeps one decimal place and adds a percent sign. The three lines that print are:

D1: 21.5 degrees, 85.8% of the limit
D2: 19.0 degrees, 76.2% of the limit
D3: 26.9 degrees, 107.8% of the limit

The third reading is above the limit, so its percentage is above 100. The fourth block still stops with the same ValueError.

Understanding check

  1. 2.0: / always gives a float, even when the division is exact.
  2. 333: multiplying a string by a whole number repeats it.
  3. ValueError: invalid literal for int() with base 10: '12.5'. int() accepts only whole-number text; use float("12.5"), or int(float("12.5")) if you really want 12.
  4. TypeError: can only concatenate str (not "int") to str. Convert the number first with str(3), or write f"total: {3}".

References

25 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy