Download Variables, Conditions, Loops, Functions and Scripting in

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
ME 171
Computer Programming
Language
Partha Kumar Das
Lecturer,
Department of Mechanical Engineering, BUET
Lecture 8
Variables, Conditions, Loops and
Functions and Scripting in Python
Variables
• No need to declare
• Need to assign (initialize)
• Everything is a "variable": even functions, classes, modules
 More importantly, we don’t need to put semicolon (;) after each statement.
 So number of errors reduces to a great extent.
N.B.: Using Ipython
Variables
• Variable Name:
 Names are given to variables, functions, modules, etc.
 These names are called identifiers
 Every identifier must begin with a letter or underscore (“_”), followed by any
sequence of letters, digits, or underscores
 Identifiers are case sensitive
• Variable Type:
 Boolean:
Variables of this type can be either True or False.
 Integer:
An integer is a number without a fractional part, e.g. -4, 5, 0, -3.
 Float:
Any rational number, e.g. 3.432.
 String:
Any sequence of characters.
 Complex number:
‘j’ represents imaginary part of the complex number.
Strings
•
•
A new kind of variable in python.
A sequence of text characters in a program.
•
Strings start and end with quotation mark " or apostrophe ' characters.
•
A string may not span across multiple lines or contain a " character:
 “This is a “wrong” format.”
 “No use of
multiple lines”
• Multiple line strings can be written using triple quotation marks(“ “ “
• A string can represent characters by preceding them with a backslash
\t tab character
\n new line character
\" quotation mark character
\\ backslash character
” ” ” or ‘ ‘ ‘
’ ’ ’).
String Operation
• Strings can be concatenated and multiplicated like other variables.
• Test a substring in a given string.
• Converting a number into a string using str function.
• Converting a character into its ASCII number using ord function.
• Converting a number into character using chr function.
String Operation
• Characters in a string are numbered with indexes starting at 0:
– Example:
name = “Hello Mat”
index
0
1
2
3
4
character
H
e
l
l
o
5
6
7
8
M
a
t
• Accessing an individual character of a string:
stringvariableName [ index ]
• Determining the length of the string using len function.
String Operation
• Negative indexing can be used.
• String Slicing: We can show a slice of a string using colon (:) operator.
Syntax: string [starting_index : Stopping_index]
• The slice contains the substring beginning at position start and runs up to but doesn’t
include the position end.
Immutability of strings
•
•
•
•
Strings in python are immutable that is not changeable.
Once a string variable is assigned, it can not be modified.
They can not be append, reassign an element at any index, or delete any element at any index.
To change the variable we need to assign the variabale or a new variable again.
• string.strip() returns a copy of str with all whitespace (spaces/tabs/newlines) from the
beginning and end of the string removed.
• string.upper() and string.lower() return a copy of str with all letters converted to uppercase
and lowercase, respectively.
Input
• Input can be done in python using input() function.
• By default input() function take a string variable as input.
• Integer or float variable can be taken as input using modifier before input() function.
It waits for operators input.
List
• List is simply an array of matters like numbers, strings.
• There are essentially two kinds of list objects in Python, tuples and lists.
• The difference between the two is that the tuple is fixed and can't be modified once
created like string while list allows additions and deletions of objects, sorting, and
other kinds of modifications.
• Tuples tend to be slightly faster than lists, but the speed benefit is rarely substantial and a
good rule of thumb is to always use lists.
• You can store different types of variables in the same list:
[1,3,"test",True]
• You can create a list using square brackets:
[1,2,5,1,3,"test"]
• Python lists are dynamic. They can grow and shrink on demand.
• Python lists are also heterogeneous, a single list can hold arbitrary data types.
• Python lists are mutable.
Colon (:) operator:
 Can be used for same slicing purpose both for string and list.
List
List Member Functions
Method
Meaning
<list>.append(x)
Add element x to end of list.
<list>.sort()
Sort (order) the list.
<list>.reverse()
Reverse the list.
<list>.index(x)
Returns index of first occurrence of element x.
<list>.insert(i, x)
Insert x into list at index i.
<list>.count(x)
Returns the number of occurrences of x in list.
<list>.remove(x)
Deletes the first occurrence of x in list.
<list>.pop(i)
Deletes the ith element of the list and returns its value.
Nested List
• A nested list is a list that appears as an element in another list.
Class Performance
• What are the outputs of
list[:-2]
list [0][:-2]
list[3].insert(1,5)
Conditions
• Conditional statements: The boolean expression after the if
statement is called the condition:
If x>0:
print (x is positive)
else:
print (x is negative or zero)
Syntax:
HEADER:
FIRST STATEMENT
...
LAST STATEMENT
 The header begins on a new line and ends with a colon (:).
 Indentation must be provided after the condition usually pressing
