Python Crash Course

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Ex 2-11 Via python, enter import this into a python terminal session and skim through the additional principles

AT the >>> import this and hit enter

What is the python 3 for loop colon used for?

After the iterable object, there must be a colon. Python requires this colon to indicate that what follows will be the body of the loop.

What is recommended regarding variables in Python3?

All variable and function names must be at least 3 characters. The first character of a name should follow these conventions: Variable names should always start with a lower case letter. (Except for variables that represent constants, which should use all upper case letters.) Function names should always start with a lower case letter.

What is recommended indentation in python3?

Each indentation level should be indented by 4 spaces. As Python requires indentation to be consistent, it is important not to mix tabs and spaces. You should never use tabs for indentation. Instead, all indentation levels should be 4 spaces. Note that CodeSkulptor automatically converts all tab indents into 4 spaces.

Why do you need a colon element in a python3 function?

colon: After the parameters, there must be a colon. Python requires this colon to indicate that what follows will be the code for the function.

What is the python 3 for element?

for: All for loops begin with the keyword for.

What are example of good python3 comments?

# This is a block comment # that spans multiple lines # explaining the following code. val = some complicated expression

Ex 2-10 Via python, choose two programs and add comments to each of them.

#!/bin/bash # The hello world program #This is the start of the program Print("Hello world") #This is the end of the program.

How do you open the REPL for python? What does REPL mean?

At the Linux terminal type: python3; then you should see >>>; REPL stands for Read Evaluate Print Loop

What are some python3 common mistakes?

It is a common mistake to try to refer to parameters and other local variables of a function outside of the body of the function. This will not work. Furthermore, if you create variables with the same names as those within the function, they are different variables that have nothing to do with the variables you have created inside the function. When you call functions, you should only try to interact with functions by passing them arguments and using their return values. The caller of a function should not try to use any of the local variables of a function outside of that function.

What is the python range function?

Python has a builtin function, called range, which allows you to easily construct sequences of integers. The function range does not return a list, rather it returns a special range object. However, you can pass it to the list function to convert the range object into a list, if you need or want a list instead. The range function takes from 1 to 3 arguments. These arguments are converted into a start, stop, and step value

What REPL math commands can you do in python?

Python3; >>> 2+ 2; >>> 10-4; >>> 3*9; >>> 5/3; >>> 5//3; >>> 8%3; >>> 2**3; >>> str(1.1); >>> int("10"); >>> int(5.999); float(5.6); >>> float(5); type("string"); >>> type(1); >>> type(1.0)

What is the in element used for in a python 3 for loop?

The keyword in must appear directly after the loop variable and indicates that the following is the object that will be iterated over. This makes the for loop read somewhat like an English sentence.

What is the body of a python 3 for loop?

