[go: up one dir, main page]

0% found this document useful (0 votes)
23 views14 pages

Note

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views14 pages

Note

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

GOOGLE IT AUTOMATION WITH PYTHON

COURSE 1:
MODULE 1:
I. What is Python?
 The Python interpreter is the program that reads what is in the recipe and translates it into
instructions for your computer to follow
 Python is:
 a general purpose scripting language;
 a popular language used to code a variety of applications;
 a frequently used tool for automation;
 a cross-platform compatible language;
 a beginner-friendly language.

 Python is not:
 a platform-specific / OS-specific scripting language;
 a client-side scripting language;
 a purely object-oriented programming language.

 Code comparison with Python

II. Python Resources


https://www.python.org/shell/
https://www.onlinegdb.com/online_python_interpreter
https://repl.it/languages/python3
https://www.tutorialspoint.com/execute_python3_online.php
https://rextester.com/l/python3_online_compiler
https://trinket.io/python3
III. A Note on Syntax and Code Blocks
1. Common syntax errors
 Misspellings
 Incorrect indentations
 Missing or incorrect key characters:
 Bracket types - ( curved ), [ square ], { curly }
 Quote types - "straight-double" or 'straight-single', “curly-double” or ‘curly-single’
 Block introduction characters, like colons - :
 Data type mismatches
 Missing, incorrectly used, or misplaced Python reserved words
 Using the wrong case (uppercase/lowercase) - Python is a case-sensitive language

2. Common semantic errors:


 Creating functional code, but getting unintentional output
 Poor logic structures in the design of the code

IV. Why is Python relevant to IT?


 Python scripts are easy to write, understand, and maintain.
 Python is a language that tries to mimic our natural language and so Python scripts are
generally easy to write, understand and maintain.
 There are many system administration tools built with Python.
 Over the years, the Python community has developed a lot of additional tools that can be used
by system administrators to get their job done.
 Python is available on a wide variety of platforms.
 Python is available on Windows, Linux, MacOS and even on mobile devices, making it a
great tool for IT specialists looking to create scripts that can work across platforms.

V. Other Languages
 Python does this by specifying range(10), Bash uses a sequence notation to count from 1 to 10.
PowerShell has the most complex syntax
 Example:

for i in range (10):


print ("Hello, World!")

VI. Hello, World!


 Print is a Python function that writes what we tell it to on the screen
 Functions are pieces of code that perform a unit of work
 Keywords are reserved words that are used to construct instructions
 The print function outputs messages to the screen
 Using the print() we can generate output for the user of our programs.
 Wrapping text in quotation marks indicates that the text is considered a string, which means it's
text that will be manipulated by our script
 Any text that isn't inside quotation marks is considered part of the code
Example:
print ("I'm programming in Python!")

VII. Getting Information from the User


Example:
Name = “Brook”
print (“Hello” + name)

VIII. Python Can Be Your Calculator


print (4+5)
9
Example: 210
print (2**10)
1024
Calculate (((1+2)∗3)/4)
print (((1+2)∗3)/4)
2.25

IX. Study Guide: First Programming Concepts


 Values: True, False, None
 Conditions: if, elif, else
 Logical operators: and, or, not
 Loops: for, in, while, break, continue
 Functions: def, return

1. Arithmetic operators
x+y Addition + operator returns the sum of x plus y
x–y Subtraction - operator returns the difference of x minus y
x*y Multiplication * operator returns the product of x times y
x/y Division / operator returns the quotient of x divided by y
x**e Exponent ** operator returns the result of raising x to the power of e
x**2 Square expression returns x squared
x**3 Cube expression returns x cubed
x**(1/2) Square root (½) or (0.5) fractional exponent operator returns the square root of x
x // y Floor division operator returns the integer part of the integer division of x by y
x%y Modulo operator returns the remainder part of the integer division of x by

2. Order of operations
a) Parentheses ( ), { }, [ ]
b) Exponents xe (x**e)
c) Multiplication * and Division /
d) Addition + and Subtraction –
MODULE 2:
I. Basic Python Syntax introduction
 Some basic building blocks of Python syntax, things like variables, expressions, functions, and
conditional blocks
 Syntax: How to formulate statements of code that the computer can understand

II. Explore Python syntax


1. The Language of Python
 Variables: Represent data stored as strings, tuples, dictionaries, lists, and objects (note: future
readings explain these categories)
 Keywords: Special words that are reserved for specific purposes and that can only be used for
