def main(): celsius = eval(input("What is the Celsius temperature? ")) fahrenheit = (9/5) * celsius + 32 print("The temperature is", fahrenheit, "degrees Fahrenheit") main()
What is the Celsius temperature? 10 The temperature is 50.0 degrees Fahrenheit
Identifiers are labels that refer to data values, function or class names (among other examples.) They follow certain rules, such as they must begin with a letter or underscore ("_") and can contain letters, underscores and numbers afterwards.
Variables are also case insensitive. e.g.:
FooBar = 10 foobar = 20
You may receive a
NameError exception if you attempt to refer to a variable before it is even given a value. For example, we attempt to print
blah, but that will fail because we have no value associated with it.
Som examples of statements, two arithmetic and one function call to
x = 3.14 y = 20 * (1/2) + x print(y)
Did you know you can assign multiple variables simultaneously on one line? Consider setting
x = 100 y = 33 _sum, diff = x+y, x-y #sum([10, 20]) print(_sum, diff)
A special use case of this simulatenous assignment is to swap values! Using the values of
y, above, we can swap their values.
x,y = y,x print(x, y)
In other programming languages, you may not have this nicety. Instead, you would need a temporary variable (
temp) to hold a value while a swapping occurs. This traditional technique is below (but, unnecessary in Python).
temp = x x = y y = temp print(x, y)
Another unique trick is using the
input() pattern to have a user of a program enter a string a values on one line, instead of asking for multiple lines of input. The variables
c are set to integer values as processed by
input() (which returns the text input from the keyboard) and
eval() (which attempts to interpret the literal text as Python expressions, so numbers are converted into either
float data types.
a,b,c = eval(input("Enter three numbers (a,b,c): "))