The line immediately following the colon starts the body of the loop. This is the actual code that will be executed for each value in the iterable object. During the execution of the loop body, the loop variable (in this case animal will contain one of the values within the iterable object. For lists, the loop variable will take on the values of the list in order

What is a python container that holds elements?

The list: The list is one of the most basic and most commonly used. You will rarely, if ever, see a Python program that does not use lists

What is a local variable in a python3 function?

There are two types of local variables that exist in this function: the parameters and variables that are defined within the function body. These local variables are newly created each time the function is called and then they only exist during the execution of the function. This is important to understand.

How do you access elements within a python list?

You access elements of a list using their index. The first element of a list is located at index 0 (not 1!). The last element of a list is located at index len(lst) -1 (not len((lst)). The syntax to access an element of a list is to place the index in square brackets after the variable that refers to a list.

What are some scope rules in python3?

You should not use names that knowingly duplicate other names in an outer scope. This would make the name in the outer scope impossible to access. In particular, you should never use names that are the same as existing Python built-in functions. For example, if you were to name one of your local variables max inside of a function, you would then not be able to call max() from within that function.

What is the python3 body in a function?

body: After the docstring, is the body of the function. This is the actual code that will be executed when the function is called. The code for this function is on lines 5 through 8. A function can contain any valid Python code. This function includes arithmetic expressions and variable assignments. Note that you can even call other functions.

What is an example of a python3 function local variable?

def sum_of_squares(num1, num2): """ Return the sum of the squares of the two inputs. """ sq1 = num1 * num1 sq2 = num2 * num2 sumsq = sq1 + sq2 return sumsq

What is the example of a python3 function?

def sum_of_squares(num1, num2): """ Return the sum of the squares of the two inputs. """ sq1 = num1 * num1 sq2 = num2 * num2 sumsq = sq1 + sq2 return sumsq

What is the python3 def element?

def: All function definitions must begin with the Python keyword def; def (short for "define"). Note that def is not indented at all.

What is an example of arithmetic comparisons in python3?

if (value > -10) and (value < 10): # do something elif (value <= -10): # do something different elif (value >= 10): # do another different thing This program has three possible paths, depending on the value of the variable value. If it is between -10 and 10 (but not exactly -10 or 10), then the body on line 2 will be executed. If, instead, it is less than or equal to -10, the body on line 4 will be executed. Finally, if it is greater than or equal to 10, the body on line 6 will be executed. No else clause is necessary here, since all possibilities have been covered. Note, however, that the final elif clause could be replaced with an else clause, since if the code gets to that point, value must be greater than or equal to 10.

What are examples of python 3 range and index commands?

lst = list(range(10)) # First element print(lst[0]) # Third element print(lst[2]) # Length print(len(lst)) # Last element print(lst[9]) print(lst[len(lst) - 1]) print(lst[-1])

What is an example of a python3 function call?

number = 3 value = sum_of_squares(number, 5) print(value)

How do you create and read from python lists?

python3; my_list = [1, 2, 3, 4, 5]; my_list[0]; my_list[1]; my_list[5]; len(my_list); my_list[0:2]; my_list[1:0]; my_list[0:2]; my_list[1:0], my_list[0::1]; my_list[0::2]

What is a good way to check your python3 syntax?

use pylint pylint week2_quiz.py

What is a example docstring coding standard?

""" An example program that illustrates the use of docstrings """ def welcome(location): """ Takes input string location and returns a string of the form "Welcome to the location" """ return "Welcome to the " + location Documentation strings ("docstrings") are an integral part of the Python language. They need to be in the following places: - At the top of each file describing the purpose of the program or module. - Below each function definition describing the purpose of the function.

Ex 2-2 Via Python, store a message in a variable, print that message. Change the value of your variable and print the message again

#!/bin/python # 2-2 Date 9/16/19 Message = "Hello Conrad, welcome to python" Print(Message) Message="You will learn a lot via principles."

Ex 2-7 Via python, store a persons name and include some white space characters at the beginning and end of the hand. Make sure you use each character combination "\t" and "\n", at least once. Print the name once, then print using lstrip(), rstrip() and strip().

#!/bin/python # Ex 2-7 Date: 9/16 Name="\tFake Break\n" Print(Name) Print(Name.lstrip()) Print(Name.rstrip()) Print(Name.strip())

Ex 2-1 How do you via python store a message in a variable and then print that message?

#!/bin/python # ex 2-1 Date 9/16 Message = "Hello World!" Print(Message)

Ex 2-3 Via Python, store a persons name in a variable, print a message to that person. Your message should look like "Hello Conrad, would you like to learn python today?"

#!/bin/python # ex 2-3, date: 9/16/19 Person = "Conrad" Print("Hello", Person, "would you like to learn some python today?"

Ex 2-5 Via Python, find a quote from a famous person you admire. Print the quote and name of its author. You output should look like Albert Einstein once said, "A person who never made a mistake never tried anything new."

#!/bin/python # ex 2-5 Date 9-16 Print("Albert Einstein once said, \"A person who never made a mistake never tried anything new.\""

Ex 2-6 Via python, repeat ex 2-5 but store the persons name in a variable called famous_person. The compose your message and store it in a new variable called message. Print your message

#!/bin/python # ex 2-6 Famous_person="Albert Einstein" Message = "Hello ," + famous_person.title() + "you are very smart!" Print(Message)

Ex 2-8 Via python, write addition, subtraction, multiplication and division operations that each result in the number 8. Be sure to enclose your operations in print statements. I.e. print(5+3)

#!/bin/python # ex 2-8 date 9/16 Print(5+3) Print(16-8) Print(8 * 1) Print(16 / 2)

Ex 2-4 Via Python, store a person's name in a variable, then print that person's name in lowercase, uppercase and title case.

#!/bin/python Name = "Conrad" Print(name.lower()) Print(name.upper()) Print(name.title())

Ex 2-9 Via python, store you favorite number in a variable. Then using that variable, create a message that reveals your favorite number. Print that message

#!/bin/python Favorite_number=7 Print("My favorite number is", favorite_number)

Ex 3-2 How do you use the names list, to print each person's name and a message to them?

#!/usr/bin/python3 Aws = ["beach", "rosser", "cappadona", "Weissman"] For i in aws: Print(i + "is a complete fake break!")

Ex 3-1 How do you store the names of your friends in a list called names? How do you print each name by accessing each elements?

#!/usr/bin/python3 Friends = ["Taylor", "Bobby", "Dave", "Kobe"] Print("my first friend is" + friends[0]) Print("my second friend is" + friends[1]) Print("my 3rd friend is" + friends[2]) Print("my 4th friend is" + friends[3])

How do you create a python script?

#!/usr/bin/python3 Print("Hello, world") # make sure you Chmod 777 the program, the file names ends in *.py

Ex 3-3 How you you create a list with your favorite toys? How do you print a message that says. I would like to own a toy where each toy is an element of the toy list

#!/usr/bin/python3 toys = ["iPad Pro", "car", "book"] for toy in toys: print("One day, I would like to own a " + toy)

What is the python 3 for loop variable?

After the keyword for, you must provide a loop variable name. This variable will hold each of the values in the list as the for loop is executed. This is a variable like any other in Python.

What is the iterable object of a python 3 for loop element?

After the keyword in, you must provide an iterable object. This is any type of Python object that allows iteration. Python lists are iterable. So are range objects and strings. There are also many other iterable types that we have not seen yet.

What are elements of a python 3 for loop?

Elements of a for loop include: for, loop variable, in, iterable object, colon, indentation, body?

What is recommended regarding Global variables in python3?

Global variables should never be used. Avoiding their use is good programming practice in any language. There is one exception to this rule: you may have global constants. Because the Python language does not actually support constants, by convention, Python programmers use global variables with names that are in all capital letters for constants. When you see a variable with a name in all capital letters, you should always assume that it is a constant and you should never change it. Again, such global constants are the only global variables that will be allowed in this specialization.

What is a key best practice about lists?

It is generally good practice to only include elements of the same type as each other within a list. You will see other programmers violate this practice. You should not. It leads to bugs and confusion when you (the programmer) have to remember the different types of the elements within a single list.

What are python 3 loops?

Loops are a powerful programming concept. It is very common to want to repeat the same action(s) for every element of a list. This is exactly what a loop does. Python allows you to use a loop to iterate over lists. In this way, you do not need to know the length of the list ahead of time, rather you just tell Python to repeat some action as many times as there are items in the list. Iteration is not tied to lists in any way, however. Python allows iteration over a wide variety of types that contain other elements.

What is the python 3 indentation in a for loop?

Note that the remainder of the loop must be indented. In some languages, indentation is optional and is used simply to help the person reading the code to understand what is and what is not a part of the loop. In Python, this indentation is required. By convention, the body of the loop should all be indented exactly 4 spaces.

How do you grab multiple elements of a python 3 list?

Python allows you to extract a sublist from a list using slicing. When you slice a list you access it with two indices separated by a colon. This will produce a new list with the elements with indices starting at the first index up to, but not including, the second index. If the index before the colon is missing, the slice starts at the first element of the list. If the index after the colon is missing, the slice ends at the last element of the list.

What are some string commands you can create in python via the REPL?

Python3; >>> 'single quote'; >>> "double quote"; >>> ''' this is a quote /n of a triple quote '''; >>> "pass" + "word"; >>> "Ha" * 4; >>> print("'single'"); >>> print('"double"'); >>> "double".find('s'); >>> "double".find('e'); >>> "double".find('u'); >>> "Testing".lower(); >>> "AAA".lower(); >>> "PassWord123".lower(); >>> print("Tab\tDelimited"); >>> print("New\nLine"); print("Slash\\char"); print("\"Double\" in d")

How do you do booleans in python?

Python3; >>> True; >>> False; >>> type(True); >>> type(False); >>> None; type(None)

What are some variables you can perform in python?

Python3; my_str = "simple string"; print(my_str); my_str += "testing"; my_str; my_str = 1; print(my_str); my_int = my_str; my_str = "Test String" print(my_int); print(my_str)

What are elements of a python3 function?

def, name, parameter, colon, indentation, docstring, body, return. All functions should have these elements (except possibly the return statement). You may define as many functions as you need to perform the computation of your program.

What is a python3 docstring in a function?

docstring: The line immediately following the colon should be a docstring (short for "documentation string"). The docstring for this function is on lines 2 through 4. This is a multiline string that describes, in English, what the function does. You should not be describing how the function performs the computation. Rather, this is a description of how to use the function. The docstring can be as long as necessary to explain the behavior of the function. However, it should be clear and concise so as not to confuse the reader.

What is an example of an elif clause?

if hungry and thirsty: print("Go have lunch!") elif hungry: print("Have a snack!") elif thirsty: print("Have a drink!") else: print("Save your food and drinks for later!") You can also add elif clauses (short for "else if") to an if statement. Each elif clause includes a condition, exactly like the initial if statement. An elif clause must directly follow either the initial if statement or another elif clause and has the following structure: the elif keyword, an expression that evaluates to True or False, and a colon. The body of the elif clause is then indented by 4 spaces and ends when the indentation ends.

What is an if statement example in python 3?

if hungry: print("Have a snack!") Note the structure of the if statement on line 1. It starts with the if keyword. Then you have a condition that evaluates to either True or False. The condition can be any Python expression that will evaluate to True or False. Finally, the line ends with a colon. This colon is required and it indicates to Python that what follows is the body of the if statement. The body of the if statement can contain any Python code and can be as long as necessary. But, all lines in the body of the if statement must be indented. As with functions, the convention is that the body should be indented by 4 spaces. Once the indentation stops, the body of the if statement is over and the subsequent code will execute regardless of the value of the condition.

What is an else example in python 3?

if hungry: print("Have a snack!") else: print("Save your snack for later!") An if statement can also include optional clauses following the body of the if statement. You can optionally include an else clause which will execute if the condition of the if statement evaluates to False. The else clause starts with the keyword else followed by a colon. After that, the body of the else clause must be indented, again with 4 spaces by convention. As with the if statement body, the body of the else clause can contain any Python code and ends when the indentation stops. Note that either the body of the if or the body of the else will execute, but not both. If hungry is True, then the code on line 2 will execute. If it is False, then the code on line 4 will execute.

Is indentation required in a python3 function?

indentation: Note that the remainder of the function must be indented. In some languages, indentation is optional and is used simply to help the person reading the code to understand what is and what is not a part of the function. In Python, this indentation is required. By convention, the code of the function should all be indented exactly 4 spaces.

What is an example of python 3 list slicing?

lst = list(range(10)) # Slice with 3 elements print(lst[4:7]) # Slice with the last 2 elements of the list print(lst[8:10]) print(lst[8:]) print(lst[-2:]) # Slice with the first 4 elements of the list print(lst[0:4]) print(lst[:4]) # Empty slices print(lst[20:25]) print(lst[7:3])

What is an example of a python 3 list?

lst1 = [1, 5, 9, -32] print(lst1) lst2 = ["dog", "cow", "horse"] print(lst2) emptylst = [] print(emptylst)

How do you modify a list in python?

my_list = [1, 2, 3, 4, 5]; my_list[0] = a; my_list; my_list.append(6); my_list.append(7); my_list; my_list + [8,9,10]; my_list += [8, 9, 10]; my_list[1:3] = ['b','c']; my_list[3:5] = ['d', 'e', 'f']; print(my_list); my_list; my_list[4:] = []; my_list; my_list.remove('b'); my_list.pop(); my_list.pop(0)

What is the python3 name element?

name: After the keyword def, your function must have a name. In this case, it is sum_of_squares. Function names must begin with a letter. Function names can include letters, numbers, and underscore (_) characters. By convention in Python function names should not use uppercase letters and words should be separated by underscores. You should choose clear, understandable function names that indicate what the function does.

What is the python3 parameter element?

parameters: The parameters, or inputs, of the function appear directly after the name. They are surrounded by parentheses. A function in Python can have zero or more parameters. The parameters should be separated by commas. In the above example, there are two parameters, num1, num2.

What is a simple example of python 3 for loop?

pets = ["cat", "dog", "ferret"] for animal in pets: print(animal)

What is a python3 function return used for?

return: Functions often return values to the caller. This is not strictly required however. The function may be performing actions (such as printing messages) that do not require it to return anything to the caller. However, more often than not, a function is computing some result that should be returned to the caller. The return keyword is used to indicate what should be returned from the function. Whatever appears after the return keyword is what will be returned. This can be any expression, which will first be evaluated and then the result will be returned. In this case, the value of the variable sumsq will be returned. If you omit the return statement from your function, Python will automatically return the special value None from the function.


Kaugnay na mga set ng pag-aaral

Chapter 9: Long-Term Assets: Fixed and Intangible

View Set

[Sociology] Chapter 16: Education

View Set

Chapter 5 - Citizenship and the Constitution

View Set

EAQ Pharmacology: Diabetes Drugs

View Set

Final Exam - every study guide combined into 1 (missing 7/23 lecture)

View Set

Unit 22 Investing in Real Estate

View Set