Variables¶
Variables¶
Just like any other programming language, Python also has variables.
>>> x = 4
>>> x * 3
12
Variables can contain any of the types we’ve covered so far: strings, floats, integers…just about anything can be shoved in a variable. When we assign a value to a variable we can do other things with that variable without having to explicitly state their values.
So, variables can be used just like any other value:
>>> bunnies = 2
>>> kitties = 1
>>> hedgies = 1
>>> cuties = bunnies + kitties + hedgies
>>> cuties
4
String Formatting with F-Strings¶
Having to concatenate strings with all those open and close quotes and plus signs and spaces to forget can be a pain. But there’s a better way. F-strings!
Here’s how we’ve been doing things:
>>> conference = "PyCon"
>>> year = "2019"
>>> conference + " " + year + " is super duper!"
'PyCon 2019 is super duper!'
With f-strings we can simplify quite a bit.
>>> conference = "PyCon"
>>> year = "2019"
>>> f'{conference} {year} is super duper!'
'PyCon 2019 is super duper!'
So we create a variable for the conference, and a variable for the year, then we can reference them within the string with {variable}
syntax. The only thing we need to do to make this work is to include f
at the beginning of string. No need to concatenate a bunch of spaces, and it’s much easier to read. Neato!