Python Operators and Input/Output

Numeric Operators

Python operators allow you to perform addition, subtraction, multiplication, division, power, modulo, and floor division operations on numeric values. Take note that all integer division results in a float value.

a = 1 + 2
b = 3 - 4
c = 5 * 6
d = 6 / 3     # integer division outputs float, returns 2.0
e = 7 ** 8    # power, returns 5764801
f = 9 % 2     # remainder division, returns 1
g = 9 // 2    # floor division, returns 4

String Operators

String concatenation is the practice of combining two strings together to form a larger string. This is accomplished in Python with the + operator.

Strings can also be repeated with the * operator. Pay close attention whenever you see strings being multiplied. Single integers are treated as string characters. They are not multiplied by their numeric value.

string1 = 'Hello'
string2 = ', World!'
string3 = string1 + string2
print(string3) # prints Hello, World!

print('5' * 3) # prints 555

Shortcut Operators

Shortcut operators are available for changing the values of existing variables.

a = 10    # initial assignment of a = 10
a += 1    # the same as a = a + 1
a -= 1    # the same as a = a - 1
a *= 5    # the same as a = a * 5 
a /= 2    # the same as a = a / 2
a %= 2    # the same as a = a % 2
a ** 2    # the same as a = a ** 2
a // 2    # the same as a = a // 2

Unary Operators

Apply unary operations with the plus (+) and minus (-) symbols.

a = 1
b = 2
print(-a) # prints -1
print(+b) # prints 2

Order of Operations

Operations in Python have an order of precedence in the same way they do in mathematics. Multiplication comes before addition, parentheses comes before division, and so on.

One mnemonic that people use to remember priority is PEMDAS:

P   Parentheses, then
E   Exponents, then
M   Multiplication, then
D   Division, then
A   Addition, then
S   Subtraction

Given the operations 2 + 3 * 4, 3 is first multiplied by 4, resulting in 12. Then, 2 is added, making 14.

print(2 + 3 * 4)                        # prints 14
print(10 ** 2 + 12 // 5)                # prints 102
print(15 % 2 ** 2 + 1)                  # prints 4
print( (5 * 2) - (2 + 1) ** 2 + 5 // 2) # prints 3

Bitwise Operators

Bitwise operations are used to compare or modify binary numbers. Below is a list of operators.

Operator Name Description
& AND Returns 1 if both bits are 1.
| OR Returns 1 if either bit is 1.
^ XOR Returns 1 if only one bit is 1.
~ NOT Inverts the value of the bits.
« Left shift Adds 0s from the right. Lets leftmost bits be removed.
» Right shift Adds 0s from the left. Lets right most bits be removed.
a = 10    # 1010
b = 7     # 0111

print(a & b) # & returns 0010, prints 2

print(a | b) # returns 1111, prints 15

print(a ^ b) # returns 1101, prints 13

print(~a) # returns -1101, prints -11

print(a << 2) # returns 101000, prints 40

print(a >> 2) # returns 10, prints 2

Bitwise operations are a method of programming that is rarely, if ever, used in Python programming. However, just know that they exist. You may see one out in the wild some day.

Boolean Operators

Boolean operators, also called logical operators, compare conditional statements and return True or False.

Operator Description
and Returns True if both statements are True
or Returns True if either statement is True
not Returns True if statement is False
a = True
b = False
print(a and b)          # prints False
print(a or b)           # prints True
print(not a)            # prints False

print( 6 > 7 and 1 < 2) # prints False

Relational Operators

Use relational operators to compare values with one another. The comparison returns a True or False boolean value. Combine them with boolean operators to make even more complex comparisons.

Operator Description
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
print(5 > 6) 		  # prints False
print(5 > 6 or 5 < 6) # prints True

print(5 != 6) 			 # prints True
print(5 != 6 and 5 <= 6) # prints True

Type Casting

There may be times when you want to convert one data type to another. For instance, a string like "5" could be cast as an integer 5 and assigned to a different variable. Casting is frequently used when working with user input or when parsing text data for numeric values.

Python includes the following built-in functions that will cast variables or values to a different data type.

Function Description
int() Converts value to an integer
float() Converts value to a float
str() Converts value to a string
a = '5'
b = 3.14
c = 16

print(a * 4) # prints 5555
print(int(a) * 4) # prints 20

print(str(b) * 2) # prints 3.143.14

print(float(c)) # prints 16.0

The Print Function

The print() function prints output to the screen. You can pass any number of arguments to the print function, including zero. Optional parameters can be set to change the default separator, which is a space, and the end character, which is a new line.

When no arguments are passed into the function a new line is printed.

The syntax to know is: print(argument(s), sep=separator, end=end).

print('1','2','3', sep='-') # prints 1-2-3

print('1', end='') #
print('2', end='') #
print('3', end='') # together prints 123

msg = ['one','two','three','four','five']
for c in msg:
	print(c, end='-')
# prints one-two-three-four-five-

print() # prints a new line

The default separator is a space when printing two or more string arguments. You can remove the space by including sep='' as a parameter or with string concatenation.

print('one','two')          # prints: one two
print('one', 'two', sep='') # prints: onetwo
print('one' + 'two')        # prints: onetwo 

The Input Function

The input() function prompts the user to enter data. You can assign the input to a new or existing variable. The default type the input() function returns is a string. Cast the value as an integer or float when needed.

The syntax to know is: input(prompt message)

name = input('Enter your name: ')
print('Hi, ' + name)

age = int(input('Enter your age: '))
print('You are', age, 'years old')

height = input('Enter your height in inches: ')
in_feet = height / 12 # produces an TypeError; the height variable is a string

There is a saying among programmers that goes, “Never trust user input.” It can be surprising to see how the end user can intentionally or unknowingly enter incorrect or invalid data. Always test and and validate incoming data when working with user input.