<jupyter_start><jupyter_text>**Type Conversions**
***int to float***<jupyter_code># convert int to float
x = 3 # int
print(x)
print(type(x))

y = float(x)
print(y)
print(type(y))<jupyter_output>3
<class 'int'>
3.0
<class 'float'><jupyter_text>***float into int***<jupyter_code># convert float to int
y  = 3.142 # float
print(y)
print(type(y))

z = int(y)
print(z)
print(type(z))<jupyter_output>3.142
<class 'float'>
3
<class 'int'><jupyter_text>***string to int***<jupyter_code># convert string into int
x = '50' # string
print(x)
print(type(x))

y = int(x) # converting x to int
print(y)
print(type(y))<jupyter_output>50
<class 'str'>
50
<class 'int'><jupyter_text>***int to string***<jupyter_code># convert int to string
x = 2020
print(x)
print(type(x))

y = str(x)
print(y)
print(type(y))<jupyter_output>2020
<class 'int'>
2020
<class 'str'><jupyter_text>***string to float***<jupyter_code># convert str to float
x = '3.14'
print(x)
print(type(x))

y = float(x) # converting x to float
print(y)
print(type(y))<jupyter_output>3.14
<class 'str'>
3.14
<class 'float'><jupyter_text>***float to string***<jupyter_code># convert float to string
x = 3.14
print(x)
print(type(x))

y = str(x)
print(y)
print(type(y))<jupyter_output>3.14
<class 'float'>
3.14
<class 'str'><jupyter_text>***List to tuple***<jupyter_code># convert list to tuple
new_list = [3,7,20, '@', 'TECH I.S', 'makes learning fun!']
print(new_list)
print(type(new_list))

new_tuple = tuple(new_list)
print(new_tuple)
print(type(new_tuple))<jupyter_output>[3, 7, 20, '@', 'TECH I.S', 'makes learning fun!']
<class 'list'>
(3, 7, 20, '@', 'TECH I.S', 'makes learning fun!')
<class 'tuple'><jupyter_text>***tuple to list***<jupyter_code># convert tuple to list
new_tuple = 4,1,45,92,31,60,84
print(new_tuple)
print(type(new_tuple))

new_list = list(new_tuple) # converting new_tuple to new_list
print(new_list)
print(type(new_list))<jupyter_output>(4, 1, 45, 92, 31, 60, 84)
<class 'tuple'>
[4, 1, 45, 92, 31, 60, 84]
<class 'list'><jupyter_text>***List to set***<jupyter_code># define list
new_list = ['olivia', 'kaseem', 'caleb', 'olivia', 'owen', 'olivia']
print(new_list)
print(type(new_list))

# convert to set
new_set = set(new_list) # extracts only the unique values
print(new_set)
print(type(new_set))<jupyter_output>['olivia', 'kaseem', 'caleb', 'olivia', 'owen', 'olivia']
<class 'list'>
{'kaseem', 'caleb', 'owen', 'olivia'}
<class 'set'><jupyter_text>***set to list***<jupyter_code># define a set
new_set = {'kaseem', 'olivia', 'caleb', 'owen'}
print(new_set)
print(type(new_set))

# convert this set to a list
new_list = list(new_set)
print(new_list)
print(type(new_list))<jupyter_output>{'kaseem', 'caleb', 'owen', 'olivia'}
<class 'set'>
['kaseem', 'caleb', 'owen', 'olivia']
<class 'list'><jupyter_text>**Flow Control**
**if... elif... else...**
* if, elif and else keywords are used to make decisions
 * executes different blocks of code based on certain conditions
* comparison operators and logical operators can be used to specify these conditions<jupyter_code># 'if' conditional
x = 5
y = 5

if x == y:
  print('x and y are equal')
# 'if' conditional
x = 5
y = 6

if x == y:
  print('x and y are equal')
# no output because x and y are not equal
# 'if...else...' conditional
x = 5
y = 6

if x == y:
  print('x and y are equal')
else:
  print('x and y are not equal')
# 'if...elif...else...' conditional
x = 6
y = 3

if x == y:
  print('x and y are equal')
elif x < y:
  print('x is smaller')
else:
  print('y is smaller')<jupyter_output>y is smaller<jupyter_text>**single line if...else...**
* use if and else in a single line as shown below<jupyter_code>is_single = True
message = 'You can date.' if is_single else 'You cannot date.'
print(message)<jupyter_output>You can date.<jupyter_text>**"=" vs. "=="**
* = is an assignment operator
 * is used to set values to variables
* == is a comparison operator
 * is used to compare the equality of two objects/variables
* if == is used instead of = for comparison in if statement, for instance, then a syntax error is thrown<jupyter_code># get user input for variables 'x' and 'y'
x = float(input('Enter a number for x: '))# '=' is an assignment operator
y = float(input('Enter a number for y: '))# '=' is an assignment operator

