Module 1 · Python crash course · Lesson 2 of 66
Strings and printing
Text in quotes, and filling values into text.
In this lesson · about 10 minutes
- Write strings with single or double quotes
- Print values
- Fill values into text with .format() and f-strings
A string is text in quotes. Single and double quotes work the same, so pick the one that lets you use the other inside: "it's fine" or 'she said "hi"'.
In a notebook, a bare value shows its representation, with quotes. print() shows the text itself.
Putting values into text
You'll often build a sentence from variables. Two common ways:
.format(): put{}where values go, then pass the values in order. You can also name the slots:'{name} is {age}'.format(name='Sam', age=12).- f-strings: put an
fbefore the quote and write the variable right inside the braces:f'{name} is {age}'. This is the modern favorite.
Exercise
The size of a planet
Using .format() and the two variables, print exactly:
The diameter of Earth is 12742 kilometers.
Exercise
A receipt line
With an f-string, print 3 coffees cost $13.5 using the variables (calculate the cost inside the braces).
Exercises solved: 0 of 2
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.