Week 2 — Types, Variables, Expressions, Functions PDF

Title Week 2 — Types, Variables, Expressions, Functions
Course Computer Graphics
Institution University of Ottawa
Pages 25
File Size 810 KB
File Type PDF
Total Downloads 36
Total Views 144

Summary

The melting point of the formation of a material...


Description

Week 2 — Types, Variables, Expressions, Functions

Thonny Demo — Editor vs Shell Python interpreter can work in an interactive or shell mode in which lines of code are executed immediately as soon as they are entered and output is visible immediately. Shell mode is apparent whenever you see the prompt

>>> .

In Script mode, a Python file ( .py ) is executed by interpreter as a program (whole file, not line-by-line). !onny allows us to use both modes.

Objects and Data Types All data in a Python program is represented by objects. An object always has a

type (or class) associated with it.

>>> 5 5 >>> 3.1415 3.1415 >>> "Hello" 'Hello' # Using type() function to know the type of objects >>> type(5)

>>> type(3.1415)

>>> type("Hello")

An object’s type determines the operations that the object supports: #

objects of int type can be added using +

>>> 10 + 5 15 # But an object of type str cannot be added to an int using + >>> "Hello" + 5 Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate str (not "int") to str

Summary We saw the three basic data types in Python: int : Integers such as

..., −1, 0, 1, 2, ...

float : Floating-point numbers such as

−1.2, 3.14, etc.

str : Text data (a sequence of characters) such as “hello world”, “Python”, etc.

!e terms Object and Value are used interchangeably. So are the terms Class and Type.

Comments

Comments are annotations we add to our program and are ignored by the Python interpreter. In Python, we start a comment using

#.

A comment can appear on a line by itself or at the end of a line. We use comments to: Make the code easier to read and understand by explaining how it works. Indicate authorship and license. Disable some code (prevent it from executing) but still keeping it in the file. # Author: Deven # My first program # This is a comment on its own line & it will be ignored print("Hello, world!") print(123) print(1.614)

# str

# int # float

In !onny, we can use

Edit menu -> Toggle comment

to comment/uncomment the

selected lines.

Variables In Python, a Variable is a name that refers to an object in computer memory. A variable can be created using Assignment Statement:

variable_name = value

=

is known as the assignment operator.

# create a variable and assign it value 20 temperature = 20 # variable temperature refers to 20 which is displayed print("Today's temperature is", temperature) # show type of the variable print("Type of temperature variable is", type(temperature))

Output Today's temperature is 20 Type of temperature variable is

Arithmetic with numbers Calculations with numbers can be done using arithmetic operators.

# Addition print(1.5 + 1.5) # 3.0 # Subtraction print(10 - 20)

# -10

# Multiplication print(42 * 42)

# 1764

# Division print(1 / 5)

# 0.2

# Exponentiation (x to the power of y) print(2 ** 16)

# 65536

temperature = 20 # Unary minus operator print(-temperature)

# -20

# Computing rest mass energy of an electron rest_mass = 9.109e-31

# Using scientific notation for floating point numbers

speed_of_light = 3e8 rest_mass_energy = rest_mass * (speed_of_light ** 2) print(rest_mass_energy)

# 8.198099999999999e-14

Floor division and remainder 6

20 // 3

3 20 –18 2 20 % 3

# E = mc^2

# floor division print(20 // 3)

# 6

# remainder print(20 % 3)

# 2

# Converting seconds to minutes duration = 320 print(duration, "seconds equal", duration / 60, "minutes.") # 320 seconds equal 5.333333333333333 minutes. # Alternative approach:



minutes = duration // 60 seconds = duration % 60 print(duration, "seconds equal", minutes, "minutes and", seconds, "seconds.") # 320 seconds equal 5 minutes and 20 seconds.

Result type of arithmetic operations For all operators (except division

/ ):

if one or more of the operands are of type

float , result value will have type

float

if both operands are of type For division operator