# compare values of x and y
if x == y: # '==' is a comparison operator
  print('x and y are equal') # if the equality test passed
  if y != 0:
    print('therefore x/y is ', x/y)
elif x < y:
  print('x is smaller') # if x is less than y
else:
  print('y is smaller') # if y is less than x

print('thanks')<jupyter_output>Enter a number for x: 4
Enter a number for y: 6
x is smaller
thanks<jupyter_text>**"while" loops**
* the while loop executes a block of code as long as condition is true<jupyter_code># while loop example #1 
n = 0
while n < 5:
  print(n)
  n += 1<jupyter_output>0
1
2
3
4<jupyter_text>***`"While" loop with "else" statement`***
* else can be added at the end of a while loop
* to run a piece of code when the while condition is no longer true<jupyter_code># while loop example # 2 
n = 0
while n < 5:
  print(n)
  n += 1
else:
  print('n is not less than 5 anymore')<jupyter_output>0
1
2
3
4
n is not less than 5 anymore<jupyter_text>**"for" Loops**
* for keyword is used along with in memebership query keyword to loop over strings, lists, tuple, and dictionaries ***`for... in range()`***

* for can be used with in and range() to generate numbers<jupyter_code>for n in range(5):
  print(n)
for n in range(2,6):
  print(n)
for x in range(2, 30 , 3):
  print(x)<jupyter_output>2
5
8
11
14
17
20
23
26
29<jupyter_text>***`"for" loops with strings`***
* for loops can be used to loop over strings<jupyter_code>text = "TECH I.S."
for letter in text:
  print(letter)<jupyter_output>T
E
C
H
 
I
.
S
.<jupyter_text>***`"for" loop can be used with data types like lists, tuples, sets and dictionaries`***<jupyter_code># define a list
fruits_list = ['apple', 'banana', 'cherry']

# run a for loop to print the elements of the list
for fruit in fruits_list:
  print(fruit)
# define a tuple
animals_list = 'dog', 'cat', 'elephant', 'otter'

# run a for loop to print the elements of the tuple
for animal in animals_list:
  print(animal)
# define a set
names = {'oilivia', 'caleb', 'kaseem'}

# loop over the set with for
for name in names:
  print(name)
# define a dictionary
translations = {'a':1, 'b':2, 'c': 3}

# loop over the dictionary

# keys:
for entry in translations:
  print(entry)

# values
for entry in translations.values():
  print(entry)<jupyter_output>a
b
c
1
2
3<jupyter_text>***List comprehension***
* for loops can be written in a single line in python
 * using list comprehension<jupyter_code># create a new list of powers of 0 to 9
powers = [num**2 for num in range(10)] # a for loop defined with list comprehension

print(powers)<jupyter_output>[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]<jupyter_text>***generator object***
* is not explicitly executed at creation
* the formula (expression) for creating values is stored inside the generator
* the values are accessed with the next function<jupyter_code># create a generator object with powers of 0 to 9
powers = (num**2 for num in range(10))
print(powers)

next(powers) # call trhe first value in the generator
next(powers)
next(powers)
next(powers)
next(powers)<jupyter_output><empty_output><jupyter_text>***`nested "for" loops`***
* for loops can be nested to achieve looping over multiple lists<jupyter_code>adjectives = ['juicy', 'big', 'tasty'] # list 1
fruits = ['apple', 'bananas', 'oranges'] # list 2

for fruit in fruits:
  for adjective in adjectives:
    print(adjective, fruit)<jupyter_output>juicy apple
big apple
tasty apple
juicy bananas
big bananas
tasty bananas
juicy oranges
big oranges
tasty oranges<jupyter_text>***`"Break" statement`***
* stops a while loop even if the while condition is true<jupyter_code>n = 0
while n < 6:
  print(n)
  if n == 3:
    break # break loop when it is equal to 3
  n += 1<jupyter_output>0
1
2
3<jupyter_text>* stops a for loop before it has looped through all the items<jupyter_code>fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
  print(fruit)
  if fruit == 'banana':
    break # break loop after printing banana<jupyter_output>apple
banana<jupyter_text>**`"continue" statement`**
* the continue statement stops the current iteration, and continues with the next<jupyter_code>n = 0
while n < 6:
  n += 1
  if n == 3: # skip 3
    continue
  print(n)
fruits = ['apple', 'banana', 'cherry']
for x in fruits:
  if x == 'banana': # skips banana
    continue
  print(x)<jupyter_output>apple
cherry<jupyter_text>**Indentation**
* matters in Python
* blocks of codes are denoted by indentation
* if ..., while and for code examples above shows how indentation works
 * the codes below if, elif and else are indented
 * the code below while is indented
 * the code below for is indented
