Docsity

Python notes for students, Summaries of Computer Science

Toggle sidebar
bg1
CMP 201 Note
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Python Installation
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start bar for Python or run
the following on the Command Line (cmd.exe):
C:\Users\Your Name>python –version
Execute Python Syntax
As we learned in the previous page, Python syntax can be executed by writing directly in the
Command Line:
>>> print("Hello, World!")
Hello, World!
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Python notes for students and more Summaries Computer Science in PDF only on Docsity!

CMP 201 Note

What is Python?

Python is a popular programming language. It was created by Guido van Rossum, and released in

It is used for:  web development (server-side),  software development,  mathematics,  system scripting.

What can Python do?

 Python can be used on a server to create web applications.  Python can be used alongside software to create workflows.  Python can connect to database systems. It can also read and modify files.  Python can be used to handle big data and perform complex mathematics.  Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).  Python has a simple syntax similar to the English language.  Python has syntax that allows developers to write programs with fewer lines than some other programming languages.  Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.  Python can be treated in a procedural way, an object-oriented way or a functional way.

Python Installation

Many PCs and Macs will have python already installed. To check if you have python installed on a Windows PC, search in the start bar for Python or run the following on the Command Line (cmd.exe): C:\Users\ Your Name >python –version Execute Python Syntax As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line: >>> print("Hello, World!") Hello, World!

Python Indentation

Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code. Example if 5 > 2: print("Five is greater than two!")

Python Variables

In Python, variables are created when you assign a value to it:

Example

Variables in Python x = 5 y = "Hello, World!"

Python Comments

Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code.

Creating a Comment

Comments starts with a #, and Python will ignore them: Example #This is a comment print("Hello, World!")

Multiline Comments

Python does not really have a syntax for multiline comments.

Single or Double Quotes?

String variables can be declared either by using single or double quotes: Example x = "John"

is the same as

x = 'John'

Case-Sensitive

Variable names are case-sensitive. Example This will create two variables: a = 4 A = "Sally" #A will not overwrite a

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:  A variable name must start with a letter or the underscore character  A variable name cannot start with a number  A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )  Variable names are case-sensitive (age, Age and AGE are three different variables)  A variable name cannot be any of the Python keywords.

Built-in Data Types

In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset

Boolean Type: bool Binary Types: bytes, bytearray, memoryview None Type: NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:

Example

Print the data type of the variable x: x = 5 print(type(x))

Python Operators

Operators are used to perform operations on variables and values. In the example below, we use the + operator to add together two values:

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example

  • Addition x + y
  • Subtraction x - y
  • Multiplication x * y / Division x / y

**= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3

Python Comparison Operators

Comparison operators are used to compare two values: Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y

>= Greater than or equal to x >= y <= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements: Operator Description Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object: Operator Description Example in Returns True if a sequence with the specified value is present in the object x in y

| (^) Bitwise OR == != > >= < <= is is not in not in Comparisons, identity, and membership operators not (^) Logical NOT and (^) AND or (^) OR

Python Collections (Arrays)

There are four collection data types in the Python programming language:  List is a collection which is ordered and changeable. Allows duplicate members.  Tuple is a collection which is ordered and unchangeable. Allows duplicate members.  Set is a collection which is unordered, unchangeable, and unindexed. No duplicate members.  Dictionary is a collection which is ordered* and changeable. No duplicate members.

Python List

Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. Lists are created using square brackets:

Example

Create a List: thislist = ["apple", "banana", "cherry"] print(thislist)

List Items

List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc.

Tuple

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.

Example

Create a Tuple: thistuple = ("apple", "banana", "cherry") print(thistuple)

Set

Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection which is unordered , unchangeable* , and unindexed.

Example

Create a Set: thisset = {"apple", "banana", "cherry"} print(thisset)

Python Dictionaries

Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

Example

Create and print a dictionary:

i = 1 while i < 6 : print(i) i += 1

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example

Print each fruit in a fruit list: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x)

The range() Function

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Example

Using the range() function: for x in range(6): print(x)

Python Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

Example

def my_function(): print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

def my_function(): print("Hello from a function") my_function() Example

function with two arguments

def add_numbers(num1, num2): sum = num1 + num print("Sum: ",sum)

function call with two values

add_numbers(5, 4)

Output: Sum: 9

Python Arrays

Arrays are used to store multiple values in one single variable:

Example

Create an array containing car names: cars = ["Ford", "Volvo", "BMW"]

Access the Elements of an Array

You refer to an array element by referring to the index number. Example Get the value of the first array items: x = cars[0]

Python Classes and Objects

class Person: def init(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object. Let us create a method in the Person class:

Example

Insert a function that prints a greeting, and execute it on the p1 object: class Person: def init(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36 ) p1.myfunc()