0% found this document useful (0 votes)
34 views

Python Summary: Simple Types

This document provides a summary of Python fundamentals including: 1) Data types like integers, floats, booleans, strings and their operations. 2) Variables and assignments, input/output functions. 3) Control flow structures like if/else statements, for loops, while loops and functions. 4) String, list, and tuple operations including slicing, indexing, concatenation and more.

Uploaded by

Sami Abdul
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)
34 views

Python Summary: Simple Types

This document provides a summary of Python fundamentals including: 1) Data types like integers, floats, booleans, strings and their operations. 2) Variables and assignments, input/output functions. 3) Control flow structures like if/else statements, for loops, while loops and functions. 4) String, list, and tuple operations including slicing, indexing, concatenation and more.

Uploaded by

Sami Abdul
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/ 2

Sept.

2015 Python Summary KH

Simple Types # x is y is e.g.


# −−−−−− −−−−−−−
Type Literals Notes i f age >= 6 5 :
x = 1 + 2 ∗ 3 # 7
integer 123 Any positive, negative or p r i n t ( " Apply f o r bus p a s s " )
y = " seven " # 7 " seven "
0 zero value; no limit on size
x = y # " seven " " seven "
-12345 x , y = 2 3 , 101 # 23 101
Indentation
float 3.14 Real numbers; decimal or
6.02E23 scientific notation; limits x = x + 1 # 24 101 Indentation matters in Python. Indent statements of
on scale and precision if/elif/else body four spaces (not tabs). Ditto for loop bod-
True, False Other assignment operators: +=, -=, *= etc.
boolean Logical true/false quanti- ies and function bodies.
ties
string ¨Tuesday¨ Textual snippets compris- Input Repetition and Iteration
¨¨ ing any number of charac-
¨Luigi's¨ ters; delimited by double mood = i n p u t ( "How a r e you ? " )
quotes lucky_num = i n t ( i n p u t ( " Enter l u c k y number : " ) ) while hconditioni : f o r hvar i in hiterablei :
hstatementsi hstatementsi
Type conversions (int(), float() and str()) Input prompt optional; strips end-of-line newline.
To integers: int(3.14)(truncates), int("123"); to reals: Print output
float(3), float("3.14"); to strings: str(123). e.g.

Int/Float Operators print (17)


total = 0 total = 0
print ( " seventeen " )
Arithmetic operators: +, −, ∗ and parentheses with stan- n = 1 f o r n in r a n g e ( 1 0 1 ) :
dard precedence rules; operator ∗∗ denotes exponentiation e.g. # p r i n t i t e m s s e p a r a t e d by s p a c e s while n <= 1 0 0 : total = total + n
total = total + n
2 ∗∗ 3 ==> 8. p r i n t ( " one " , "two" , " t h r e e " )
Op. Example Notes n = n + 1
// 8 // 4 => 2 Integer division: fractional # u s e s e p f o r a l t e r n a t i v e s e p a r a t o r ( h e r e #)
10 // 3 ==> 3 part discarded range(n) generates values 0, 1, · · · , n − 1; range(n, m) gen-
p r i n t ( " one " , "two" , " t h r e e " , s e p = "#" ) erates n, · · · , m − 1; opt. 3rd argument specifies step.
/ 8 / 4 ==> 2.0 Real division: returns
8 / 3 ==> float i.e. fractional part
p r i n t ( " a l p h a " , end = " " ) # s u p p r e s s n e w l i n e Functions
2.66 retained
% 8 % 4 ==> 0 (Integer) remainder on di- p r i n t ( " beta " )
8 % 3 ==> 2 vision def s h o u t ( ) : # function def 'n .
Control Flow p r i n t ( " Hip Hip Horray ! " )
Expressions with mixed integer and float operands yield float
result, otherwise int result (apart from / operator). Selection
def plus_one ( n ) :
Boolean expressions and conditions return n + 1 # return statement
i f hconditioni : i f hconditioni :
Comparison operators: ==, ! =, < . <=, >, <= hstatementsi hstatementsi r e p s = plus_one ( 2 ) # function c a l l
Boolean operators: not, and, or e l i f hconditioni :
............................ f o r n in r a n g e ( r e p s ) :
Variables and Assignments hstatementsi shout ( ) # function c a l l
i f hconditioni : else :
Identifiers (variables etc.) comprise letters, digits and under- hstatementsi hmore statementsi
scores, may not begin with a digit and are case sensitive. else :
hmore statementsi
Assignment
Python variables are untyped. No declarations! Use type()
function to test a value’s type.

Operator precedence: (lowest) or; and; not; in, <, <=, >, >=, ! =, ==; +, −; ∗, /, //, %; ∗∗ (highest)
Sept. 2015 Python Summary KH