* nested indentations:
 * when while, for and if statements are nested within each other, the code has to be further indented
  **`"for" and "while" loops`**
* choosing the right loop type makes your code more legible and can also help prevent bugs
* everything that can be written with a for loop can be written with a while loop, but while loops can solve problems that for loops don't address easily
* you should usually write for loops when possible; use for loops when
 * you know the number of iterations you need to do e.g., 500 trials,
 * one operation per character in a string, or
 * an action on every element in a list
* if you can describe the problem you are trying to solve in terms of each or every element in an iterable object, aim for a for loop.
* benefits of a for loop:
 * using a for loop when possible will decrease the rist of writing an infite loop
 * will generally prevent you from running into errors with incrementing counter variables  **Exception Handling**
* exception handling block framework
```
try:
...
except:
...
finally:
...
```
* try block:
 * lets you test ablock of code for errors
* except block:
 * lets you set the respose to an error
* finally block:
 * execute code regardless of the outcome of the try-except block ***Exception Handling Examples***<jupyter_code># setup an error handling block
try:
  print(x_val) # without defining x_val before, we try to print the value of x_val
except:
  print('An exception occured')

'''
here, since the try block code throws an error because of x_val not being
defined, the except bock is excecuted # let's try this without a try block
'''
print(x_val)# this raises a name error
# multiple exception handling
try:
  print(x_val)
except NameError: # exceotion handling # 1
  print('x_val is not defined')
except:
  print('something else went wrong')
# `finally` block example #1
try:
  print(x)
except:# this excecutes if the try block has an error
  print('something went wrong')
finally:# this is excecuted wether an error is raised or not
  print("The 'try except' is finished")<jupyter_output>cherry
The 'try except' is finished<jupyter_text>***finally block example 2***<jupyter_code>try:
  f = open("file.txt")# open a file that exists, nut with no write permission
  f.write("text to write")# try to write to file
except:# respond to error
  print("Something went wrong when writing to file")
finally: # this will run regardless
  f.close()<jupyter_output>Something went wrong when writing to file<jupyter_text>***raise() keyword***
* you can generate a custom error if an exception occurs
 * this is done with the raise key word<jupyter_code># raise exception example # 1
x = -1

if x < 0:
  raise Exception("Sorry! number below zero!") 
# raise exception example #2
# you can choose the specific type of Exception to raise
x  = "Hello"

if not type(x) is int:
  raise TypeError("Only integers are allowed!")<jupyter_output><empty_output><jupyter_text>**Functions**
* functions are reusable pieces of code
* they only run when called
* they make input arguments
* they may return prosessed values
* `def` key word is used at the begining of a functionto start defining
a function
* return keyword is used to send some value back after processing<jupyter_code># define function to calculate area of a circle
# input argument is radius

def area_circle(radius):

  area = (22.0/7.0) * radius**2
  return area
print(area_circle(5))<jupyter_output>78.57142857142857<jupyter_text>**Scope**
* a variable is only available from inside the region it is created
 * this is called *scope* **Local Scope**
* a variable created inside function belongs to the local scope of that function
 * and can only be used inside that function<jupyter_code>def myfunc():
  inside_variable = 300 # inside_variable is avilable only inside myfunc() and not accessible outside
  print(inside_variable)

myfunc() # call the function myfunc()
print(inside_variable)#throws error<jupyter_output>300<jupyter_text>* however, the local variable can be accessed from a function within
the function<jupyter_code>def myfunc():
  inside_variable = 300
  def myinnerfunc():# this is the inner function
    print(inside_variable) # this line accesses the inside_variable

  myinnerfunc() # call the function myinnerfunc()

myfunc() # call the function myfunc()

print(inside_variable) # but this still throws error<jupyter_output>300<jupyter_text>**Global Scope**
* a variable created in the main body of the Python code is a global
variable and belongs to global scope.
* global variables are variable from within any scope, global and local<jupyter_code>outer_variable = 300

def myfunc():
  print(outer_variable)

myfunc()

print(outer_variable)<jupyter_output>300
300<jupyter_text>***`"global" keyword`***
* if you need to create a global variable, but are stuck in the local scope, you can use the `global` keyword
* the global keyword makes the variable global.<jupyter_code>def myfunc():
  global global_variable
  global_variable = 300
  print(global_variable)

myfunc()

print(global_variable)<jupyter_output>300
300<jupyter_text>**Lambda**
* is a small anonymous function
* can take any number of arguments, but can only have one expression
* syntax: lambda arguments: expression<jupyter_code># lambda function example #1
plus_ten = lambda x : x + 10
print(plus_ten(5))
# lambda function example #2
multiply = lambda a, b: a*b
print(multiply(5, 6))
# lambda function example #3:
triple_sum = lambda a,b,c: a+b+c
print(triple_sum(1,2,3))<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup