Python Overview

¡Supera tus tareas y exámenes ahora con Quizwiz!

%Y

year, full version

%p

AM/PM

Assignment operators

Assignment operators are used to assign values to variables. They are +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=, and =

%j

Day number of year (001-365)

%d

Day of month (1-31) would be 31

Floor division

It takes the floor upon dividing. To do it, type x // y

Adding items in a dictionary

dict = dict(apple = "green", banana = "yellow", cherry = "red") dict["damson"] = "purple" print(dict)

Constructing a dictionary

dict = dict(apple = "green", banana = "yellow", cherry = "red") print(dict)

Length of a dictionary

dict = dict(apple = "green", banana = "yellow", cherry = "red") print(len(dict))

Changing definitions in a dictionary

dict = { "apple": "green" "banana": "yellow" "cherry": "red" } dict["apple"] = "red" print(dict)

Examples of a dictionary

dict = { "apple": "green" "banana": "yellow" "cherry": "red" } print(dict)

Example of file handling

f = open("demofile.txt") is the same as f = open("demofile.txt", "rt")

%z

UTC offset

%W

Week number of year, Monday as the first day of week, 00-53

%U

Week number of year, Sunday as the first day of week, 00-53

%w

Weekday as a number (6 is Sunday)

%A

Weekday, full version

%a

Weekday, short

Binary vs. Text

When opening a file, you need to specify if it should be read as binary or as text. "t" = text. Default value. Text mode. "b" = binary. Binary mode. This is used for things like images.

%y

Year, short version, without century

Four data types in Python

List, tuple, dictionary, set.

Example of lists

1. Remember that if you use words in Python, you have to use quotation marks. list = ["apple", "banana", "cherry"] print(list) 2. To change lists, list = ["apple", "banana", "cherry"] list[1] = "blackcurrant" print(list) 3. To convert sets into lists, list = list(("apple", "banana", "cherry")) print(list)

Dates in Python

1. A date in Python is not a data type of it's own, but there is a module called datetime to work with dates as date objects. 2. The datetime module has many methods to return information about the date object. 3. To create a date, we can use the datetime() class (constructor) of the datetime module. 4. The datetime() class requires three parameters to create a date: year, month, day. 5. The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and have a default value of 0 or None. 6. The datetime() object has a method for formatting date objects into readable strings. The method is called strftime(), and takes one parameter, format, to specify the format of the returned string.

Properties of dictionaries

1. A dictionary is a collection that is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. 2. You can use the dict() constructor to make a dictionary. 3. You can add items to a dictionary by using an index key and adding a definition to it. 4. You can deleted items from a dictionary. You can also use len() to return the length of a dictionary.

Properties of lists

1. A list is a collection of data that is ordered and changeable. In Python, lists are written with square brackets. 2. You can convert sets to lists. To add an item, use the append() function. To remove an item, use the remove() function. To find the length of a list, use the len() function.

Properties of sets

1. A set is a collection of data that is unordered and unindexed. 2. You can use the set() constructor to make a set. You can use the add object method to add an item, and the remove object method to remove an item.

Properties of tuples

1. A tuple is a collection of data that is ordered and unchangeable. In Python, tuples are written with round brackets. 2. They work similar to lists, but you can't change values. You also can't add or remove values. This is referred to as being immutable. 3. You can use the tuple() constructor to create a tuple. 4. Tuples are comparable and hashable.

Rules with variables

1. A variable can change it's type anywhere in the file. 2. A variable must start with a letter or an underscore character. It cannot start with a number. 3. It can only contain alpha-numeric characters and underscores. 4. They are case-sensitive (age and AGE would be different). 5. If you try to combine a number or integer and a string, Python will give you an error.

Example of using modules

1. Say we had a module file for the Fibonacci sequence, fibo.py that calculates the nth term of the Fibonacci sequence. import fibo print(fibo.fib(n)) 2. If you want the module name using global names - fibo.__name__ 'fibo' 3. Assigning a module a local name - fib = fibo.fib

