0% found this document useful (0 votes)
7 views25 pages

CS L5

The document provides an overview of Python programming concepts, including variable declaration, data types, control flow, and basic programming structures. It highlights the differences between Python and C syntax, such as the absence of type declarations and the use of whitespace for block definition. Additionally, it covers lists as a compound data type, their methods, and various operators applicable to them.

Uploaded by

alrashidy015
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)
7 views25 pages

CS L5

The document provides an overview of Python programming concepts, including variable declaration, data types, control flow, and basic programming structures. It highlights the differences between Python and C syntax, such as the absence of type declarations and the use of whitespace for block definition. Additionally, it covers lists as a compound data type, their methods, and various operators applicable to them.

Uploaded by

alrashidy015
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
You are on page 1/ 25

Field of Technological Industries

For All Programs

Computer Science (ETP211): (Lec5)

Dr : Wael Mohamed Fawaz Date : 28 / 10 / 2024


Variables
• No need to declare
• Need to assign (initialize)
• use of uninitialized variable raises exception
• Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
• Everything is a variable:
• functions, modules, classes
Python Syntax
• Much of it is similar to C syntax
• Exceptions:
• missing operators: ++, --
• no curly brackets,{}, for blocks; uses
whitespace
• different keywords
• lots of extra features
• no type declarations!
Numbers
• The usual notations and operators
• 12, 3.14, 0xFF, 0377, (-1+2)*3/4**5, abs(x), 0<x<=5

• C-style shifting & masking


• 1<<16, x&0xff, x|1, ~x, x^y
• Integer division truncates :-(
• 1/2 -> 0 # float(1)/2 -> 0.5
• Long (arbitrary precision), complex
• 2L**100 -> 1267650600228229401496703205376L
• 1j**2 -> (-1+0j)
Simple data types
• Numbers
• Integer, floating-point, complex!

• Strings
• characters are strings of length 1

• Booleans are False or True


Simple data types: operators

• + - * / % (like C)
• += -= etc. (no ++ or --)
• Assignment using =
• but semantics are different!
a = 1
a = "foo" # OK
• Can also use + to concatenate strings
Comments

• Start with # and go to end of line

• What about C, C++ style comments?


• NOT supported!
Strings and formatting
i = 10
d = 3.1415926
s = "I am a string!"
print "%d\t%f\t%s" % (i, d, s)
print “newline\n"
print "no newline"
Compound Data Type: List
• List:
• A container that holds a number of other objects, in a
given order
• Defined in square brackets
a = [1, 2, 3, 4, 5]
print a[1] # number 2
some_list = []
some_list.append("foo")
some_list.append(12)
print len(some_list) # 2
List
• a = [99, "bottles of beer", ["on", "the", "wall"]]
• Flexible arrays, not Lisp-like linked lists
• Same operators as for strings
• a+b, a*3, a[0], a[-1], a[1:], len(a)
• Item and slice assignment
• a[0] = 98
• a[1:2] = ["bottles", "of", "beer"]
-> [98, "bottles", "of", "beer", ["on", "the", "wall"]]
• del a[-1] # -> [98, "bottles", "of", "beer"]
Example:

x = str(3) # x will be '3'


k = str(5)
y = int(3) # y will be 3
z = float(3) # z will be 3.0

print(x)
print(y)
print(z)
print(x + k)
print(y + z)
Basic programming
a,b = 0, 1
# non-zero = true
while b < 10:
# formatted output, without \n
print b,
# multiple assignment
a,b = b, a+b
Control flow: if
x = int(raw_input("Please enter #:"))
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
▪ no case statement
Control flow: for
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)

▪ no arithmetic progression, but


▪ range(10) → [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
▪ for i in range(len(a)):
print i, a[i]
▪ do not modify the sequence being iterated over
Loops: break, continue, else
▪ break and continue like C
▪ else after loop exhaustion
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is prime'
Defining functions
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b

>>> fib(2000)

▪ First line is docstring


▪ first look for variables in local, then global
▪ need global to assign global variables
29-Oct-24 Advanced Programming
Spring 2002
List
▪ a = [99, "bottles of beer", ["on", "the", "wall"]]
▪ Flexible arrays, not Lisp-like linked lists
▪ Same operators as for strings
▪ a+b, a*3, a[0], a[-1], a[1:], len(a)
▪ Item and slice assignment
▪ a[0] = 98
▪ a[1:2] = ["bottles", "of", "beer"]
-> [98, "bottles", "of", "beer", ["on", "the", "wall"]]
▪ del a[-1] # -> [98, "bottles", "of", "beer"]
Compound Data Type: List
▪ List:
▪ A container that holds a number of other objects, in
a given order
▪ Defined in square brackets
a = [1, 2, 3, 4, 5]
print a[1] # number 2
some_list = []
some_list.append("foo")
some_list.append(12)
print len(some_list) # 2
List methods
▪ append(x)
▪ extend(L)
▪ append all items in list (like Tcl lappend)
▪ insert(i,x)
▪ remove(x)
▪ pop([i]), pop()
▪ create stack (FIFO), or queue (LIFO) → pop(0)
▪ index(x)
▪ return the index for value x
List methods
▪ count(x)
▪ how many times x appears in list
▪ sort()
▪ sort items in place
▪ reverse()
▪ reverse list
del – removing list items
▪ remove by index, not value
▪ remove slices from list (rather than by assigning an empty list)
>>> a = [-1,1,66.6,333,333,1234.5]
>>> del a[0]
>>> a
[1,66.6,333,333,1234.5]
>>> del a[2:4]
>>> a
[1,66.6,1234.5]
Conditions
▪ can check for sequence membership with is and is not:
>>> if (4 in vec):
... print '4 is'
▪ chained comparisons: a less than b AND b equals c:
a < b == c
▪ and and or are short-circuit operators:
▪ evaluated from left to right
▪ stop evaluation as soon as outcome clear
Conditions
▪ Can assign comparison to variable:
>>> s1,s2,s3='', 'foo', 'bar'
>>> non_null = s1 or s2 or s3
>>> non_null
foo
▪ Unlike C, no assignment within expression
Questions?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy