Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
ES 102 Lecture 4
Shivakumar Jolad
Indian Institute of Technology Gandhinagar
Sept 10, 2013 IITGn
Python Identifiers
¨ Name used to identify a variable, function, class, module or other object.
¨ Starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
¨ Python does not allow punctuation characters such as @, $ and % within identifiers.
¨ Python is a case sensitive programming language: Ahmedabad and ahmedabad are different
2 http://www.tutorialspoint.com/python/python_basic_syntax.htm
Reserved Words
3
Reserved words may not be used as constant or variable or any other identifier names
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Quotation in Python
¨ Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.
¨ The triple quotes can be used to span the string across multiple lines.
4
word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
http://www.tutorialspoint.com/python/python_basic_syntax.htm
Comments in Python ¨ A hash sign (#) that is not inside a string literal begins a comment.
¨ All characters after the # and up to the physical line end are part of the comment and the Python interpreter ignores them.
¨ A comment may be on the same line after a statement or expression:
5
# First comment print "Hello, Python!"; # second comment
Output Hello, Python!
http://www.tutorialspoint.com/python/python_basic_syntax.htm
name = "Amitabh Bachhan" # This is again comment
User Input
¨ raw_input() takes in any input that you give . Converts to string
¨ Input() : Expects a numerical value
6
raw_input("\Press the enter key to exit.") name=raw_input("\n Enter your name \n") number=raw_input("Enter any number")
Temperature=input("\n\n What is today’s temperature?")
Variables
¨ Variables are reserved memory locations to store values. ¨ Interpreter allocates memory based on data types (integer,
floating point , characters).
¨ The equal sign (=) is used to assign values to variables.
7
RollNo= 131100001 # An integer assignment Height = 162.5 # A floating point Name = "Amitabh" # A string print RollNo print Height print Name
a = b = c = 1 Assign a single value to several variables simultaneously.
Python Data Types
¨ Numbers
¨ String
¨ List
¨ Tuple
¨ Dictionary
8
Python has five standard data types:
var1 = 1
var2 = 10
Delete variables del var1, var2
Number Types
¨ Number objects are created when you assign a value to them.
¨ Python supports four different numerical types: Ø int (signed integers) Ø long (long integers) Ø float (floating point real values) Ø complex (complex numbers)
9
var1 = 2
var2 = 35638790988739 var3=4.27 var4=3+4j
Strings
¨ Strings are identified as a contiguous set of characters in between quotation marks.
¨ Python allows for either pairs of single or double quotes.
¨ plus ( + ) sign is the string concatenation
¨ asterisk ( * ) is the repetition operator.
¨ Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes starting at 0
10
String Example
11
str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string
http://www.tutorialspoint.com/python/python_basic_syntax.htm
Python Lists
¨ Versatile objects to create almost any combination of data types!
12
list = [ 'Sept', 10 , 2013, 'Temp', 32.5 ] tinylist = ['Humidity', '70%'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists
Data Type Conversion
13
Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
str(x) Converts object x to a string representation.
list(s) Converts s to a list.
set(s) Converts s to a set.
Operators
¨ Arithmetic Operators
¨ Comparison (i.e., Relational) Operators
¨ Assignment Operators
¨ Logical Operators
¨ Bitwise Operators …
14
Operation between operands are represented by operators. Addition (+), Multiplication (*) etc,
Comparison Operators
15
Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true.
(a == b) is not true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(a != b) is true.
>
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(a > b) is not true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(a >= b) is not true.
Assignment Operators
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand
c = a + b will assigne value of a + b into c
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
c += a is equivalent to c = c + a
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
c -= a is equivalent to c = c - a
16 http://www.tutorialspoint.com/python/python_basic_syntax.htm
Logical Operators
17
Operator Description Example
and Called Logical AND operator. If both the operands are true then then condition becomes true.
(a and b) is true.
or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.
(a or b) is true.
not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
not(a and b) is false.
Conditions and Decision Making
18
if expression: statement(s)
Statement Description
if statements
An if statement consists of a boolean expression followed by one or more statements.
if...else statements
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
nested if statements
You can use one if or else if statement inside another if or else if statement(s).
http://www.tutorialspoint.com/python/python_decision_making.htm
If-else expressions
19
if expression: statement(s) else: statement(s)
True=1 if True: print "True" else: print "False"
http://www.tutorialspoint.com/python/python_if_else.htm
Indentation
20
True=1 if True: print "True“ else: print "False" # Not lined up properly Indentation Error: expected an indented block
True=1 if True: print "True" else: print "False"
Else if : elif condition
¨ condition1, condition2, are an expressions that can either be true or false. These type of expressions are called Boolean Expressions.
¨ Relational Operators: == equality; ! = non-equality, <= for ≤, >= for ≥
¨ Example y == 2, n <= 10, x! = 42
21
if condition 1: statement(s) elif condition2: statement(s) elif condition 3: statement(s) else: statement(s)
Example of control Flow
¨ If x is positive then the square roots are ¨ else the square roots are
22
Finding Square Root Given a number x find the square root of that number.
±√𝑥
±𝑖 √−𝑥
Practice Problems
¨ Write a python program which takes students roll number between 1 to 99( ) as input and assigns them into groups: Group1, Group2 or Group3, depending on the reminder after dividing by 3 (i.e. 0, 1 or 2). Output the Group name
¨ Displacement of a particle in a uniform gravitational field (1D) is given by
( where standard symbolic convention is used). Write a program to accept the initial velocity and time t, to predict the oistion at time t.
23
n = 1, 2, · · · , 99
y = v0t�1
2gt2
Loops
24