A lot of times we need to save some information for later in the program. For this, we use variables. Here's a sample!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
The variable 'x' is <type 'int'> The variable 'e' is <type 'float'> The variable 'title' is <type 'str'> The variable x contains 10 The value -400 is stored in the variable y. The experiment took 4.71 seconds. A favorite irrational number is Euler's number: 2.71828182846 Hopefully you have more than $ 1.89! My name is Mr. Graham Mitchell.
There are several different types of variables in Python, and we are looking at three of them here. Python figures out what type a variable should be when you first put a value into it. This is different from some other languages where you have to explicitly "declare" the type first.
You can use the built-in type()
function in Python to display the type of any variable.
Integers are whole numbers. They have no fractional part, nothing after the decimal, that sort of thing. They can be positive or negative, and are essentially unlimited in size.
Floating-point values (floats) have a decimal point, and are stored in scientific notation. They have limited precision, and computing with floats may result in rounding.
Strings hold letters, symbols, words and phrases.
There are two good ways to display the value of a variable on the screen. The first is shown on lines 23 and 24: you stop the quotes, put a comma, then the name of the variable, then another comma, and start the quotes back up again.
Python will automatically add a space for you between each value. If you don't like this, or if you have several variables, then use the second method.
For the second way, just keep everything in the quotes, but put an open and close curly brace {}
as a placeholder for the value you want to show. Then, immediately after the close quote, type .format()
and list the variables. The variables will be substituted into their proper locations in the order they appear.
Add four more variables: one integer, one float and two strings. Put some symbols (like
@
or#
) into at least one of the strings, and put several words separated by spaces into another.Add some
print()
statements to display the new variables you added.
©2017 Graham Mitchell