Chapter 2: Getting Started with Python

Chapter 2: Getting Started with Python

Input from keyboard: <variable identifier> = input(<a string prompt>)

Generate output: print(<expression>)

name = input(“Enter your name:”)
print(“Your name is”, name)

Data types

  • Integers
  • Range is infinite, includes negative, 0, and positive numbers without decimals
  • Computer’s memory places a limit on largest magnitude of integers
  • Python’s int typical range is - to -1
  • Floating-Point Numbers
  • Real numbers [with decimals], including _.0
  • Python’s float typical range is - to
  • Typical precision: 16 digits
  • Note: e-1 means
  • Characters and Strings
  • Characters: 26 English characters, space, question mark, Chinese character, etc
  • String: sequence of characters (e.g. word, sentence, paragraph)
  • Unicode set and ASCII set are character sets used to represent English characters and notations; both needed to represent characters as numbers for text processing
  • Unicode was developed to use a variable bit encoding program & Unicode standard defined UTF-8, UTF-16 & UTF-3
  • Large capacity of Unicode makes many non-English languages available (e.g. Chinese) ⇒ Unicode supports (more) characters from many languages, including special characters and symbols like emojis, punctuations, or sqrt
  • ASCII is compatible with Unicode ⇒ All ASCII encoding is compatible with unicode, but not vice versa
  • Bit = binary digit (1 or 0)
  • E.g. use 7 bits = have (=128) possible binary representation of numbers 0-127
  • Using more digits take up more memory space
  • Python: use ord and chr to convert characters to and from ASCII
>>> ord(‘a’)
97
>>> chr(65)
‘A’
>>> chr(ord(‘A’)+5) # traverse within the alphabets
‘F’ # ASCII code 70
  • Boolean: True and False

Literal = the way a value of a data type looks to a programmer

  • In python, a string literal is a sequence of characters enclosed in single or double quotation marks
  • ‘’ and “” represent empty string
  • Use ‘’’ and ‘’’’’’ for multi-line paragraphs
Escape sequenceMeaning
\bBackspace (removes character before it?)
\n or print()Newline (e.g. a\nb means line 1 is a, line 2 is b)
\tHorizontal tab
\\The \ character
\’Single quotation mark (e.g. print(‘It**\‘**s Monday’))
\”Double quotation mark

Variable = associates a name with a value to make it easy to remember and use later

  • Variable naming rules
  • Reserved words cannot be used as variable names
  • E.g. if, def, import
  • Name must begin with a letter or _
  • Name can contain any number of letters, digits, or _
  • Names are case sensitive
  • E.g. WEIGHT is different from weight
  • All uppercase letters for symbolic constants
  • E.g. TAX_RATE
  • “camel casing”
  • E.g. InterestRate
  • Short names are preferred. If necessary, write comments to explain short forms
  • Receive initial values, and can be reset to new values with an assignment statement
  • <variable name> = <expression>
  • Variable references = subsequent uses of the variable name in expressions
>>> firstName = “Ken”
>>> secondName = “Lambert”
>>> fullName = firstName + “  ” + secondName

Expressions: provide easy way to perform operations on data values to produce other values

  • A literal evaluates to itself
  • A variable reference evaluates to the variable’s current value
  • When entered at Python shell prompt, expression’s operands are evaluated and its operator is then applied to these values to compute value of the expression
  • Arithmetic expression: consists of operands and operators combined
OperatorMeaningSyntax
**Exponentiationa ** b
-Negation or Subtraction-a or a-b
//Quotienta // b (e.g. 3//2 = 1)
%Remainder or modulusa % b (e.g. 6%2=0)
  • Precedence rules of operators
  • ** has the highest precedence, is evaluated first
  • Unary negation (negative sign?) is evaluated next
  • *,/,//, and % evaluated before + and -
    • and - evaluated before =
  • With 2 exceptions, operations of equal precedence are left associative, so they are evaluated from left to right (** and = are right associative, E.g. 2**3**2 = 2**9 = 512; 3.14*3**2 =3.14*(3**2) = 28.26)
  • Can use () to change order of evaluation
  • Anything /0 or %0 or // 0 gives “Error: cannot divide by 0”
  • Note: output of / is a float, not int
  • Augmented assignment
  • Standard formatting: <variable> = <variable><operator><expression>
  • Can be shortened to: <variable><operator> = <expression>
  • E.g. a %= 3 is equivalent to a = a%3
  • E.g. s += “ there” is equivalent to s = s + “ there”
  • Only for python, not for pseudocode
  • String concatenation
  • Join 2 or more strings to form new string using concatenation operator +
  • * operator builds a string by repeating another string a given number of times
  • Type conversions
  • Converting data types for calculation or formatting