Strings Sequence Operations List/Tuple Operations


len(s) Length of s Name Note
String literals enclosed double-quotes ("). Blackslash (\) is the s + t Concatenate s and t a.append(v) Append v into end of list
escape chararacter. Multiline strings delimited by three quote s * n Concatenate n copies of s x.remove(v) Remove leftmost occurance of v
characters ("""). s == t Return True is s and t are equal x.insert(i, v) Splice v into list at index i
String Operations
(item by item). Also <= etc. (lex- x.index(v) Return index of leftmost occurance
igraphic order). of v
s.strip(ch) Strip all ch chars from begin- s[i] i-th item of s x.reverse() Reverse list order
ning and end of s; use .lstrip(), x.sort() Rearrange list into increasing order
.rstrip() for one-sided version
s.lower() Convert s to lowercase; also Splicing (any sequence type) List Comprehensions
.upper() for uppercase
s.center(n, ch) Centre s within string of length # Generate l i s t o f f i r s t 20 odd nums
n, padding left/right with ch char- s = " abcdefgh " odds = [ 2 ∗ n + 1 f o r n in r a n g e ( 2 0 ) ]
acters; .ljust(n, ch), .rjust(n,
ch) for left, right justifying versions print ( s [ 2 ] ) # ==> c
s.replace(t, u) Replace every occurance of t with u
# Generate l i s t o f pr im es l e s s t ha n 100
print ( s [ −3]) # ==> f ( t h i r d from r i g h t ) p r i m e s = [ n f o r n in r a n g e ( 1 0 0 ) i f is_prime ( n ) ]
(left to right)
s.count(t) Count the number of occurences of
t within s print ( s [ 2 : 5 ] ) # ==> cde ( i t e m s 2 t o 5−1) Dictionaries
s.isnumeric() Determine if s consists entirely print ( s [ 4 : ] ) # ==> e f g h ( i t e m s 4 onwards )
of numeric characters; also print ( s [ : 3 ] ) # ==> abc ( i t e m s 0 t o 3−1) a n i m a l s = { "cow" : "moo" , " dog " : " bark " , \
.isalpha(), .isspace() etc.; see " duck " : " quack " }
book for list
s.find(t) Index in s where t first occurs (−1 if print ( s [ : : 2 ] ) # ==> a c e g ( e v e r y 2nd i te m )
nowhere); .rfind() for right to left print ( s [:: −1]) # ==> h g f e d c b a ( r e v e r s e d ) p r i n t ( a n i m a l s [ " duck " ] ) # ==> quack ( l o o k u p )
search
s.split(t) Split s into a list of substrings sep- a n i m a l s [ " dog " ] = " woof " # ( i n s e r t i o n / u p d a t e )
arated by t p r i n t ( a n i m a l s [ " dog " ] ) # ==> woof ( l o o k u p )
Lists and Tuples (unmodifiable lists)
String Formatting # i n t e r a t e through keys / values
# x a m u t a b l e l i s t , y an immutable t u p l e f o r b e a s t in a n i m a l s :
Format characters: i (integer), f(real), s(string).
x = [ " a " , "b" , " c " , "d" , " e " , " f " , " g " , "h" ] p r i n t ( beast , animals [ beast ] )
y = (2 , 3 , 5 , 7 , 11 , 13)
" Answer = %6 i " % ( 4 2 ) # f i e l d width 6 File I/O
" Pi = %6.3 f " % ( 3 . 1 4 1 5 9 ) # w i d t h 6 , m a t i s s a 3 print (x [ 2 ] ) # ==> c
"Sky i s %s " % ( " b l u e " ) # width optional try :
print (x [ −3]) # ==> f
i n f i l e = open ( "poem . t x t " , " r " )
o u t f i l e = open ( " capped . t x t " , "w" )
# l i s t s only for these
except IOError :
Sequences (Strings, Lists and Tuples) x [ 2 ] = " cee " # s e t s l o t 2 to " cee "
p r i n t ( " Problems o p e i n g f i l e ! " )
x [ −6] = " c " # r e v e r s e the above ; n e g a t i v e
Python sequence types: # i n d i c e s work r i g h t t o l e f t
f o r l i n e in i n f i l e :
a l l _ c a p s = l i n e . upper ( )
s = [ 2 , 3 , 5 , 7 , 11 , 13] # l i s t # i t e r a t e through l i s t elements
o u t f i l e . write ( all_caps )
s = ( " one " , 2 , True ) # t u p l e ( immutable ) f o r e l t in x :
s = " abcdefgh " # string print ( elt )
i n f i l e . close ()
outfile . close ()

Operator precedence: (lowest) or; and; not; in, <, <=, >, >=, ! =, ==; +, −; ∗, /, //, %; ∗∗ (highest)

You might also like