0% found this document useful (0 votes)
0 views32 pages

L10_Python Basics I

The document provides an overview of elementary Python syntax, including indentation, comments, and best coding practices. It covers data types, dynamic typing, mutability, control flow, and various sequence types like lists and dictionaries. Additionally, it discusses operations on these data structures and the use of modules to extend Python's functionality.
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)
0 views32 pages

L10_Python Basics I

The document provides an overview of elementary Python syntax, including indentation, comments, and best coding practices. It covers data types, dynamic typing, mutability, control flow, and various sequence types like lists and dictionaries. Additionally, it discusses operations on these data structures and the use of modules to extend Python's functionality.
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

ME171: Computer Programming Language

Elementary Python Syntax - Whitespaces and


Blocks
§ Indentation level and line breaks are syntactically relevant!
• useful: enforces readable code

#Note: dots represent white spaces

• Warning: Never mix tabstops and whitespaces!


• Good practice: Do not use tabs at all
• Set your editor/IDE to fill tabs with white spaces automatically
• Recommendation: 4 spaces per indent level

Ref. Daniel Bauer, Programming languages: Python Course materials, Columbia University, NY, USA
1 Department of Mechanical Engineering, BUET
Elementary Python Syntax - Linebreaks
§ Compiler ignores blank lines
§ Indentation level only counts after finished lines
• if open (, {, or [ has not been closed, the next line is joined automatically
• can join lines manually with the \ symbol for readability
• sometimes needed with very long lines

2 Department of Mechanical Engineering, BUET


Elementary Python Syntax - Comments

§ Single line comments with # at the end of a line

§ `Docstrings' at the beginning of function, method, class


definitions and modules.
• Triple ‘ or " surround multi-line strings

3 Department of Mechanical Engineering, BUET


Code Style - Best Practices
§ Do not use semicolons ; they are legal, but unnecessary
§ Limit lines to 79 characters
§ Python is case-sensitive:
• All keywords are lower case
• Class names should be written in camelCase
• Everything else (variables, function, modules...) should be
lowercase_with_underscore

4 Department of Mechanical Engineering, BUET


Variables and Assignments
§ Evaluate expression on the right-hand side of = and assign to it the
variable (name) on the left-hand side
§ No declaration for variables needed

§ Multiple assignments in one line is possible

5 Department of Mechanical Engineering, BUET


Python Data Types - Built-In Types
§ Elementary types
• None Type: None
• bool: True, False
• (Numeric) int: 42, long, float: 3.14, complex: (0.3+2j)
§ Container types
• str: 'Hello'
• list: [1, 2, 3]
• tuple: (1, 2, 3)
• dict: {'A':1, 'B’:2} #store data values in key:value pairs
• set: {1, 2, 3}
§ file
§ function, class, instance ...
§ In Python everything is an object and every object has a type

6 Department of Mechanical Engineering, BUET


Python uses Dynamic Typing
§ Type checks (making sure variables have the correct type for
an operation) performed at runtime.
§ No need to declare variable types.
§ Can get type of an object with 'type(variable)'

7 Department of Mechanical Engineering, BUET


Mutability
§ All the data in python is represented by objects
§ Every object has an identity, a type, and a value
• Identity: An object’s identity never changes once it has been created; you
may think of it as the object’s address in memory.
• Type: An object’s type defines the possible values and operations (e.g.
“does it have a length?”) that type supports. The type() function returns
the type of an object. An object type is unchangeable like the identity.
• Value: The value of some objects can change. Objects whose value can
change are said to be mutable; objects whose value is unchangeable once
they are created are called immutable.
§ The mutability of an object is determined by its type

8 Department of Mechanical Engineering, BUET


Mutability
§ Python has mutable and immutable objects, based on data type
• Mutable objects (lists, dictionaries, sets) can be modified

• Immutable objects (int, float, boolean, strings, tuples, range) cannot be


changed once they are initialized

1657696608

1657696640
9 Department of Mechanical Engineering, BUET
Booleans

§ Boolean expressions:
• == equals: 5 == 5 yields True
• ! = does not equal: 5 != 5 yields False
• > greater than: 5 > 4 yields True
• >= greater than or equal: 5 >= 5 yields True
• Similarly, we have < and <=
§ Logical operators:
• True and False yields False
• True or False yields True
• not True yields False

10 Department of Mechanical Engineering, BUET


Control flow
§ Similar to C, Control statements allow you to do more complicated tasks

• If one if or elif matches the indented


block
• statement is executed
• Remaining conditions are ignored
• elif and else are optional
• If no if or elif matches, the indented
block statement below else is executed

11 Department of Mechanical Engineering, BUET


Control flow
§ Loops: while Statements
• Execute the indented statements repeatedly while conditionExp
evaluates to True

12 Department of Mechanical Engineering, BUET


Control flow
§ continue and break
'continue' interrupts the current 'break' interrupts the complete
iteration of the loop and loop and continues execution
continues at the next iteration. below the loop

13 Department of Mechanical Engineering, BUET


Sequence Types
§ Container objects that contain ordered sequences of elements:
• String (a sequence of encoded characters)

• list (mutable sequence of objects)

• tuple (immutable sequence of objects)

§ All sequence types support some common operations:


• Get length, Concatenation and repetition
• Test for membership
• Access specific elements and `slicing'
• Iterate through elements

14 Department of Mechanical Engineering, BUET


Length of a Sequence / Concatenation and
Repetition
§ len(x) returns the length of sequence x

§ x + y concatenates sequences x and y


• x and y need to have the same type

§ x*n or n*x repeats sequence x n times

15 Department of Mechanical Engineering, BUET


Testing for Sequence Membership
§ x in y returns True if collection y contains object x, False otherwise
• Based on value equality (==)
• x not in y is equivalent to not x in y

§ For strings only:


• in also tests if x is a substring of y

16 Department of Mechanical Engineering, BUET


Finding Index and Counting Elements
§ [Link](y) returns the number of times y occurs in x

§ [Link](y) returns the sequence index of the first occurrence of y

17 Department of Mechanical Engineering, BUET


Sequence Indexing
§ x[i] indexes the ith element of sequence x (starting from 0)

§ reverse indexing starts at -1

18 Department of Mechanical Engineering, BUET


Sequence Slicing
§ Slicing returns a copy of a subsequence
§ x[i:j] returns the subsequence from position i (inclusive) to position j
(exclusive)
§ x[i:] returns the subsequence from position i (inclusive) to the end
§ x[:j] returns the subsequence from the beginning to position j (exclusive)

19 Department of Mechanical Engineering, BUET


Iterating Through Sequences
§ Sequence data types implement the iterator protocol
§ Iterate through all elements of the sequence
§ Execute the statement with x bound to the current element

§ Can use break and continue in for loops

20 Department of Mechanical Engineering, BUET


range
§ range(i) produces an iterator of integers from 0 to i (exclusive)
#Note: to print range, you need to convert it to a list.
# print(list(range(10))

§ range(i,j) produces an iterator over integers from i (inclusive) to j (exclusive)

§ range(i,j,s) produces an iterator over integers from i (inclusive) to j (exclusive)


in steps of s

21 Department of Mechanical Engineering, BUET


List Comprehension
§ Perform some operation on each element of an iterator and get a new list

§ Can use multiple for statements (e.g., compute all pairs)

22 Department of Mechanical Engineering, BUET


else in List Comprehension
§ Can use conditional expressions within a list comprehension

23 Department of Mechanical Engineering, BUET


List Operations
§ Lists are mutable and can be manipulated

§ [Link](x) adds element x to the end of list

§ [Link]() removes the last element from list and returns it. Lists can be
used as stacks.

24 Department of Mechanical Engineering, BUET


List Operations
§ [Link](x) removes the first occurrence of element x from the list

§ [Link]() reverses the order of the list

§ [Link]() sorts the list (using <=)

25
25 Department of Mechanical Engineering, BUET
Dictionaries
§ A dictionaries is a collections of objects indexed by unique keys
§ Most powerful built-in data structure

§ Assigning a new object to an unseen key inserts the key into the
dictionary

§ Testing for membership


• x in dict returns True if x is a key of dict, False otherwise

26 Department of Mechanical Engineering, BUET


Dictionary Items, Keys and Values
§ [Link]() gets a list of keys

§ [Link]() gets a list of dictionary values

§ [Link]() gets a list of (key, value) tuples

27 Department of Mechanical Engineering, BUET


Sets
§ Sets (mutable) / frozensets (immutable) are unordered bags of unique
objects

§ Set membership: x in s

§ is s a subset/superset of t?

28 Department of Mechanical Engineering, BUET


Sets - Union/Intersection/Difference
§ get union of s and t as a new set

§ get intersection of s and t as a new set

§ get difference between s and t as a new set

29
29 Department of Mechanical Engineering, BUET
Mutable Sets - update, add, remove
§ These operations do not work for frozensets
§ add all elements of set to set s

§ add object x to s

§ remove object x from s

30
30 Department of Mechanical Engineering, BUET
Modules
§ Not all functionality available comes automatically when starting python,
and for good reasons
§ We can add extra functionality by importing modules:

§ Useful modules: math, string, random, numpy, scipy, matplotlib and so on

31 Department of Mechanical Engineering, BUET


Math module

from math import *


32 Department of Mechanical Engineering, BUET

You might also like