Python Programming/Variables

From Wikiversity
Jump to navigation Jump to search

This lesson introduces variables, expressions, and statements.

Objectives and Skills[edit | edit source]

Objectives and skills for this lesson include:[1]

  • Language Basics
    • Language elements (constants, numbers and strings)
    • Strings types (single quotes, double quotes and triple quotes)
    • Escape Sequence, string concatenation and format method
    • Variables naming, types and objects
    • Indentation, logical and physical lines
  • Operators and Expressions
    • Operators and Expressions
    • Evaluation Order and Associativity
  • Input Output
    • User input

Readings[edit | edit source]

  1. Wikipedia: Variable (computer science)
  2. Wikipedia: Data type
  3. Wikipedia: Expression (computer science)
  4. Wikipedia: Statement (computer science)
  5. Wikipedia: Order of operations
  6. Python for Everyone: Variables, expressions, and statements

Multimedia[edit | edit source]

  1. YouTube: Python for Informatics: Chapter 2 - Expressions
  2. YouTube: Python Numbers
  3. YouTube: Python3 Input & Output
  4. Youtube: Python 3 Programming Tutorial: Variables
  5. Youtube: Setting up Pycharm and getting started

Examples[edit | edit source]

Data Types[edit | edit source]

Built-in Python data types include integer (int), floating point (float), string (str), and Boolean (bool) data types.[2]

value = 1 + 1
print(value)          # Displays 2
print(type(value))    # Displays <type 'int'>

value = 0.1 + 0.1
print(value)          # Displays 0.2 
print(type(value))    # Displays <type 'float'>

value = '1' + '1'
print(value)          # Displays 11
print(type(value))    # Displays <type 'str'>

value = True
print(value)          # Displays True
print(type(value))    # Displays <type 'bool'>

Type Conversion[edit | edit source]

An object’s type is accessed by the built-in function type().[3]

value = 1.9
print(value)          # Displays 1.9
print(type(value))    # Displays <type 'float'>
value = int(value)
print(value)          # Displays 1
print(type(value))    # Displays <type 'int'>

value = 1
print(value)          # Displays 1
print(type(value))    # Displays <type 'int'>
value = float(value)  
print(value)          # Displays 1.0
print(type(value))    # Displays <type 'float'>

value = 1
print(value)          # Displays 1
print(type(value))    # Displays <type 'int'>
value = str(value)  
print(value)          # Displays 1
print(type(value))    # Displays <type 'str'>

Quotes[edit | edit source]

String literals are written in a variety of ways, including single quotes, double quotes, and triple quotes. Triple quoted strings may span multiple lines.[4] The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.[5]

value = 'single quotes'
print(value)

value = "double quotes"
print(value)

value = \
'''triple quotes
    span multiple lines'''
print(value)

value = '"nested quotes"'
print(value)

value = "'nested quotes'"
print(value)

value = "\"escape character quotes\nand multiple lines\""
print(value)

Numeric Operations[edit | edit source]

All numeric types (except complex) support the following operations, sorted by ascending priority.[6]

a = 3
b = 2

print(a + b)     # 5
print(a - b)     # 1
print(a * b)     # 6
print(a / b)     # 1.5
print(a // b)    # 1
print(a % b)     # 1
print(-a)        # -3
print(a ** b)    # 9

Assignment Operations[edit | edit source]

An assignment statement evaluates the expression and assigns the result to the target. Augmented assignment is the combination, in a single statement, of an operation and an assignment statement.[7]

a = 3
b = 2

a += b    # a = 5
a -= b    # a = 3
a *= b    # a = 6
a /= b    # a = 1.5
a //= b   # a = 1
a %= b    # a = 1.0
a **= b   # a = 1.0

Input Function[edit | edit source]

Python 2: If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), which is then parsed and evaluated as a Python expression.[8]

Python 3: If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.[9]

input([prompt])

#Python 2
value = input("Enter a numeric value: ")
print("You entered " + str(value))

value = input('Enter a string value in "quotes": ')
print("You entered " + value)

#Python 3
value = input("Enter a value: ")
print("You entered a string value " + value)

Activities[edit | edit source]

Tutorials[edit | edit source]

  1. Complete one or more of the following tutorials:

Practice[edit | edit source]

  1. Experiment with different numeric operations to ensure you understand how they work. Then review either MathsIsFun: Order of Operations or Teachoo: What is BODMAS?. Create a Python program that demonstrates the order of operations.
  2. Create a Python program to prompt the user for hours and rate per hour to compute gross pay (hours * rate).[10]
  3. Review MathsIsFun: Conversion of Temperature. Create a Python program that asks the user for a Fahrenheit temperature and then calculate and display the corresponding Celsius temperature or ask the user for a Celsius temperature and then calculate and display the corresponding Fahrenheit temperature.
  4. Create a Python program that asks the user how old they are in years, and then calculate and display their approximate age in months, days, hours, and seconds.
  5. Review MathsIsFun: Area of Plane Shapes. Create a Python program that asks the user for the dimensions of different shapes and then calculate and display the area of the shapes.

