Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Lessons Basic Commands

The document provides an overview of common Python functions and concepts: - It describes many built-in functions in the Python standard library for tasks like math, strings, lists, loops, and boolean logic. - It also covers user-defined functions, loops (for, while), conditional statements (if/else), and lists - including common list methods for appending, inserting, removing, sorting, and converting between strings and lists. - Finally, it discusses concepts like data types, operators, slicing/substring, escape characters, and comparing values.

Uploaded by

Paul Suciu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lessons Basic Commands

The document provides an overview of common Python functions and concepts: - It describes many built-in functions in the Python standard library for tasks like math, strings, lists, loops, and boolean logic. - It also covers user-defined functions, loops (for, while), conditional statements (if/else), and lists - including common list methods for appending, inserting, removing, sorting, and converting between strings and lists. - Finally, it discusses concepts like data types, operators, slicing/substring, escape characters, and comparing values.

Uploaded by

Paul Suciu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

import math, random, string modules

Python Standard Library of Functions

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true

ascii() Returns a readable version of an object. Replaces none-ascii characters with escape
character

bool() Returns the boolean value of the specified object

chr() Returns a character from the specified Unicode code.

enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object

float() Returns a floating point number

input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified object

issubclass() Returns True if a specified class is a subclass of a specified object

len() Returns the length of an object

list() Returns a list

map() Returns the specified iterator with the specified function applied to each item

max() Returns the largest item in an iterable

min() Returns the smallest item in an iterable

next() Returns the next item in an iterable

ord() Convert an integer representing the Unicode of the specified character

pow() Returns the value of x to the power of y

print() Prints to the standard output device

property() Gets, sets, deletes a property

range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)

reversed() Returns a reversed iterator

round() Rounds a numbers

set() Returns a new set object

slice() Returns a slice object


sorted()Returns a sorted list

str() Returns a string object

sum() Sums the items of an iterator

type() Returns the type of an object

= is assign variable value, == is equal to value

Can assign variable value from another variable simply with =

variableCamel or variable_snake and CONSTANT_NAME

BODMAS (brackets, other functions, division, multiplication, addition, subtraction)

Lesson 2 and 8 Strings and Integers

Addition (Concatenation) and Multiplication (Repetition)

Can’t add or multiply to float.

String can be multiplied by number to repeat it.

Can only add string to string and num to num.

Lesson 2 (inbuilt) and 4 Functions (user defined)

Define First, Use Later

def functionName(parameter) arguments are values for parameters

statements

“”” doc “””

print, return are used to call the function

def cubeVolume(sideLength):

if sideLength < 0 : # deal with the exceptional case

return 0

else : # then deal with the usual case

return sideLength**3

Lesson 5 (for, while) and 9 Loops (nested)

Event-Controlled Loops
Collection-Controlled Loops (while / for)

Avoid infinite loops

range(start, stop, step)

It generates a sequence of integers

•start: Starting number of the sequence -- 0 by default

•stop: Generate numbers up to, but not including this number

•step: Difference between each number in the sequence -- 1 by default

Count up from 0 or down from -1 with negative steps.

Collections can be a string – a set of characters. for-loops for strings will loop through each character
in the string

Break

Used for stopping while, for loops when no if condition.

i = 1
while i <= 4:
print(i)
if i == 3:
break
i += 1

print("outside")
print(i)

Continue

Used for skipping items, without breaking the loop.

list1 = [12, 15, 32, 42, 55, 75, 122, 150, 180, 87, 102, 100]
for item in list1:
if item > 120:
continue
elif item%3 == 0:
print(item)

without continue

list1 = [12, 15, 32, 42, 55, 75, 122, 150, 180, 67, 102, 100]
for item in list1:
if item <= 120 and item%3 == 0:
print(item)
While True or Not False condition loop exit

Boolean used for infinite loops

while True:
num = int(input("Please enter a number: "))
if num%2==0 and 21<num<29:
break
print("The number is", num)

success = False
while not success:
num = int(input("Please enter a number: "))
if num%2==0 and 21<num<29:
success = True
print("The number is", num)

Nested loops

Used for tables

V height = 4

width = 7
for i in range(height): #how many rows
for j in range(1, width+1): #the numbers in each row
print(j, end=" ")
print()

#Alternative code
height = 4
width = 7

for i in range(height):
for j in range(1, width+1):
print(j, end=" ")
if j == width:
print()

F Strings

Used to simplify code and introducing {} brakets

num = 1
height = 68
width = 15
field = len(str(height*width))

for i in range(height):
for j in range(width):
print(f'{num:0{field}}', end=" ")
# at least 2 width, align to right by default
num += 1
print()

Lesson 6 and 8 Lists

Individual values within a list can be accessed using the index.

• Positive index starts from the front of the list.

• Positive index starts from 0.

• Negative index starts from the back of the list.

