Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

1 Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

Advanced Programming Lab

•       Python programming
Pattern
• We get 4 labs (4hrs+4hrs+2hrs+2hr)
• There will be 2 evaluations (2nd and 3rd lab) for 20 marks
each. 
• 40 marks scaled up to 60
• Each evaluation :
6 marks for record
4 marks  execution 
10 marks quiz / give some code to execute 

• Last lab Final exam (1.5hrs including write up + execution)


What are Scripting Languages ??

– A high-level programming language that is interpreted


by another program at runtime rather than compiled by
the computer's processor as other programming
languages.

– Scripting languages, which can be embedded within


HTML, commonly are used to add functionality to a
Web page, such as different menu styles or graphic
displays.
Python
–Python is a general-purpose, interpreted, interactive, object-oriented and
high-level programming language.

–Python was created by Guido van Rossum in the late eighties and early
nineties.

• It’s a true cross-platform language, running equally well on Windows,


Linux/UNIX, and Macintosh platforms, as well as others, ranging from
supercomputers to cell phones.

• It can be used to develop small applications and rapid prototypes, but it


scales well to permit development of large programs.

• It comes with a powerful and easy-to-use graphical user interface (GUI)


toolkit, web programming libraries, and more. And it’s free.
Python is expressive
• Python is a very expressive language.
• Expressive in this context means that a single line of Python
code can do more than a single line of code in most other
languages.
• The fewer lines of code you have to write, the faster you can
complete the project.
• For example, let’s consider swapping the values of two
variables, var1 and var2.
In Java, this requires three lines of code and an extra variable:
int temp = var1;
var1 = var2;
var2 = temp;
Using Python, var2, var1 = var1, var2
Compiling and interpreting
Many languages require you to compile (translate) your
program into a form that the machine understands.
compile execute
source code byte code output
Hello.java Hello.class

interpret
source code output
Hello.py

• Python is instead directly interpreted into machine


