Unit 1 Introduction to Python PDF

Summary

This document provides a basic introduction to Python programming. It covers fundamental concepts like instructions, variables, and input/output operations in a clear and concise manner. The text also discusses common errors and debugging practices.

Full Transcript

1.1 Programming A computer program consists of instructions executing one at a time. Basic instructions types: Input: A program receives data from a file, keyboard, touchscreen, network, etc. Process: A program performs computations on that data, such as adding two values like x + y. Output: A prog...

1.1 Programming A computer program consists of instructions executing one at a time. Basic instructions types: Input: A program receives data from a file, keyboard, touchscreen, network, etc. Process: A program performs computations on that data, such as adding two values like x + y. Output: A program puts that data somewhere, such as a file, screen, or network. Computational thinking - creating a sequence of instructions to solve a problem Algorithm - a sequence of instructions that solves a problem Variables - used to refer to values saved in memory by the interpreter Programs use variables to refer to data, like x, y, and z 1.2 Programming using Python Python interpreter - a computer program that executes code written in the Python programming language Interactive interpreter - is a program that allows the user to execute one line of code at a time - displays a prompt (“>>>”) that indicates the interpreter is ready to accept code Code - word for the textual representation of a program Line - a row of text Statement - a program instruction - a program mostly consists of a series of statements, each statement appearing on its own line Expressions - code that return a value when evaluated - Ex: the code wage * hours * weeks is an expression that computes a number A new variable is created by performing an assignment using the = symbol - salary = wage * hours, the new variable is ‘salary’ Print() - displays variables or expression values Comments - indicated with a “#” (used to explain portions of code to a human reader) - many code editors color certain words to assist human readers 1.3 Basic Input and Output Text is output from a Python program using the built-in function print(). Ex: print(‘hello world!’) → hello world! String - text enclosed in quotes - may have letters, numbers, spaces, or symbols like @ or # Keeping output on the same line Each use of print() outputs on a new line. Adding end=’ ‘ keeps the output of the next print on the same line, separated by a single space character. Any character, or multiple characters, can be used instead of a space character. Moving output to the next line Newline character “\n”- can move output to the next line Escape sequence - a string that has a special meaning - “\t” to insert tab, “\\” to print an actual backslash character Whitespace - any space, tab, or newline Basic input The input() function is used to read input from a user - program will wait until user has entered text and pushed the return key Converting input types The string ‘123’ is different from the integer 123. ‘123’ is a sequence of characters and 123 represents the integer value one-hundred twenty-three Type - determines how a value can behave - Strings and integers are examples of a type 1. input() reads an input value ‘8’ from the keyboard as a new string 2. int() converts ‘8’ from a string to an integer type, and the integer is stored as the variable wage 3. The integer value of wage can then be used to perform a calculation, like adding 10 to create a new variable new_wage 1.4 Errors Syntax errors - a mistake in coding that violates a programming language’s rules on how symbols can be combined to create a program. Note that syntax errors are found before the program is run by the interpreter. In the example below, none of the prints prior to the error is in the output. GOOD CODING PRACTICE To avoid continually encountering error messages, a good practice is to execute the code frequently Runtime errors - runtime error, in which a program's syntax is correct but the program attempts an impossible operation, such as: - Dividing by zero - Multiplying strings together - ‘Hello’*’ABC’ Runtime errors halt the execution of the program. Abrupt and unintended termination of a program is often called a crash of the program. Runtime errors are categorized into types that describe the sort of error that has occurred: SyntaxError - Program contains invalid code that cannot be understood IndentationError - Lines of the program are not properly indented ValueError - An invalid value is used, which can occur if giving letters to in() NameError - Program tries to use a variable that does not exist TypeError - Operation uses incorrect types, which can occur if adding an integer to a string Logic errors Logic errors are a bug in a computer program that causes it to produce incorrect results or behave unexpectedly, but doesn't cause the program to crash. Such as: - Incorrect conditional statements - Misplaced operators - Using the wrong formula or algorithm - Assigning the wrong value to a variable 1.5 Development environment Integrated development environment (IDE) - web material embeds a Python interpreter so that the reader may experiment with Python programming. For normal development, a programmer installs Python as an application on a local computer. Code development is usually done with an integrated development environment. Popular IDEs online: IDLE is the official Python IDE that is distributed with the installation of Python from https://python.org. IDLE provides a basic environment for editing and running programs. PyDev (http://pydev.org) is a plugin for the popular Eclipse program. PyDev includes extra features such as code completion, spell checking, and debugging, which are useful tools while programming. For learning purposes, web-based tools like CodePad (http://www.codepad.co) or Repl (http://www.repl.it) are helpful. 1.6 Computers and programs (general) Switches, electronically controlled switches performing simple calculations. - 1 = positive voltage - 0 = zero voltage 0s and 1s are known as bits (binary digits). Processors and memory To support different calculations, circuits called processors process (or execute) a list of desired calculations, each called an instruction. Instructions were specified by configuring external switches. Memory - a circuit that can store 0s and 1s in each of a series of thousands of addressed locations. - Like, a series of addressed mailboxes that each can store an envelop (the 0s and 1s). - Instructions operate on data, which is stored in memory locations as 0s and 1s. A computer is basically a processor interacting with a memory. A processor computes data, whil the memory stores data and instructions Previously computer data can be read from memory Data can be output to the screen The arrangement is akin to a chef (processor) who executes instructions of a recipe (program), where each instruction modifies ingredients (data), with the recipe and ingredients kept on a nearby counter (memory). Instructions Sample processor instructions where X, Y, Z, and num are each an integer Add X, #num, Y - Adds data in memory location X to the number num, storing result in location Y Sub X, #num, Y - Subtracts num from data in location X, storing result in location Y Mul X, #num, Y - Multiplies data in location X by num, storing result in location Y Div X, #num, Y - Divides data in location X by num, storing result in location Y Jmp Z - Tells the processor that the next instruction to execute is in memory location Z Program, application, or app - programmer-created sequence of instructions (large list of instructions) Writing computer programs Machine instructions - instructions represented as 0s and 1s Executable program (executable) - a sequence of machine instructions Assemblers - automatically translates instructions for humans, such as "Mul 97, #9, 98", known as assembly language instructions, into machine instructions. Programmers created high-level languages to support programming using formulas or algorithms. To support high-level languages, programmers created compilers, which are programs that automatically translate high-level language programs into executable programs. 1.7 Computer tour The term computer has changed meaning over the years. Originally, it referred to a person that perform computations by hand, like an accountant (We need to hire a computer). 1940-50s it refers to large machines 1970-80s, it expanded to refer to smaller home/office computers known as personal computers or PCs and to portable/laptop computers 2000-10s it covered other computing devices such as pads, book readers, and smartphones. It also refers to computing devices embedded inside other electronic devices such as: Medical equipment, automobiles, aircraft,c onsumer elctronics, and military systems. In the early days of computing, physical equipment was prone to failures. As it stabilized and programs increased in size and functionality, the term “software” became popular to distinguish a computer’s programs from the “hardware” on which they ran. Computer components: Input/output devices: A screen (monitor) displays items to a user. A keyboard allows users to provide input to the computer. Other devices provide additional input and output means, such as: Touchscreens, microphones, speakers printers, and USB interfaces. I/O devices are commonly called peripherals. Storage: A disk (harddrive) stores files and other data, such as program files, songs and movies, or office documents. Disks are non-volatile, meaning they maintain their contents even when powered off. New flash storage devices store 0s and 1s in a non-volatile memory rather than disk, by tunneling electrons into special circuits on the memory’s chip, and remvoing them with a “flash” of electricity that draws the electrons backout Memory: RAM (random-access memory) temporarily holds data read from storage and is designed so any address can be accessed much faster than from a disk. RAM chips typically appear on a printed circuit board along with a processor chip. RAM is volatile, losing its contents when powered off. Memory size is typically listed in bits, or in bytes where a byte is 8 bits. (Common sizes involve megabytes (million bytes), gigabytes (billion bytes), or terabytes (trillion bytes). Processor: Runs the computer’s programs, reading and executing instructions from memory, performing operations, and reading and writing data from and to memory. When powered on, the processor stats executing the program. The first instruction is typically at memory location 0. That program is commonly called the BIOS (basic input/output system), which sets up the computer’s basic peripherals. The processor executes a program called an operating system (OS). Operating system allows a user to run other programs and interfaces with the many other peripherals. Processors are also called CPUs (central processing unit) or microprocessors. Speed is important so a processor may contain a small amount of RAM on its own chip, called cache memory, accessible in one clock tick rather than several, for maintaining a copy of the most-used instructions/data. Clock: A processor’s instructions execute at a rate governed by the processor’s clock, which ticks at a specific frequency. Processors have clocks that tick at rates such as 1 MHz (1 million ticks/second) for an inexpensive processor (found in microwave oven, washing machine, etc.) to 1 GHz (1 billion ticks/second) for costlier processors (found in mobile phones, desktop computers, etc.) Computers typically run multiple programs simultaneously (web browsers, office applications, photo editing programs). The operating system runs a little of program A, then a little of program B, etc. switching between programs thousands of times a second A disk is able to store Terabytes of data and may contain various programs such as ProgA, ProgB, Doc1, Doc2, and OS. The memory is able to store gigabytes of data. User runs ProgA. The disk spins and the head loads ProgA from the disk, storing the contents into memory. The OS runs ProgB. The disk spins and the head loads ProgB from the disk, storing the contents into memory. The OS lets ProgA run again. ProgA is already in memory so there is no need to read ProgA from the disk. Transistors - smaller switches created after computers were invented and occupied entire rooms. In 1958, they were integrated onto a single chip called an integrated circuit or IC. Engineers continued to find ways to make smaller transistors, leading to Moore’s law: The doubling of IC capacity roughly every 18 months. Which continues today. (Moore actually said every 2 years, and the actual trend has varied from 18 months. The key is that doubling occurs roughly every couple years, cursing enormous improvements over time.) New, powerful microprocessors appeared every few years, and by 2012, a single IC had several billion transistors containing multiple processors, each called a core. 1.8 Language history Scripting languages and Python Scripting languages - execute programs without the need for compilation. Script - a program whose instructions are executed by another program called an interpreter. Interpreted execution is slower because it requires multiple interpreter instructions to execute on script instruction. (But the advantages include avoiding the compilation step during programming and running the same script on different processors as long as each processor has an interpreter installed) Python timeline Python, is a scripting language created by Guido van Rossum in late 1980s. It’s derived from an existing language called ABC. The goals of Python included simplicity and readability, while providing as much power and flexibility as other scripting languages such as Peri. Python 1.0 was released in 1994 with support for some functional programming constructs derived from Lisp. Python 2.0 was released in 2000 and introduced automatic memory management (garbage collection: form of automatic memory management) and features from Haskell and other languages. Python 2.0 officially reached “end-of-life” (no more fixes or support) in 2020. Python 2.7 still remained popular for years, largely because third-party libraries supporting only Python 2.7/ Python 3.0 was released in 2008 to rectify various language design issues. Python 3.0 is not backward compatible, so Python 2.7 programs cannot run on Python 3.0 or later interpreters. However, Python 3.x versions have become widely used as new projects adopted the version. Python is an open-source language, meaning the user community participates in defining the language and creating new interpreters. 1.9 Why whitespace matters Whitespace and precise formatting Whitespace - any blank space or newline (for program output) The program computes a schedule and creates a unique meeting ID while outputting text formatted neatly for a calendar event The invitation of the right wasn’t careful with white space. “Join meeting” is buried Link hard to see “Phone” text is dangling at line’s end Didn’t end with newline Looks unprofessional Programming is all about precision Programs must be created precisely to run correctly. Ex: - = and == have different meanings - Using i where j was intended yields hard-to-find bugs. - Not considering that n could be 0 in sum/n can cause program to fail entirely in rar but not insignificant cases. - Counting from i being 0 to i

Use Quizgecko on...
Browser
Browser