Week 2 - Variables and Operators PDF
Document Details
Uploaded by PlushSchrodinger
Macquarie University
Yan Wang
Tags
Related
Summary
This document is a set of lecture notes on Python variables and operators. It covers a wide range of topics, from basic concepts to more advanced techniques for handling and manipulating data and implementing instructions; It includes explanations and examples using Python code to demonstrate different concepts.
Full Transcript
COMP6010 Fundamentals of Computer Science Week 2 variables and operators Yan Wang [email protected] 1 Python New Lines and Indentation a = 50 b = 30 if b > a: print("b is greater than a") This is the...
COMP6010 Fundamentals of Computer Science Week 2 variables and operators Yan Wang [email protected] 1 Python New Lines and Indentation a = 50 b = 30 if b > a: print("b is greater than a") This is the entire If Else elif a == b: block print("a and b are equal") 2 Python New Lines and Indentation i = 1 while i < 6: print(i) This is the entire while loop i += 1 3 comments comments.py Comments starts with a #, and Python will ignore them: Comments are used to make the code more readable. # Below it is to output something print("Hello, World!") print("Hello, World!") # it is to output something Python has no syntax for multiline comments But you can add a multiline string (triple quotes) as comments as long as it is not assigned to a variable """ This is a comment line 1 This is a comment line 2 This is a comment line 3 """ print("Hello, World!") 4 Variables types.py A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type, A variable’s type is determined when a value is assigned to it A variable’s type can even change when a value of a new type is assigned to it We can explicitly specify the data type of a variable with casting x=5 y = "John" print(type(x)) print(type(y)) print(x) print(type(x)) x = str(x) print(x) print(type(x)) x = float(x) print(x) print(type(x)) 5 Variables names A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables: A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables) 6 Variable names # Legal variable names: myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" # Illegal variable names: 2myvar = "John" my-var = "John" my var = "John" 7 Variable names It is worthwhile to give a variable a name that is descriptive enough to make clear what it is being used for. Camel Case: Second and subsequent words are capitalized, to make word boundaries easier to see. (Presumably, it struck someone at some point that the capital letters strewn throughout the variable name vaguely resemble camel humps.) Example: numberOfCollegeGraduates Pascal Case: Identical to Camel Case, except the first word is also capitalized. Example: NumberOfCollegeGraduates Snake Case: Words are separated by underscores. Example: number_of_college_graduates 8 Multiple Variables Many Values to Multiple Variables x, y, z = "Apple", "Peach", "Cherry" print(x) print(y) print(z) One Value to Multiple Variables x = y = z = "Apple" print(x) print(y) print(z) 9 Output Variables types2.py Values of the same data type x = "COMP6010" print("I like " + x) y = 10 print(y * 10) Values of different data types x = "COMP60" y = 10 print(x + str(y)) 10 Local and Global Variables types3.py If a variable is created within a function, it is valid within the function. A variable created outside a function is a global variable, valid inside and outside the function x = "awesome" def myfunc(): x = "fantastic" print("Python is " + x) myfunc() print("Python is " + x) 11 Data Types Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview 12 Python Number types5.py int, float, complex x = 100 # int print(x) print(type(x)) y = 111.25 # float print(y) print(type(y)) x = 2e5 # 2 * 10^5 print(x) print(type(x)) # x is now a float z = 2 + 3j # a complex number print(z) print(type(z)) 13 Python Booleans True or False Expression 100 < 200 evaluates to a Boolean value We can use function bool() to evaluate any value to a Boolean value Only empty values, such as (), [], {}, "", 0 and None, can be evaluated to False All other values are evaluated to True 14 input(sth:) + type conversion input1.py name = input("Your name: ") age = input('Your age: ') print('You are ' + name) print("You are " + age + " years old.") 15 input(sth:) + type conversion input2.py myAge = 50 yourName = input("Your name: ") yourAge = input('Your age: ') print('You are ' + yourName) print("You are " + yourAge + " years old.") # below is wrong for type # myAge - yourAge # need to convert str to int, then convert int result to str ageDiff = myAge - int(yourAge) # now conver int result to str for output print('I am ' + str(ageDiff) + ' years older.') 16 Use ‘’ or “” for string and output Use a pair ‘’ or “”, rather than ‘” or “’ ‘hello’ # legal “hello” # legal ‘hello” # illegal If you need to include ‘ or “ in output print(‘a book titled “Python Tutorial”’) Use ‘‘‘…’’’ to output multiple lines print(‘‘‘How are you? This is our first class to learn Python Wish you all enjoy this unit.’’’) 17 strings string1.py word = 'How r u?' #index 01234567 print(word) print(word) # first character print(word) # 2nd character print(word[-1]) # last character print(word[-2]) # 2nd last character print(word[:3]) # start from 1st character, 3 is the ending index exclusive - the character with index of 3 is exclusive print(word[4:8]) # 4 is the beginning index inclusive, 8 is the ending index exclusive, length=8-4=4 print(word[4:]) # until the end of the string 'r u?' print(word[:-1]) # the entire string without ‘?’ print(word[0:-1]) # the entire string without ‘?’ print(word[:]) # the entire string print(word[-4:-1]) # 'r u' 18 Strings string2.py unitName = "Fudamental of Computer Science" unitCode = 'COMP6010' print(unitCode) print(unitName) # below is straightforward print(unitCode + " is " + unitName) # alternatively, we use f'' to format the entire string directly, {unitCode} is the value of unitCode msg = f'{unitCode} is {unitName}' print(msg) 19 Strings string3.py String length: len(str) Check string unitName = "Fudamental of Computer Science" unitCode = 'COMP6010' print(len(unitCode)) print(len(unitName)) print("COMP" in unitCode) # True print("comp" in unitCode) # false, case-sensitive print("comp" not in unitCode) # True if "COMP6010" not in unitCode: print("This is NOT our unit!") else: print("This is the right unit for us!") 20 Methods of Strings string4.py str = " Hello, World!" print(str.upper()) print(str.lower()) print(str.strip()) # removes any whitespace from the beginning or the end print(str.replace("Hello", "HELLO")) # replaces a string with another string print(str.split(",")) # returns list ['Hello', ' World!'] 21 Format - Strings string5.py # Format - Strings # example from w3schools quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." # The format() method takes unlimited number of arguments, and are placed into the respective placeholders: print(myorder.format(quantity, itemno, price)) # use index numbers {0} to be sure the arguments are placed in the correct placeholders: myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) 22 Python Operators Python has the following groups of operators: Arithmetic operators Bitwise operators Assignment operators Comparison operators Logical operators Identity operators Membership operators 23 Python Arithmetic Operators ArithmeticOperators.py + addition 2+3 is 5, 1.2+2.3 is 3.5 - subtraction 5-3 is 2 3-1.5 is 1.5 * multiplication 2*3 is 6 2*1.5 is 3.0 / division 6/3 is 2 7/3 is 2.33333333 % remainder (modulus operator) 6%3 is 0 7%3 is 1 (remainder) 24 Python Arithmetic Operators ArithmeticOperators.py ** exponentiation 2**3 is 8 // floor division 15 // 2 is 7 (7.5 rounded down to 7) ++ or – – are not used in Python!!! 25 Python Bitwise Operators & AND # Sets each bit to 1 if both bits are 1 2 & 3 is 2 (in binary: 010 & 011 = 010) | OR # Sets each bit to 1 if one of two bits is 1 2 & 3 is 3 (in binary: 010 | 011 = 011) ^ XOR # Sets each bit to 0 if both bits are the same 2 ^ 3 is 3 (in binary: 010 | 011 = 001) ~ NOT # Inverts all the bits > 1 means 101 becomes 010 (2), 5 >> 2 means 101 becomes 001 (1) 26 Python Assignment Operators = x =5 x=5 AssignmentOperators.py += x += 3 x=x+3 -= x -= 3 x=x-3 *= x *= 3 x=x*3 /= x /= 3 x=x/3 %= x %= 3 x=x%3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x=x&3 |= x |= 3 x=x|3 ^= x ^= 3 x=x^3 >>= x >>= 3 x = x >> 3