Cs Practice
Cs Practice
if/else: if the statement is true the rst statement will be executed (if), if the statement is false, the
second statement will be executed (else)
range
start: starting number of sequence
stop: generate numbers up to but not including the stopping value
step: update/di erence between each number in the sequence
for loops
mysum = 0 (initialize)
for ? in range(x,y,z):
mysum += ?
print(mysum)
mysum=0 (initialize)
for i in range (7,10)
MYSUM += İ
print(mysum)
output=24
x=4
for i in range(x)
print(i)
output= 0,1,2,3
letters = “abcdef”
for i in range(0, len(letters)):
print(letters[i])
output=abcdef
break
immediaately exists whatever loop it is in
skips remianing expressions
break exits only containing loop
random
import random
num = random.randint(1,10)
generates a value between the two values, inclusive
ff
fi
lists
empty list: my_list = [ ]
list: my_list = [1,2,3,4,5]
display a list: print(my_list)
display the number of elements in a list: print(len(my_list))
traversing a list
for i in my_list:
appending: my_list.append(x) -> adds the element x to the end of the list
nd: my_list.index(x) -> returns the index of the rst occurrence of x in my_list
removing: my_list.pop(x) -> removes and returns the item at index x in my_list
if no index is given, it removes the last element of the list
x=[1,16,9,4]
sum(x) will give 30
max(x) will give 16
min(x) will give 1
x.sort() will make x=[1,4,9,16]
x.sort(reverse=True) will make x=[16,9,4,1]
fi
fi
fi
tuple
empty tuple: t1 = ( )
tuple with 3 values: t2 = (1,”two”,3)
print(t1)
print(t2)
display an element in a tuple: print(t2[2])
display the type of an element: print( type(t2[1]))
TUPLES ARE IMMUTABLE. CANNOT ASSIGN.
concatenation: t1 = t1 + t2
indexing: print( t1 [2] )
silcing: print(t1 [1:3])
dictionary
keys must be unique in a dictionary
dict [ key x] -> returns the value associated with a given key.
updating example:
name = input (“Enter person to update: “)
number = input (“Enter phone number: “)
if name in phone:
phone[name] = number
print (name, “updated! (“, phone [name],”)”)
else:
phone [name] = number
print (name, “added! (“, phone[name],”)”)