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

Python3 Cheat Sheet - Language - V3.0

Uploaded by

Shadi Diab
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)
31 views

Python3 Cheat Sheet - Language - V3.0

Uploaded by

Shadi Diab
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

Python 3 Cheat Sheet

Comments String Concatenation Filter, Map, and Reduce


# This is a comment word1 = "Hello" from functools import reduce
word2 = "Python"
''' sentence = word1 + ", " + word2 lst = [1,2,3,4,5,6,7,8,9]
This is a
block words = evens = filter(
of ["The","quick","brown","fox", lambda x: x % 2 == 0, lst)
comments "jumps","over","the","lazy", print(evens) # [2, 4, 6, 8]
''' "dog"]
print(' '.join(words)) squares = map(lambda x: x ** 2, lst)
""" print(', '.join(words)) print(squares) # [1, 4, 9,
This is another # 16, 25, 36,
block # 49, 64, 81]
of Getting Inputs
comments total = reduce(
""" name = input( lambda s, x: s + x, lst)
"What is your name?") print(total) # 45
year_born = input(
Strings "Enter your year born: ")
Exceptions Handling
# use single or double quotes current = 2018
str_1 = "This is a string" my_age = current - int(year_born) try:
str_2 = 'This is another string' # need to convert string to int a = input('Enter first num: ')
b = input('Enter second num: ')
result = a/b
Length of Strings Defining Function except ZeroDivisionError as e:
print(e)
length = str(len(str_1)) def do_something(): except: # catch all exceptions
print("In do_something()") e = sys.exc_info()[0]
print(e)
Special Characters else: # no exception
Calling Function print(result)
print("Col 1\tCol 2\tCol 3") finally: # do this regardless of
print("Line 1\nLine 2\nLine 3") do_something() # exception or not
print("End of program")
path_1 = "c:\\windows\\"
sentence_1 = Function with Parameters
'He\'s allergic to cats' Raising Exceptions
def add_nums(x,y):
return x+y def perform_division(a,b):
Multi-lines if b == 0:
print(add_nums(5,6)) # 11 raise ZeroDivisionError
long_str = """This is a long print(add_nums(y = 6,x = 5)) # 11 return a/b
long
long
string""" Optional Parameters try:
result = perform_division(5/0)
except ZeroDivisionError as e:
def merge(lst, spacer=" "): print(e)
Raw String s = ""
for item in lst:
raw1 = s = s + str(item) + spacer Lists
r"The \n is the newline character" return s
int_list = [1,2,3,4,5]
list1 = [1,2,3,4,5] mix_list = [3.14, 5, "Hello"]
String Formatting print(merge(list1)) list_of_list = [int_list, mix_list]
print(merge(list1,"-"))
fname = "Wei-Meng" print(merge(list1, spacer = "*")) print(len(int_list)) # 5
lname = "Lee" print(merge(spacer = "*", print(len(mix_list)) # 3
lst = list1)) print(len(list_of_list)) # 2
print("%s %s" %(fname, lname))
# Wei-Meng Lee
Global Variable print(int_list[0])
print(int_list[1])
# 1
# 2
print("%s %s" %(lname, fname))
# Lee Wei-Meng count = 0
def addcounter(): Inserting and Removing
print("{} {}" .format(fname, lname)) global count
# Wei-Meng Lee count = count + 1 Items
print("{0} {1}" .format(fname,
lname)) Lambda Functions # insert 9 into index 3
int_list.insert(3, 9)
# Wei-Meng Lee print(int_list)
def square(n): # [1, 2, 3, 9, 4, 5]
print("{1} {0}" .format(fname, return n**2
lname)) # insert 8 into index 20; appended
# Lee Wei-Meng print(square(5)) # 25 # to the end instead
int_list.insert(20, 8)
print(f"{fname} {lname}") g = lambda n: n**2 print(int_list)
# Wei-Meng Lee print(g(5)) # 25 # [1, 2, 3, 9, 4, 5, 8]