Conversion functionE.g.Value returned
int(<a number or a string>)int(3.77)
int(“33”)
3 # by truncation, not rounding
int(round(6.75)) returns 7
33
float(<a number or a string>)float(22)22.0
str(<any value>)str(99)‘99’
  • Need to be of the same type to concatenate a string
  • E.g. print(‘$’ + str(profit))
  • Input data type is string by default
  • So if input has to be integer for calculation, use int(input(“Enter number:”))
  • x = “8.8”
    int(x)
    ⇒ Value error
  • Formatting text for output
  • Many data-processing applications require output that has tabular format
  • Field width: total no. of data characters and additional spaces for a datum in a formatted string
  • Using f-string formatting
  • Place the text that you want displayed between quotations marks after ‘f’
  • Enclose variables to be displayed within the text in curly braces
  • Within those curly braces, place colon (:) after variable
  • Format the variable using a format specification (width, alignment, data type) after the colon
  • E.g. print(f’{qty} {item} cost ${price}’)
i = 12345
s = ‘abcde’
print(f“{i:<8}|{s:<8}”) # left aligned in a field width of 8
print(f“{s:>8}|{i:>8}”) # right aligned in a field width of 8
OUTPUT:
12345      |abcde
      abcde|     12345
# {__:<field width>.<precision>f}
x = 78.2348
print(f”{x:<8.2f}”) # 78.23
print(f”{x:>8.2f}”) #      78.23 ⇒ 3 spaces + 4 numbers + 1 ‘.’ = 8
# no field width
print(f”{x:.3f}”)     # 78.235
# no precision specified, python auto-fill up to 6 d.p.
print(f”{x:<12f}”)  # 78.234800
print(f”{x:>12f}”)  #      78.234800 ⇒ 3 spaces + 8 numbers + 1 ’.’ = 12

Functions and modules

  • Calling Functions: Arguments and Return Values
  • Function = chunk of code that can be called by name to perform a task
  • Often require arguments or parameters
  • Once complete its task, it may return a value back to the part of the program that called it
  • E.g. help(round)
  • Math module
  • import math
    dir(math)
  • To use resource from module: write name of module as a qualifier, followed by a dot (.), and name of resource
  • E.g. math.pi
  • E.g. math.sqrt(2)
  • Can avoid using qualifier with each reference by importing individual resources
  • E.g. from math import pi, sqrt
    print(pi, sqrt(2))
  • Can import all (*) if a module’s resources to use without the qualifier
  • from math import *
  • The Main module
  • Like any module, it can be imported
  • Save the first file myprogram.py in the libraries of Python, then can import directly
  • import myprogram
  • Program format and structure
  • Start with comment in the form of docstring. Include author’s name, purpose of program, etc
  • Then include statements that:
  • Import any modules needed by program
  • Initialise important variables, suitably commented
  • Prompt user for input data and save input data in variables
  • Process inputs to produce results
  • Display results

Functions and modules

  • Calling Functions: Arguments and Return Values
  • Function = chunk of code that can be called by name to perform a task
  • Often require arguments or parameters
  • Once complete its task, it may return a value back to the part of the program that called it
  • E.g. help(round)
  • Math module
  • import math
    dir(math)
  • To use resource from module: write name of module as a qualifier, followed by a dot (.), and name of resource
  • E.g. math.pi
  • E.g. math.sqrt(2)
  • Can avoid using qualifier with each reference by importing individual resources
  • E.g. from math import pi, sqrt
    print(pi, sqrt(2))
  • Can import all (*) if a module’s resources to use without the qualifier
  • from math import *
  • The Main module
  • Like any module, it can be imported
  • Save the first file myprogram.py in the libraries of Python, then can import directly
  • import myprogram
  • Program format and structure
  • Start with comment in the form of docstring. Include author’s name, purpose of program, etc
  • Then include statements that:
  • Import any modules needed by program
  • Initialise important variables, suitably commented
  • Prompt user for input data and save input data in variables
  • Process inputs to produce results
  • Display results