Python Programming - Introduction to Computational Thinking PDF

Document Details

Uploaded by Deleted User

Nanyang Technological University

Tags

python programming computational thinking data types programming

Summary

This document is a presentation on the topic of computational thinking, focused on introduction to Python programming. It covers topics such as variables and data types used in Python programs.

Full Transcript

SC1003 Introduction to computational thinking and programming 1 Course Review Flowchart Pseudocode Introduction to Computational Thinking 2 ...

SC1003 Introduction to computational thinking and programming 1 Course Review Flowchart Pseudocode Introduction to Computational Thinking 2 Please download and install the Slido app on all computers you use Which of the following statements is true regarding pseudocode and flowcharts? ⓘ Start presenting to display the poll results on this slide. Introduction to Computational Thinking 3 Flowchart vs. Pseudocode Flowchart Start Pseudocode Find the distance to location 1 FIND the distance to location 1 FIND the distance to location 2 Find the distance to location 2 IF distance1 >> e = ''' (''‘…''‘) to display a paragraph with multiple Welcome to Stock Master! lines Please select a function to continue: First collection type that was discussed (1) Search for a stock code by keyword Collection type contains multiple objects (2) View stock trend by code organized as a single object (sample input 1 or 2) ''' 33 Basic string operation-string concatenation String concatenation is the operation of joining two or more strings together. In Python, you can concatenate strings using the + operator or by using formatted strings. string1 = "Hello" string2 = "World" result = string1 + " " + string2 print(result) # Output: Hello World Introduction to Computational Thinking 34 str() function The str() function in Python is used to convert an object to a string representation. This is useful when you need to output or store data as a string. Here are some key details about the str() function: str(object) object: The object you want to convert to a string. This can be any Python object, including numbers, lists, dictionaries, tuples, etc. Example: When you need to concatenate a non-string type with a string, str() is handy: age = 25 message = "I am " + str(age) + " years old." print(message) # Output: I am 25 years old. Introduction to Computational Thinking 35 FUNCTION CALL INPUT, OUTPUT Introduction to Computational Thinking 36 Typically, computer performs three-step process Receive input Input: any data that the program receives while it is running Perform some process on the input Example: mathematical calculation Produce output INPUT, PROCESSING, AND OUTPUT Content Copyright Nanyang Technological University 37 38 https://docs.python.org/3/library/functions.html Passing Argument: piece of data that is sent into a function Function can use argument in calculations and Arguments to processing When calling the function, the argument is placed Functions in parentheses following the function name Parameter variable in Functions Parameter variable: variable that is assigned the value of an argument when the function is called The parameter and the argument reference the same value General format: def function_name(parameter): Scope of a parameter: the function in which the parameter is used Reading Input from the Keyboard Most programs need to read input from the user Built-in input function reads input from keyboard Returns the data as a string, even if the user enters numeric data. Format: variable = input(prompt) prompt is typically a string instructing user to enter a value Does not automatically display a space after the prompt Please download and install the Slido app on all computers you use What does the following Python code do? name = input("Enter your name: ") print("Hello, " + name + "!") ⓘ Start presenting to display the poll results on this slide. Reading Numbers with the input Function input function always returns a string Built-in functions convert between data types int(item) converts item to an int float(item) converts item to a float Type conversion only works if item is valid numeric value, otherwise, throws exception Please download and install the Slido app on all computers you use What is the correct way to read an integer from the user in Python? ⓘ Start presenting to display the poll results on this slide. Python allows writing a function that accepts multiple arguments Parameter list replaces single parameter Passing Multiple Parameter list items separated by comma Arguments Arguments are passed by position to corresponding parameters First parameter receives value of first argument, second parameter receives value of second argument, etc. Passing Multiple Arguments (cont’d.) Displaying Output with the print Function print function: displays output on the screen Argument: data given to a function Example: data that is printed to screen Statements in a program execute in the order that they appear From top to bottom Displaying Multiple Items with the print Function Python allows one to display multiple items with a single call to print Items are separated by commas when passed as arguments Arguments displayed in the order they are passed to the function Items are automatically separated by a space when displayed on screen while using default sep Displaying Multiple Items with the print Function cont’ print function uses space as item separator Special argument sep='delimiter' causes print to use delimiter as item separator argument end in print function print function displays line of output Newline character at end of printed data Special argument end='delimiter' causes print to place delimiter at end of data instead of newline character Please download and install the Slido app on all computers you use What will the following Python code output? print("Hello", "World", sep="-", end="!") print(" How are you?") ⓘ Start presenting to display the poll results on this slide. print function with multiple values name = "Alice" age = 21 country = “Singapore" print("Hello, my name is", name, ".", "I am", age, "years old and I live in", country, ".") Hello, my name is Alice. I am 21 years old and I live in Singapore. 52 using the str() function and string concatenation with the + operator to combine the variables into a single string name = "Alice" age = 21 country = “Singapore" print("Hello, my name is " + name + ". I am " + str(age) + " years old and I live in " + country + ".") Hello, my name is Alice. I am 21 years old and I live in Singapore. 53 print function with an f-string F-strings are available in Python 3.6 and later versions and provide a more readable and concise way to format strings, especially when dealing with multiple variables. purpose of the f in an f-string:tells Python to format the string name = "Alice" age = 21 The f-string allows you to directly insert country = “Singapore" variables into a string by placing them inside curly braces {}. # Using f-string to format the output print(f"Hello, my name is {name}. I am {age} years old and I live in {country}.") 54 Please download and install the Slido app on all computers you use How can you include a variable's value and a string literal side by side using an f-string? ⓘ Start presenting to display the poll results on this slide. f-string: formatting numbers f-strings in Python can handle formatting numbers, including specifying the number of digits after the decimal point, adding padding, and more. value = 3.14159 formatted_value = f"{value:.2f}" print(formatted_value) # Output: 3.14 56 f-string: Formatting a Number as a Percentage :.2%: This formats the number as a percentage with two decimal places. The number 0.1234 is converted to 12.34%. If you want to format the percentage without any decimal places, you can specify 0 decimal places: value = 0.1234 formatted_percentage = f"{value:.2%}" print(formatted_percentage) # Output: 12.34% value = 0.5678 formatted_percentage = f"{value:.0%}" print(formatted_percentage) # Output: 57% 57 Please download and install the Slido app on all computers you use Which of the following f-strings correctly formats the variable percentage = 0.875 as a percentage with no decimal places? ⓘ Start presenting to display the poll results on this slide. Introduction to Computational Thinking 58 f-string: more examples f-strings in Python can be created using single quotes ', double quotes ", or triple quotes ''' or """. The choice between these depends on your needs, such as whether your string spans multiple lines or contains quotes inside it. name = 'Alice' name = "Bob" greeting = f'Hello, {name}!' greeting = f"Hello, {name}!" print(greeting) print(greeting) name = "Charlie" message = f""" Hello, {name}. Welcome to our service! """ print(message) 59 f-string: Including Expressions: You can include any valid Python expression within the curly braces. result = f"The sum of 4 and 5 is {4 + 5}." print(result) 60 COMMON MISTAKE Introduction to Computational Thinking 61 What is the output of the following code? alice = 50 peter = 70 sum = alice + peter print (sum, end = "#") scores = [1,2,3,4] total = sum(scores) print (total) ⓘ Start presenting to display the poll results on this slide. alice = 50 peter = 70 sum = alice + peter print (sum, end = "#") 120# scores = [1,2,3,4] total = sum(scores) print (total) 63 64 https://docs.python.org/3/library/functions.html If you get syntax error for the following code which line of code we need to correct? ⓘ Start presenting to display the poll results on this slide. WEEK 3 LAB BRIEFING Introduction to Computational Thinking 66 You can choose your own preferred IDE 67 Battleship game Understand the logic of the game Introduction to Computational Thinking 68 Exercise 1: Pseudo Code Pseudo Code: Write pseudo code for initializing the game board. o Write pseudo code for placing a ship on the board. o Introduction to Computational Thinking 69 Exercise 2: Flowcharts Flowcharts:  Create a flowchart for initializing the game board.  Create a flowchart for the process of placing a ship on the board. Introduction to Computational Thinking 70 Exercise 3: Basic coding Data Types and Variables: oDefine the data types and variables required for the Battleships game (e.g., board, ships, coordinates). oWrite a short program to declare these variables and print their initial values. Input and Output Operations: oTake user input for attack coordinates and display the result. 71 Exercise 3: Basic coding-If you are new to Python programming If you are new to Python programming, copy the following hint code to your IDE, e.g., IDLE, follow the TODO task lists and sample output as follows to complete the exercises. Follow the sample output Fill in the blank according to comments 72 LAB:NO SUBMISSION 73 CCDS New measures on student learning and teaching Introduction to Computational Thinking 74 Bonus Marks for Participation: Your active engagement in tutorials is valuable and enriching for all. Students with consistent participation (at 70% and above of tutorials) will earn 5 bonus marks. Participation rates at 50-70% of tutorials will receive 2 bonus marks. Taking tutorial attendance from Week 3 onward, as the first two weeks are the add/drop period and class lists have not yet been finalized. Introduction to Computational Thinking 75 Make-up session For attendance and make-up sessions, please email me directly and cc the Technical Executive (TE) in charge, providing evidence of a valid reason. Once your leave is approved, please choose a session conducted on a later date in the same lab to simplify attendance tracking. Introduction to Computational Thinking 76

Use Quizgecko on...
Browser
Browser