a tab or several spaces.
 The indented statements that follow are called a block.
Conditions
• Example:
• Use elif instead of else if.
Loops
• We use loops when we want to keep repeating a set of statements.
• There are two ways to loop : while and for loops
Syntax:
while [expression that evaluates True or False]:
[statements to be executed]
for [variable] in range([start],[stop], [step] ):
[statements to be executed]
for variableName in groupOfValues:
statements
 Always use a colon (:) after the condition.
Loops
• Examples:
Output:
N.B.: Using Ipython
Loops
• Examples:
Output:
• The range function specifies a range of integers:
range(start, stop)
• The integers between start value and stop value.
• It can also accept a third value specifying the change/ interval between the values.
range(start, stop, step) # the integers between start and stop by step
 Always use a colon (:) after the definition.
 Use indentation to be inside the loop.
N.B.:
In Using
orderIpython
to get out from the loop, don’t use any indentation.
Functions
• A function is a named sequence of statements that performs a desired operation.
• This operation is specified in a function definition.
• A function takes an argument and returns a result.
Example:
def function_name(list of parameters):
statements
• The variable in parentheses is the input to the function. We call this a parameter or
argument. We say we pass x as a parameter/argument to the function.
• To call a function, you always need to include the parentheses and give it input
 Always use a colon (:) after the definition.
 Use indentation to be under the function.
Functions
Command name
Description
Constant
Description
abs(value)
absolute value
e
2.7182818...
ceil(value)
rounds up
pi
3.1415926...
cos(value)
cosine, in radians
floor(value)
rounds down
log(value)
logarithm, base e
log10(value)
logarithm, base 10
max(value1, value2)
larger of two values
min(value1, value2)
smaller of two values
round(value)
nearest whole number
sin(value)
sine, in radians
sqrt(value)
square root
• To use many of these commands, you must write the following
from math import *
Array
•
•
•
•
•
Array is a collection of some elements (specially numeric data: int or float) similar to lists.
The only difference is its homogeneity, i.e. the elements of a n array must be of same type.
An array can be manipulated, edited and modified any tome like list.
Array is the special feature of NumPy.
To get access of different NumPy features (like arrays, vectors, etc.) we should
import the NumPy module.
• The standard approach is to use a simple import statement: import numpy
•
Creating an Array:
• Here, inside array, at first a list should be created as array elements and then the type of
elements should be mentioned.
• However, for large amounts of calls to NumPy functions, it can become tedious to write
numpy.X over and over again. Instead, it is common to import under any briefer name.
Array
• Array elements can be accessed and modified like lists.
• Multidimensional array (Matrix) can be created in python.
• This feature make python a good competitor of MATLAB.
Array
• To store the elements of an array use copy.
• There are different functions that can done on arrays to form different operation.
Array Mathematics
• These additions, multiplications or deduction and divisions are performed element by
element.
• So if the shape of the two arrays are not the same, error message will be shown.
Array Mathematics
• Matrix multiplications can be done using dot function.
• For many more array operations, just go through the reference [6].
Polynomial Mathematics
• Polynomial formation from roots can be done using poly() function.
• Root finding of a polynomial can be done using roots() function.
• Polynomial Integration and Differentiation using polyint() and polyder()
functions, respectively:
Polynomial Mathematics
• Polynomial value at a particular point can be evaluated using polyval() function.
• For many more polynomial operations, just go through the reference [6].
Scripting
• In python interactive prompt, the code will be interpreted and executed instantly and upon
exiting from the prompt, the written statements will gone.
• To save the statements or code for future work (like source code in c), script can be written.
• These scripts are no different from the commands and instructions that you would enter at the
command prompt. Python scripts end in the extension .py in all platforms.
• Scripting can be done in any text editor like Notepad, Notepad++, Komodo Edit, Emacs,
Pyscrpter, etc. [Microsoft word is not recommended for python scripting.]
Using Interactive Prompt
Using Script file
cd (Change Directory)
cd (Change Directory)
Scripting (Continuing from previous prompt)
Scripting
References
1. Beginning Python, Peter Norton, et al.
2. Learning Python, Mark Lutz
3. Programming Python, Mark Lutz
4. https://docs.python.org/3/tutorial/
5. An introduction to Python for scientific computing, M. Scott Shell
6. An introduction to Numpy and Scipy, M. Scott Shell
Special Thanks to:
Dr. Mohammed Eunus Ali
Department of Computer Science and
Engineering, BUET
Never Stop Learning, Because Life Never
Stops Teaching.