Python/Tutorial/Variables, Statements and Expressions/Int Literals

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Introduction

Python allows the expression of literals, numbers and strings that are embedded directly in the program itself.

For starters, we'll use int literals. int is short for integer. We'll use these to use Python's most basic features to use Python as a calculator.

Syntax

Int Literals

We will explore int literal syntax in full in another section. For now, the following rules are enough.

  • Ints must start with number 1-9. (Don't use 0---that means something else!)
  • Ints can have numbers 0-9.
  • If you put a '+' or '-' in front of the int, that is okay.
  • Don't use commas or spaces to separate thousands.

Here are some examples:

99
107

These are not what you think:

017
100 000
300,000

In Practice

Int Literals

Just remember these basic rules:

  • Decimal int literals start with 1-9, not 0!
  • Octal int literals start with '0' and can only have digits 0-7.
  • Binary int literals start with '0b' and can only have digits 0 and 1.
  • Hexadecimal int literals start with '0x' and can only have digits 0-9 and a-f.

Pitfalls

  • Don't start your decimal int literals with 0!

Theory

  • Understand that the same number can be represented in binary, octal, decimal, and hexadecimal.
  • 32-bit computers can easily handle numbers between +/- 4 billion.
  • 64-bit computers can easily handle numbers between +/- 18 pentillion.
  • When you exceed these limits, Python converts the number to a long.
  • Although longs take more time to calculate, they are still fast.
  • The limit of the largest number you can store on your computer depends on how much memory you have.

When to Use Other Bases

  • In general, I only use another base when that's the way the number was communicated to me. For instance,the ASCII character map usually lists the numbers in octal, so I'll use octal. Other documentation may list numbers as binary, hexadecimal, or decimal, so I'll use those.
  • If I'm doing bit-wise math (more on this later), I'll use binary or hexadecimal. That's because the two are easy to convert back and forth, and you have to think of the binary version of the number to do bit-wise math.