🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Lecture 2.1_ Variables, Statements, and Comments.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Lecture 2.1 Variables, Statements, and Comments Topic 2 Intended Learning Outcomes ◎ By the end of week 2 you should be able to: ○ Write simple statements and expressions, ○ Use sensible variable names and comments to improve the readability of code, and ○ Understand the difference between integ...

Lecture 2.1 Variables, Statements, and Comments Topic 2 Intended Learning Outcomes ◎ By the end of week 2 you should be able to: ○ Write simple statements and expressions, ○ Use sensible variable names and comments to improve the readability of code, and ○ Understand the difference between integers, floats, and strings. 2 Labs Start This Week ◎ Please attend the lab that you have enrolled in. ◎ Bring your laptop if you have one. ○ You will be setting up programming software. 3 Lecture Overview 1. Literals and Variables 2. Statements 3. Naming Conventions and Comments 4 Users vs. Programmers o Users see computers as a set of tools - word processor, email, excel, note, website, messenger, etc. o Programmers learn computer languages to write a Program. o Programmers use some tools (Python) that allow them to build new tools (Program or Software). o Programmers often build tools for lots of users and/or for themselves. What is a program? 5 6 7 Writing a program ◎ A program can be used to solve complex problem ○ ○ Programs are a set of written actions in order to fulfil a need / solve a problem A programming language is the tool used to create a solution (Program) Design a flowchart Implement: Python print data Problem Task Definition if condition true print data Solution for x in range print x Call function ... By writing a program using Python, you can make a computer do something useful 8 Computer Program A program is a sequence of instructions that specifies how to perform a computation. • Input: Get data from the keyboard, a file, the network, or some other devices. • Process: • Math: Perform basic mathematical operations like addition (+) and multiplication (*). • Conditional execution: Check for certain conditions and run the appropriate code. • Repetition: Perform some action repeatedly, usually with some variation. • Output: Display data on the screen, save it in a file, send it over the network, etc. Computer programs 10 Computer programs 11 1. Literals and Variables 12 Values A value (Literal) is one of the basic things a program works with, like a number or a letter. 13 Literals ◎ Literals are values that Python interprets literally (as written). ◎ Represent numbers, text, and other values that are: ○ Required by the program, and ○ Known ahead of time. ◎ For example, a calendar program might contain string literals such as 'Wednesday' and 'August'. 14 Numeric and String Literals ◎ Numeric literals are written as you'd expect. ○ e.g. 42 means the number 42. ◎ String literals (snippets of text) are written between matched quotation marks. ○ e.g. 'text' or "text". >>> 42 42 >>> 27.5 27.5 >>> 'Hello there!' 'Hello there!' >>> "Double quotes work too." 'Double quotes work too.' 15 Check Your Understanding Q. Which lines in the shown program contain numeric/string literals? 1 2 3 4 5 x = 5.1 y = x + 2 z = x + y print('Result:') print(z) 16 Check Your Understanding Q. Which lines in the shown program contain numeric/string literals? A. Lines 1, 2, and 4. ◎ Line 1: 5.1 (numeric). ◎ Line 2: 2 (numeric). ◎ Line 4: 'Result:' (string). 1 2 3 4 5 x = 5.1 y = x + 2 z = x + y print('Result:') print(z) 17 Variables ◎ A variable allows you to give a name to a value. ◎ You can think of a variable like a labelled box. ◎ A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variables “name” ◎ Variable names are decided by the programmer. ◎ The contents of a variable can change. 18 Creating Variables ◎ A variable can be defined (created) via assignment. ◎ Assignment links a variable name with a value. >>> day = 'Wednesday' >>> day 'Wednesday' >>> age = 28 >>> age 28 ◎ Assignment in Python is performed using the equals symbol, e.g. x = 5. 19 Single Equals (=) Mathematics ◎ '=' indicates equality. ◎ An expression of state (how things are). ◎ x = 5 means "x is equal to 5". Python ◎ '=' indicates assignment. ◎ An instruction. ◎ x = 5 means "assign 5 to x" (i.e. "store 5 in x"). x = 5 20 Updating Variables ◎ Assignment can also be used to update the value of an existing variable. ◎ In the example shown, x originally has a value of 5 but is later updated to contain 10 instead. >>> x = 5 >>> x 5 >>> y = 'Hello' >>> y 'Hello' >>> x = 10 >>> x 10 21 Updating Variables Variable Value x = 5 y = 'Hello' x = 10 22 Updating Variables Variable Value x 5 x = 5 y = 'Hello' x = 10 23 Updating Variables Variable Value x 5 y 'Hello' x = 5 y = 'Hello' x = 10 24 Updating Variables Variable Value x 5 10 y 'Hello' x = 5 y = 'Hello' x = 10 25 Variable Naming Rules ◎ Variable names: ○ Must only contain letters, digits, and underscores. ○ Must not begin with a digit. ◎ Lowercase/uppercase matters. ○ myVariable, MyVariable, and MYVARIABLE are all different in Python. 26 Variable Naming Rules Allowed ✓ ✓ ✓ ✓ ✓ x name2 street_address MyAge _rocket Not allowed ✗ ✗ ✗ ✗ ✗ 2d_map best-score school/work $Cost my variable 27 Reserved Words ◎ There are reserved words which have special meanings in the Python language. ◎ Reserved words can't be used as variable names. and as assert break class continu e def del elif else except finally False for from global if import in is lambda nonloca l None not or pass raise return True try with while yield 28 Selecting Variable Names ◎ Variable names are for programmers, not computers. ○ Regardless of whether you name a variable x, age, or zz23v, Python will interpret your program in the same way. ○ However, good variable names can help make code more understandable to humans. 29 Selecting Variable Names s2sfg = 5 s2sgf = 10 s2sff = s2sfg * s2sgf print(s2sff) width = 5 height = 10 area = width * height print(area) ◎ The two programs above are equivalent to Python. ◎ But the one on the right is much easier to understand as a human! 30 Check Your Understanding Q. Which of the following are valid variable names? ◎ ◎ ◎ ◎ ◎ paper,scissors,rock _friend 2_friends KEKWait if 31 Check Your Understanding Q. Which of the following are valid variable names? ◎ ◎ ◎ ◎ ◎ paper,scissors,rock _friend 2_friends KEKWait if A. _friend and KEKWait. ◎ Variable names can't contain commas. ◎ Variable names can't begin with a digit. ◎ if is a reserved word. 32 Ask the Audience ◎ What name might you give a variable which represents the cost of a product? 33 2. Statements 34 What is a Statement? ◎ A statement is a complete "step". ◎ A program consists of multiple statements. ◎ When you run a Python program, the statements within are executed in a well-defined order. ◎ Often a statement takes the form of a line of code. 35 What is a Statement? ◎ We have already seen a few different kinds of statements, for example: ○ width = 5 is an assignment statement. ○ print(area) is a print statement. 36 Expression Statements ◎ Common uses: ○ Interacting with the Python interpreter. ○ Calling functions. 23 y - 5 max(100, 200) ◎ More about expressions and functions in future lectures. 37 Print Statements ◎ Technically a kind of expression statement. print('Hello my friend!') print(x * 2) ◎ Used to display output text to the user. 38 Assignment Statements ◎ Common uses: ○ Defining a variable. ○ Updating the contents of a variable. minimum_age = 18 area = 2 * pi * radius ◎ Assignment statements involve an equals sign. ○ Remember, this is different to = in mathematics! 39 Input Statements. ◎ Technically a kind of assignment statement. ◎ Used to accept input from the user. ◎ Waits for the user to type input and hit "Enter". ◎ Input is stored in a variable. ◎ Optionally specify a prompt to show the user. name = input() c = input('Enter a colour: ') 40 Python Interactive Sessions vs. Scripts Interactive interpreter session ◎ Start an interactive session with the python command. ◎ Write and execute a single statement at a time. ◎ If a statement produces a result, the result will be shown. Python script ◎ Write multiple statements in a ".py" text file. ◎ Execute all of the statements together, for example: ○ python my_script.py ◎ If a statement produces a result, the result will not be shown. ○ Use print statements to display results. 41 Example: Interactive Session >>> x = 5 >>> x + 2 7 >>> name = input('Enter your name: ') Enter your name: Billy >>> print('Hello ' + name) Hello Billy ◎ Writing and running code is interleaved. ◎ Expression statements display results. 42 Example: Script x = 5 x + 2 name = input('Enter your name: ') ◎ First write all the code, then run all of the code. print('Hello ' + name) $ python my_script.py ◎ Expression statements so not display results unless printed. Enter your name: Billy Hello Billy 43 Check Your Understanding Q. What output(s) will be displayed after executing these statements in a Python script? age = 36 print(age) age + 1 print('Done') 44 Check Your Understanding Q. What output(s) will be displayed after executing these statements in a Python script? A. 36 and Done. ◎ Only the print statements produce output messages. ◎ Even though line 3 contains a statement which produces a result, it is not shown. age = 36 print(age) age + 1 print('Done') 45 3. Naming Conventions and Comments 46 Meaningful Variable Names ◎ It is good practice to give variables meaningful names. ◎ Meaningful names are for the benefit of human programmers only. ○ Naming a variable "interest_rate" won't magically give Python the ability to calculate interest. ◎ Spending a few moments to select good variable names can greatly increase code readability. ○ This saves time in the long run! 47 Example: Meaningful Variable Names variable1 = 10 variable2 = 5 variable3 = 20 variable4 = variable1 * variable2 if variable4 > variable3: print('Danger!') acceleration = 10 acceleration_time = 5 maximum_safe_speed = 20 speed = acceleration * acceleration_time if speed > maximum_safe_speed: print('Danger!') ◎ The names of the variables in the second program are meaningful to humans. ◎ When the meaning of a program is unclear, as in the first program, the programmer is more likely to make mistakes. 48 Common Python Naming Conventions ◎ Multiple words in a variable name are separated with_underscores. ◎ Ordinary variables are named in lowercase, with underscores separating words. ○ e.g. current_score = 0 ◎ Constants (variables with values that are never updated) are named in UPPERCASE. ○ e.g. EARTH_GRAVITY = 9.81 49 Other Naming Conventions ◎ Where appropriate, you may want to adopt your own naming conventions. ○ Indicate units: ◉ time → time_secs ○ Indicate that a count is being stored: ◉ participants → num_participants ○ Indicate subtle differences: ◉ password1, password2 → old_password, new_password 50 Comments ◎ Comments are sections of code ignored by Python. ◎ Can be used to annotate code in plain English (good variable names aren't always enough) ◎ In Python, a comment starts with a hash (#) and continues to the end of the line. # This is a comment on its own line. x = 5 # This comment shares a line with actual code. # You can't place a comment before code # y = 7 51 Common Uses for Comments ◎ Explain to other programmers (or your future self) how a complex section of code works. ◎ Leave notes about future work to do. ◎ Add a copyright notice or indicate authorship. ◎ Temporarily disable a section of code ("commenting out" code). 52 Comments in the Wild: Description Don't be afraid of writing comments which are longer than the associated code if you deem it appropriate! 53 Comments in the Wild: Future Work Future work comments often start with "TODO:" (as in "this is future work to do"). 54 Comments in the Wild: License Information 55 "Commenting Out" Code ◎ Since comments are effectively ignored by Python, they can be used to disable lines of code. ○ Simply add a "#" to the start of the line. ◎ The program below outputs 5 (not 6) since line 2 is "commented out". x = 5 # x = x + 1 print(x) 56 Check Your Understanding Q. What result will be displayed by the program? x = 2 five = x + 2 y = five + 4 # y = y + 1 print(y) 57 Check Your Understanding Q. What result will be displayed by the program? A. 8. ◎ Naming a variable "five" does not affect its value. ◎ The commented line is not executed (line 4 is ignored). x = 2 five = x + 2 y = five + 4 # y = y + 1 print(y) 58 Summary 59 In This Lecture We... ◎ Discovered what literals and variables are. ◎ Explored some basic statements in Python. ◎ Learnt how to make code more understandable using comments and well-named variables. 60 Next Lecture We Will... ◎ Delve deeper into programming fundamentals by learning about expressions and types. 61 Thanks for your attention! The slides and lecture recording will be made available on LMS. The “Cordelia” presentation template by Jimena Catalina is licensed under CC BY 4.0. PPT Acknowledgement: Dr Aiden Nibali, CS&IT LTU. 62

Use Quizgecko on...
Browser
Browser