int , result value will have type int .

/:

the result value is always of type of type

int

or

float

regardless of whether the operands are

float .

x = 2 + 1 print(x, type(x))

# 3

x = 2 + 1.0 print(x, type(x))

# 3.0

# Classic division always results in float x = 1 / 2 print(x, type(x))

# 0.5

Try Try the the above above examples examples with with other other operators! operators!

Function calls Function take zero or more input values, perform an action or computation, and return the result value. Input values passed to a function are called arguments. A Function Call is an expression that looks like below:

function_name(argument1, argument2, …, argumentN)

How do we say it? — function “takes” argument(s) and “returns” a result. !e result is also called the return value. !e number of arguments required by a function depends on how that function is defined. Following are some built-in functions available in Python: # min() function takes 2 or more numbers and returns minimum of those x = min(1, -4, 6) print(x)

# -4

# abs() function takes one number and returns absolute value of the number y = abs(-6) print(y)

# 6

# Gives an error if we do not give exactly one number z = abs(-1, 4) # TypeError: abs() takes exactly one argument (2 given)

Function composition Function composition is applying or calling one function with the result of another function. It is a very useful thing to do especially when we do need to store intermediate results. Compare the following two examples: Using Using intermediate intermediate variables variables

Using composition

x = -5

x = -5

y = -8

y = -8

abs_x = abs(x)

z = min(abs(x), abs(y))

abs_y = abs(y)

print(x, y, z)

z = min(abs_x, abs_y) print(x, y, z)

Converting types explicitly Sometimes we need to convert precision.

int

to/from

float

or round a number to desired

# truncate fractional part using int() function price = 100.6 print(int(price))

# 100

# round to nearest int (price to nearest dollar) price = 100.679 print(round(price))

# 101

# round to two digits after decimal (price to nearest cent) print(round(price, 2))

# 100.68

# convert int to float (e.g. to show zero cents) price = 100 print(float(price))

# 100.0

Question Write a program that converts 85 degrees Fahrenheit to Celsius and displays the results. c=

5(f −32) 9

Basic string operations Strings are sequences of zero or more characters. In Python, strings are enclosed by either single or double quotes.

"Hello" 'everyone!' "I'm Batman."

# single quote allowed inside double quotes,

'You can call me "Bruce".'

# and vice versa.

'123' # this is a string, not a number! "" # this is an empty string " " # this is a string with just one space # a multi-line string using triple quotes """The woods are lovely, dark and deep, But I have promises to keep, And miles to go before I sleep, And miles to go before I sleep. """ # We can also use single quotes for multi-line strings '''I hold it true, whate'er befall; I feel it when I sorrow most; 'Tis better to have loved and lost Than never to have loved at all. '''

String concatenation Strings can be joined with

+

operator.

message = "Hello" + "everyone" print(message)

# Helloeveryone

name = "Alice" message = "Hello " + name print(message)

# Hello Alice

# Result is a string "123" and not the number 6 string = "1" + "2" + "3" print(string)

# 123

price = 100 print(price + " USD") # TypeError: unsupported operand type(s) for +: 'int' and 'str'

String repetition

String can be repeated multiple times using print("Welcome! " * 3) print(4 * "ha")

*

operator.

# 'Welcome! Welcome! Welcome! '

# 'hahahaha'

String length !e function

len()

returns length of its argument string.

password = "xyz1234" print("Password length:", len(password)) # Password length: 7 print(len(1234)) # TypeError: object of type 'int' has no len()

Converting string to/from numbers !is is useful for Reading/writing text files because data will also be stored as text in a file. Reading user input from keyboard, which will also be in text form.

# float to str s = str(1.718) print(s, type(s))

# 1.718

# int to str s = str(-42) print(s, type(s))

# -42

# int to str, then join strings price = 100 message = str(price) + " USD" print(message, type(message))

# 100 USD

# str to int x = int("3370") print(x, type(x))

# 3370

