Lecture Content.pdf
Document Details
Uploaded by EnticingPromethium4180
New York University Abu Dhabi
Full Transcript
Intro to Computer Science CS-UH 1001 Lecture 0 – Introduction Course/Slide Credits § Many slides are based on those developed by Prof. Yasir Zaki (NYUAD, Department of Computer Science) Today’s Lecture § Why Computer Science? § Course logistics § Computer basics § Computer s...
Intro to Computer Science CS-UH 1001 Lecture 0 – Introduction Course/Slide Credits § Many slides are based on those developed by Prof. Yasir Zaki (NYUAD, Department of Computer Science) Today’s Lecture § Why Computer Science? § Course logistics § Computer basics § Computer setup “Hello World” from Us! § Your lecturer: § Thomas Pötsch § [email protected] § Your teaching assistant: § Faisal Zeeshan § [email protected] Introduction Round § Your name § Your programming experience? § Why are you taking this class? § What do you hope to gain from this course? Why Computer Science? § Computer science is all around us § It’s a growing field with excellent job opportunities § You can do lots of creative and challenging things Space Movies Why Computer Science? CERN Particle Accelerator Computer Science and Programming § The most important skill for a computer scientist is problem solving § Programming is the basic tool in Computer Science to solve problems § Good news! § For this course, no prior programming knowledge is required Course Objectives § Provide an introduction to computer science and programming § Learn how to approach and tackle computer science problems § Develop the ability to translate problems to coded solutions § Get familiar with fundamental concepts of programing § Develop skills to read existing code § Learn how to write computer programs § Accumulated sufficient knowledge to write code § Build arcade like games (Super Mario, Tetris, Pac-man, etc.) Games from Previous Years Class Structure § We will meet twice a week for 2:40h § This class has a built-in lab component § Interactive lecture: 1. Introduce a concept (~30 min) 2. Practice the concept during the lab (hands-on sessions) (~30 min) 3. Solve the exercise together (~15 min) 4. Break (~10 min) 5. go back to 1. Course Unification § The goal of the unification process is to ensure a consistent learning experience for every student, no matter which section they are enrolled in § What we did: § Making clarifying revisions to the academic integrity and code of conduct guidelines § Explicitly prohibiting the use of generative AI tools in assignments, while offering recommendations for their use in self-learning § Having fixed number of quizzes evenly distributed over the whole semester § Having unified assignments and final exams Course Material § All course material will be placed at the course website on Brightspace § Course Syllabus § Announcements § Lecture slides (uploaded before class) § Solved exercises (uploaded after class) § Homework assignments § All your grades (check them regularly!) Text Book § “How to Think Like a Computer Scientist: Learning with Python 3”, by Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris Meyers § Online: www.openbookproject.net/thinkcs/ § Interactive Edition: https://runestone.academy/ns/books/published/thinkcspy /index.html Graded Activities Type Description Weight Class participation Interaction, exercises, etc. 5% Random Quizzes 6 pop quizzes 10 %* Assignments 3 in total 15 %* Final project Group based (last 2-3 weeks) 15 % Mid-term exam Last lecture before break 25 % Final exam Date as advertised on Albert 30 % *Grades are averaged Graded Activities Type Description Weight Class participation Interaction, exercises, etc. 5% Random Quizzes 6 pop quizzes 10 %* Assignments 3 in total 15 %* Final project Group based (last 2-3 weeks) 15 % Mid-term exam Last lecture before break 25 % Final exam Date as advertised on Albert 30 % *All grades are averaged Class Participation § Attend the class (on time) § and show us that you are there (don’t “hide” behind your screen) § as per NYUAD policy, class attendance is mandatory § Actively contribute to the class § Ask questions at any time (and ask many!) § Respond to questions asked § Warning: On low class participation, we will ask random students to present their exercise solution in front of the class Class Participation: Rubrics Description Points (/5) Description 5 Engagements in activities of 90%-100% of classes 4.5 Engagements in activities of 80%-89% of classes 4 Engagements in activities of 70%-79% of classes 3.5 Engagements in activities of 60%-69% of classes 3 Engagements in activities of 50-59% of classes 2 Engagements in activities of a maximum of 50% of classes 1 Engagements in activities of less than 50% of classes 0 Not engaging in activities of any of the course classes In summary, to get 5/5, you should attend 90%-100% of the classes and actively participate in them Quizzes § There will be 6 pop quizzes based on the previous class material (quiz schedule see course schedule in syllabus) § Quizzes will be conducted via Brightspace § But, you have to take the quiz from within the classroom! § If you miss a class, you might miss a quiz § Be on time, otherwise you might miss a quiz § There will be no retakes and no late hand outs Homework Assignments § There will be 3 homework assignments throughout the semester § 2 before the break (approx. in week 4 and 6) § 1 after the break (approx. in week 9) § Each is due after 10 days § Due at exactly 11:59 pm § No extensions will be granted § Late submission policy: § 20% penalty for each day late, for up to 3 days § 1 sec = 1 minute = 1 hour = 1 day § Submit via Brightspace. Submissions via email are not accepted § Double check the files you submitted!!! Midterm and Final Exam § Both exams are § in-class and paper-based § closed-book and multiple-choice questions § 15 questions, 10 answer options each § covering all material up to that point in the course § final exam with emphasis on the second half of the course § not curved!!! § The midterm exam will be § held during last class before break (same room and time as the lecture) § 90 min § The final exam will be § held as announced on Albert (date and room) § 90 min Grade Distribution Score Grade § Questions about grading must be 95 – 100 A discussed within 90 – 95 A- § 2 days for assignments 87 – 90 B+ § 1 day for exams after receiving the grade 83 – 87 B 80 – 83 B- 77 – 80 C+ § No curving and no extra credit! 73 – 77 C 70 – 73 C- 67 – 70 D+ 63 – 67 D < 63 F How to Succeed in This Course? § Attend and participate in class § Many of the exam questions are related to discussions/questions in class § Do all exercises and assignments yourself! § Look into solutions provided § Practice makes perfect – study as many examples as possible § Understand and enhance the examples provided in class/labs as well as the ones in the textbook § Solve suggested exercises according to the course schedule § Seek help when needed and ask questions (and do it early) § During lectures or come to office hours (Virtual) Office Hours § If you have questions or need help, please come during office hours or schedule an appointment via email § My office hours: § By appointment § Zoom or A1-181 § [email protected] § Faisal’s office hours: § Monday and Wednesday 12:00 – 02:00PM § A2-186C § Please book a timeslot: https://calendly.com/fz2335/ics § We are happy to help! § But please keep in mind we also have weekends ;) Agenda Until Fall/Spring Break* Week Topic Assignments 1 Command line terminal, Programming basics 2 Input and output, characters and strings 3 Sequences and lists, decision structures 4 Boolean logic, loops HW 1 release 5 Functions and modules 6 Dictionaries, File I/O HW 2 release 7 Midterm review, Midterm exam (last class before break) *subject to change Academic Integrity Academic Integrity and Dishonesty § Academic integrity means § Responsibility § Honesty § Respect § Academic dishonesty and integrity violations include § Plagiarism § Submitting work of another person § Submitting work previously used/submitted § Submitting work from other sources (including generative AI tools) § Seeking unauthorized guidance § Knowingly sharing your solutions (or part of them) with another student by any means § Responding to quizzes without attending classes in person § Signing the attendance sheet for an absent student § etc. Academic Integrity Violations § Academic integrity violations will not be tolerated in this course: § Every student found to be involved in an integrity violation will be penalized and reported according to the policies of NYU Abu Dhabi* § In case a first integrity violation is reported, the penalty is a 10% deduction from the final grade, or the full percentage of the graded assessment, whichever is higher § A second integrity violation will result in an automatic course failure § Absolutely NO second chances and NO exemptions/exceptions *https://students.nyuad.nyu.edu/academics/registration/academic-policies/academic-integrity/ How to Avoid Integrity Violations? § Submit your own work!!! § Do not copy work from others, in parts or fully § Do not share your work with others § Do not complete work for others § Do not let others write your work § Avoid working in groups (unless it is a group project) § Most importantly: Don’t be afraid to ask us for help § Good news 1: You are allowed to use work from the slides and/or exercises! § Good news 2: You are allowed to use generative AI tools for explanatory purposes, such as understanding error messages or code lines. However, you are not allowed to use them to generate code at all. How can you use generative AI (e.g. ChatGPT) § Explain line(s) of code you don’t understand: § Enter the prompt: ‘Can you explain the following Python code?’ Then, paste the code you wrote or found in your slides or exercises after that § Explain error messages you don’t fully understand: § Enter the prompt: ‘Can you explain the following error message generated when I try to run Python code?’ After that, paste the specific error message you encountered § Again, do not use ChatGPT or any generative AI tool to generate code for you!!! What former students think about the course? Let’s see! A Computer System § A computer consists of: § Input (e.g. keyboard, mouse) § Output (e.g. screen) § Central Processing Unit (CPU) Operating System § Memory (RAM) § Storage unit (HDD, SSD) § Interfaces (e.g. NIC, USB) § Operating System (OS) § offers services/interfaces to components § e.g. Windows, MacOS, Linux CPU Executes Instructions § With the help of the OS, the CPU executes sequences of instructions to accomplish computational tasks § Sequences of instructions are called programs § A sequence of instructions has to reach the CPU so that the computer carries out its intended operations (or computation) § Programs are written in programming languages (low- and high- level languages) Programming Languages § A programming language is a basic tool for users to interact with computers § All programming languages offer § A set of rules and symbols used to construct a computer program § Instructions that allow to do § Input § Output § Computation Programming Syntax § Syntax is the structure of a program as well as the rules behind the structure § Set of legal expressions in that language § In the English language, a sentence is composed of a noun + verb + noun § John plays chess (noun verb noun) § John chess plays (noun noun verb) § Programming languages also have a syntax: § 2 + 2 (Operand Operator Operand) § 2 2 + (Operand Operand Operator) Programming Errors § Syntax error § using illegal terms, expressions or rules § Example: 2 2 + § Runtime errors § no syntax errors, but the program can’t complete execution § Division by zero § Invalid input data § Semantic errors (logical errors) § program completes execution, but delivers incorrect results § Example: 2+4/2 Programming Languages § There are two kinds of programming languages: § Low-level (Machine language, Assembly) § Mostly binary-code, machine-dependent and not portable § High-level (Python, C, C++, Java, etc.) § Use English-like commands § Machine independent § Portable (must be compiled for different platforms) Machine Language § A representation of a computer program which is actually read and understood by the computer § A program in machine code consists of a sequence of machine instructions § Instructions: § are in binary code (0 and 1) § specify operations and memory cells involved in the operation Hello World in Machine Language 0010 0001 0000 1010 0000 0000 0000 0000 21 0a 00 00 #moving "!\n" into eax 0c 10 00 06 #moving eax into first memory location 6f 72 6c 64 #moving "orld" into eax 08 10 00 06 #moving eax into next memory location 6f 2c 20 57 #moving "o, W" into eax 04 10 00 06 #moving eax into next memory location 48 65 6c 6c #moving "Hell" into eax 00 10 00 06 #moving eax into next memory location 00 10 00 06 #moving pointer to start of memory location 10 00 00 00 #moving string size into edx 01 00 00 00 #moving "stdout" number to ebx 04 00 00 00 #moving "print out" syscall number to eax 80 #calling kernel to execute the print to stdout 01 00 00 00 #moving "sys_exit" call number to eax 80 #executing it via linux sys_call Assembly Language § A symbolic representation of the machine language of a specific processor § Converted to machine code by an assembler § Usually, each line of assembly code produces one machine instruction (one-to-one correspondence) § Programming in assembly language is slow and error-prone but more efficient in terms of hardware performance Hello World in Assembly section.text global _start ;must be declared for linker _start: ;tells linker entry point mov edx,len ;message length mov ecx,msg ;message to write mov ebx,1 ;file descriptor (stdout) mov eax,4 ;system call number (sys_write) int 0x80 ;call kernel mov eax,1 ;system call number (sys_exit) int 0x80 ;call kernel section.data msg db 'Hello, world!', 0xa ;string to be printed len equ $ - msg ;length of the string High-level Language § A language which use statements consisting of English-like keywords, such as "FOR", "PRINT”, “INPUT”, “IF“,... etc. § Each statement corresponds to several machine language instructions (one-to-many correspondence) § Much easier to program than assembly language § Data is referenced using descriptive names (variables) § Operations can be described using familiar symbols (math symbols) High- vs. Low-level Programming Languages § High-level instructions have to be transformed to Assembly and ultimately to Machine Code to be “understood” by the CPU High-Level Assembly Machine instructions instructions instructions... movl $46, %edx … … leaq.LC0(%rip), 08 10 00 06 c=a+b %rsi movl $1, 6f 2c 20 57 … %edi 04 10 00 06 movl $0, %eax... … High-level Code Conversion § Compilation vs. Interpretation § Compiler transforms the entire program into an executable § The executable is loaded entirely into memory to be executed § Most high-level languages use a compiler § Interpreter executes a program in a line-by-line fashion Program Program Compiler Interpreter Program is Program is executed CPU CPU executed as a line-by-line whole The Python Programming Language § The name Python has nothing to do with the type of Snake § Python implementation started in 1989 by Guido Van Rossum § he liked Monty Python § High-level and interpreted language § designed for rapid prototyping and easily maintainable code § We use Python as a tool to learn programing Why Python? § Simple and easy to learn § Very popular language § Highly productive as compared to other programming languages like C and Java § Clear and readable syntax § Excellent documentation § It’s fun! Hello World in High-level Languages C Java #include public class HelloWorld { int main(int argc, char** argv) { public static void main(String[] args) { printf("Hello, World!\n"); System.out.println("Hello, World"); return 0; } } } Python print("Hello, World!") Breakout Session I Computer Setup MacOS § For this class we will be using Python 3.X § You can download and install the latest version of Python from: https://www.python.org/downloads/ § Once you finish installing: § Sit back and relax!!! Windows: Installing the Linux Subsystem 1. Navigate to Control Panel | Programs | 4. Navigate to the Windows/Microsoft Turn Windows feature on or off Store and search for Ubuntu 24.04 LTS.Click the Get button to download 2. Enable Virtual Machine Platform and Windows Subsystem for Linux 5. After the download and installation, search for Ubuntu 24.04 LTS in the Start Menu and open it § When asked for a password (not visible while typing), make sure you pick an easy one you remember!!! For example, use your netID for username and password! 3. Restart your computer Intro to Computer Science CS-UH 1001 Lecture 1 – Command Line Terminal Recap from last class ▪ Two kinds of programing languages exists: ▪ High level ▪ Low level ▪ High-level languages have to be translated to Assembly/Machine Code ▪ Compiler ▪ Interpreter ▪ Programing languages can have errors: ▪ Syntax, Runtime and Semantics Errors Command Line Terminal Operating Systems ▪ An Operating System (OS) is ▪ a set of programs that manages a computer’s hardware ▪ acts as an interface between the user and the hardware ▪ When computers were invented, there was no graphical user interface ▪ Linux/Unix is the beginning of the computer OS’s ▪ Windows/MacOS came much later ▪ Many state-of-the-art OS’s are still based on Unix ▪ MacOS ▪ iOS ▪ Android ▪ Chrome OS ▪ etc. What is the Command Line/Terminal? ▪ The command line, or terminal, is a text based interface to the operating system ▪ You can enter commands by typing them on the keyboard and feedback will be given to you similarly as text ▪ It’s is more powerful than you think! Why you Need the Terminal? ▪ A terminal is a powerful interface between the system and the user ▪ It provides an efficient way to access the true power of the OS better than any graphical interface ▪ There are just a few standard terminals and commands, but GUI interfaces are countless ▪ Some devices don’t even have a GUI ▪ Things done in a terminal are easily repeatable ▪ Scripting/automating is nearly as easy as entering commands ▪ Most importantly: You are not a real computer scientist if you don’t know how to use the terminal! ☺ Terminal on Windows ▪ The Windows terminals (cmd, PowerShell) and the Unix terminal operate on the same principals, but use different commands ▪ Windows user will use the Windows Subsystem for Linux ▪ It is a full Linux/Unix system inside of Windows ▪ We use Ubuntu as the OS Finding the Command Line Mac OS Windows The Command Line User name Abbreviation for Blinking cursor (where you your Home folder can execute commands) (where all your personal files are stored) Computer name Current working directory (folder) Terminal Commands ▪ Terminal commands are programs that are installed in your operating system ▪ The components of a command are: ▪ the command ▪ any options required by the command, preceded by a hyphen/dash (optional) ▪ the command’s arguments (if required) command ▪ To run a command, type the name of the command, along with options and/or arguments, and press Enter ▪ Commands usually operate on the folder you are currently in Unix File System ▪ The Unix file system is organized in a tree structure ▪ The file tree can be arbitrarily deep ▪ Every folder is separated by a / ▪ You have access to the same files and folders of your computer, e.g. Desktop, Documents, Downloads, etc. File and Folder Hierarchy File and Folder Hierarchy ▪ In a Unix file system, all your personal files are stored in the home folder of your OS home Desktop PythonFiles IntroCS addition.py myProgram.py Current Working Directory ▪ The command pwd shows your current working directory (the full path from root) MacOS: Home directory Ubuntu: Home Directory ▪ All your files (Desktop, Documents, etc.) can be found here: ▪ On MacOS you are already in your home directory when you open the Terminal /Users/YOURUSERNAME/ ▪ On Windows (Linux Subsystem - Ubuntu) your personal Windows files are here: /mnt/c/Users/YOURUSERNAME/ Windows users, please keep this path in mind! Files ▪ Generally, two types of files: ▪ binary: images, audio, videos, MS Word, executables, etc. ▪ text: files that contain characters ▪ Most files have a file extensions to indicate the type of the file, e.g.: image.jpg File name File extension ▪ Operating systems usually do not show the extensions, but use them to know what program should open it Common File Extensions ▪ A JPEG uses.jpg or.jpeg ▪ A Word document uses.docx, or.doc for older versions ▪ A PowerPoint slide uses.pptx, or.ppt for older versions ▪ An MP3 audio file uses.mp3 ▪ A text file uses.txt ▪ A Python file uses.py ▪ An executable uses.exe (on Windows only) Determine File Types ▪ The command file can be used to determine the type of a file Listing Directories/Files ▪ The command ls can be used to list all folders and files in the current working directory ▪ Useful options: ▪ ls -l → show files in long format ▪ ls -r → show files in reverse order ▪ ls -1 → show one file per line ▪ ls -S → sort output by file size Changing Directories ▪ cd (change directory) is used to change the current working directory ▪ Similar to double clicking on a folder in Explorer (Windows) or Finder (Mac) Change Directory ▪ cd is also used to move one folder up ▪ cd.. (.. means one folder up) ▪ cd../.. (../.. means two folders up,../../.. means three folders up, etc.) ▪ Similar to the up icon/arrow in explorer or finder ▪ Windows – Linux Subsystem only: ▪ cd /mnt/c/Users/USERNAME ▪ Keep this line in mind as you have to execute it whenever you open Ubuntu terminal ▪ Folders with spaces in their names, must be ‘escaped’ by \ or using “ ” ▪ cd subfolder\ 1 or cd “subfolder 1” Useful Tricks ▪ Use tab key to autocomplete file, folder names and commands ▪ The up and down arrow keys get to the last commands used ▪ Type clear (or Ctrl-l) to clear the screen Breakout Session I Navigating the File System Terminal Commands ▪ Perform the following tasks on the terminal: 1. navigate to your Desktop* 2. use the ls –l command to list all files on your Desktop 3. Compare the output with the the files on your Desktop *Windows Subsystem Linux: cd /mnt/c/Users/USERNAME/Desktop Let’s Take a Break!!!!! Creating Directories ▪ mkdir (make directory): ▪ Make subdirectories at once using the option -p: Getting Help with Commands ▪ The command line/terminal has a built-in documentation for all commands ▪ The man command shows a manual for the command ▪ For example: man command ▪ Exit the manual page by pressing q ▪ Fun fact: The man command has also a manual Creating/Editing a File ▪ You can use nano to create or edit a file ▪ For example: nano intro.txt ▪ if the file does not exist, it will be created! ▪ Save using ctrl-o and enter ▪ You can exit nano by pressing ctrl-x ▪ If you edit the file you need to confirm if you want to save by typing y and then enter Viewing a File with cat ▪ The cat command gives you a sneak peak on what’s inside a file and returns to the command line Deleting Files ▪ rm can be used to delete files ▪ If you want to delete a folder use, the option –r rm –r foldername ▪ If you want to delete all files inside a folder, but not the folder, use asterisk (*) rm foldername/* Moving Files ▪ You can use the mv command to move files within your file structure mv filename foldername/ ▪ Examples: ▪ Move a file into a folder called myfolder: mv file.txt myfolder/ ▪ Move a file one folder up: mv file.txt../ Renaming Files ▪ You can also use mv to rename files within the same location mv filename newfilename ▪ Example: mv file.txt file_new.txt Copying Files ▪ You can copy a file from one location to another using cp cp filename foldername/ ▪ Examples: ▪ Copy file.txt into a folder called myfolder: cp file.txt myfolder/ ▪ Make a copy of the file (within same folder): cp file.txt file_new.txt Copying Folders ▪ You can copy an entire folder using the –r option (-r stands for recursively): cp -r folder other_folder Compare Text Files ▪ The diff command compares text files and show where they differ Compare Text Files Compare Text Files Compare Text Files Terminating a Running Program ▪ You can stop any running program in the terminal at any time by pressing CTRL-C Breakout Session II Navigating the File System Terminal Commands ▪ Perform the following tasks on the terminal: 1. navigate to your Desktop* 2. make a directory called introCS 3. change directory to the introCS folder 4. create a file called test.txt and write your name into it 5. rename test.txt to another.txt 6. in the same directory, make a copy of the another.txt file and name it copy.txt 7. delete the another.txt file 8. create a directory inside introCS and name it lecture1 9. create a directory inside lecture1 and name it ex_1 10. move the copy.txt file from the introCS directory into the lecture1/ex_1 directory 11. navigate back to your Desktop *Windows Subsystem Linux: cd /mnt/c/Users/USERNAME/Desktop Intro to Computer Science CS-UH 1001 Lecture 2 – Data Types, Variables, Output Today’s Lecture ▪ Python Data Types can operate differently in different languages ▪ Operators and Operands ▪ Variables can store data ▪ Python Output computers only understand 0s and 1s Data Types characters have to be translated into zeros and ones using data types Data type: mapping of characters into 0s and 1s ▪ Everything on a computer gets reduced to a number! ▪ Deep down, they are just groups of binary numbers ▪ Letters/characters are represented with codes (ASCII, Unicode) ▪ How do programs distinguish the above numbers? ▪ This distinction occurs through data types ▪ Each data type consists of: ▪ A set of values that a data type can hold ▪ A set of operations that can be performed on the data type Simple Data Types ▪ Python uses different data types to represent data Type of Data Python Type Name Value Examples Integers int 5, 11, -100, -55, 150 for computers a int (5) and float(5.0) are Real numbers float 4.5, -0.6, 3.14, 5.0 different Character strings str ‘a’, ‘Robb’, ‘$’, ‘150’, “a” quotes are how you tell the computer you Logical boolean True, False are using a string Equivalent to: 1, 0 None/Null/Nothing NoneType None ▪ Keep in mind: unchangeable ▪ All simple data types are immutable more complex data types are changeable, but simple ones aren't Operators and Operands ▪ Operators are special symbols that perform an action on one or more operands (data types) Examples: +, -, *, / ▪ The values the Operators are applied to are called Operands Operands 10 + 5 Operators Arithmetic Operators Operator Meaning Examples Result + Addition 5+2 7 * Multiplication 5*2 10 - Subtraction 5-2 3 / Division result of a division is always a float, because it is 6/2 3.0 more consistent rather than having float sometimes and sometimes having an integer 5/2 2.5 ** Power 10**2 100 // Integer division with no decimal value (no 5//3 1 decimals are remainder) 14//5 2 cut off/ignored % Modulus: remainder of the division 5%3 2 10%2 0 Breakout Session I: Arithmetic Operators Opening the Terminal MacOS Windows Arithmetic Operators ▪ Enter the interactive mode of Python by typing the command python3 in your terminal, then execute the following: >>> 3+3 >>> 3**2 >>> 3/2 >>> 5//2 >>> 5%3 ▪ How about averaging two numbers? >>> 4+10/2 need to use parenthesis for it to work since it evaluates from left to right Precedence (Order) of Arithmetic Operations ▪ Operations in arithmetic expressions have precedence i.e., order on how they are performed 1. Parentheses 2. Exponents 3. Multiplication and Division Left to Right (5*4-3 is 17 and not 5) 4. Addition and Subtraction Again, Left to Right Operators for Strings TypeError: the operation u tried to apply isn't working on this data type u can only add stringers together, u can't perform any other operations ▪ Which one is a valid syntax? >>> ‘9’ - ’1’ ✗ TypeError >>> ‘1’ + ’9’ ✓ ’19’ int + str what u want isnt clear >>> 1 + ’9’ ✗ TypeError u can't mix data types >>> ‘ab’ + ’cd’ ✓ ’abcd’ Overloaded >>> ‘ab’ - ’bc’ ✗ TypeError Operators >>> ‘ab’ * ’a’ ✗ TypeError reptations >>> ‘ab’ * 3 ✓ ’ababab’ >>> ‘ab’ / ’c’ ✗ TypeError Overloaded Operators ▪ Some operators work differently on different data types: ▪ The + (addition) will ▪ add numbers ▪ concatenate strings ▪ The * (multiplication) will ▪ multiply numbers ▪ perform repetition on strings ▪ Note: Subtraction (-) and division (/) cannot be applied to strings even if they look like numbers How to Change Data Types? ▪ Some data types can be changed to other data types by type casting ▪ A number as a string can be changed to an integer or float using int() or float() 1 + ‘9’ → ✗ TypeError 1 + int(‘9’) → 10 Function: piece of code that can be executed by python that does some kind of command 1 + float(‘9’) → 10.0 - always have a specific name - always followed by () ▪ A number as an integer can be concatenated with a string by casting the number into a string using str() 1 + ‘9’ → ✗ TypeError str(1) + ‘9’ → ’19’ ▪ Note: not all casts are legal some of these type casts might not work Type Casting ▪ What do you think this will give us? >>> int(4.58) ✓4 >>> float(5) ✓ 5.0 we are mixing things >>> str(1) + int(’9’) ✗ TypeError >>> str(int(‘1’) + 9) ✓ ‘10’ >>> int(2 * str(4)) ✓ 44 we are trying to do multiple steps at ✗ ValueError we need to turn string into float first one correction >>> int(‘100.0’) ✓ 100 then we can turn into an integer >>> int(float(‘100.0’)) Expressions vs. Statements ▪ Expressions: represents something that gets evaluated and then returns a value: gives a result back >>> 10*(5+4) 90 >>> “Robb” + “ Stark” Robb Stark ▪ Statements: a unit of code that Python can execute. It does not return a value: doesn't give back a result >>> x = 5 >>> Breakout Session II: Expressions and Statements Expressions and Statements ▪ In the interactive mode of Python, execute the following: >>> x=2+2 Statement >>> x Expression statement has an equal sign >>> x*2 Expression x is a variable >>> x Expression >>> x=x*2 Statement x=8 >>> x bc python reads Expression from left to right ▪ Which of them is a statement and which is an expression? Variables ▪ Variables are named memory locations that are used to: ▪ Bind data to names ▪ Store data ▪ Manipulate the data and re-assign it object: container that contains ▪ The assignment operator (=) assigns data to variables a bunch of things ▪ In Python, every data type is an object and contains three pieces of data: ▪ Reference (Memory location) where data can be found, not vv imp but helps undertsand immutability ▪ Data type ▪ Value ▪ Python sets the variable data type based on the value that is assigned to it u dont have to state what data type the value u r inputing is Variable Assignment ▪ Variables are created by an assignment operator (=): python figured it out location of variables in based on variable computer memory so Variable Data it can find this again Value Reference Name Type x = 42 x 42 int 94529957049376 price = 10.99 price 10.99 float 48659924322644 name = “Robb” name Robb str 78345092741937 1 or valid = True valid True bool 63223939577737 Variable Names ▪ Give meaningful variable names! ▪ If a variable name requires a comment, then the name does not reveal its intent! u can but it will be difficult to work with and remember ▪ Variable names in Python ▪ can only contain letters, numbers or underscores (_) ▪ MUST NOT start with a number! ▪ MUST NOT be Python keywords Python Reserved Keywords might cause issues if u name ur variable that ▪ and ▪ False ▪ nonlocal ▪ as ▪ finally ▪ not ▪ assert ▪ for ▪ or ▪ break ▪ from ▪ pass ▪ class ▪ global ▪ raise ▪ continue ▪ if ▪ return ▪ def ▪ import ▪ True ▪ del ▪ in ▪ try ▪ elif ▪ is ▪ while ▪ else ▪ lambda ▪ with ▪ except ▪ None ▪ yield Naming Conventions ▪ Common names for temporary variables or counters are: ▪ i, j, k, m, and n for integers ▪ c, d, and e for characters ▪ Python recommends: ▪ lowercase_separated_by_underscores for variables ▪ CAPITALIZED_WITH_UNDERSCORES for constants ▪ UpperCamelCase for class names Variables Re-assignment ▪ Assignment statements create variables: x=5 x 5 10 x = 10 overwrote old command ▪ Assignment statements can have an expressions in them: x = x + 10 x 10 20 will use previous x (evaluates right hand side first) ▪ Remember the order of the re-assignment: 1. Evaluate the expression 2. Store the value Obvious, but Common Mistakes ▪ You must assign something to a variable (create the variable) before you can use (evaluate) it!!! Example: This will throw an error if y has y = y + 10 not been created before ▪ Don't confuse the assignment operator (single equal sign, =) with the Equality-Test operator (double equal sign, ==) =: used to add things ==: equality test operator (used to compare Example: things) x=5 This will evaluate to False, x == x + 10 not 15 # let’s take a 15 min break break_time = True Python type() ▪ Python has a built-in function that outputs the data type of a value or variable: >>> type(5) ▪ or: >>> x = 5 >>> type(x) Python id() ▪ Python has a built-in function that outputs the memory location of a variable >>> x = 5 >>> id(x) there are funky questions about memory locations and immutability in exams 4542294800 just important to figure out if u modify a variable does the location change Breakout Session III: Data Types and Memory Locations Data Types ▪ Execute the following statements in the interactive mode of Python and observe the output: >>> type(3) >>> type(4.5) >>> type(‘abc’) >>> type (‘1’) >>> type (True) >>> type (None) Variable Assignments / Re-assignments ▪ Execute the following statements: ▪ What will happen if you now execute the following: >>> x = 2 >>> type(x) >>> x = x + 5 >>> x = x + 8 >>> type(x) >>> type(x) >>> x = 3 * x + 20 >>> type(x) >>> x = x / 10 >>> type(x) ▪ Do you notice something? Variable Assignments / Re-assignments II ▪ Execute the following statements: other languages python >>> x = 2 x (2) ---> 8 2 creates another >>> id(x) x location/box with new data clear out old space in 8 and switches connection >>> x = 8 memory to fill with new info reuses old boxes when >>> id(x) necessary, even when u switch variables ▪ Do you notice something? they are different Immutability ▪ All simple data types in Python are immutable (unchangeable): ▪ Changing a value of a variable creates a new memory location holding the same variable name ▪ Immutability is used for internal memory management ▪ Old/orphaned memory locations will be discarded after some time (garbage collector) immutable: when u change a variable it will create a new memory location always unless a new variable is occupying the old space. - python has a "garbage collector" that clears out old memories when it thinks u don't need it anymore - it is good if u are constantly using the same variables, but it isnt very efficient when u keep creating variables and makes programs much slower (java does it the same way) - only true for simple data types Python Output ▪ The Python built-in function print() outputs a specific message on the screen ▪ The message can be a string or any other data type ▪ Python will automatically convert the argument into a string! ▪ Example: >>> print(“Hello World“) Hello World Breakout Session IV: Hello Word The “Real World” Setup for Programming ▪ A text editor, where you write ▪ The command line (terminal), your code (the.py file) where you execute your code: ▪ python3 filename.py Text Editor ▪ You are free to use any text editor you like ▪ We recommend: Sublime Text 4 ▪ www.sublimetext.com ▪ A very easy to use and powerful text editor ▪ It provides color-coding for Python keywords ▪ It’s free! Hello World! ▪ The next tasks should be coded in a text file rather than through the interactive mode ▪ Exit the Python interactive mode (>>>) now by typing exit() or hit CRTL-D ▪ Create a new text file with Sublime Text and save the text file with a.py extension to your Desktop, for example hello_world.py ▪ Remember: Avoid Python keywords and spaces in the filename! ▪ Write the following inside the file and save it print(“Hello World!”) ▪ Execute the file from the terminal: ▪ Navigate to your Desktop (cd Desktop)* ▪ Run the program by typing: python3 hello_world.py *Windows user with Linux subsystem, execute the following command first: cd /mnt/c/Users/YOURUSERNAME/Desktop or: cd /mnt/c/Users/YOURUSERNAME/OneDrive/Desktop Printing Special Characters ▪ How about printing the following: can't use multiple quotes >>> print(“Strings “literally” consist of characters”) u can use 3 double quotes or a single quote or ▪ Escape characters are special characters that start with a backslash (\) Escape Character Effect \” Prints double quote fixes probelm \n most imp Adds a line break (newline) \t Adds a tab Examples: >>> print(“Strings \“literally\” consist of characters”) Strings “literally” consist of characters >>> print(“Hello \nWorld”) Hello World Python Output ▪ The print() function prints the argument in one line on the screen: >>> print(“Hello World“) Hello World ▪ How about: >>> print(”Hello”) >>> print(“World”) Hello World ▪ By default, every print() function ends with a newline (“\n”) Python Output Line Ending ▪ The “\n” of the print() function can be overwritten with any character/string using the (end=“”) parameter comma separates multiple arguments print can take as many arguments as u want >>> print(“Hello”, end=“ “) >>> print(“World”) Hello World >>> print(“Hello”, end=“_“) >>> print(“World”) Hello_World Long Python Output ▪ Printing several strings at once, you can either ▪ use the + operator to concatenate the strings into one long string must have space to print space >>> print(“Sunday “+”Monday ”+“Tuesday“) Sunday Monday Tuesday ▪ or use the , separator within the print() function: >>> print(“Sunday”,“Monday”, “Tuesday”) Sunday Monday Tuesday adds space between strings converts print into strings ▪ By default, a , will be replaced by a space (“ ”) Python Output Separator ▪ The space separator can be changed into something else, by defining the separator using (sep=“”) at the end of the print() statement >>> print(“Sunday”,”Monday”,”Tuesday”, sep=‘,’) Sunday,Monday,Tuesday overrides space and makes it int whatever u want >>> print(“Sunday”,”Monday”,”Tuesday”, sep=‘_’) Sunday_Monday_Tuesday >>> print(“Sunday”,”Monday”,”Tuesday”, sep=‘\n’) Sunday Monday Tuesday Python Variable Output ▪ The print() function can also output the value of a variable: >>> my_string = “Hello World” >>> print(my_string) Hello World >>> x = 5 >>> print(x) 5 ▪ Python will automatically convert the data into a string! Python Variable Output ▪ The print() function can also output the values of multiple variables at once: >>> month = “April” >>> day = 10 by default comma is space >>> print(month, day) April 10 ▪ How about the following: does not work because u are mixed data types when using + u cant mix data types >>> print(month + day) ✘ Type Error >>> print(month + str(day)) April10 wont give space bc u used + so it isnt automatic Breakout Session V: Simple Calculator Simple Calculator (ex_2.1.py) ▪ Inside a new file, create a simple calculator that sums 2 numbers and prints the result on the screen ▪ The program should be structured as follows: ▪ Assign an integer of your choice to a variable, e.g. x ▪ Assign another integer of your choice to another variable, e.g. y ▪ Sum both variables and assign the result to another variable, e.g. result ▪ Print the result Simple Calculator II (ex_2.2.py) ▪ Modify the previous exercise so that the result is printed as follows: >>> The sum of 2 and 4 is 6 Intro to Computer Science CS-UH 1001 Lecture 3 – Input, Characters, Strings Today’s Lecture ▪ Python Input ▪ Characters ▪ Strings ▪ String Indexing/Slicing ▪ String Methods Recap ▪ Python has simple data types: ▪ int ▪ float ▪ str ▪ boolean ▪ NoneType to use data types, you need variables ▪ Variables contain 3 pieces of data: ▪ Reference ▪ Data type ▪ Value ▪ Overloaded operators operators have different behaviors for different data types ▪ The + operator does concatenation for strings ▪ The * operator does repetition for strings Recap ▪ Create variables using an assignment statement ▪ number = 10 ▪ Change the value of a variable using a re-assignment statement ▪ number = 40 or ▪ number = number * 2 Recap ▪ The Python built-in function print() outputs a specific message on the screen ▪ Printing several variables at once: month = “April” day = 10 print(month, day) April 10 ▪ or print(month + str(day)) April10 Recap ▪ The sep=“” argument overwrites the , separator of a print() function ▪ The end=“” argument overwrites the line ending “\n” of a print() function Python Input ▪ Programming often requires input from users to interact with the program ▪ The input() function is used in Python to read data from the keyboard >>> input(message) ▪ The input() function cycle: ▪ Prints the string given in the message argument (optional) ▪ Waits for input from user (until enter/return) ▪ Returns what was typed as a string!! Python Input ▪ The data returned from the input() function should be assigned/stored into a variable to use it later >>> name = input(“Please enter your name: “) ▪ Even if a number is entered, the returned value will still be a string!! ▪ If you want to use the returned value as a number, you have to use type casting: ▪ int() or float() Breakout Session I: Input and Output Simple Calculator III (ex_3.1.py) ▪ Modify the previous exercise (ex_2.2.py) so that the program asks the user to enter the 2 numbers (each at a time) ▪ For example, the user enters 2 and 4: Characters ▪ Computers do not store characters as characters ▪ but rather store their numeric code ▪ American Standard Code for Information Interchange (ASCII) is a commonly used character coding system ▪ In ASCII, every letter, digit, and symbol is represented as a number ASCII Table only need to know 65=A 97=a know only that there is mapping, and its ASCII ASCII-Character Conversion ▪ Convert a character to its ASCII ▪ Convert an ASCII numerical value numerical value (number) to a character: >>> number = ord(character) >>> character = chr(number) ▪ Example: ▪ Example: >>> print(ord(‘A’)) >>> print(chr(65)) 65 A Recap on Strings ▪ Strings are one of the “simple” data types in Python ▪ Strings are sequences of characters ▪ Defined by single or double quotations (‘ ’, “ ”) ▪ Example: >>> name = ‘python’ String Indexing ▪ Individual characters of a string can be accessed by using square- brackets ([]) after the string: >>> character = my_string[index] ▪ Arguments: ▪ index is an integer representing the index (position) of the character to access String Indexing 0 1 2 3 4 5 name p y t h o n ▪ What is the output of the following? >>> name = “python” >>> print(name) y ▪ Index is an offset from the beginning of the string ▪ The offset to the first letter is 0 String Indexing 0 1 2 3 4 5 name p y t h o n -6 -5 -4 -3 -2 -1 ▪ What about the following: >>> print(name[1.5]) ✗ TypeError >>> print(name) ✗ IndexError >>> print(name[-1]) n String Slicing (Substrings) ▪ To get a slice (substring) of a string, use the following expression: yellow: have to put >>> substring = string[start:end:step] green: you can omit mandatory to put something, u can skip start as long as u put something else in ▪ Arguments: ▪ start: first character (inclusive) in the slice part of the result ▪ end: last character (exclusive) in the slice (optional) ▪ step: step size (optional) ▪ default value: +1 there is always a slicing question in the exam ▪ It returns the substring according to the arguments ▪ start, end and step must be integers and can be positive or negative ▪ |start| or |end| can be larger than the string length ▪ Note: If the start index is greater than or equal to the end index when slicing from left to right, the result is an empty string! String Slicing Example 0 1 2 3 4 5 6 name p y t h o n the end is always excluded -7 -6 -5 -4 -3 -2 -1 >>> print(name[0:2]) py >>> print(name[:2]) py >>> print(name[-6:-1]) pytho will print the whole string >>> print(name[-6:]) python >>> print(name[-1:-6]) ‘’ >>> print(name[-2:2]) ‘’ No wrapping around! >>> print(name[0:5:2]) pto >>> print(name[-1:-7:-1]) nohtyp end can be out of bounds, it just means that they will include everything that is it the string >>> print(name[::-1]) nohtyp numbers = "0123456789" print("Let's take a " + numbers + numbers + " min break!”) Breakout Session II: String Slicing String Slicing (ex_3.2.py) ▪ Create a program that contains the following string: >>> phrase = ‘Pony stash token’ ▪ Print the string slice ‘stash’ using positive indices ▪ Print the string slice ‘Pony’ using negative indices ▪ Print the phrase in reverse ▪ How to get the string ‘Python’? Strings are Immutable ▪ Remember: Strings are immutable ▪ Once created, characters within a string cannot be changed or re-assign >>> name = ‘python’ you can't change the content inside a string >>> name = ‘P’ ✗ Type Error ▪ However, you can create a new string using string slicing >>> new_name = ‘P’ + name[1:] >>> print(new_name) Python String Length ▪ Python has a built-in function that can be used to get the string length >>> length = len(string) ▪ It returns the total count of characters in the string ▪ Example: >>> name = ‘python’ >>> length = len(name) >>> print(length) 6 >>> print(name[length]) ✗ IndexError String Length 0 1 2 3 4 5 name p y t h o n ▪ There are 6 characters in name, but index does not exists! >>> name = ‘python’ >>> length = len(name) >>> print(name[length-1]) n String Comparison ▪ Strings can be compared using the Equality operator == ▪ It compares the numeric value of the characters in the strings ▪ It returns either True or False (boolean) ▪ Example: >>> print(‘apple’ == ‘banana’) compares ASII, goes from left to right if there is one mismatch it will stop and give false False >>> print(‘apple’ == ‘apple’) True String Comparison ▪ Remember: Upper and lower case characters are not the same in the ASCII table! ▪ Example: >>> print(‘Apple’ == ‘apple’) False String Comparison asks if they r not equal ▪ You can also check if strings are not equal using the != operator ▪ Example: >>> print(‘Apple’ != ‘apple’) True The in Operator ▪ The in operator is an operator that checks the existence of a string in another string ▪ Example: >>> print(‘p’ in ‘apple’) True >>> print(‘ple’ in ‘apple’) checks if there is something in something else (sequence has to match) True >>> print(‘ae’ in ‘apple’) False String Methods ▪ Python has a number of useful string methods that can help manipulate strings: ▪ Change letters/sentences case ▪ Replace characters ▪ Search for characters ▪ Count characters ▪ etc. String Methods ▪ Methods are functions that are associated with an object ▪ Since strings are objects in Python, they use the dot (.) notation to access their methods >>> value = object.method(argument) ▪ All string methods return a value! They do not change the string! ▪ Example: new answer, doesn't change the string because a string is immutable >>> name = “python” >>> upper_name = name.upper() >>> print(upper_name) PYTHON String Methods Method syntax Method function.upper() Returns a copy of the string converted to upper case.lower() Returns a copy of the string converted to lower case.capitalize() Returns a copy of the string with the first character capitalized.title() Returns a copy of the string as title cased version (first character of every word).isupper() Returns True if all characters within a string.islower() are upper/lower case, and False otherwise More methods: https://docs.python.org/3/library/stdtypes.html#string-methods Breakout Session III: String Slicing and String Methods String Methods (ex_3.3.py) ▪ Write a program that requests the following from the user: ▪ First and last name using one input() statement ▪ in lower case and separated by a space ▪ Birthday date represented by an 8-digit number, e.g.: 19530512 (May 12 1953) ▪ The program should output ▪ the first and the last name (both should be capitalized) ▪ the string “was born on” ▪ the birthday in the standard format DD/MM/YYYY ▪ Example output: >>> Homer Simpson was born on 12/05/1953 Intro to Computer Science CS-UH 1001 Lecture 4 – String Methods, Lists Today’s Lecture ▪ More string methods ▪ Lists ▪ List indexing ▪ List methods Recap ▪ The input(message) function is used to get data from the user ▪ You can give a message as an argument to prompt the user what input you expect ▪ Everything is read and returned as a string ▪ If you want to use the returned value as a number, you have to use type casting ▪ The data returned from the input() function should be assigned/stored into a variable to use it later >>> name = input(“Please enter your name: “) Recap ▪ String indexing: string[index] ▪ The len() function returns the ▪ Always starts from 0 string length ▪ Can be positive ▪ Can be negative ▪ ASCII ▪ ord() and chr() ▪ String slicing: string[start:end] ▪ start is inclusive ▪ Comparison operators ▪ end is always excluded ▪ ==, != ▪ You can also define the step size [start:end:step] Recap ▪ Some string methods ▪.upper() ▪.lower() ▪.capitalize() ▪.title() ▪ All string methods return a value (string)! They do not change the data/value in the string variable! Finding Substrings ▪ Finding a substring in a string: >>> index = string.find(sub, start, end) ▪ Arguments: ▪ sub: substring to find ▪ start: start index (inclusive) for the search (optional) ▪ end: end index (exclusive) for the search (optional) ▪ It returns: ▪ The lowest (positive) index of the first character where sub is found within the string ▪ -1 if no match was found Example: Finding Substrings 0 1 2 3 4 5 >>> name = ‘python’ >>> print(name.find(‘p’)) name p y t h o n 0 -6 -5 -4 -3 -2 -1 >>> print(name.find(‘th’)) 2 >>> print(name.find(‘th’, 3)) -1 >>> print(name.find(‘th’, 0, 3)) -1 >>> print(name.find(‘th’, -4, -1)) 2 Counting String Occurrences ▪ Counting how many times a substring is present in a string: >>> occurrences = string.count(sub, start, end) ▪ Arguments: ▪ sub: substring to count ▪ start: start index (inclusive) for the count (optional) ▪ end: end index (exclusive) for the count (optional) ▪ It returns the number of occurrences of sub in the string Example: Counting String Occurrences >>> name = ‘banana’ >>> print(name.count(‘a’)) 3 >>> print(name.count(‘p’)) 0 >>> print(name.count(‘na’)) 2 >>> print(name.count(‘a’, 3)) 2 >>> print(name.count(‘a’, 0, 3)) 1 Replacing Substrings ▪ Replacing a substring in a string: >>> new_string = string.replace(old, new, max) ▪ Arguments: ▪ old: substring to be replaced ▪ new: new substring to replace the old substring ▪ max: number of replacements (optional) ▪ It returns a copy of the string in which the occurrences of old have been replaced with new Example: Replacing Substrings >>> name = ‘This is not an advertisement!’ >>> name.replace(‘is’, ‘was’) >>> print(name) ‘This is not an advertisement!’ >>> new_name = name.replace(‘is’, ‘was’) >>> print(new_name) ‘Thwas was not an advertwasement!’ How to replace only the word ‘is’? >>> new_name = name.replace(‘ is ’, ’ was ’) >>> print(new_name) ‘This was not an advertisement!’ Breakout Session I: String Methods String Methods (ex_4.1.py) ▪ Download ex_4.1.py file from Brightspace and write a program to do the following tasks: ▪ Task 1: ▪ Translate the encoded word @)[?$ using the hidden_text string as follows: ▪ Count how many times each symbol in the word @)[?$ appears in the hidden_text string ▪ Subtract the year NYUAD was founded from each count ▪ Print the character representing each count. All characters should be printed in one line without spaces ▪ What is the resulting word? ▪ Task 2: ▪ Find all hidden characters (characters that are not @)[?$) in the string and print them print(“Let’s take a 90 min break!”) break!”.replace(‘90’, ‘15’)) Sequences ▪ A sequence is an object that holds multiple items of data ▪ It stores the data one after the other ▪ Python has several types of sequences: ▪ String: sequence of characters ▪ range() sequence: sequence of numbers ▪ Tuple: sequence of items of any data type (immutable) ▪ List: sequence of items of any data type (mutable) Data Type: List ▪ A list is used to store multiple items in a single variable ▪ Lists can contain: ▪ Items from the same data type ▪ Items from different data types ▪ Lists are dynamic and mutable (changeable): ▪ List items can be added or removed from the list during runtime ▪ List items can be modified after they have been created Lists ▪ Lists are created using square brackets [ ] >>> empty_list = [ ] >>> odd_numbers = [1, 3, 5, 7, 9] List items are (visually) separated by commas (,) ▪ Lists allow duplicate values ▪ List items are ordered* *ordered != sorted Examples: Lists >>> odd_numbers = [1, 3, 5, 7, 9] odd_numbers 1 3 5 7 9 >>> names = [‘Jon’, ‘Sansa’, ‘Arya’, ‘Robb’] names Jon Sansa Arya Robb >>> mixed_list = [‘Jon’, 1, 2.5, ‘a’, True] mixed_list Jon 1 2.5 a True Overloaded Operators on Lists ▪ Similar to strings, some operators can be applied on lists: ▪ Concatenate lists using the + operator ▪ Apply repetition using the * operator ▪ Examples: >>> list1 = [1, 2] >>> list1 = [1, 2] >>> list2 = [3, 4] >>> num = 3 >>> list3 = list1 + list2 >>> list2 = list1 * num >>> print(list3) >>> print(list2) [1, 2, 3, 4] [1, 2, 1, 2, 1, 2] List Indexing and Slicing ▪ List items are indexed 0 1 2 3 4 numbers 1 2 3 4 5 >>> numbers = [1, 2, 3, 4, 5] >>> print(numbers) 2 ▪ Slicing works too! >>> print(numbers[2:4]) [3, 4] >>> print(numbers[1:2]) ▪ Note: Slicing always returns a list! Strings vs. Lists ▪ Strings: ▪ Lists: >>> name = ‘python’ >>> numbers = [1, 2, 3, 4, 5] name p y t h o n numbers 1 2 3 4 5 ▪ Strings are defined using single or double ▪ Lists are defined by items inside [ ]; items quotation are separated by commas ▪ Indexing/slicing ▪ Indexing/slicing: >>> print(name) >>> print(numbers) ‘p’ 1 >>> print(name[2:4]) >>> print(numbers[2:4]) ‘th’ [3, 4] Strings vs. Lists or Immutability vs. Mutability ▪ Strings are immutable: >>> name = ‘python’ >>> name = ‘P’ ✗ Type Error ▪ Lists are mutable: >>> even_numbers = [1, 4, 6, 8] >>> even_numbers = 2 >>> print(even_numbers) [2, 4, 6, 8] Immutability vs. Mutability ▪ Strings: ▪ Lists: >>> name = ‘python’ >>> numbers = [1, 4, 6, 8] >>> print(id(name)) >>> print(id(numbers)) 1404677820 7750390128 >>> name = ‘hello’ >>> numbers = 2 >>> print(id(name)) >>> print(id(numbers)) 4488006416 7750390128 1404677820 7750390128 name python numbers 1 2 4 6 8 4488006416 hello Recap: Copying Strings >>> name = ‘python’ >>> name_copy = name name python >>> name = ‘hello’ hello >>> print(name) ‘hello’ >>> print(name_copy) name_copy python ‘python’ Copying Lists ▪ Since Lists are mutable, list variables only store a reference (pointer) to the object in memory ▪ If you want to copy a list, you need to copy all its elements ▪ Just assigning the list to a new variable will not create a copy of the list ▪ Both variables are pointing to the same memory location (reference) where the list is stored! Example: Copying Lists >>> names = [‘Jon’, ‘Sansa’, ‘Arya’] >>> names_copy = names >>> names_copy = ‘Robb’ >>> print(names) [‘Jon’, ‘Robb’, ‘Arya’] names Jon Sansa Robb Arya names_copy How to Copy a List then? >>> names = [‘Jon’, ‘Sansa’, ‘Arya’] >>> names_copy = [] + names >>> names_copy = ‘Robb’ >>> print(names) [‘Jon’, ‘Sansa’, ‘Arya’] names Jon Sansa Arya names_copy Jon Sansa Robb Arya Length of a List ▪ The len() function also works on lists and returns the total count of items in the list: >>> names = [‘Jon’, ‘Sansa’, ‘Robb’] >>> print(len(names)) 3 >>> names = [] >>> print(len(names)) 0 The in Operator for Lists ▪ The in operator examines if an item is part of a list ▪ It returns True or False >>> names = [‘Jon’, ‘Sansa’, ‘Arya’] >>> print(‘Jon’ in names) True >>> print(‘Cercei’ in names) False >>> print(‘A’ in names) False List Methods Note: Since lists are mutable, most list methods can alter the content of the list. They do not return the altered list Finding the Index of an Item in a List ▪ The index(item) method returns the index of the first element in the list that matches the item in the argument ▪ An error is given if the item is not found in the list >>> names = [‘Jon’, ‘Sansa’, ‘Arya’] >>> print(names.index(‘Sansa’)) 1 >>> print(names.index(‘Cersei’)) ValueError: ‘Cersei’ is not in list Appending an Item to a List ▪ Remember: A list is a dynamic data type ▪ The append(item) method dynamically adds an item to a list during runtime ▪ The item appended is added to the end of the list ▪ The append(item) method modifies the list and does not return a new list (None is returned) >>> numbers = [1, 2, 3] >>> numbers.append(4) >>> print(numbers) [1, 2, 3, 4] Careful: Do not Re-assign the Return Value to a Variable* >>> numbers = [1, 2, 3] >>> numbers.append(4) >>> print(numbers) [1, 2, 3, 4] >>> new_numbers = numbers.append(5) >>> print(new_numbers) None >>> print(numbers) [1, 2, 3, 4, 5] >>> numbers = numbers.append(5) >>> print(numbers) None >>> numbers.append(5) AttributeError: 'NoneType' object has no attribute 'append' *Favorite exam/quiz question Inserting an Item Into a List ▪ The insert(index, item) method ▪ inserts an item to the list at a specific index ▪ does not return the new/altered list! >>> names = [‘Jon’, ‘Sansa’, ‘Arya’] >>> names.insert(1, ‘Robb’) 0 1 2 3 names Jon Sansa Arya names Jon Sansa Arya names Jon Robb Sansa Arya Example: Inserting an Item into a List 0 1 2 names Jon Sansa Arya -3 -2 -1 ▪ Insertion also works with an out-of-bound index: >>> names.insert(50, ‘Robb’) >>> print(names) [‘Jon’, ‘Sansa’, ‘Arya’, ‘Robb’] ▪ Insertion also works with a negative index: >>> names.insert(-3, ‘Robb’) >>> print(names) [‘Robb’, ‘Jon’, ‘Sansa’, ‘Arya’] Converting a String to a List ▪ A string can be converted into a list using the list() type cast: >>> name = ‘python’ >>> my_list = list(name) >>> print(my_list) [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’] >>> sentence = ‘I love python’ >>> print(list(sentence)) [‘I’, ‘ ‘, ‘l’, ‘o’, ‘v’, ‘e’, ‘ ‘, ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’] Splitting a String into a List ▪ The split(separator) method splits a string >>> string_list = string.split(separator) ▪ The separator argument is optional; by default “ “ ▪ It returns a list of strings >>> sentence = ‘I love python’ >>> print(sentence.split()) [‘I’, ‘love’, ‘python’] Examples: Splitting a String into a List ▪ You can also re-define the separator: >>> sentence = ‘I-love-python’ >>> print(sentence.split(‘-’)) [‘I’, ‘love’, ‘python’] >>> print(sentence.split(‘o’)) [‘I-l’, ‘ve-pyth’, ‘n’] >>> print(sentence.split(‘love’)) [‘I-’, ‘-python’] >>> print(sentence.split()) [‘I-love-python’] Joining a List into a String ▪ The join(list) method does the opposite of the split() method ▪ It joins all items of the list using the string as the separator between the items ▪ Note: The list must contain string items! >>> new_string = string.join(list) Example: Joining a List into a String >>> separator = “ “ >>> word_list = [‘I’, ‘love’, ‘python’] >>> joined_string = separator.join(word_list) >>> print(joined_string) I love python >>> separator = “_” >>> joined_string = separator.join(word_list) >>> print(joined_string) I_love_python Breakout Session II: Lists Guessing Game (ex_4.2.py) ▪ Develop a Python program with the following functionalities: ▪ Prompt the user in a single input statement to enter 4 words, all related to a common theme (e.g., fruits), separated by commas ▪ Create a list from the provided words ▪ Ask the user for one additional word and add it to the beginning of the list ▪ Prompt the user to guess one of the words in the list ▪ Display "True" if the guess is correct and "False" if the guess is incorrect ▪ Play the guessing game with your neighbor: ▪ Ask your neighbor to input the 5 words without you looking ▪ Then try yourself to guess one word ▪ Hints: ▪ Use print(‘\n‘ * 100) to clear the screen before the guessing starts ▪ Use the in operator to check for a match ▪ Extra task #1: ▪ Ensure the program handles spaces after the comma if the user includes them in the input ▪ Extra task #2: ▪ Instead of displaying True or False, display “Congratulations” or “Sorry, wrong guess” (without if statements!!) ▪ Hint: True has the value of 1, and False has the value of 0. Use them as indices to print the two strings above Intro to Computer Science CS-UH 1001 Lecture 5 – List Methods, Decision Structures, Logical Operators, Loops Today’s Lecture ▪ List Methods ▪ Decision structures ▪ Logical Operators ▪ Loops Recap String Methods ▪ Replacing substrings ▪.replace(old, new, max) ▪ Finding substrings ▪.find(substring, start, end) ▪ Counting substrings ▪.count(substring, start, end) Recap Lists ▪ Lists are created by [] ▪ Empty list: my_list = [] ▪ List with initial values: my_list = [1, 2, 3, 4] ▪ Lists are mutable ▪ List items are indexed: my_list -> 2 ▪ List slicing always returns a list: my_list[1:2] -> ▪ Adding items to a list: ▪.append(item) ▪.insert(index, item) Removing an Item From a List ▪ An item can be removed from a list using one of the three options below: ▪ list.remove(item) removes the first occurrence of item from the list ▪ The method does not return the item! (None is returned) ▪ del list[index] removes the item at the specific index from the list ▪ list.pop() removes the last item from the list and returns it ▪ list.pop(index) removes an item at the specific index from the list and returns it Example: remove() Method 0 1 2 3 names Jon Sansa Arya Robb >>> names.remove(‘Sansa’) names Jon Sansa Arya Robb names Jon Arya Robb ▪ Again, do not re-assign the return value to a variable: >>> names = names.remove(“Sansa”) >>> print(names) None Example: del Statement 0 1 2 3 names Jon Sansa Arya Robb >>> del names names Jon Sansa Arya Robb names Jon Sansa Robb >>> del names IndexError: list assignment index out of range Example: pop() Method 0 1 2 3 names Jon Sansa Arya Robb names Jon Sansa Arya Robb names Jon Sansa Arya >>> name = names.pop() >>> print(name) Robb Example: pop() Method with Index 0 1 2 3 names Jon Sansa Arya Robb names Jon Sansa Arya Robb names Jon Sansa Robb >>> name = names.pop(2) >>> print(name) Arya Other Useful List Methods and Functions Method Description.sort() Sort the items within the list in ascending order (from lower value to upper value).reverse() Reverse the order of the items in the list.count(item) Counts how may times an item appears in the list min(myList) returns the element with the minimum value in the list max(myList) returns the element with the maximum value in the list You can find more list methods here: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists Decision Structure ▪ In programing it is often required to make decisions ▪ The program branches out based on a condition ▪ The program executes different code depending on a condition ▪ Conditions are boolean expressions that always evaluate to either True or False! ▪ in operator ▪ Comparison operators (==, !=, 4 = 4 The if Statement ▪ An if statement is used to check a condition ▪ if the condition expression is satisfied (evaluates to True), it executes a certain code block ▪ if the condition expression is not satisfied (evaluates to False), the code block is skipped ▪ Syntax: if condition_expression: # indented code block if condition expression is True Simple Example word = input(“Enter the word ‘python’: ”) if word == 'python’: print('Correct’) print(‘Good bye') Another Example first_age = int(input(“Please enter your age: “)) second_age = int(input(“Please enter your friends age: “)) if first_age < second_age: print(“You are younger than your friend”) print(“Good bye”) Let’s Take a Closer Look The condition expression can have two outcomes: True or False if first_age < second_Age : True (execute the code below) print(“You are younger than your friend”) False (skip the code above and go directly to the next statement) The indentation tells the Python interpreter print(“Good bye”) that the statement belongs to a block executed when the condition expression evaluates to True The if statement ▪ You noticed in the previous example that it only prints if the first age is smaller than the second ▪ “Good bye” appears in both cases (True or False) since its not part of the if statement ▪ How to print the False case? ▪ if first age is larger than the second age The if/else Statement ▪ An if statement can also have an else code block (optional) ▪ if the condition expression was not satisfied (False), the else block is executed ▪ Syntax: if condition_expression: # indented code block if condition expression is True else: # indented code block if condition expression is False Simple Example word = input(“Enter the word ‘python’: ”) if word == ‘python’: print(‘Correct’) else: print(‘Wrong’) print(‘Good bye') Remember the Guessing Game? ▪ Without if condition: guess = input("Please guess a word: ") message = ["Sorry, wrong guess", "Congratulations"] print(message[guess in word_list]) ▪ With if condition: guess = input("Please guess a word: ") if guess in word_list: print(“Congratulations”) else: print(“Sorry, wrong guess”) The if/else statement first_age = int(input(“Please enter your age: “)) second_age = int(input(“Please enter your friends age: “)) if first_age < second_age : True print(“You are younger than your friend”) else: False print(“You are older than your friend”) print(“Good bye”) The if/elif/else Statement ▪ if statement is used to check a condition ▪ if the condition expression is satisfied (True), it executes a certain code block ▪ elif statements are used to check for further conditions (optional) ▪ if the elif condition expression is satisfied (True), it executes a certain code block ▪ else is executed if none of the above are True (optional) ▪ Syntax: if condition_expression: # indented code block if condition expression is True elif condition_expression: # indented code block if the if condition expression is False but the elif condition # expression is True else: # indented code block if all above condition expressions are False Simple Example word = input(“Enter the word ‘python’: ”) if word == ‘python’: print(‘Correct’) elif word == ‘’: print(‘Nothing entered’) else: print(‘Wrong’) print(‘Good bye') If, elif and else if first_age < second_age: print(“You are younger than your friend”) elif first_age > second_age: print(“You are older than your friend”) else: print(“You and your friend have the same age”) print(“Good bye”) Case 1: First Person is Younger True if first_age < second_age: print(“You are younger than your friend”) elif first_age > second_age: print(“You are older than your friend”) else: print(“You and your friend have the same age”) print(“Good bye”) Case 2: First Person is Older False if first_age < second_age: print(“You are younger than your friend”) True elif first_age > second_age: print(“You are older than your friend”) else: print(“You and your friend have the same age”) print(“Good bye”) Case 3: Both Have the Same Age False if first_age < second_age: print(“You are younger than your friend”) elif first_age > second_age: False print(“You are older than your friend”) else: print(“You and your friend have the same age”) print(“Good bye”) Breakout Session I: Selection Statement Pass or Fail (ex_5.1.py) ▪ Write a program that requests the user to input a grade (in numerical form, e.g. 90). Then the program will display whether the class is PASSED or FAILED ▪ Use if and else statements to do this ▪ The table below can help you do the mapping Score Result >= 60 Passed < 60 Failed Test Score (ex_5.2.py) ▪ Write a program that requests the user to input a grade (in numerical form, e.g. 90). Then your program will display the corresponding letter grade ▪ Use if, elif and else. The table below can help you do the mapping Test Score Grade 90 and above A 80 - 89 B 70 - 79 C 60 - 69 D Below 60 F Nested Decision Structure ▪ Decision structures can be nested inside each other: if grade > 60: print(“You have passed”) if grade < 70: print(“Your grade is D”) Test Score Grade elif grade < 80: 90 and above A print(“Your grade is C”) 80 - 89 B elif grade < 90: 70 - 79 C print(“Your grade is B”) else: 60 - 69 D print(“Your grade is A”) Below 60 F else: print(“You have failed the class”) Let’s Take a Break! Logical Operators ▪ Sometimes it is required to check several conditions at once ▪ Python has three logical operators to create complex Boolean expressions: ▪ not: negate a Boolean expression ▪ and: combines two Boolean expressions, both need to be True for the overall expression to evaluate to True ▪ or: combines two Boolean expressions, only one needs to be True for the overall expression to evaluate True not Operator ▪ Used to negate the condition (the inverse of the condition): guess = int(input(“Make a guess: “)) if not guess < 7: print(“Evaluated to True”) guess Expression Overall expression -1 True False 10 False True not Operator ▪ Used to negate the condition (the inverse of the condition): guess = int(input(“Make a guess: “)) if not guess < 7: print(“Evaluated to True”) guess Expression Overall expression -1 True False 10 False True and Operator ▪ Check if both conditions are met: guess = int(input(“Make a guess: “)) if guess < 7 and guess > 0: print(“Evaluated to True”) guess Expressions Overall expression -1 True and False False 10 False and True False 5 True and True True 7 False and True False and Operator ▪ Check if both conditions are met: guess = int(input(“Make a guess: “)) if guess < 7 and guess > 0: print(“Evaluated to True”) guess Expressions Overall expression -1 True and False False 10 False and True False 5 True and True True 7 False and True False or Operator ▪ Check if one or both conditions are met: guess = int(input(“Make a guess: “)) if guess < 7 or guess > 0: print(“Evaluated to True”) guess Expressions Overall expression -1 True or False True 10 False or True True 5 True or True True or Operator ▪ Check if one or both conditions are met: guess = int(input(“Make a guess: “)) if guess < 7 or guess > 0: print(“Evaluated to True”) guess Expressions Overall expression -1 True or False True 10 False or True True 5 True or True True Order of Evaluation ▪ The order of evaluation from highest to lowest Operator Description , ==, !=, in Comparison operators not boolean NOT and boolean AND or boolean OR Breakout Session II: Logical Expressions Long Logical Expressions ▪ Solve the following logical expressions on a piece of paper: x = True a=5 y = False b=2 z = False c = [True, False] >>> not x and y >>> not y == x >>> False >>> True >>> x or not y and z >>> not a > b or not a == b >>> True >>> True >>> not x or y or not y and x >>> (a > b) == (b < a) and y >>> True >>> False >>> not x and not y and not y and x or z >>> not x in c or (not x) in c >>> False >>> True Rock, Paper, Scissors (ex_5.3.py) ▪ Download ex_5.3.py file from Brightspace and complete the program to play the game ▪ Use the given table to write code that determines the winner of the game based on the choices made by the computer and the player Computer Player Winner ▪ For example: Rock Rock Draw if computer == "rock" and player == "rock": Rock Paper Player Rock Scissors Computer print(”It’s a draw") Paper Rock Computer elif computer == "rock" and player == ”paper": Paper Paper Draw print(”Player wins!") Paper Scissors Player … Scissors Rock Player Scissors Paper Computer ▪ Extra task: Scissors Scissors Draw ▪ Instead of typing out all 9 possible combinations, explore and implement a more efficient approach Short-circuit Evaluation donuts = 50 students = int(input(“Number of students: “)) if students > 0 and donuts/students < 1: print(“Insufficient donuts :(”) ▪ The and and or operators are evaluated using short-circuit evaluation ▪ As soon as the truth value of the entire expression is determined, no further conditions are evaluated Chaining Comparison Operators ▪ Comparison operators can be chained: x=2 if x > 1 and x < 3: print(“x == 2”) ▪ Chained comparison operators: x=2 if 1 < x < 3: print(“x == 2”) Loops ▪ There are two kinds of loops: ▪ A count-controlled loop (for loop) ▪ A condition-controlled loop (while loop) ▪ A count-controlled (for) loop ▪ iterates a specific number of times ▪ always iterates over a sequence ▪ A sequence can be: ▪ string ▪ list ▪ tuple ▪ range() sequence The for Loop ▪ Syntax: for item in sequence: # indented code block ▪ The for loop execution is as follows: ▪ The first element in the sequence is assigned to the temporary variable item ▪ The indented code block is executed ▪ The loop repeats by assigning the next element in the sequence to item ▪ The for loop keeps repeating until the last element of the sequence is reached Example: Looping Over a String for char in “Jon”: print(char) 1st Iteration: for char in “Jon”: print(char) J 2nd Iteration: for char in “Jon”: print(char) o 3rd Iteration: for char in “Jon”: print(char) n Example: Looping Over a List for item in [’Jon', ’Sansa', ’Arya']: print(item) 1st Iteration: for item in [’Jon', ’Sansa', ’Arya']: print(item) Jon 2nd Iteration: for item in [’Jon', ’Sansa', ’Arya']: print(item) Sansa 3rd Iteration: for item in [’Jon', ’Sansa', ’Arya']: print(item) Arya The range() Sequence ▪ The range() function is used to create a sequence of integers >>> integer_sequence = range(start, end, step) ▪ Arguments: ▪ start: first integer (inclusive) of the sequence (optional) ▪ end: last integer (exclusive) of the sequence, starting from 0 (inclusive) ▪ step: step size (optional) ▪ default +1 ▪ It returns a sequence ranging from start to end in steps of step Examples: The range() Sequence >>> print( range(5)) 0, 1, 2, 3, 4 >>> print(range(5, 10)) 5, 6, 7, 8, 9 >>> print(range(-1, 2)) -1, 0, 1 >>> print(range(0, 10, 2)) 0, 2, 4, 6, 8 ▪ Note: The return value is an integer sequence, not a list! It can be converted into a list using type casting: >>> print(list(range(5))) [0, 1, 2, 3, 4] The range() Sequence in Loops ▪ The range() function can be used as a sequence in a for loop ▪ Example: for n in range(5): 0 1 print(n) 2 3 4 Breakout Session III: Count-controlled Loops FIZZ BUZZ (ex_5.4.py) Expected output: 1 2 FIZZ ▪ Write a program that prints the numbers from 1 to 100 4 BUZZ FIZZ 7 ▪ However, if the number is 8 ▪ divisible by 3, print “FIZZ” instead of the number FIZZ ▪ divisible by 5, print “BUZZ” instead of the number BUZZ 11 ▪ divisible by both 3 and 5, print “FIZZ BUZZ” instead of the number FIZZ