Py Fun Pre
Py Fun Pre
f = 0
print(f)
# re-declaring the variable works
f = 'guru99‘
print(f)
Keywords in python 3
print() Function
The print() function is used to output text, numbers, or other printable information to the
console.
It takes one or more arguments and will output each of the arguments to the console separated
by a space. If no arguments are provided, the print() function will output a blank line.
print("Hello World!")
print(100)
pi = 3.14159
print(pi)
Strings
A string is a sequence of characters (letters, numbers, whitespace or punctuation) enclosed by
quotation marks. It can be enclosed using either the double quotation mark " or the single
quotation mark '.
If a string has to be broken into multiple lines, the backslash character \ can be used to indicate
that the string continues on the next line.
Variables
A variable is used to store data that will be used by the program. This data can be a number, a
string, a Boolean, a list or some other data type. Every variable has a name which can consist
of letters, numbers, and the underscore character _.
The equal sign = is used to assign a value to a variable. After the initial assignment is made,
the value of a variable can be updated to new values as needed.
Modulo Operator %
A modulo calculation returns the remainder of # Modulo operations
a division between the first and second number.
For example: zero = 8 % 4
The result of the expression 4 % 2 would result
in the value 0, because 4 is evenly divisible by nonzero = 12 % 5
2 leaving no remainder.
The result of the expression 7 % 3 would return
1, because 7 is not evenly divisible by 3,
leaving a remainder of 1.
String Concatenation
Python supports the joining (concatenation)
of strings together using the + operator. #String concatenation
The + operator is also used for mathematical first = "Hello "
second = "World"
addition operations. If the parameters passed
result = first + second
to the + operator are strings, then long_result = first + second + "!"
concatenation will be performed. If the
parameter passed to + have different types,
then Python will report an error condition.
Multiple variables or literal strings can be
joined together using the + operator.
Plus-Equals Operator +=
The plus-equals operator += provides a convenient way to add a value to an existing variable
and assign the new value back to the same variable. In the case where the variable and the
value are strings, this operator performs string concatenation instead of addition.
The operation is performed in-place, meaning that any other variable which points to the
variable being updated will also be updated.
#Plus-Equal Operator
counter = 0
counter += 10 # This is equivalent to counter = 0
counter = counter + 10 #The operator will also perform string concatenation
message = "Part 1 of message"
message += "Part 2 of message"
Functions
Some tasks need to be performed multiple times within a program. Rather than rewrite the
same code in multiple places, a function may be defined using the def keyword. Function
definitions may include parameters, providing data input to the function.
Functions may return a value using the return keyword followed by the value to return.
print(my_function(2)) # Output: 3
print(my_function(3 + 5)) # Output: 9
Calling Functions
Python uses simple syntax to use, invoke, or call a preexisting function. A function can be
called by writing the name of it, followed by parentheses.
For example, the code provided would call the doHomework() method.
doHomework()
Function Indentation
Python uses indentation to identify blocks of code. Code within the same block should be
indented at the same level. A Python function is one type of code block. All code under a
function declaration should be indented to identify it as part of the function. There can be
additional indentation within a function to handle other statements such as for and if so long
as the lines are not indented less than the first line of the function code.
#Indentation is used to identify code blocks
def testfunction(number): # This code is part of testfunction
print("Inside the testfunction")
sum = 0
for x in range(number):
# More indentation because 'for' has a code block
# but still part of the function
sum += x
return sum
print("This is not part of testfunction")
Function Parameters
Sometimes functions require input to provide data for their code. This input is defined
using parameters.
Parameters are variables that are defined in the function definition. They are assigned the
values which were passed as arguments when the function was called, elsewhere in the code.
For example, the function definition defines parameters for a character, a setting, and a skill,
which are used as inputs to write the first sentence of a book.
Multiple Parameters
Python functions can have multiple parameters. Just as you wouldn’t go to school without
both a backpack and a pencil case, functions may also need more than one input to carry out
their operations.
To define a function with multiple parameters, parameter names are placed one after
another, separated by commas, within the parentheses of the function definition.
findvolume(1, 2, 3)
findvolume(length=5, depth=2, width=4)
findvolume(2, depth=3, width=4)
Returning Value from Function
A return keyword is used to return a value from a Python function. The value returned from a
function can be assigned to a variable which can then be used in the program.
In the example, the function check_leap_year returns a string which indicates if the passed
parameter is a leap year or not.
def check_leap_year(year):
if year % 4 == 0:
return str(year) + " is a leap year."
else:
return str(year) + " is not a leap year."
year_to_check = 2018
returned_value = check_leap_year(year_to_check)
print(returned_value) # 2018 is not a leap year.
Returning Multiple Values
Python functions are able to return multiple values using one return statement. All values that
should be returned are listed after the return keyword and are separated by commas.
In the example, the function square_point() returns x_squared, y_squared, and z_squared.
def my_function(value):
print(value)
a = "Hello"
def prints_a():
print(a)
prints_a()
The Scope of Variables
In Python, a variable defined inside a function is called a local variable. It cannot be used
outside of the scope of the function, and attempting to do so without defining the variable
outside of the function will cause an error.
In the example, the variable a is defined both inside and outside of the function. When the
function f1() is implemented, a is printed as 2 because it is locally defined to be so. However,
when printing a outside of the function, a is printed as 5 because it is implemented outside of
the scope of the function.
a = 5
def f1():
a = 2
print(a)
c = '2'
d = 2
if c == d:
print('They are equal')
else:
print('They are not equal')
Not Equals Operator !=
The Python not equals operator, !=, is used to compare two values, variables or expressions to
determine if they are NOT the same. If they are NOT the same, the operator returns True. If
they are the same, then it returns False.
The operator takes the data type into account when making the comparison so a value
of 10 would NOT be equal to the string value "10" and the operator would return True. If
expressions are used, then they are evaluated to a value of True or False before the comparison
is made by the operator.
val1 = 10
val2 = 20
if val1 != val2:
print("They are NOT equal")
a = 2
b = 3
a < b # evaluates to True
a > b # evaluates to False
a >= b # evaluates to False
a <= b # evaluates to True
a <= a # evaluates to True
and Operator
The Python and operator performs a Boolean True and True # Evaluates to True
comparison between two Boolean values,
True and False # Evaluates to False
variables, or expressions. If both sides of the
operator evaluate to True then False and False # Evaluates to False
the and operator returns True. If either side
(or both sides) evaluates to False, then 1 == 1 and 1 < 2 # Evaluates to True
the and operator returns False. A non-
Boolean value (or variable that stores a value) 1 < 2 and 3 < 1 # Evaluates to False
will always evaluate to True when used with
"Yes" and 100 # Evaluates to True
the and operator.
if Statement
The Python if statement is used to # if Statement
determine the execution of code based
on the evaluation of a Boolean test_value = 100
expression. if test_value > 1:
If the if statement expression evaluates # Expression evaluates to True
to True, then the indented code print("This code is executed!")
following the statement is executed.
if test_value > 1000:
If the expression evaluates # Expression evaluates to False
to False then the indented code print("This code is NOT executed!")
following the if statement is skipped and
the program executes the next line of print("Program continues at this point.")
code which is indented at the same level
as the if statement.
else Statement # else Statement
The Python else statement provides test_value = 50
alternate code to execute if the expression if test_value < 1:
in an if statement evaluates to False. print("Value is < 1")
The indented code for the if statement is else:
executed if the expression evaluates print("Value is >= 1")
to True. The indented code immediately
following the else is executed only if the test_string = "VALID"
expression evaluates to False. To mark the if test_string == "NOT_VALID":
end of the else block, the code must be print("String equals
unintended to the same level as the NOT_VALID")
starting if line. else: print("String equals
something else!")
Boolean Values
Booleans are a data type in Python, much like
integers, floats, and strings. However, is_true = True
booleans only have two values: is_false = False
True
False print(type(is_true)) # will
Specifically, these two values are of output: <class 'bool'>
the bool type. Since booleans are a data type,
creating a variable that holds a boolean value
is the same as with other data types.
elif Statement
The Python elif statement allows for continued checks to be performed after an
initial if statement. An elif statement differs from the else statement because another
expression is provided to be checked, just as with the initial if statement.
If the expression is True, the indented code following the elif is executed. If the
expression evaluates to False, the code can continue to an optional else statement.
Multiple elif statements can be used following an initial if to perform a series of checks.
Once an elif expression evaluates to True, no further elif statements are executed.
# elif Statement
pet_type = "fish"
if pet_type == "dog":
print("You have a dog.")
elif pet_type == "cat":
print("You have a cat.")
elif pet_type == "fish":
# this is performed
print("You have a fish")
else:
print("Not sure!")
Handling Exceptions in Python
A try and except block can be used to handle error in code block. Code which may raise an error
can be written in the try block. During execution, if that code block raises an error, the rest of
the try block will cease executing and the except code block will execute.
def check_leap_year(year):
is_leap_year = False
if year % 4 == 0:
is_leap_year = True
try:
check_leap_year(2018)
print(is_leap_year) # The variable is_leap_year is declared inside
the function
except:
print('Your code raised an error!')
Lists
In Python, lists are ordered collections of items that
allow for easy use of a set of data.
primes = [2, 3, 5, 7, 11]
List values are placed in between square
brackets [ ], separated by commas. It is good
print(primes)
practice to put a space between the comma and the
empty_list = []
next value. The values in a list do not need to be
unique (the same value can be repeated).
Empty lists do not contain any values within the
square brackets.
# Result:
['cake', 'cookie', 'bread', 'biscuit', 'tart']
Determining List Length with len()
The Python len() function can be used to determine the number of items found in the list it
accepts as an argument.
# Output: 5
Zero-Indexing
In Python, list index begins at zero and ends at the length of the list minus one. For example, in
this list, 'Andy' is found at index 2.
names = ['Roger', 'Rafael', 'Andy', 'Novak']
List Indices
Python list elements are ordered by index, a number referring to their placement in the list. List
indices start at 0 and increment by one.
To access a list element by index, square bracket notation is used: list[index].
exampleList = [4, 2, 1, 3]
exampleList.sort()
print(exampleList)
# Output: [1, 2, 3, 4]
sorted() Function
The Python sorted() function accepts a list as an argument, and will return a new, sorted list
containing the same elements as the original. Numerical lists will be sorted in ascending order,
and lists of Strings will be sorted into alphabetical order. It does not modify the original,
unsorted list.
unsortedList = [4, 2, 1, 3]
sortedList = sorted(unsortedList)
print(sortedList)
# Output: [1, 2, 3, 4]
Python For Loop
A Python for loop can be used to iterate for <temporary variable> in <list variable>:
over a list of items and perform a set of <action statement>
actions on each item. The syntax of <action statement>
a for loop consists of assigning a #each num in nums will be printed below
temporary value to a variable on each
successive iteration. nums = [1,2,3,4,5]
for num in nums:
When writing a for loop, remember to
print(num)
properly indent each action, otherwise
an IndentationError will result.