0% found this document useful (0 votes)
3 views6 pages

Python Lesson1

This document serves as an introductory lesson to Python programming, covering fundamental concepts such as identifiers, keywords, operators, literals, data types, and naming conventions. It emphasizes the importance of indentation and structure in Python code, as well as the characteristics of various data types including sequences, strings, tuples, lists, and dictionaries. Additionally, it discusses naming conventions and the use of special methods and attributes in Python.

Uploaded by

Hejun
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

Python Lesson1

This document serves as an introductory lesson to Python programming, covering fundamental concepts such as identifiers, keywords, operators, literals, data types, and naming conventions. It emphasizes the importance of indentation and structure in Python code, as well as the characteristics of various data types including sequences, strings, tuples, lists, and dictionaries. Additionally, it discusses naming conventions and the use of special methods and attributes in Python.

Uploaded by

Hejun
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python-Lesson1

August 22, 2024

0.1 Introduction to Python


• I am going to assume that you have done some programming before this class.
• The following cheat sheets are useful: [Link]
sheets/
[3]: print("Hello world") # This is the first program in most languages

Hello world

[92]: greeting = "Hello world!" # We first assign hello world to a string variable␣
↪and print it

print(greeting)

Hello world!

0.1.1 Python programs


• A Python progam is a sequence of logical lines.
– Logical line: one or more physical lines.
– Physical line: may end with a comment. (#)
• Hash sign # starts a comment.
• In most cases, logical line = physical line.
• If the physical line is too long, we can type a backslash and the logical line continues on the
next line.
• Python is very particular about lines and indentation (indentation rules).
– Indentation is used to determine the block structure of a Python program.
• Terminology:
– Bracket [ ]
– Brace { }
– Parenthesis ( )

0.1.2 Identifier
• A name used to specify a
– variable
– function
– class
– module
– other object

1
• Naming rules
– Starts with letter or underscore _
– Followed by zero or more letters, digits or underscores.
– Case is significant.
– @, #, $, !, $ not allowed in identifiers.
[16]: _first_variable_1 = 3

0.1.3 Keywords in Python


• There are 35 keywords in Python. We can find them from the keyword module.
[41]: import keyword
#help(keyword)
print([Link])

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',


'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
• In addition there are some soft keywords:
[43]: print([Link])

['_', 'case', 'match', 'type']

0.1.4 Operators
• Operator: One or more symbols to perform a specific operation.
– Unary operator: 1 operand.
– Binary operator: 2 operands.
+ - * / % ** //
<< >> & @ | ^ ~ ~ < <= > >= != ==
@= := += -= *= /= //= %= < <= > >= != ==

0.1.5 Literals
• Literal: Direct listing of the data value.
• It can be a number, string or container.
[72]: Pii = 3.1415
class_name = 'AD699'
students = ['Alice',
'Bob']

0.1.6 Data Types


1. Numbers

2
• There are several built-in numeric types in Python. We will only focus on a few of them.
– Float
∗ Example: 1.0, 3.1415
∗ Common methods: as_integer_ratio, is_integer
– Integer
∗ Example: 1, 1729
• To help visual assessment of the magnitude of a number, numeric literals can include a single
underscore.
– Example: 100_000, 10_00_00

2. Booleans
• Any data value can be used as a truth value: true or false
– True: Any nonzero number or nonempty container.
– False: 0 (any numeric type), None, an empty container.

3. None
• Built-in object.
• None has no methods or other attributes.
– Can be used as a placeholder.
– Used to indicate that no object is present.
– None can be used as a dict key.
• Ellipsis (...)
– Used in numerical applications.
– Can be used as an alternative to None if None is a valid entry.

0.1.7 4. Sequences
• There are different kinds of sequences in Python including strings, lists and tuples.
• Sets and dictionaries are not sequences.
• Sequences: Ordered containers with elements that are accessible by indexing and slicing.
• Functions:
1. len: Number of items in the container.
2. min: Smallest value
3. max: Largest value
• Concatenation: Use the + operator
• Repetition: It takes the form S * n. Here we make n copies of S.
• Membership Testing: x in S. This checks whether object x equals any item in the sequence
S.
• Indexing: S[n]. This denotes the nth item in the sequence S. Indexing is 0-based.
– A negative index n points to the same item as L+n where L = len(S)
– S[-1] is the same as S[len(S) - 1]
• Slicing: S[i:j] indicates a subsequence from the ith item (included) to the jth item (ex-
cluded).
– S[i:j:k] indicates a subsequence with stride k.
– S[::2] gives the elements with even indexes.
– S[::-1] indicates the same sequence as S in reverse order.

3
4a. Strings
• Strings are immutable objects in Python.
• Two built-in string types: str and bytes.
• In this course, we will only consider str objects.
• str object: A immutable sequence of characters used to store text-based information.
• When we perform an operation on a string, we create a new string. We do not mutate the
existing string.
1. Quoted string: Sequence of zero or more characters with matching quotes, single(’) or
double(“)
– For multline strings, use \ as the last character in the line.
2. Triple quoted string: Multiline strings are enclosed with matching three double
quotes(“ “ “)
• Most of the functions used for sequences can also be used for strings.
• Common functions
1. Predefined constants ascii_letters, ascii_lowercase, ascii_uppercase, digits,
punctuation, whitespace, printable
2. Functions isupper, islower, isdigit, isalpha, isalnum, isnumeric, startswith,
endswith, strip, lstrip, rstrip, split, splitlines, join, find, index, rindex,
upper, lower, capitalize
3. String Formatting
character_name = 'SpongeBob'
print(f"The character's name is {character_name} and it contains {len(character_name)}

4b. Tuples
• Tuples are immutable object in Python.
• The items of a tuple are arbitrary objects and may be of different types.

4c. Iterables
• This is a concept that captures in abstract the iteration behavior of sequences.

4d. Lists
• Mutable ordered sequence of items.
• Items of a list can be of different types.
• A list is a sequence. The concepts from the sequence discussion apply to lists.
• Functions
– Nonmutating
1. count: [Link](x)
2. index: [Link](x)
– Mutating
1. append
2. clear
3. extend
4. insert
5. pop
6. remove

4
7. reverse
8. sort

6. Dictionaries
• A dictionary is a container of key/value pairs.
• Membership: k in D returns True if dictionary D contains the key k
• Creating a dictionary:
– d = {'AD699':'ABA', 'AD678':'Finance', 'AD605':'SupplyChain'}
• Indexing: D[k] returns the value associated with key k in the key is present. If the key is
not present, it returns an error.
• – Functions
– Nonmutating
1. copy
2. get
3. items
4. keys
5. values
– Mutating
1. clear
2. pop
3. popitem
4. setdefault
5. update

0.1.8 Naming Conventions


• Function names should be lowercase, with words separated by underscores as necessary to
improve readability. PEP8
• Variable names follow the same convention as function names.
1. Camel case (myVariableName): Lowercase the first word, capitalize the first letter of subse-
quent words. Used in: JavaScript, Java, C#, Swift.
2. Pascal case (MyVariableName): Capitalize the first letter of each word. Used in: Python (for
class names), C#, Pascal, Java, C++.
3. Snake case (my_variable_name): Words are lowercase and separated by underscores. Used
in: Python (for variables and function names), Ruby.
4. Screaming snake case (MY_VARIABLE_NAME): All letters are uppercase with words separated
by underscores. Used in: Python (for constants), C, C++, Java.
5. Kebab case (my-variable-name): Words are lowercase and separated by hyphens. Used in:
URLs and CSS classm1. es.
6. Hungarian notation (iCount, strName): Variable names use prefixes indicating types or
scopes. Used in: Older C and C++ c
Source: [Link]

5
• If a function argument’s name clashes with a reserved keyword, it is generally better to
append a single trailing underscore rather than use an abbreviation or spelling corruption.
Thus class_ is better than clss. e.g class_, type_
• Constants are usually defined on a module level and written in all capital letters with under-
scores separating words. e.g. DEBUG_FLAG
• Python classes typically do not use the underscore. So, you will unlikely name a class as
book_publisher but BookPublisher

Dunder (double underscore, or magic) methods


• Due to the use of the double underscore, such methods are sometimes called “dunder” methods
— dunder as in double underscore.
• Here are several examples of dunder methods in Python
– __init__: responsible for creating instances of the class.
– __str__: defines the behavior of str() and print() functions used on the object; see this
article to learn more
– __len__: returns the length of the container.
– __getitem__: allows and defines indexing.
– __add__, __mul__, etc.: allow objects to support arithmetic operationsations
Special attributes While methods that begin and end with double underscores are called magic
or dunder, attributes following this naming convention are typically called special attributes. Au-
tomatically created and managed by Python, such attributes provide information about objects.
Here are some examples:
name: used by modules, classes, class methods and functions (interestingly, partial functions
created using [Link] don’t have this attribute) to keep the name of an object. doc:
keeps the docstring of a module, class, method or function. file: used by modules to store the path
to the file from which the module was loaded.
Dummy variables Another frequent use of the underscore is as dummy variables. This means that
the underscore is used as a name to represent a variable that will not be used in the current code.
Something like that is often used in loops, when we don’t use the looping variable. Compare the
following situations:
for _ in range(3):
print("Hello")
[ ]:

You might also like