Full Transcript

COMPSCI 101 variables, literals, expressions mathematical operators, operands, print() Recap Literals -- actual values that we type into our programs ("A", 2, 2.5) Variables -- storage location for information (age_of_person) Types -- different kinds of information (int, float, str) Operators -- sym...

COMPSCI 101 variables, literals, expressions mathematical operators, operands, print() Recap Literals -- actual values that we type into our programs ("A", 2, 2.5) Variables -- storage location for information (age_of_person) Types -- different kinds of information (int, float, str) Operators -- symbols that are used to apply an operation (+, -, *, /) Operands -- the values that the operation applies to (x = 7) Expressions -- can be treated as a value (e.g., calculation, value) Assignment -- stores the result of an expression in a variable (=) Recap Statement -- an instruction in a programming language Function -- a named piece of code that performs a defined task Arguments -- information given to a function print() -- displays information in the standard output round() -- built-in function used to round numeric values Comments -- elements of code that are ignored by the computer comment #Convert inches to centimetres and display with 1 dp assignment inches_to_centimetres = 2.54 float type statements expression inches = 7 int type operator centimetres = inches * inches_to_centimetres variable operand centimetres_1dp = round(centimetres, 1) round() function arguments print(inches, "inches is" centimetres_1dp, "centimetres") print() function string type literal value Docstrings A docstring is a special kind of string (text) used to provide documentation. A docstring: appears at the top of every COMPSCI 101 program, three double-quotes are used to surround the docstring, all programs should include a docstring at the top of the program, the docstring contains the author and a description of what the program does. """ Program which calculates the area of a circle. Author: Damir Azhar """ radius = 10 area = 3.14159265359 * radius ** 2 print("Area of circle", area) Python comments Comments are part of the program that is ignored by the computer These are exclusively for the human audience Start with the hash symbol (#) Everything between # and end of the line is ignored Used to explain decisions when needed speed = 10 time = 40 distance = speed * time #in metres per second #in seconds #metres print("The distance is", distance) Self-documenting code Programs should be easy to understand without comments Comments are used to explain decisions to another programmer when needed Poor variable names make the code difficult to understand v = 10 Very poor choice of variable names v1 = 3.14159265359 * v ** 2 v2 = round(v1, 2) print(v2) Code has poor style - hinders understanding Self-documenting code Good variable names are the first step to improve code quality Names should describe the data stored in the variable Names should be correctly spelled Names should not be too long or too short """ Program which calculates the area of a circle. Descriptive variable names improve understanding which reduces maintenance costs. Author: Andrew """ radius = 10 area = 3.14159265359 * radius ** 2 area_approximation = round(area, 2) print("Area of circle", area_approximation) Simple template for a Python program Program often follow the same general pattern (template) Recognizing the pattern helps with reading and writing docstring """ Calculates the area of a rectangle. Author: Damir Azhar """ initialisation calculation output width = 3.56 height = 8.4 area = width * height print("Area of rectangle", area) practice time COMPSCI 101 input() converting types using int(), float() input() So far we have "hard coded" all our starting values But that limits the usefulness of the program because we need to modify the program each time we perform a new calculation Instead, it is better to create programs that do not require editing Reading input from the user input() function requires a prompt which is displayed to the standard output input() function returns a string with the data entered by the user user_input = input(prompt) Example """ Prints a greeting """ user_name = input("Please enter your name: ") print("Pleased to meet you", user_name) Converting the type of the input input() always returns a str When we want a number, we need to convert the type of data If we try to use the input string as a number, we will get a TypeError """ Convert inches to centimetres """ inches_to_centimetres = 2.54 inches = input("Enter number of inches: ") centimetres = inches * inches_to_centimetres centimetres_1dp = round(centimetres, 1) print(inches, "inches is", centimetres_1dp, "centimetres") Causes a TypeError when the program is executed May not multiply a str by a float int() int() function used to convert a string to an integer string must contain a valid integer generates a ValueError if the argument cannot be converted docstring initialisation """ Convert inches to centimetres """ inches_to_centimetres = 2.54 read input raw_input = input("Enter number of inches: ") inches = int(raw_input) calculation centimetres = inches * inches_to_centimetres centimetres_1dp = round(centimetres, 1) output print(inches, "inches is", centimetres_1dp, "centimetres") float() float() function used to convert a string to a float string must contain a valid float (or an integer, since Python can add.0 easily) generates a ValueError if the argument cannot be converted docstring initialisation """ Convert inches to centimetres """ inches_to_centimetres = 2.54 read input raw_input = input("Enter number of inches: ") inches = float(raw_input) calculation centimetres = inches * inches_to_centimetres centimetres_1dp = round(centimetres, 1) output print(inches, "inches is", centimetres_1dp, "centimetres") str() str() function used to convert any type to a string not needed yet, but this will be useful later type() Can always check the type of a value Not typically needed in a program But can be useful when debugging standard output data = 3 print(type(data)) data = 3.0 print(type(data)) data = "3" print(type(data)) data = "3.0" print(type(float(data))) COMPSCI 101 Strings, Style considerations Three ways of creating a string Double quote "Hello" Single quote 'Hello' Triple quotes """Hello""" or '''Hello''' Triple quotes allows string to span multiple lines phrase_one = 'Andrew said "Hello."' phrase_two = "Andrew's program crashed." phrase_three = '''Andrew's program crashed and he said "Gosh"''' phrase_four = """Andrew bought a new computer with the specs: Intel 12th Gen Core i9-12900KF 16Core 64 GB DDR5 RAM""" Formatting strings for output -- option 1 Specify the string used to separate arguments passed to print() dollars = 25 cents = 12 print("Price print("Price print("Price print("Price is is is is Price Price Price Price $", $", $", $", is is is is dollars, dollars, dollars, dollars, "and", cents, "c") "and", cents, "c", sep="") " and ", cents, "c", sep="") "and", cents, "c", sep="...") $ 25 and 12 c $25and12c $25 and 12c $...25...and...12...c Formatting strings for output -- option 2 Use fstring to insert contents of variables into string string literal is specified with a prefix of f variables are included within the string using curly braces dollars = 25 cents = 12 output = f"Price is ${dollars} and {cents}c" print(output) Price is $25 and 12c Strings consist of Unicode characters https://unicode-table.com/en/ Paste special letter directly into the string Use an "escape code" print("Zoё") Escape code start with backslash \ Letter following the backslash indicates the function For Unicode, use \u, followed by the number corresponding to the letter print("Zo\u0451") https://unicode-table.com/en/0451/ Splitting long lines Sometimes a single line of python extends beyond 80 characters Surround expression in parentheses and then split the expression stone_height = 200 stone_width = 400 stone_depth = 100 hole_height = 100 hole_width = 200 hole_depth = 300 remaining = (stone_height * stone_width * stone_depth hole_height * hole_width * hole_depth) COMPSCI 101 import math import Python has libraries of functions that perform useful tasks. The files in these libraries are called modules. To use the functions of a module, we first need to import the module. Standard Python Library https://docs.python.org/3/library/index.html math, random, doctest import this run this statement in Python math import math https://docs.python.org/3/library/math.html The math module contains many useful math functions and constants, e.g., math.pi, math.sqrt(), math.ceil(), … To use the functions of a module, we first need to import the module. """ Program which calculates the area of a circle. Author: Damir Azhar """ import math radius = 10 area = math.pi * radius ** 2 print(f"Area of circle is {area}") COMPSCI 101 Floor Division and Modulo // % Floor Division (//) Evaluates to the next lowest integer value Result is the same type as the operands If one operand is a float, then the result will be a float. The floor of a number is the largest integer less than or equal to the number. print(11 / 2) 5.5 print(11 // 2) 5 https://www.pythontutorial.net/advanced-python/python-floor-division/ Example Assume a cup of coffee requires 15g of coffee beans. A bag of beans contains 200g. How many cups can we make? We want to know how many times we can get a full 15g from 200g. This would be 200 // 15 (i.e., calculate 200 / 15, but round down to the nearest integer value since we don't care about amounts that are less than 15g). print(200 / 15) 13.333333333333334 print(200 // 15) 13 Practice exercises print(200 / 20) print(200 // 20) print(6.0 / 13) print(6.0 // 13) print(100 / 15) print(100 // 15) print(23.0 / 5) print(23.0 // 5) print(10 / 7) print(10 // 7) print(19.0 / 5) print(19.0 // 5) print(13 / 6) print(13 // 6) print(7.5 / 2) print(7.5 // 2) Modulo (%) For any number n, the following equation is True. n == d * (n // d) + (n % d) For positive numbers, you can think of this as the remainder For example, if n = 11 and d = 2: 11 == 2 * (11 // 2) + (11 % 2) 5 1 11 2 =5 1 2 11 % 2 11 // 2 https://www.pythontutorial.net/advanced-python/python-modulo/ Example Assume a cup of coffee requires 15g of coffee beans. A bag of beans contains 200g. How many grams of coffee beans remain in the pack after making as many cups as we can? We want to know how much remains after all the full cups of coffee. That would be 200 % 15 (i.e., when divide by 15, how much is remaining)? print(200 // 15) 13 200g makes 13 full cups of coffee, each of which is 15g, using up 195g of the bag print(200 // 15 * 15) 195 print(200 % 15) 5 The amount remaining in the bag is 5g Practice exercises print(200 // 20) print(200 % 20) print(6.0 // 13) print(6.0 % 13) print(100 // 15) print(100 % 15) print(23.0 // 5) print(23.0 % 5) print(10 // 7) print(10 % 7) print(19.0 // 5) print(19.0 % 5) print(13 // 6) print(13 % 6) print(7.5 // 2) print(7.5 % 2) COMPSCI 101 Example Heron’s Formula Heron's formula states that the area of a triangle whose sides have lengths a, b, and c is: a a c b c a b c b Test Data Choose some triangles and calculate the area Use this data to test our program 5 4 3 area = 0.5 * base * height area = 6 5 5 4 6 area = 12

Use Quizgecko on...
Browser
Browser