# str to float x = float("1.35") print(x, type(x))

# 1.35

# error because int cannot have decimal point x = int("1.35") # ValueError: invalid literal for int() with base 10: '1.35' # error because of letter other than digits x = int("123x") # ValueError: invalid literal for int() with base 10: '123x' # contains letter other than digits x = float("1.35x") # ValueError: could not convert string to float: '1.35x'

Getting user input We use

input()

function to ask for input data from keyboard.

number = input("Please enter your favorite number: ") print("You entered:", number) print("Your number squared is", number ** 2)

Output >>> %Run week2.py Please enter your favorite number: 7 You entered: 7 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

How to fix the error in the above program? — Convert string to number! input_string = input("Please enter your favorite number: ") number = int(input_string)

Or in a single line: number = int(input("Please enter your favorite number: "))

What if you enter a number of decimal point? How will you fix the error?

More on Variables Variables allow “saving” intermediate results of a computation Consider the question from above: # convert fahrenheit to celsius print("10 F in C is", 5 * (10 - 32) / 9)

We can use variable to store the result so that we can reuse it in the program later.

# Using variable fahrenheit, now we just change value here # instead of changing it in the formula below fahrenheit = 10 # Store the result of the expression celsius = 5 * (fahrenheit - 32) / 9 print(fahrenheit, "F in C is", celsius) # Use variable celsius for more calculations print("Adding 10 degrees today:", celsius + 10)

Variables can be reassigned new values # Create variable name "number" and assign a value to it number = 123 print(number)

# displays 123

# Assign new value to existing variable "number" number = -50 print(number)

# displays -50

# add 10 and assign the result value to existing variable "number" number = number + 10 print(number)

# displays -40

New values can be of different type.

Print output (drag lower right corner to resize)

Python 3.6

1 2 3 4 5 6 7 8 9 10 11

number = 123 # an int value message = "hello" # a string print(number, type(number)) print(message, type(message))

Frames

Objects

# Now variable number refers to t number = message print(number, type(number)) print(message, type(message))

line that just executed next line to execute

< Prev

Next >

Step 1 of 7 Rendered by Python Tutor Customize visualization

However, variables should be changed with caution as it can produce errors or strange results. number = 123

# an int value

message = "hello"

# a string

# Now variable number refers to the string "hello" number = message print(number * 2) # String repetition! print(number - 10) # minus won't work with string.

Output hellohello Traceback (most recent call last): print(number - 10) TypeError: unsupported operand type(s) for -: 'str' and 'int'

Example: Swapping values

Sometimes we need to swap (interchange) values of two variables. A naive attempt (which does not work): x = 137 y = 42 # Try swapping x = y y = x print(x, y)

# 42 42

!e following will work: x = 137 y = 42 # Correct way to swap temp = x x = y y = temp print(x, y)

# 42 137

Rules for variable names A variable name can only contain alpha-numeric characters and underscores A-Z, a-z, 0-9, _

A variable name cannot start with a number Variable names are case-sensitive ( cat , Cat , and CAT are three different variables) !ey cannot be keywords. Python has 33 reserved keywords, you can see a list of them by typing help("keywords") in the Python shell.

Python files should be named using the same rules as above.

Good practice for naming variables Name your variable something descriptive of its purpose or content. If the variable is one word, all letters should be lowercase. Eg: hour , day . If the variable contains more than one word, then they should all be lowercase and each separated by an underscore. !is is called snake case. e.g. is_sunny , cat_name Good variable names: Bad variable names:

hour , is_open , number_of_books , course_code

asfdstow , nounderscoreever , ur_stupid ,

CaPiTAlsANyWHErE

Expressions vs Statements An Expression is any valid combination of values, variables, operators, function calls. When executed, it always evaluates to a single object. x = 3 y = 4 z = x ** 2 + y ** 2 print(z)

# this expression evaluates to an int object

# 25

s = "hello" s2 = s * len(s) # this expression evaluates to str value print(s2)

