Variables in Python¶
Objectives¶
- assign scalar values to variables and perform calculations
- Trace value changes in programs that use scalar assignment
Variables¶
Variables are names for values.
- Can only contain letters, digits, and underscore
_ - cannot start with digit
- are case sensitive
- Can only contain letters, digits, and underscore
names should be meaningful so you or another programmer knows what it is.
variables that start with
_have special meaning=symbol assings value on the right to the name on the left
age = 15
first_name = 'Tom'
print function¶
- displays the value of variables
age = 15
first_name = 'Tom'
print(age)
print(first_name, age)
print(first_name, 'is', age, 'years old')
15 Tom 15 Tom is 15 years old
Variables persist between cells!
Reading Errors¶
print(second_name)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[29], line 1 ----> 1 print(second_name) NameError: name 'second_name' is not defined
Variables can be used in calculations¶
later_age = age + 4
print('Age in four years', later_age)
Age in four years 19
Excercise 2: Swapping Values¶
Fill the table showing the values of the variables in this program after each statement is executed.
# Command # Value of x # Value of y # Value of swap #
x = 1.0 # # # #
y = 3.0 # # # #
swap = x # # # #
x = y # # # #
y = swap # # # #
If you doubt, test it by yourself on a jupyter notebook!
Takeaway¶
- Use variables to store values.
- Use
printto display values. - Variables persist between cells.
- Variables must be created before they are used.
- Variables can be used in calculations.
- Use the built-in function
lento find the length of a string. - Python is case-sensitive.
- Use meaningful variable names.
Data Types and Type Conversion¶
Data Types¶
- Every value has a specific type.
print(type(2))
<class 'int'>
print(type(age))
int
Some more examples
print(type(print))
<class 'builtin_function_or_method'>
print(type(3.14))
<class 'float'>
print(type("Every value has a type!"))
<class 'str'>
print(type(type))
<class 'type'>
Data types control what operations can be performed on a given value¶
print(5-3)
2
print('hello' - 'h')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[14], line 1 ----> 1 print('hello' - 'h') TypeError: unsupported operand type(s) for -: 'str' and 'str'
print(5+3)
8
print('hello' + 'h')
helloh
Functions may be type specific¶
print(first_name)
print('Number of characters: ', len(first_name))
Tom Number of characters: 3
print(len(52))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[34], line 1 ----> 1 print(len(52)) TypeError: object of type 'int' has no len()
Can mix integers and floats¶
print('half is', 1 / 2.0)
print('three squared is', 3.0 ** 2)
half is 0.5 three squared is 9.0
Operands¶
Best way of learning this is by trial and error! Create a new cell, state what you want to do, and see if the result is what you expect :) . You can also read the documentation
print('Multiplication', '5 * 3: ', 5 * 3)
print('Power', '5**3: ', 5**3)
print('Division', '5/3: ', 5/3)
print('Sum', '5+3: ', 5+3)
print('Subtract', '5-3: ', 5-3)
Multiplication 5 * 3: 15 Power 5**3: 125 Division 5/3: 1.6666666666666667 Sum 5+3: 8 Subtract 5-3: 2
On division
print('Integer division', '5 // 3:', 5 // 3)
print('Floating point division', '5 / 3:', 5 / 3)
print('Remainder from integer division (modulo)', '5 % 3:', 5 % 3)
Integer division 5 // 3: 1 Floating point division 5 / 3: 1.6666666666666667 Remainder from integer division (modulo) 5 % 3: 2
Treating complex numbers, python understands special character j for imaginary part.
a_complex_number = 6 + 2j
print(type(a_complex_number))
print(a_complex_number.real)
print(a_complex_number.imag)
<class 'complex'> 6.0 2.0
Takeaway¶
- Every value has a type
- use built-in function
typeto find the type of a value - Types control what operations can be done on values
- String can be added and multiplied
- Strings have a length
- Variables only change values when something is assigned to them
x='hi'
len(x)
2
A function is called when we pass arguments to it (with the parenthesis)
every function returns something. If no return statement is present, it returns
None.
result = print("example")
example
print(result)
None
- Commonly-used built-in functions include
min,max, andround
print(min(1,2,3))
print(max('a','0'))
1 a
- Accessing the function
helpof a function
help(print)
# print? also works
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
Shift+Tabin Jupyter lab also accesses the help documentation
Methods¶
- Functions attached to objects are called methods (very used in pandas).
- Methods are functions that can be called from within an python
object. They come after the variable and are accessed by a.symbol as follows:
my_string = 'Hello World!'
print(len(my_string))
print(my_string.swapcase())
print(my_string.__len__())
12 hELLO wORLD! 12
print(my_string.isupper()) # Not all the letters are uppercase
print(my_string.upper()) # This capitalizes all the letters
print(my_string.upper().isupper()) # Now all the letters are uppercase
False HELLO WORLD! True
Takeaway¶
- Use comments to add documentation to programs. A function may take zero or more arguments.
- Commonly-used built-in functions include max, min, and round.
- Functions may only work for certain (combinations of) arguments.
- Functions may have default values for some arguments.
- Use the built-in function help to get help for a function.
- The Jupyter Notebook has two ways to get help.
- Every function returns something.