33 2 263KB
String “string”.title() :1st litter is capital , note : title() and other () come after “.”,is method “string”.upper() : all litters is capital “string”.lower() : all litters is small F” sring {string} {string} string” : called f-string method , earlier method was (var=”{} {}”.format (1st string, 2nd string,…)) “\n” : add new line to text “\t” : add tab to text “\n\t” : move to a new line, and start the next line with a tab “string”.strip() : to eliminate the whitespace before & after string, .rstrip() for right whitespace & .lstrip() for left whitespace
Number : Note : you can writing long numbers in Python prog. using underscores to make large numbers more readable ‘universe_age = 14_000_000_000’ when you print, python will prints only the digits : 14000000000 Note : divide int number. on int number will give float number
Multiple assignment : x,y,z =0,0,0
List : list name(lstn)=[‘string’,’string’,…’last’] : In Python, square brackets( [ ] )indicate a list lstn[index] : access any element in a list by telling Python the position, or index, of the item desired. 1st item in list has index 0 and cont. , also may use last item index from -1 ,-2,… to 1st item lstn[index].method : you can use same method above in string as title() , upper(), lower() , … Note : to print all list item, print(lstn) _ to print individual item in list, print(lstn[index]) lstn[index]=’string’ : to change an element in list with same index 1
lstn.append(‘string’) : to add new element at the end of list lstn=[ ] : to create new empty list lstn.inser(index,‘string’) : to add a new element at any position in list del lstn[index] lstn.pop()
: to remove an item or a set of items from a list.
: to removes the last item in a list and isolate the removed item in pop()
lstn.pop(index) : to remove an item from any position in a list and isolate the removed item in pop(index) lstn.remove(“string”) : to remove an item by value Note : The remove() method deletes only the first occurrence of the value you specify. If there’s a possibility the value appears more than once in the list, you’ll need to use a loop to make sure all occurrences of the value are removed
lstn.sort()
: to sort a list alphabetical permanently
lstn.sort(reverse=True) : to sort a list permanently in reverse alphabetical (from Z to A) sorted(lstn) : to sort a list temporarily sorted(lstn,reverse=True) : to sort a list temporarily lstn.reverse() len(lstn)
: To reverse the original order of a list
: to get the length of list (no. of element in list)
rule : to read all items in list, must doing loop: this known as “for item in list_of_items:” for item in lstn: # read from list ‘listn’ print (item)
# printing
Making Numerical Lists:
Method1: Using the range() Function , ex for value in range(1, 5) # 5 not include in value range print(value)
result : 1,2,3,4 (vertically) Method2: Using range() to Make a List of Numbers , lstn=lsit(range(1st number ,last number, increment)
2
Ex1 : numbers = list(range(1, 6)) print(numbers)
result : [1, 2, 3, 4, 5] Ex2 : squares = [] for value in range(1, 11): square = value ** 2 squares.append(square) print(squares)
result : [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Ex3 : List comprehension (give same result of above ex but in few lines) squares = [value**2 for value in range(1, 11)] print(squares) Some of Simple Statistics with a List of Numbers :
min(lstn) : give min value in list max(lstn) : give max value in list sum(lstn) : give sum of list values
Working with Part of a List: * Slicing a List : ex players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) res : ['charles', 'martina', 'michael']
note : -Without a starting index, Python starts at the beginning of the list players[0:3] = players[ :3] -Without ending index, Python return all items from stating index to end of the list players[1: ] = players[1:3] * Looping Through a Slice : explayers = ['charles', 'martina', 'michael', 'florence', 'eli'] for player in players[:3]: print(player.title()) res : Charles Martina Michael * Copying a List , by using [ : ] my_foods = ['pizza', 'falafel', 'carrot cake'] 3
friend_foods = my_foods[:] print(my_foods) print(friend_foods) res : ['pizza', 'falafel', 'carrot cake'] ['pizza', 'falafel', 'carrot cake']
Tuples : Python refers to values that cannot change as immutable, and an immutable list is called a tuple. A tuple looks just like a list except you use parentheses ( ) instead of square brackets ,EX – dimensions = (200, 50) print(dimensions[0]) , res : 200
* Looping Through All Values in a Tuple : dimensions = (200, 50) for dimension in dimensions: print(dimension) res : 200 , 50 * Writing over a Tuple : dimensions = (200, 50) dimensions = (400, 100) for dimension in dimensions: print(dimension) res : 400 , 100
Note :
car = 'Audi' car == 'audi', False
to Ignore the Case When Checking for Equality : car = 'Audi' car.lower() == 'audi', True
Dictionaries :
A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key.
alien = {'color': 'green', 'points': 5} print(alien ['color']) print(alien ['points'])---} green , 5
Adding New Key-Value Pairs alien= {'color': 'green', 'points': 5} print(alien_0) alien['x_position'] = 0 alien['y_position'] = 25 4
print(alien) ---}
{'color': 'green', 'points': 5} {'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}
Starting with an Empty Dictionary alien= { }
Modifying Values in a Dictionary
alien= {'color': 'green'} alien ['color'] = 'yellow' print(alien) ---} {'color': 'yellow'} Removing Key-Value Pairs alien= {'color': 'green', 'points': 5} del alien ['points'] print(alien) ---} {'color': 'green'}
Note : you can write dictionary in multiline :
{ …… ……}
Using get() to Access Values you can use the get( ) method to set a default value that will be returned if the requested key doesn’t exist alien={'color': 'green', 'speed': 'slow'} value = alien.get('points', 'No point value assigned.') print(value) ---} No point value assigned.
Looping Through a Dictionary a- Looping Through All Key-Value Pairs, by using dictionary.items() dic={'nazar':1975,'amjad':1976,"hatam":1984,'ahmed':1986 } for k,v in dic.items() : print(f"{k.tilte()} : {v.title()}") b- Looping Through All the Keys in a Dictionary,by using dictionary.keys() for k in dic.keys() :print(k) c- Looping Through a Dictionary’s Keys in a Particular Order for k in sorted(dic.keys()) :print(k) d- Looping Through All Values in a Dictionary for v in dic.values() : print(v) Note to pull out the unique items in list that contains duplicate items we use set()
for v in set(dic.values()) Nesting : a- A List of Dictionaries prog
result
5
alien_0 = {'color': 'green', 'points': 5} alien_1 = {'color': 'yellow', 'points': 10} alien_2 = {'color': 'red', 'points': 15} aliens = [alien_0, alien_1, alien_2] for x in aliens: print(x) lst=[] # Make 30 green lst. for i in range(30): dic = {'color': 'green', 'points': 5, 'speed':'slow'} lst.append(dic) # Show the first 5 lst for i in lst[ : 5]: print(i) b- A List in a Dictionary
{'color': 'green', 'points': 5} {'color': 'yellow', 'points': 10} {'color': 'red', 'points': 15}
{'speed': 'slow', 'color': 'green', 'points': 5} {'speed': 'slow', 'color': 'green', 'points': 5} {'speed': 'slow', 'color': 'green', 'points': 5} {'speed': 'slow', 'color': 'green', 'points': 5} {'speed': 'slow', 'color': 'green', 'points': 5}
dic={ 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } for k in dic['jen']: print(f" language : {k}")
language : python language : ruby
dic={ 'jen': ['python', 'ruby'], 'sarah': ['c'], 'edward': ['ruby', 'go'], 'phil': ['python', 'haskell'], } for k,v in dic.items(): print(f" name : {k}") for i in v : print(f"language is : {i}")
name : jen language is : python language is : ruby name : sarah language is : c name : edward language is : ruby language is : go name : phil language is : python language is : haskell
c- A Dictionary in a Dictionary family={"nazar":{"first":'abody' , 'second':"sohaib"},'amar':{'first':"yosif", 'second':"aos"}}
family name : nazar his sons : abody & sohaib family name : amar his sons : yosif & aos
for name,son in family.items(): print(f 'family name : {name}') hson=f '{son["first"]} & {son["second"]}' print(f 'his sons : {hson}')
User Input and while Loops * Sometimes you’ll want to write a prompt that’s longer than one line , ex. prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name? "
6
name = input(prompt) print(f"\nHello, {name}!")
---} If you tell us who you are, we can personalize the messages you see. What is your first name? Eric Hello, Eric!
While Loop :
current_number = 1 while current_number