Classes

1. Almost everything in Python is an object, with its properties and methods. 2. A class is like an object constructor, or a blueprint for creating objects. 3. Some of the examples given are classes in their simplest forms, and are not really useful. To understand the meaning of classes, we have to understand the built-in __init__() function. 4. All classes have a function called __init__(), which is always executed when the class is being initiated. 5. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created. 6. The __init__() function is called automatically every time the class is being used to create a new object.

Arrays

1. Arrays are used to store multiple values in one single variable. An array is a special variable which can hold more than one item at a time. When you have a list of items, storing them in single variables could become tedious if instead of having 3 elements, you had three hundred. It can hold many values, and you can access them using an index number. Python doesn't have built in support for arrays, but you can use lists. 2. Basically they are the same exact thing as lists in Python, this is just to educate you about arrays.

Reading files in Python

1. Assume you have a file. To open the file, use the built in open() function. The open() function returns a file object, which has a read() method for reading the content of the file.

Reading only parts of the file

1. By default the read() method returns the whole text, but you can also specify how many characters you want, which kind of works like lists. 2. To return the first five characters of a list, do f = open("demofile.txt", "r") print(f.read(5))

Downloading a package

1. Downloading a package is easy. 2. Open the command line interface and tell PIP to download the package you want. 3. Navigate your command line to the location of Python's script discovery, and type the following: C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install camelcase

Python File Open

1. File handling is an important part of any web application. 2. Python has several functions for creating, reading, updating, and deleting files. 3. The key function for working with files in Python is the open() function. 4. The open function takes two parameters: filename and mode.

Example of casting in Python

1. For integers, x = int(1) will be 1 y = int(2.8) will be 2 z = int("3") will be 3 2. For floats, x = float(1) will be 1.0 y = float(2.8) will be 2.8 z = float(3) will be 3.0 w = float("4.2") will be 4.2 3. For strings, x = str("x1") will be 'x1' y = str(2) will be '2' z = str(3.0) will be '3.0'

Examples of how strings are used

1. Get the character at position 1: a = "hello" print(a[1]) 2. Substring. Get the characters from the position 2 to position 5: b = "world" print(b[2:5]) 3. The strip() method removes any whitespace from the beginning to the end: a = " Hello, World! " print(a.strip()) # returns "Hello, World!" 4. The len() method returns the length of a string: a = "Hello, World!" print(len(a)) 5. The lower() method returns the string in lower case: a = "Hello, World!" print(a.lower()) 6. The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) 7. The replace() method replaces a string with another string: a = "Hello, World!" print(a.replace("H", "J")) 8. The split() method splits the string into substrings if it finds instances of the separator: a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']

Writing comments

1. If it is a one-line comment, you can just use a hashtag. 2. If it is a block of text, you need to use three quotation marks on each side.

Importing part of a module

1. If we only wanted to import the person1 dictionary from our module. from mymodule import person1 print (person1["age"])

Modules

1. If you quit the Python terminal and enter again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a longer program, you need to use a text editor to prepare the input for the interpreter and running it with that file as input. This is called creating a script. 2. As your program gets longer, you may want to split it into several files for easier maintenance. You'll want to use a function instead of copying it's definition into each program. 3. Python has a way to put definitions in a file and use them in a script, called a module. A module is a file containing Python definitions and statements. The file name is the module with .py attached. 4. When you import the module into your program, it won't automatically know what the function is, you have to clarify that too. 5. The modules name (as a string) is available as the value of the global variable __name__ 6. If you intend to use a function often, you can assign it a local name. 7. You can create a Python module using a text editor, and by naming the extension .py 8. Another way to think of a module is that it is a code library. It is a file containing a set of functions you want to include in your application. 9. When using a function from a module, use the syntax: module_name.function_name. 10. You can choose to only use parts of a module, by using the from keyword.

Lambda