Games[edit | edit source]

  1. Play CodeCombat.

Lesson Summary[edit | edit source]

  • Built-in Python data types include integer (int()), floating point (float()), string (str()), and Boolean (bool()).[11]
  • An object’s type is accessed by the built-in function type().[12]
  • String literals are written in a variety of ways, including single quotes, double quotes, and triple quotes. Triple quoted strings may span multiple lines.[13]
  • The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.[14]
  • Numeric operators include +, -, *, /, //, %, and **.[15]
  • Assignment operators include +=, -=, *=, /=, //=, %=, and **=.[16]
  • The Python 2 input() function reads a line from input, converts it to a string (stripping a trailing newline), which is then parsed and evaluated as a Python expression.[17]
  • The Python 3 input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that.[18]

Key Terms[edit | edit source]

assignment
A statement that assigns a value to a variable.[19]
concatenate
To join two operands end to end.[20]
comment
Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.[21]
escape character
A character which invokes an alternative interpretation on subsequent characters in a character sequence.[22]
evaluate
To simplify an expression by performing the operations in order to yield a single value.[23]
expression
A combination of variables, operators, and values that represents a single result value.[24]
floating point
A type that represents numbers with fractional parts.[25]
floor division
The operation that divides two numbers and chops off the fractional part.[26]
integer
A type that represents whole numbers.[27]
keyword
A reserved word that is used by the compiler to parse a program; you cannot use keywords like if, def, and while as variable names.[28]
mnemonic
A memory aid. We often give variables mnemonic names to help us remember what is stored in the variable.[29]
modulus operator
An operator, denoted with a percent sign (%), that works on integers and yields the remainder when one number is divided by another.[30]
operand
One of the values on which an operator operates.[31]
operator
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.[32]
rules of precedence
The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.[33]
statement
A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.[34]
string
A type that represents sequences of characters.[35]
type
A category of values. The types we have seen so far are integers (type int), floating-point numbers (type float), and strings (type str).[36]
value
One of the basic units of data, like a number or string, that a program manipulates.[37]
variable
A name that refers to a value.[38]

Review Questions[edit | edit source]

Enable JavaScript to hide answers.
Click on a question to see the answer.
  1. Built-in Python data types include _____, _____, _____, and _____.
    Built-in Python data types include integer (int()), floating point (float()), string (str()), and Boolean (bool()).
  2. An object’s type is accessed by the built-in function _____.
    An object’s type is accessed by the built-in function type().
  3. String literals are written in a variety of ways, including _____, _____, and _____. _____ may span multiple lines.
    String literals are written in a variety of ways, including single quotes, double quotes, and triple quotes. Triple quoted strings may span multiple lines.
  4. The _____ character is used to escape characters that otherwise have a special meaning, such as _____.
    The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
  5. Numeric operators include _____.
    Numeric operators include +, -, *, /, //, %, and **.
  6. Assignment operators include _____.
    {{{2}}}
  7. The Python 2 input() function _____.
    The Python 2 input() function reads a line from input, converts it to a string (stripping a trailing newline), which is then parsed and evaluated as a Python expression.
  8. The Python 3 input() function _____.
    The Python 3 input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

Assessments[edit | edit source]

See Also[edit | edit source]

References[edit | edit source]

  1. Vskills: Certified Python Developer
  2. Python.org Built-in Types
  3. Python.org: Built-in Types
  4. Python.org: Built-in Types
  5. Python.org: Lexical analysis
  6. Python.org: Built-in Types
  7. Python.org: Simple Statements
  8. Python.org: Built-in Functions
  9. Python.org: Built-in Functions
  10. PythonLearn: Variables, expressions, and statements
  11. Python.org Built-in Types
  12. Python.org: Built-in Types
  13. Python.org: Built-in Types
  14. Python.org: Lexical analysis
  15. Python.org: Built-in Types
  16. Python.org: Simple Statements
  17. Python.org: Built-in Functions
  18. Python.org: Built-in Functions
  19. PythonLearn: Variables, expressions, and statements
  20. PythonLearn: Variables, expressions, and statements
  21. PythonLearn: Variables, expressions, and statements
  22. Wikipedia: Escape character
  23. PythonLearn: Variables, expressions, and statements
  24. PythonLearn: Variables, expressions, and statements
  25. PythonLearn: Variables, expressions, and statements
  26. PythonLearn: Variables, expressions, and statements
  27. PythonLearn: Variables, expressions, and statements
  28. PythonLearn: Variables, expressions, and statements
  29. PythonLearn: Variables, expressions, and statements
  30. PythonLearn: Variables, expressions, and statements
  31. PythonLearn: Variables, expressions, and statements
  32. PythonLearn: Variables, expressions, and statements
  33. PythonLearn: Variables, expressions, and statements
  34. PythonLearn: Variables, expressions, and statements
  35. PythonLearn: Variables, expressions, and statements
  36. PythonLearn: Variables, expressions, and statements
  37. PythonLearn: Variables, expressions, and statements
  38. PythonLearn: Variables, expressions, and statements