those purposes
 in
 not
 or
 for
 while
 return

 Operators: Symbols that perform operations on objects and values


 +
 -
 *
 /
 **
 %
 //
 >
 <
 ==

 Expressions: A combination of numbers, symbols, and variables to compute and return a result
upon evaluation
 Functions: A group of related statements to perform a task and return a value
def to_celsius(x):
'''Convert Fahrenheit to Celsius'''
return (x-32) * 5/9
to_celsius(75)

 Conditional statements: Sections of code that direct program execution based on specified
conditions
number = - 4

if number > 0:
print ('Number is positive.')
elif number == 0:
print ('Number is zero.')
else:
print ('Number is negative.')

 As you’ll surely discover, Python generates syntax errors for incorrectly used keywords and
syntax.
print (This will throw an error because I didn’t make it a string.)

2. Naming rules and conventions


When assigning names to objects, programmers adhere to a set of rules and conventions which help
to standardize code and make it more accessible to everyone. Here are some naming rules and
conventions that you should know:
 Names cannot contain spaces.
 Names may be a mixture of upper and lower case characters.
 Names can’t start with a number but may contain numbers after the first character.
 Variable names and function names should be written in snake_case, which means that all letters
are lowercase and words are separated using an underscore.
 Descriptive names are better than cryptic abbreviations because they help other programmers (and
you) read and interpret your code. For example, student_name is better than sn. It may feel excessive
when you write it, but when you return to your code you’ll find it much easier to understand.

3. The Zen of Python


 Beautiful is better than ugly.
 Explicit is better than implicit.
 Simple is better than complex.
 Complex is better than complicated.
 Flat is better than nested.
 Sparse is better than dense.
 Readability counts.
 Special cases aren't special enough to break the rules.
 Although practicality beats purity.
 Errors should never pass silently.
 Unless explicitly silenced.
 In the face of ambiguity, refuse the temptation to guess.
 There should be one—and preferably only one—obvious way to do it.
 Although that way may not be obvious at first unless you're Dutch.
 Now is better than never.
 Although never is often better than *right* now.
 If the implementation is hard to explain, it's a bad idea.
 If the implementation is easy to explain, it may be a good idea.
 Namespaces are one honking great idea -- let's do more of those!

III. Data Types


 String: A data type
 An int type and an str type, which are short names for integer and string
 The message unsupported operand type: The integer seven and the string eight
Example:
print (type ("a"))
 class “str”
print (type (2))
 class “int”
print (type (2.5))
 class “float”

 Remember: Strings with strings, integers with integers, and floats with floats

IV. Data Types Recap


 String data type: Text in between quotes -- either single or double quotes
 An integer is a whole number, without a fraction
 A float is a real number that can contain a fractional part

V. Variables
 Variables: To certain values in our programs
 Assignment: The process of storing a value inside a variable
 An expression: A combination of numbers, symbols or other variables that produce a result when
evaluated
 Assign a value to a variable by using the equal sign in the form of variable equals value
 Variable naming restrictions:
 Don’t use keywords or functions that Python reserves for its own
 Don’t use spaces
 Must start with a letter or an underscore (_)
 Must be made up of only letters, numbers and underscores
Example:
 I_am_a_variable: Valid variable name.
 I_am_a_variable2: Valid variable name.
 1_is_a_number: Invalid (variable names must start with a letter or underscore)
 Apples_&_oranges: Invalid (the special character ampersand)
 Remember: precision is important when programming. Python variables are case sensitive, so
capitalization matters. Lowercasename, uppercasename and ALLCAPSNAME are all valid and
different variable names, and that rule on variables is invariable.

VI. Annotating variables by type


I. How to annotate a variable
Example: name: str = “Betty”
The variable name is declared using a colon (:) which is annotated with the type str, indicating that
the name variable should hold a string value

Example: age: int = 34


age is the variable, and int is the type annotation that provides you and other developers a hint that
the age variable should store an integer value.

2. Dynamic typing
Example: a=3 #a is an integer
a = “Hello world” #a is now a string
Dynamic typing allows programmers to write code more quickly and offers flexibility because you
don’t have to explicitly declare the type of variable.

3. Duck typing
Example: a = “Hello world” #looks like a string
Python will infer the variable type at runtime and decide which behaviors are available to the given
object.

4. Annotating variables with type comments


Example: captain = “Picard” # type: str
Another way to annotate variables is to use type comments where the interpreter will ignore the
comments.
5. Annotating variables directly
Example: captain: str = “Picard”

VII. Expressions, Numbers, and Type Conversions


 Implicit conversion: The interpreter automatically converts one data type into another