1. In Python, the keyword lambda is used to create anonymous functions, functions without a name. They are good for constructing adaptable functions, and thus good for event handling. 2. There's an example of a basic lambda function, and a function you use when you generate anonymous functions at run-time.

Parameters

1. Information can be passed to functions as parameters. 2. Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

Objects

1. Objects can also contain methods. Methods in objects are functions that belong to the object. 2. You can modify properties on objects. 3. You can delete properties on objects. 4. You can delete objects.

PIP

1. PIP is a package manager for Python packages, or modules. 2. A package contains all the files you need for a module. Modules are Python code libraries you can include in your project. 3. Any version of Python past 3.4 has PIP installed.

Command-line string input

1. Python allows for command line input. 2. That means we are allowed to ask the user for input. 3. Create a file using this, save the file, and load it through the command line.

Python operators

1. Python divides it's operators into several types: arithmetic, assignment, comparison, logical, identity, membership, bitwise.

String literals

1. String literals in Python are surrounded by either single quotation marks or double quotation marks ('hello' is the same as "hello") 2. Strings in Python are arrays of bytes representing unicode characters. Python doesn't have a character data type, a single character is simply a string of length one.

Break statements

1. The function is obvious. A break statement stops the execution of a loop. Sometimes they are useful. In the event that you need an infinite loop, don't use it without a break statement. 2. A break statement can only be nested in a for or while loop, but not nested in a function or class definition within that loop. 3. It terminates the nearest closing loop, skipping the optional else if the loop has one. 4. If a for loop is terminated by a break, the loop control target keeps it's current value. 5. When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

Numeric types in Python

1. There are three numeric types in Python: int, float, and complex. 2. To verify the type of any object in Python, use the type() function. 3. The definition of a float is a number (positive or negative) containing one or more decimals. 4. Floats can also be scientific numbers with an "e" to indicate the power of 10. 5. Complex numbers are written with a j to indicate the imaginary part.

Infinite loops

1. These are what they sound like. They never quit and on older computers, can cause the system to become unresponsive. 2. Remember when Spock asked the computer to compute the last digit of pi, causing the computer to shut down. That's an example of an infinite loop. It can cause older computers to malfunction. 3. There are some practical uses to infinite loops. For example, OS systems use infinite loops to check data. Video games use infinite loops, such as chess. The program will look for possible moves to do. 4. Don't use infinite loops without a break. There will be no way to quit without quitting the program, which could deleted unsaved progress.

While loop

1. They are used for repeating sections of code. 2. Unlike for loops, they don't run a certain number of times, but until a defined condition is no longer met. 3. If the condition is false, the loop part will not be executed at all. 4. While loops are used whenever the input of a user is being tested or required. Even though they are rarely used because of for loops, the uses are infinite and can be combined with conditionals for efficient results.

Casting

1. This is done when you want to specify a type on to a variable. 2. Casting in Python is done with three constructor functions: int(), float(), and str().

Syntax in files

1. To open a file for reading it is enough to specify the name of the file. This is the default mode, if you put nothing else, this is what you get.

Running a Python file

1. Type python to signify that it is a Python file. 2. Type the file name with .py attached.

List functions

1. clear() - clears the elements in the list 2. copy() - returns a copy of the list 3. count() - returns the number of elements in the list with that specific value. 4. extend() - adds the elements of a list to the end of the list. 5. index() - returns the index of the first element with the specified value. 6. insert() - adds an element at the specified position. 7. pop() - removes an element at the specified position. 8. remove() - removes the item with the specified value. 9. reverse() - reverses the order of the list 10. sort() - sorts the list.

Four different modes for opening a file

1. r - "Read" - This is the default value. It opens a file for reading, prints an error if the file does not exist. 2. a - "Append" - Opens a file for appending, creates the file if it does not exist. 3. w - "Write" - Opens a file for writing, creates the file if it does not exist. 4. x - "Create" - creates the specified file, returns an error if it does not exist.

%%

A % character

%I

Hour 00-12

%H

Hour 00-23

Default parameter values