instructions.
Variables, Expressions, and Statements
• Fixed values such as numbers, letters, and strings are
called “constants” because their value does not change.
• Numeric constants are as you expect .
• String constants use single quotes (') or double quotes (")
>>> print (123)
123
>>> print (98.6)
98.6
>>> print ('Hello world‘)
Hello world
Variables
• A variable is a named place in the memory
where a programmer can store data and later
retrieve the data using the variable “name”
• Programmers get to choose the names of the
variables .
• You can change the contents of a variable in a
later statement
– X=11.2
– Y=19
Python Variable Name Rules
1. Must start with a letter or underscore _
2. can consist of letters and numbers and
underscores
3. Case Sensitive
– Good: spam eggs spam23 _speed
– Bad: 23spam #sign var.12
– Different: spam Spam SPAM
Reserved Words
• You cannot use reserved words as variable
names / identifiers.
Ex:
[and del for is raise assert elif from lambda
return break else global not try class except if or
while continue exec import pass yield def finally
in print as with]
Assignment Statements
• We assign a value to a variable using the
assignment statement (=)
• An assignment statement consists of an
expression on the right-hand side and a
variable to store the result
Numeric Expressions
• You can manipulate them using the
arithmetic operators:
+ (addition), – (subtraction), *(multiplication), /
(division), ** (exponentiation)
and % (modulus).
Operator Precedence Rules
• Highest precedence rule to lowest precedence
rule:
– Parenthesis are always respected
– Exponentiation (raise to a power)
– Multiplication, Division, and Remainder
– Addition and Subtraction
– Left to right
Math commands
• Python has useful commands for performing calculations.

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 at the top of your Python program:
from math import *
Python Integer Division
• Integer division can produce decimal numbers
• Floating point division produces floating point
numbers (put brackets for parameters in print
in python 3.x)
Eg. >>> print (9/2)
4.5
Mixing Integer and Floating
• When you perform an operation where one operand is an
integer and the other operand is a floating point, the result is a
floating point
• The integer is converted to a floating point before the
operation (put brackets for parameters in print in python 3.x)
What does “Type” Mean?
• In Python variables, literals and constants have a “type”
• Python knows the difference between an integer number and a
string
• For example “ + ” means “addition” if something is a number
and “concatenate” if something is a string
Type Matters
• Python knows what “type” everything is
• Some operations are prohibited
• You cannot “add 1” to a string
• We can ask Python what type something is by using the type()
function
Type Conversions
• When you put an integer and floating point in an expression,
the integer is implicitly converted to a float
• You can control this with the built-in functions int() and float()
String Conversions
• You can also use int() and float() to convert between strings
and integers
• You will get an error if the string does not contain numeric
characters
User Input
• We can instruct Python to pause and read data from the user using
the input() function
• The input() function returns a string
• Eg. nam = input(‘Enter name’)
print(‘Welcome ’, nam)
Converting User Input
• If we want to read a number from the user, we must convert it
from a string to a number using a type conversion function
• Later we will deal with bad input data
inp = input(‘Europe floor?’)
usf = int(inp)+1
print (‘US floor’, usf)

Anything after a # is ignored by Python(comments)


input
• input : Reads a number from user input.
– You can assign (store) the result of input into a
variable.
– Example:
age = input("How old are you? ")
print ("Your age is", age)
print ("You have", 65 – int(age),
"years)
until retirement"

Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
list
• You can create a list as well as assign it.
• a list automatically grows or shrinks in size as
needed.
• It can have any number of items and they may
be of different types (integer, float, string etc.).
• # empty
– my_list = []
• # list of integers
– my_list = [1, 2, 3]
• # list with mixed datatypes
– my_list = [1, "Hello", 3.4]
• # nested list
– my_list = ["mouse", [8, 4, 6], ['a']]
• my_list = ['p','r','o','b','e']
• # Output: p
– print(my_list[0])
• # Output: o
– print(my_list[2])
• # Output: e
– print(my_list[4])
• # my_list[4.0]
– # Error! Only integer can be used for indexing
• # Nested List
– n_list = ["Happy", [2,0,1,5]]
• # Nested indexing
• # Output: a
– print(n_list[0][1])
• # Output: 5
– print(n_list[1][3]) <!-- -->
• my_list = ['p','r','o','b','e']
• # Output: e
– print(my_list[-1])
• # Output: p
– print(my_list[-5])
• # mistake odd = [2, 4, 6, 8]
• # change the 1st item
– odd[0] = 1
• # Output: [1, 4, 6, 8]
– print(odd)
• # change 2nd to 4th items
– odd[1:4] = [3, 5, 7]
• # Output: [1, 3, 5, 7]
– print(odd)
• my_list = ['p','r','o','g','r','a','m','i','z']
• # elements 3rd to 5th
– print(my_list[2:5])
• # elements beginning to 4th
– print(my_list[:-5])
• # elements 6th to end
– print(my_list[5:])
• # elements beginning to end
– print(my_list[:])
• odd = [1, 3, 5] odd.append(7)
• # Output: [1, 3, 5, 7]
– print(odd)
• odd.extend([9, 11, 13])
• # Output: [1, 3, 5, 7, 9, 11, 13]
– print(odd)
• my_list = ['p','r','o','b','l','e','m']
• # delete one item
– del my_list[2]
• # Output: ['p', 'r', 'b', 'l', 'e', 'm'] print(my_list)
• # delete multiple items
– del my_list[1:5]
• # Output: ['p', 'm']
– print(my_list)
• # delete entire list
– del my_list
• # Error: List not defined
– print(my_list)
• my_list = [3, 8, 1, 6, 0, 8, 4]
• # Output: 1
– print(my_list.index(8))
• # Output: 2
– print(my_list.count(8))
• my_list.sort()
• # Output: [0, 1, 3, 4, 6, 8, 8]
– print(my_list)
• my_list.reverse()
• # Output: [8, 8, 6, 4, 3, 1, 0]
– print(my_list)
Tuple
• The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas in a list,
elements can be changed.
• A tuple is created by placing all the items (elements) inside a
parentheses (), separated by comma. The parentheses are
optional but is a good practice to write it.
• A tuple can have any number of items and they may be of
different types (integer, float, list, string etc.).
String
• Strings can be delimited by single (' '), double (" "), triple single
(''' '''), or triple double (""" """) quotations and can contain tab (\
t) and newline (\n) characters.
• The operators (in, +, and *) and built-in functions (len, max, and min)
operate on strings as they do on lists and tuples.
• “hello” in “hello world” returns True
• “Hello ” + “world” returns “Hello world”
• “Hello”*3 returns “HelloHelloHello”
• len(“something”) returns 9
• max(“Returns the character with greatest ascii value in this string”)
which is ‘w’
• min(“Returns the character with least ascii value in this string”)
which is space
• odd = [1, 3, 5]
• # Output: [1, 3, 5, 9, 7, 5]
– print(odd + [9, 7, 5])
String
• The print function outputs strings. Other Python data types can be
easily converted to strings and formatted:

>>> e = 2.718
>>> x = [1, "two", 3, 4.0, ["a", "b"], (5, 6)]

>>> print("The constant e is:", e, "and the list x is:", x)


The constant e is: 2.718 and the list x is: [1, 'two', 3, 4.0, ['a', 'b'], (5, 6)]

• Objects are automatically converted to string representations for


printing.
String Operations
• Some operators apply to strings
• + implies “concatenation”
•  * implies “multiple concatenation” 
• Python knows when it is dealing with a string or a number and
behaves appropriately. Put paranthesis for print in python
3.x. 

You might also like