• Negative index starts from -1.

Length of a List

points = [32, 54, 67, 5]

print(points) # prints entire list [32, 54, 67, 5]

print(len(points)) # prints length of the list

Check if a value is in a list

guests = ['Harry', 'Ollie', 'Emily', 'Austin']


print('Harry' in guests) # returns True

Show the values in the list/ print index from position

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

for i, x in enumerate(guests, start = 1):

print(i, x)

Return index position for element of list

friends = ["Harry", "Emily", "Emily"]

n = friends.index("Emily")

# index of first occurrence: 1

Return elements from list based on various attributes

wordList = ["1", "100", "111", "2"]

maxLen = len(max(wordList, key=int))

longest = []

for word in wordList:

if len(word) == maxLen:

longest.append(word)

print(longest)

Count number of characters in list

wordList = [1, 100, 111, 2]

digitCount = 0

digit = 1

for num in wordList:

for d in str(num):

if d == str(digit):

digitCount += 1

print (digitCount)

Count string repetitions in a list

wordList = ["Ares", 100, 111, "AA"]

wordCount = 0

word = "Ares"

for item in wordList:


if str(item) == word: # Check if the item matches the word

wordCount += 1

print (wordCount)

Append elements to a list individually or an entire list

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

guests.append('Charlie')

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

friends = ['Rob', 'Fiona']

guests.append(friends)

Adding Values – extend() or +

• A better way of concatenating two lists together is to use the extend() method.

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

friends = ['Rob', 'Fiona']

guests.extend(friends)

• Another way of concatenating two lists together is to use the + operator.

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

friends = ['Rob', 'Fiona']

guests + friends

Adding Values – insert()

• The insert() method allows you to insert a value at a specified index.

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

guests.insert(1,'Charlie')

# This will return a list with the new value Charlie added in position 1.

# guests is ['Harry', 'Charlie', 'Ollie', 'Emily', 'Austin']

• All the possible indices to insert a value

guests.insert(i,'Zoe')

Removing Values – remove()

• The remove() method allows you to remove a specific value.

guests = ['Emily', 'Harry', 'Tom', 'Emily']

guests.remove('Tom')

Removing Values – pop()


The pop() method will remove the last value in the list.

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

guests.pop()

The pop(i) method will remove the value at Position i in the list.

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

guests.pop(1)

Sorting Lists – sort()

The sort() method will sort a list. By default the sort will the ascending.

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

guests.sort()

Will return the list in the order A-Z: ['Austin', 'Emily', 'Harry', 'Ollie']

• Or you can choose to sort a list in descending order.

guests = ['Harry', 'Ollie', 'Emily', 'Austin']

guests.sort(reverse=True)

Will return the list in the order Z-A: ['Ollie', 'Harry', 'Emily', 'Austin']

Print all elements in a list

stars = [3, 8, 9, 35, 0]

for i in range(len(stars)):

print(stars[i])

or

for element in stars:

print(element)

Add to list elements when printing them

guestList = ["Ann", "Betty", "Charlie"]

for guest in guestList:

print("Hello,", guest+"!")

Slicing/ substring for strings or lists

A substring or a slice is a sequence of characters within an original string


Reverse string or list

[::-1] to reverse a string

Escape Characters – The Magical Backslash \ is used to insert characters that are illegal in a string

Escape Characters – \' and \" are used to insert illegal quotes in strings.

Escape Characters – \n: new line. \n has length of 1

List to String using join()

A string method called join() can be used to turn the list into a string and joins the values together
with whatever you want.

guests = ["Harry", "Ollie", "Emily", "Austin"]


guestsStr = ", ".join(guests)
print(guestsStr)

String to List using split()

The string method split() can be used to split a string at the separator and stores each value in a
string.

guestsStr = "Harry, Ollie, Emily, Austin"


newGuestsList = guestsStr.split(', ')
print(newGuestsList)

split() and join() functions are like inverse functions, converting between strings and lists.

split(“, “) Function – Any separators can be added between (“ “), otherwise default is space

split("#", 2) – Number of Splits. The second parameter determines how many splits to do.

Lesson 3 and 7 Boolean


> >= < <= == !=

"" < " " < "0" < "1" < "9" < "A" < "B" < "Z" < "a" < "b" < "z"

A string cannot be compared to a number.

Comparing characters based on ASCII position.

All uppercase letters come before lowercase letters

Numbers come before letters

The space character comes before all printable characters

Empty string comes before all non-empty characters

and operator yields True if both Boolean values entered are True. ¼

or operator yields True if one Boolean operator is True. ¾

not changes the value of a Boolean operator from True to False and False to True

any(list) returns:

• True – if at least one item of the list is True.

• False – if all the items are False or if the list is empty

all(list) returns

• True – if all elements in the list are True

• False – if any element in the list is False

You might also like