INF1002_Lec1_PythonBasicI - Copy.pdf
Document Details
Uploaded by DistinctiveVanadium
Singapore Institute of Technology
Tags
Full Transcript
SIT Internal INF1002 Programming Fundamentals Lecture 1: Python basic I Zhang Zhengchen [email protected] SIT Internal Outline Module introduction Python introduction Some concept of softwar...
SIT Internal INF1002 Programming Fundamentals Lecture 1: Python basic I Zhang Zhengchen [email protected] SIT Internal Outline Module introduction Python introduction Some concept of software engineering Python basic I Some concept of programming SIT Internal Python First Steps in Python SIT Internal Why Python? Simple Powerful Community Ecosystem Application in Machine Learning SIT Internal TIOBE Programming Community Index: an index of evaluating language popularity https://www.tiobe.com/tiobe-index/ SIT Internal Why is Python So Popular? The Zen of Python Simple Beautiful is better than ugly. Explicit is better than implicit. Powerful Simple is better than complex. Ecosystem Complex is better than complicated. Flat is better than nested. Community Sparse is better than dense. Cross-platform Readability counts. Application in Machine Learning Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! SIT Internal Your First Python Program https://colab.research.google.com/ File New notebook in Drive Rename, Save, … SIT Internal Your First Python Program Write one program to print "Hello World!" in Python print ("Hello World!") Or print ('Hello World!') print() to print something to the screen Using either " " or ' ' around what you want to print Further Reading The arguments of print() function SIT Internal Knowing Python Single Quote and Double Quote can generally be used interchangeably. print('Hello, World! ') print("Hello, World! ") print('He said, "Python is awesome! "') print("It's a beautiful day! ") SIT Internal Knowing Python What if I want to print It's a "beautiful" day. Use a backslash ('\') to escape quotes inside the string print('It\'s a "beautiful" day! ') print("It's a \"beautiful\" day! ") Escape characters \n Newline \t Tab \\ backslash SIT Internal Knowing Python Raw strings Prefixing a string with r or R makes it a raw string, where backslashes are not treated as escape characters print(r'it\n1\t2') print('it\n1\t2') Print(r"C:\Users\Name") Print("C:\Users\Name") SIT Internal Knowing Python The language is case sensitive print ≠ Print ≠ PRINT Indention matters Some development tools would make automatic indention Be careful about indention In nested if, for, while SIT Internal Write comments Comments People may read your code Guide your thinking In a single line Using the symbol # For multiple lines Using three quotation marks ''' ''' Docstring SIT Internal Write comments Comments People may read your code Guide your thinking In a single line Using the symbol # For multiple lines Using three quotation marks ''' ''' Docstring SIT Internal Python 2 and Python 3 We use Python 3 in this module Print statement Python 2: print "abc ", print 'abc' Python 3: print("abc") Libraries Some libraries only work on P2 e.g. PyImage P3 is increasing the third party module support (especially those machine/deep learning libraries) Others Unicode and Strings Division with integers Input() is now safe to use More difference can be found at: https://www.interviewbit.com/blog/difference-between-python-2-and-3/ SIT Internal Review Hello World in python Quotation marks Escape Characters Backslash Comments Versions of Python SIT Internal Outline Module introduction Python Introduction Some concept of software engineering Python basic I Some concept of programming SIT Internal Programming and Problem Solving A problem is defined by its inputs and the desired property of the output. Evans D. Introduction to computing: explorations in language, logic, and machines[M]. CreateSpace Independent Publishing Platform, 2011. SIT Internal How to solve a problem Pólya G. How to solve it: A new aspect of mathematical method[M]. Princeton university press, 2014, first published in 1945. SIT Internal How to solve a problem SIT Internal Software Engineering Software Development Methodologies Agile Development in Software Engineering https://www.geeksforgeeks.org/what-is-agile-methodology/ SIT Internal Know the problem first Requirement Analysis Let's store files into a database What kind of files File size, numbers Will modify or not Will read them frequently … SIT Internal Design Design Pattern Reusable solutions in software development that addresses common design problems, promoting code maintainability, scalability, and reusability. SIT Internal Implementing - Debug Logic Error When the code is executed, it produces incorrect results Known as a bug Visual Studio Code Run: F5 Breakpoint: pause the execution of a program at a specific line of code Step over: F10 Step into: F11 SIT Internal Testing The act of checking whether software satisfies expectations. Automated testing Levels Unit testing Integration testing System testing Test Cases Make your program robust SIT Internal Deployment Take a website as an example Develop on Local Machine You create the website and test it on your laptop. Test on Staging Server You upload it to a staging server to simulate the production environment and catch any bugs. Deploy to Production Server Once everything works perfectly, you upload it to a production server. Now, anyone can visit your website using its URL. Monitor After deployment, you regularly check the website to ensure it’s running smoothly and fix any issues visitors report. SIT Internal Deployment Key Concepts: Continuous Integration/Continuous Deployment (CI/CD) A set of practices that involve automatically testing and deploying code changes to ensure rapid and reliable updates. Version Control Tools like Git help manage changes to the code and keep track of different versions. Rollback The ability to revert to a previous version if the new deployment causes issues. Large scale and complex real world problems SIT Internal Looking back Monitor your products Get feedback Evaluate your methods/solutions With numbers Evaluation A formal end of this step A guide to your next step SIT Internal Review Programming and problem solving Understand the problem Plan Execute the plan Lookback Programming and software engineering Plan Requirement Analysis Design Implementation Testing Deployment Maintenance Iteration… SIT Internal Outline Module introduction Python Introduction Some concept of software engineering Python basic I Some concept of programming SIT Internal Variables and Assignment Statements SIT Internal Module Road Map Variables & Selection & Advanced Functional Higher Types & Data Recursion order Operators Iteration Structures abstraction function Real World Problems / Project Management Problems/ Innovation / Self-study SIT Internal Variables and Assignment Statements Variables = expression print('Hello, World! ') print("Hello, World! ") print('He said, "Python is awesome! "') print("It's a beautiful day! ") print('Taylor') firstName = 'Taylor' print(firstName) SIT Internal Variables and Assignment Statements Variables = expression A variable is a reserved memory location used to store values SIT Internal Variables and Assignment Statements Variables = expression A name We can use the name in following expressions Variable references Values can be reset to new ones Assignment statement Variable references Assignment statements Reset a variable SIT Internal Variable Naming Rules Variables must start with a letter or an underscore _ Subsequent characters can be letters, numbers, or underscores Variable names are case-sensitive Keywords cannot be used as variable names: Examples of keywords: if, else, for, while, class, def, return, try, except, etc. Which one is valid? _myvar, Var1, 1var, -var, return, good SIT Internal Variable Naming Rules Variables must start with a letter or an underscore _ Subsequent characters can be letters, numbers, or underscores Variable names are case-sensitive Keywords cannot be used as variable names: Examples of keywords: if, else, for, while, class, def, return, try, except, etc. Which one is valid? _myvar, Var1, 1var, -var, return, good SIT Internal Variable Naming Rules Use lowercase letters and underscores for variable names (snake_case): Example: my_variable, user_name, total_sum Constants (values that do not change) are usually written in all uppercase with underscores (UPPERCASE_WITH_UNDERSCORES): Example: PI = 3.14159, MAX_LIMIT = 100 Use meaningful variable names: Choose names that clearly describe the variable’s purpose, e.g., total_sum instead of ts. Avoid single-character variable names, unless in loops (e.g., i, j, k): SIT Internal Variable Naming Rules Follow the PEP 8 style guide: PEP 8 is the Python community's style guide, recommending consistent and readable naming practices. https://peps.python.org/pep-0008/ Python 3 supports Unicode characters, allowing variable names in non-Latin scripts like Chinese or Japanese, but it's best to maintain consistency and readability. SIT Internal Variables and Assignment Statements Variables = expression A variable is a reserved memory location used to store values How can I know the memory address of a variable? id() SIT Internal Multiple Assignment SIT Internal Multiple Assignment Practice How can we swap the values of two variables? a = 10, b = 20 a = 20, b = 10 SIT Internal Multiple Assignment Practice How can we swap the values of two variables? a = 10, b = 20 a = 20, b = 10 Elegant SIT Internal Variable types Variables Name Id Type How to know a variable's type? type() SIT Internal Variable types Type Samples int 8,12,1024 float 2.3, 3.1415926 bool True, False str 'Hello, World! ', '3.1415926' None None List Tuple Set Dictionary byte SIT Internal Type Casting and Dynamic Typing Type casting Dynamic Typing SIT Internal Type Casting Numbers to string String to numbers Numeric precision adjustment SIT Internal Type Casting Numbers to string String to numbers Numeric precision adjustment SIT Internal Type Casting Numbers to string String to numbers Why 70, not 71? Numeric precision adjustment Int and float Why -100, not -101? Round vs Truncation SIT Internal Type Casting SIT Internal Arithmetic Operators Operator Name Example + Addition - Subtraction * Multiplication / Division 10/0 ZeroDivisionError 4/2 integer or float? // Floor Division 13.9//2 = 6.0 % Modulus 11%3 = 2; 11.0%3.0 = 2.0 ** Exponent 2**4 = 16 += Augmented Addition Operator a+=1 equals to a = a+1 -= *= … SIT Internal Review Variables Id Name Type Type Casting Arithmetic operators SIT Internal Outline Module introduction Python Introduction Some concept of software engineering Python basic 1 Some concept of programming SIT Internal Command Line and IDE Command line - Python Shell Interactive programming Python shell Show the results immediately after the statements Cons: Difficult to manage in large projects Difficult to refactor SIT Internal Command Line and IDE Integrated Development Environments A programming environment A code editor A compiler A debugger A graphical user interface (GUI) builder SIT Internal Command Line and IDE https://www.w3schools.com/python/ https://colab.research.google.com/ We will use this one in class Save your results easily Use the auto-complete function properly SIT Internal Jupyter Notebook https://jupyter.org/ https://jupyter.org/try-jupyter/lab/ SIT Internal What is programming? Computer programming or coding is the composition of sequences of instructions, called programs, that computers can follow to perform tasks. High Level Language ? 0s and 1s https://en.wikipedia.org/wiki/Computer_programming SIT Internal From high level code to 0 and 1 (Compiled Language) High Level Programming Languages Compiler Assembly Language Assembler Machine Code SIT Internal Bytecode https://godbolt.org/ Further Reading Interpreted Languages Compiled Languages SIT Internal Bytecode SIT Internal CPython CPython is an interpreter responsible for reading, parsing, and executing Python code. Translate high level code to bytecode Execute the bytecode SIT Internal Compiler and Interpreter Compiler Translates the entire source code of a program into machine code before execution. Generates an executable file that can be run independently of the source code. Usually faster execution after compilation because the translation is done once. Error detection happens at compile-time, making debugging easier before running the program. Examples: GCC (GNU Compiler Collection), MSVC (Microsoft Visual C++), Clang. Interpreter Translates and executes the source code line by line at runtime. Does not produce an independent executable file; the source code must be present during execution. Slower execution because translation happens every time the program is run. Immediate execution allows for easier testing and debugging of small code snippets. Examples: Python interpreter, Ruby interpreter, JavaScript engines (like V8). SIT Internal Review Command Line and IDE High Level Code Bytecode / Assembly Language Machine Code SIT Internal Assignment Assignment Install the Python 3 Try pip install Conda / Miniconda Install Conda Create an environment Install the IDE that you like to use (i.e., Pycharm , Visual Studio Code) Create a simple program Try run, debug, breakpoint, check the variant value First lab from week 2 SIT Internal Good Programming Practices Martin R C. Clean code: a handbook of agile software craftsmanship[M]. Pearson Education, 2009.