# remove element at index 3


n = int_list.pop(3)
print(n) # 9
print(int_list)
# [1, 2, 3, 4, 5, 8]

# error; pop index out of range


n = int_list.pop(20)
V2.0 © Wei-Meng Lee , Developer Learning Solutions, http://www.learn2develop.net All rights reserved.
Ranging List Comprehension While Loop
r = range(5) # r is [0,1,2,3,4] nums = [1,2,3,4,5] max = 10
print(r[0]) # 0 cubes = [n ** 3 for n in nums] count = 1
print(r[-1] # 4; -1 is for last print(cubes) while (count <= max):
# element ''' print(count) # prints 1 to 10
print(r[-2]) # 3; -2 is for second [1, 8, 27, 64, 125] count += 1
# last element '''

even_cubes = [ n ** 3 for n in nums Tuples


Slicing if n % 2 == 0 ]
print(even_cubes) pt_a = (7,8)
print(r[-2:]) # [3,4]; second last ''' pt_b = 3,4
# element onwards [8, 64] print(pt_a) # (7, 8)
print(r[:3]) # [0,1,2]; first 3 ''' print(pt_b) # (3, 4)
# element
print(r[1:3]) # [1,2]; index 1 and pt_a[1] = 7 # Error
# up to before 3 Making Decisions
print(r[1:-1]) # [1,2,3]; without
# the first and last raining = True Dictionaries
print(r[2:-2]) windy = False
heights = {}
x = r[:] # make a copy of r if raining: heights = { "john": 176,
print(x) # [0,1,2,3,4] print("Wet!!!") "peter": 158,
"susan":170
if not raining:
Membership print("Dry!!!")
}
print(heights["peter"])
print(heights["jack"]) # Error
two_in_list = 2 in r if raining and windy:
nine_in_list = 9 in r print("Cold!!!") heights["mary"] = 168
print(heights["mary"])
print(two_in_list) # True if raining or windy:
print(nine_in_list) # False print("Cool!!")
Dictionary Membership
List Concatenation Comparison have_john = "john" in heights
have_jack = "jack" in heights
r.extend([5,6]) your_age = 30
print(r) # [0, 1, 2, 3, 4, my_age = 35 print(have_john) # True
# 5, 6] print(have_jack) # False
s = r + [7,8,9] if my_age > your_age:
print(s) # [0, 1, 2, 3, 4, print("I am older than you!")
# 5, 6, 7, 8, 9] elif my_age < your_age: Sets
s.append(10) print("You are older than me!")
print(s) # [0, 1, 2, 3, 4, else: items = set()
# 5, 6, 7, 8, 9, print("We are both as old!") items.add("Apple")
# 10] items.add("Orange")
if (your_age == 100): items.add(1)
List Unpacking print("You are a centenarian!")
items.add("Durian")
if (your_age != 100): items.remove("Durian")
scores = [70,55,90] print("You are not a
math, science, english = scores centenarian!")

print("math: %d" %math)


# math: 70 Ternary Condition
print("science: %d" %science) num = 5
# science: 55 parity =
"even" if num % 2 == 0 else "odd"
print("english: %d" %english) print(parity)
# english: 90

_, _, english = scores For Loop


# only interested in english
print("english: %d" %english) for x in range(1, 15, 2):
# english: 90 print(x) # prints 1 3 5 7 9
# 11 13
Enumerating a List for x in range(10):
print(x) # prints 0 to 9
seasons = ['Spring', 'Summer',
'Fall', 'Winter']
for i, season in enumerate(seasons): Break
print(i, season)
for x in range (10):
for i, season in enumerate(seasons, print(x) # prints 0 to 5
start=1): if (x == 5):
print(i, season) break

Continue
for x in range (10):
if (x == 5):
continue
print(x) # prints 0 to 9,
# excluding 5

V2.0 © Wei-Meng Lee , Developer Learning Solutions, http://www.learn2develop.net All rights reserved.

You might also like