Summary

These lecture slides provide an introduction to Python, covering basic concepts such as variables, data types, operators, strings and formatting. It includes code examples and exercises.

Full Transcript

Week 3 – Introduction to Python Learning Objectives: Write your first Python program Learn what happens when you run a program with an error Learn how to declare a variable and inspect its value Learn how to write comment What is Python? Python is a general purpose p...

Week 3 – Introduction to Python Learning Objectives: Write your first Python program Learn what happens when you run a program with an error Learn how to declare a variable and inspect its value Learn how to write comment What is Python? Python is a general purpose programming language that is often applied in scripting roles. Python is a programming language as well as scripting language Python is an interpreted, object-oriented, high-level programming language. Programming vs. Scripting Language Program Scripting A program is executed (i.e. A script is interpreted. the source is first compiled A “script” is code written in and the result of the a scripting language. A compilation is expected) scripting language is A “program” in general, is nothing but a type of a sequence of instructions programming language in written so that a computer which we can write code to can perform certain task. control another software application. History Invented in the Netherlands, early 90s by Guido van Rossum Python was conceived in the late 1980s and its implementation was started in December 1989 Guido Van Rossum is a fan of “Monty Python’s Flying Circus”, this is famous TV show in Netherlands Named after Monty Python Open sourced from the beginning Why Use Python? It is known for its simplicity, readability, and ease of use Can create the following Systems programming Graphical User Interface Programming Database Programming Component Integration Gaming, Images, XML, Robotics Web Applications For Data Science and Data Visualization Machine Learning Script for Vulnerability Testing 5 of the many reasons to use Python 1. Easy to Learn and Use 2. Versatile 3. Large and Active Community 4. Cross-Platform Compatibility 5. Open-source Who Uses Python Today… Python is being applied in real revenue-generating products by real companies. For instance: Google makes extensive use of Python in its web search system, and employs Python’s creator. Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hard testing. ESRI uses Python as end-user customization tool for its popular GIS mapping products. The YouTube video sharing is largely written in Python. Requirements Python 3 Interpreter or above IDE Options Offline Pycharm Anacoda/Jupyter Notebook Online: onlinegdb.com colab.google replit.com online-python.com/online_python_compiler Installing Python Download the latest version of python from https://www.python.org/downloads/ Installing Python Once you start the installation process, you will see the following pop-up: Installing Python Once this process is completed, open Python from the start menu and click on Python version that you have installed to launch python command line. It is prompt with >>> where you write your single line command Using PyCharm Download the installer (.exe) preferably the community edition. Run the installer and follow the wizard steps. Mind the following options in the installation wizard 64-bit launcher: Adds a launching icon to the Desktop. Open Folder as Project: Adds an option to the folder context menu that will allow opening the selected directory as a PyCharm project..py: Establishes an association with Python files to open them in PyCharm. Add launchers dir to the PATH: Allows running this PyCharm instance from the Console without specifying the path to it. To run PyCharm, find it in the Windows Start menu or use the desktop shortcut. You can also run the launcher batch script or executable in the installation directory under bin. Create a Python project When you open PyCharm for the first time, you are presented with the Welcome Screen. In PyCharm, the next step is to create Project. The project is your central view for running code, debugging code, Python console, system terminal, tests, coverage, profiling, version control, databases, frontends... Etc. If you’ve already worked on a project, the welcome screen will look a bit different. It will have a list of your recent projects in the center but the options will stay the same. Create a Python project Although you can create projects of various types in PyCharm, in this tutorial let's create a simple Pure Python project. This template will create an empty project. Choose the project location. Click the Browse button in the Location field and specify the directory for your project. Python best practice is to create a dedicated environment for each project. In most cases, the default Project venv will do the job, and you won't need to configure anything. Still, you can switch to Custom environment to be able to use an existing environment, select other environment types, specify the environment location, and modify other options. Click Create when you are ready. Create a Python file In the Project tool window, select the project root (typically, it is the root node in the project tree), right-click it, and select File | New.... Create a Python file Select the option Python File from the context menu, and then type the new filename. Create a Python file PyCharm creates a new Python file and opens it for editing. Running Python (Using Command line) Once you’re inside the Python interpreter, type in commands such as >>>print (“Hello World”) After this line, press Enter and this command will print out Hello World Running Python (Using PyCharm) Use either of the following ways to run your code: Right-click the editor and select Run from the context menu. Press Ctrl+Shift+F10 Since this Python script contains a main function, you can click in the gutter. You'll see the popup menu of the available commands. Choose Run Python Code Execution Python’s traditional runtime execution model: source code you type is translated to byte code, which is then run by the Python Virtual Machine. Your code is automatically compiled, but then it is interpreted. Source code of python extension is.py Byte code extension is.pyc (compiled python code) Indentation Matters Unlike many other languages, indentation is crucial in Python. It defines code blocks instead of curly braces. Consistent indentation (usually 4 spaces) is essential for proper program flow and to avoid errors. Comments in Python Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. Also, Comments enhance the readability of the code and help the programmers to understand the code very carefully. # Single line ‘’’ Multiline ‘’’ Keywords in Python and False nonlocal as finally not Keywords in assert for or Python are break from pass reserved words class global raise that can not be continue if return used as a def import True variable name, del is try function name, or elif in while any other else lambda with identifier. except None yield print Command print : Produces text output on the console. Syntax: print("Message“) print(Expression) Prints the given text message or expression value on the console, and moves the cursor down to the next line. print(Item1, Item2,..., ItemN) Prints several messages and/or expressions on the same line. Elements separated by commas print with a space between them A comma at the end of the statement will not print a newline character Examples: print("Hello, world!“) age = 45 print("You have", 65 - age, "years until retirement“) Expressions expression: A data value or set of precedence: Order in which operations are operations to compute a value. computed. Examples: 1+4*3 / % ** have a higher precedence than + - 42 Arithmetic operators we will use: 1 + 3 * 4 is 13 + addition - subtraction/negation Parentheses can be used to force a certain * multiplication order of evaluation. / division // floor division or integer division (1 + 3) * 4 is 16 % modulus, a.k.a. remainder ** exponentiation Real Numbers or Floating Point Python can also manipulate real numbers. Examples: 6.022 -15.9997 42.0 2.143e17 The operators + - * / % ** ( ) all work for real numbers. The / produces an exact answer: 15.0 / 2.0 is 7.5 The same rules of precedence also apply to real numbers: Evaluate ( ) before * / % before + - When integers and reals are mixed, the result is a real number. Example: 1 / 2.0 is 0.5 The conversion occurs on a per-operator basis. What will be output of the following print(3+12) print(1+2*3**2-4) print(12-3) print(5/2) print(9+5%2-15+12) print(5//2) print(4-3*2%3) print(5//2.0) print(12/3) print(12.0/3.0) print(11.0/3.0) Answers print(3+12) = 15 print(11.0/3.0) = print(12-3) = 9 1.666667 print(9+5%2-15+12) = print(1+2*3**2-4) = 15 7 print(5/2) = 2.5 print(4-3*2%3) = 4 print(5//2) = 2 print(12/3) = 4.0 print(5//2.0) = 2.0 print(12.0/3.0) = 4.0 Math Commands Python has useful commands (or called functions) for performing calculations. To use many of these commands, you must write the following at the top of your Python program: from math import * or import math from math import * vs import math from math import * This imports all the names from the math module directly into your current namespace. You can then use functions and constants from math without the math. prefix. While this may seem convenient, it's generally discouraged. import math Use import math for clear and safe access to functions and constants from the math module. It promotes explicit use of the math module, making code more readable and maintainable. It helps prevent naming conflicts by keeping the math module separate from your local variables. Relational expressions Relational expressions in Python are used for comparisons between values. They evaluate to a boolean value (True or False) based on the condition being compared. Relational Operators: Python provides several relational operators to compare values: == Equal to != Not equal to < Less than > Greater than = Greater than or equal to Examples print(2>3) False print(4!=3) True print(3>1) True print(5==4) False print(10