Example:
print (“a”+”b”+”c”)
 abc
print (“This “+ “is “+ “pretty “ +neat!”)
 This is pretty neat

Example:
base = 6
height = 3
area = (base * height) / 2
print (“The area of the triangle is: ” + str (area))
 The area of the triangle is: 9.0
str (area): The str () function to convert a number into a string

Example:

VIII. Study Guide: Expressions and Variables


1. Terms
 Expression: a combination of numbers, symbols, or other values that produce a result when
evaluated
 Data types: classes of data (e.g., string, int, float, boolean, etc.), which include the properties and
behaviors of instances of the data type (variables)
 Variable: an instance of a data type class, represented by a unique name within the code, that
stores changeable values of the specific data type
 Implicit conversion: when the python interpreter automatically converts one data type to another
 Explicit conversion: when code is written to manually convert one data type to another using a
data type conversion function:
 Str (): converts a value (often numeric) to a string data type
 Int (): converts a value (usually a float) to an integer data type
 Float (): converts a value (usually an integer) to a float data type

2. Variables Annotated by Type


import typing
# Define a variable of type str

z: str = "Hello, world!"


# Define a variable of type int

x: int = 10
# Define a variable of type float

y: float = 1.23
# Define a variable of type list

list_of_numbers: typing.List[int] = [1, 2, 3]


# Define a variable of type tuple

tuple_of_numbers: typing.Tuple[int, int, int] = (1, 2, 3)


# Define a variable of type dict

dictionary: typing.Dict[str, int] = {"key1": 1, "key2": 2}


# Define a variable of type set

set_of_numbers: typing.Set[int] = {1, 2, 3}


3. Coding skills
 Use the assignment operator = to assign values to variables
 Use basic arithmetic operators with variables to create expressions
 Use explicit conversion to change a data type from float to string
# The following lines assign the variable to the left of the = assignment operator with the values and
arithmetic expressions on the right side of the = assignment operator.
hotel_room = 100
tax = hotel_room * 0.08
total = hotel_room + tax
room_guests = 4
share_per_person = total/room_guests

# This line outputs the result of the final calculation stored in the variable "share_per_person"
print (“Each person needs to pay: " + str(share_per_person))
 Each person needs to pay: 27.0
# change a data type

 Output multiple string variables on a single line to form a sentence


 Use the plus (+) connector or a comma to connect strings in a print () function
 Create spaces between variables in a print () function
# The following 5 lines assign strings to a list of variables.
salutation = "Dr."
first_name = "Prisha"
middle_name = "Jai"
last_name = "Agarwal"
suffix = "Ph.D."
print (salutation + " " + first_name + " " + middle_name + " " + last_name + ", " + suffix)
 Dr. Prisha Jai Agarwal, Ph.D.
# The comma as a string ", " adds the conventional use of a comma plus a space to separate the last
name from the suffix.
# Alternatively, you could use commas in place of the + connector:
print (salutation, first_name, middle_name, last_name,",", suffix)
 Dr. Prisha Jai Agarwal , Ph.D.
# However, you will find that this produces a space before a comma within a string.

 Resolve TypeError caused by a data type mismatch issue


 Use an explicit conversion function
print ("5 * 3 = " + (5*3))

# Resolution:
print ("5 * 3 = " + str(5*3))
# To avoid a type error between the string and the integer within the print () function, you can make
an explicit data type conversion by using the str () function to convert the integer to a string.

Resolve a ZeroDivisionError caused by an attempt to divide by 0


numerator = 7
denominator = 0 # Possible resolution: Change the denominator value
result = numerator / denominator
print (result)

# One possible assumption for a number divided by zero error might include the issue of a null value
as a denominator (could happen when using a loop to iterate over values in a database). In such
cases, the desired outcome may be to leave the numerator value intact. The numerator value can be
preserved by reassigning the denominator with the integer value of 1. The result would then equal
the numerator.

IX. Defining Functions


 The print function that writes text on the screen, the type function which tells us the type of a
certain value, and the str function which converts a number into a string
 Defining a function: def greeting(name)
 To define a function, we use the def keyword. The name of the function is what comes after the
keyword.
In this example, the function's name is greeting:
def greeting (name):
print (“Welcome, ” + name)
greeting("Kay")
greeting("Cameron")

def greeting(name, department):


print(“Welcome, " + name)
print("You are part of " + department)
greeting("Blake", "Software engineering")
greeting("Ellis", "Software engineering")

You might also like