# hellohellohellohellohello

A statement is one or more lines of code that performs an action but does not evaluate to any value. So, statements cannot be used as a part of an expression.

>>> x = 123 >>> x

# Assignment statement does not evaluate to anything so nothing shows below

# This is an trivially an expression

123 >>> 10 + (x = 123)

# Trying to use assignment statement in an expression

10 + (x = 123) ^ SyntaxError: invalid syntax

Order of Expression Evaluation When we have different operators the same expression, which operator should apply first?. All Python operators have a precedence and associativity: Precedence — for two different kinds of operators, which should be applied first? Associativity — for two operators with the same precedence, which should be applied first? Table below show operators from higher precedence to lower. Operator ()

(parentheses)

Associativity Right

**

Unary

-

-

* , / , // , %

Left

Binary

Left

=

+, -

(assignment)

Right

x = 3 y = 5 # Multiplication has higher precedence than addition z = x + 2 * y + 1 print(z)

# 14

# Need to use parentheses to enforce the order we want z = (x + 2) * (y + 1) print(z)

# 30

# Same precedence so left to right z = x * y / 100 print(z)

# 0.15

# Same as 2 ** (3 ** 2) because "**" goes right to left z = 2 ** 3 ** 2 print(z)

# 512

# Using parentheses to enforce the order we want z = (2 ** 3) ** 2 print(z)

# 64

x = 5 x = x + 1 print(x)

# addition happens first and then assignment # 6

Types of Errors Syntax Errors Errors: When syntax is incorrect such as wrong punctuations, invalid characters, missing quotes or parentheses etc. Program does not run at all in the case of syntax errors. # The following code has Syntax error due to missing double-quotes: x = 5 print("Square of x is) print(x ** 2)

Runtime Errors Errors, also called Exceptions, occur when there is a problem in the program during execution. All code executes until an exception occurs.

# The following code has Syntax error due to missing double-quotes: x = 5 print("Square of x is") print(y ** 2)

Semantic or Logic errors are said to occur when a program executes without a problem but does not produce correct output as expected.

Debugging is the process of finding and removing errors in a program.

Using debugging in Thonny for better understanding order of evaluation In !onny, we can use debugging features to understand how expressions are evaluated: To show variables and their values, go to menu “View -> Variables” First, run program in debug mode by clicking the “Debug current script” button (located next to the “Run current script” button and looks like a bug) !en, we have two options: Run the program line-by-line using “Step over” button next to the “Debug” button Run program going inside each expression using “Step into” button (located next to “Step over” button) Try the following code in !onny and use debug:

x = 7 # Increment value of variable x by 1 x = x + 1 # y = x * x + 2 * (x + 1) + max(x + 1, 5) # Calling print() with 4 arguments print("x =", x, "y =", y)

message = "Hello" # Calling print() with 1 argument print("+" + "-" * (len(message) + 6) + "+") # Calling print() with 3 arguments print("+", "-" * (len(message) + 6), "+")

Defining a function A function is a named block of code that performs a task. So far we have been using (calling) functions to do specific tasks —

print() ,

input() , etc.

We can also define/create our own function: def function_name(argument1, argument2, ..., argumentN): # function body statement1 statement2 . . statementN

# function header

def

is a Python keyword used to define functions

Notice how statements are indented by spaces, typically 4 spaces. In !onny, we can just use tab key once to indent by 4 spaces. When we define a function using

def

keyword:

it is not executed. Only the function name is created, which refers to the code block inside the function. When we call a function, the code block inside the function is actually executed.

Function with no arguments Such functions always do the same thing each time they are executed. Output # Define the function

+------------+ | Welcome! | +------------+ +------------+ | Welcome! | +------------+

def display_greeting(): print("+------------+") print("|

Welcome!

|")

print("+------------+") # Call the function display_greeting() # Call it again display_greeting()

Functions with arguments and return value A function can return a valu...


Similar Free PDFs