If you call a function without a parameter, it uses the default parameter value. def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil")

Renaming a module

If you had the module mymodule and you wanted to rename it mx: import mymodule as mx a = mx.person1["age"] print(a)

User input

In Python 3.x, use input() instead of raw_input()

%x

Local version of date

%c

Local version of date and time

%X

Local version of time

%f

Microsecond (000000-999999)

%M

Minute (00-59)

%m

Month as a number 01-12

%B

Month name, full version

%b

Month name, short version

%S

Second (00-59)

Example of reading files in Python

Suppose you have a file called "demofile.txt" f = open("demofile.txt", "r") print(f.read())

The self parameter

The self parameter is a reference to the class itself, and is used to access variables that belongs to the class. It does not have to be named

Logical operators

They are used to combine conditional statements. and (x < 5 and x<10), or (x<5 or x<4), not (it reverses the result, returns false if the result is true, not(x<5 and x<10).

Identity operators

They are used to compare objects, not if they are equal, but if they are the same object. is (x is y) and is not (x is not y).

Comparison operators

They are used to compare values. ==, !=, >, <, >=, <=

Membership operators

They are used to test if a sequence is in an object. in (x in y) or not in (x not in y).

%Z

Timezone

Write a program that takes a list of numbers and only prints the first and last numbers.

a = [] def list_ends(a): return a[0], a[len(a)-1]

Example of a function with parameters

def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus")

Another example of a lambda function

def myfunc(n): return lambda i: i*n doubler = myfunc(2) tripler = myfunc(3) val = 11 print("Doubled: " + str(doubler(val)) + ". Tripled: " + str(tripler(val)))

Removing items in a dictionary

dict = dict(apple = "green", banana = "yellow", cherry = "red") del(dict["banana"]) print(dict)

Example of a while loop

b = 5 while (b > 0): print(b) b -= 1 This will print 5, 4, 3, 2, 1

Example: create a class called Class, with a property named x.

class MyClass: x = 5

Example: (self parameter) Use the words mysillyobject and abc instead of self.

class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc()

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()

Example: create a class named Person, use the __init__() function to assign values for name and age:

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

Example of an infinite loop

i = 5 while (i > 0): print(i) It will print 5 infinitely.

Example of installing a package

import camelcase c = camelcase.CamelCase() txt = "hello world" print(c.hump(txt))

Example of using the strftime() method for formatting date objects into readable strings

import datetime x = datetime.datetime(2018, 6, 1) print(x.strftime("%B"))

Example of using the time module to create a date

import datetime x = datetime.datetime(2020, 5, 17) print(x)

Example of using the time module to return the weekday

import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A"))

Example of a guessing game in Python

import random number = rand.int(1,9) guess = 0 count = 0 while guess != number and guess != "exit": guess = input("What is your number?") if guess == "exit": break guess = int(guess) count += 1 if guess < number: print("Too low!") elif guess > number: print("Too high!") else: print("You got it!") print("It only took you"+" "+count+" "+"tries"

Example of a lambda function

myfunc = lambda i: i*2 print(myfunc(2))

Inefficient ways to do while loops

n = input("Please enter 'hello':") while n.strip() != 'hello': n = input("Please enter 'hello':")

Example: create an object named p1, and print the value of x.

p1 = MyClass() print(p1.x)

Example: (Modifying object properties) Set the age of p1 to 40:

p1.age = 40

Efficient ways to do while loops

while True: n = input("Please enter 'hello':") if n.strip() == 'hello': break

Example of a break statement

while True: usr_command = input("Enter your command:") if usr_command == "quit" break else: print("You typed"+usr_command)


Conjuntos de estudio relacionados

Astronomy Chapter 10: Other Planetary Systems

View Set

AP Lang Argument: AP Practice Q's

View Set

Thermal Energy Drives Plate Tectonics

View Set

Marking Period 4, Chem Quarterly

View Set

Factor markets and labor market inefficiencies

View Set

American Politics Chapter 14 Pre and Post Test

View Set