Python Coding: Problem Solving & Understanding

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is a variable in Python?

A Variable is a container for a value. Behaves as the value it contains. (See below.) (Ex.): First_name = "Sky" Value will always have " " around it, if it's text. if it's a number, then you can put just the number like this... (Ex.): Age = 30

What is a 2D list ?

A 2D list is a list of separate lists. (What a tongue twister)

What is a loop control BREAK statement for?

A BREAK statement is used to terminate the loop entirely.

What is a loop control CONTINUE statement for?

A CONTINUE statement is used to skip to the next iteration of the loop.

What is a loop control PASS statement for?

A PASS statement does nothing, it is used to act as a placeholder.

What is a Set? "{ }"

A Set is an unordered collection of unique elements/values. There are no indexes assigned to elements/values in a variable or set, and therefore, elements in a variable or set much be unique. They also do not allow any duplicate values. (Ex.:) So for example, if we had a set of utensils below: utensils = {"fork","spoon","knife","knife","fork"} for x in utensils: print(x) And your result would be the following: spoon fork knife With NO duplicates.

What is a loop control statement for?

A loop control statement serves to change a loops execution from it's normal sequence.

What are nested function calls?

A nested function call is a function call within another function call. Much like nested loops, the innermost function calls are resolved first but any returned value is used as argument for the next outer function.

What is a nested loop?

A nested loop is a loop within another loop. The "inner loop" will finish all of it's iterations before finishing one iteration of the "outer loop". Ex.: people = ("Bill", "Bob", "Barry") goodiebag = ("pen", "booklet", "flask") for attendees in people:for goodies in goodiebag:print('{} with {}'.format(attendees, goodies))print()

What's a return statement?

A return statement is a function that sends Python values/objects back to the caller. These values/objects are known as the function's return value.

What is a for loop?

A statement that will execute it's block of code a limited number of times. Different from a while loop which is unlimited.

What is a while loop?

A statement that will execute it's block of code unlimited number of times as long as it's conditions remain true. Different from a FOR loop which is limited.

What is a tuple "( )" and what is it used for?

A tuple is a collection which is ordered and unchangeable. It is used to group together related data.

What is an ELIF statement used for?

An ELIF statement similar to the IF statement is used after an IF statement to add additional conditions that will execute if it's TRUE. If it's FALSE it may fall to another ELIF statement or default into an ELSE statement - if all else fails or all conditions come back false. Note: Look at it like this... if a: do this elif b: do that elif c: do something else else: print "none of the above" is equivalent to (exactly the same as) this: if a: do this if (not a) and b: do that if (not a) and (not b) and c: do something else if (not a) and (not b) and (not c): print "none of the above"

What is an ELSE statement used for?

An ELSE statement is a block of code that will execute if all condition come back FALSE. Note: Think of it as a if all ELSE fails do this.

What are args in Python and what are they useful for?

Args is a parameter that will pack all arguments into a tuple. They're useful so that a function can accept a varying amount of arguments.

What is type casting?

Converting the data type of a value from one data type to another or different data type temporarily.

CQ: How do you find if the value of a variable contains only numbers?

If the variable and value in use is the following: name = "Dog" We'll use the following line of code: print(name.isdigit()) note: short for "is a digit" produces: False Now, if we use the following: name = "123" And use the same code as before: print(name.isdigit()) produces: True Now, what if we added them together using the following line of code: name = "Dog123" And use the same code as before: print(name.isdigit()) produces: False Why does it come back false if theres a number present? because it can ONLY come back true if only numbers are present. So it can ONLY tell you if a variable contains all numbers.

CQ: How do you change or replace specific letters of a value in a variable? For example, how would you replace the word "Dog" to read as "Log"?

If the variable and value in use is the following: name = "Dog" We'll use the following line of code: print(name.replace("D", "L")) Note: In "name.replace" parenthesis the first character will be the letter you're replacing and the second letter the one you're replacing the first letter entered with. produces: Log

EQ: How do you make a value in a variable that is capitalized or normal all lowercase?

If the variable and value in use is the following: name = "JOHN" We'll use the following line of code: print(name.lower()) produces: john note: There's no need to add anything to the parenthesis as it will result in error. This line of code is for producing all lowercase letters of the value in a container.

What are list "[ ]" and what are they used for in Python?

List are used to store multiple items or values in a single variable.

What are keyword arguments?

Keyword arguments are arguments preceded by an identifier when we pass them to a function. The order of the arguments doesn't matter, unlike positional arguments. Python knows the names of the arguments that our function receives.

What is multiple assignment?

Multiple assignment is what allows the coder to assign multiple variables at the same time in one line of code instead of it stacked. When writing codes in multiple lines (stacked) it would look something like this... (Ex.): name = "Johnny" age = 21 attractive = True Now, when writing code in one line we can do it like this to get the same result... (Ex.): name, age, attractive = "Johnny", 21, True ______ Here's one more example, if we had multiple variables with the same value such as: mans_age = 30 womans_age = 30 dogs_age = 30 We could just write the following example in one line of code. (Ex.): mans_age = womans_age = dogs_age = 30

What is the length operator used for?

The length operator can be used to count the length of a line of code and can also set conditions for lengths you'd like to have set.

How do you print text when running program?

When printing text you'll need to use "print()" in order to print text or numbers but remember for numbers or decimals we'll need to convert them back into a string using "+str()" before we can print.

CQ: Write a line of code to find the largest value between the values listed in each variable? use the following variable: x = 5 y = 10 z = 20

In order to write a line of code that can find the largest value in each variable, We'll use the following code: print(max(x, y, z)) Note: We'll use each variable we're comparing followed by a comma for the code to look through each value & find the largest value. Note: "max" short for maximum or largest.

CQ: How would you code the following number in the variable to show it's absolute value using code? use the following variable: pi = -25

In order to write a line of code that shows the number's absolute value, We'll use the following code: print(abs(pi)) note: "abs" short for absolute.

What is indexing used for in Python?

"Indexing" is used when referring to an element of an iterable by its position within the iterable. This is done through indexing [ ].

What is slicing used for in Python?

"Slicing" means getting a subset of elements from an iterable based on their indices. This is done through through a slice ( ).

What is a function and why is it useful Python?

A function is a block of code which is executed only when it is called. It is useful in the sense that we only have to write this block of code once instead of multiple times throughout a program since we can invoke or call upon it whenever it is needed instead of re-typing everything, every time.

CQ: After setting your parameters multiply two numbers with the result of those two number within the argument with a return statment? Once finished. Next, show me another method of completing this exact same task.

In order to multiply two numbers within a function and get the result back through a return statement. We'll use the following code: def multiply(number1,number2): result = number1 * number2 return result print(multiply(3,6)) OR def multiply(number1,number2): return number1 * number2 x = multiply(6,8) print(x)

What's the difference between ( ), [ ], & { }?

() is a tuple: An immutable collection of values, usually (but not necessarily) of different types. [] is a list: A mutable collection of values, usually (but not necessarily) of the same type. {} is a dict: Use a dictionary for key value pairs.

What is a dictionary "{ }" in Python and why are they useful?

A dictionary is a changeable, unordered collection of unique key: value pairs. They are faster and more efficient because they use hashing, which allows us to access a value quickly.

What is the difference between using "==", "!="?

"==" symbol is used for when a variable is equal to another. The reason we use two equal signs is so we don't accidentally define another variable if one is already present like... fruit = apple. (Ex.): "!=" symbol is the opposite this symbol is used when we are trying to tell the program that one variable is NOT equal to another variable. (Ex.):

CQ: How do you make a string of code appear multiple times? For example, how would you make the following value of this variable appear 3 times? name = "Johnny Appleseed"

If the variable and value in use is the following: name = "Johnny Appleseed" We'll use the following line of code: print(name*3)

What are logical operator?

A logical operator is AND, OR, & NOT used in coding to check if two or more conditional statement is TRUE in one line of code. AND - Both conditions must be TRUE in order to execute. (See EX. 1 below) OR - One condition or the other must be TRUE in order to execute. (See EX.2 below) NOT - This l-operator goes after an IF or ELIF statement and can be applied to both "AND" or "OR". As it makes conditional statements perform the opposite of TRUE or FALSE, it is almost reversed before executing. (See EX.2 & EX. 3 below.) ____________ (Ex.): temp = int(input("What is the temperature outside? ")) -------------- EX.1 IF temp <= 0 AND temp >=30: print("The temperature is no bueno today. ") EX.2 IF temp >= 0 OR temp <=30: print("The temperature is nice today. ") EX.3 IF NOT temp >= 0 OR temp <=30: print("The temperature is bad today") See how by adding a not statement this went from good weather to bad weather? That's the power of a NOT logical operator.

What is a scope in Python?

A scope is the region that a variable is recognized. A variable is only available from inside the region it is created. A global and locally scoped versions of the same variable can be created. Local Scope - Is a variable within a function that can only be accessed from within that function. (Ex.) def display_name(): name = "Appleseed" <---- within a function print(name) Global Scope - Is a regular variable outside a function that can be accessed from anywhere at anytime. (Ex.) name = "Johnny" <---- outside a function def display_name(): <---- this is a function name = "Appleseed" <---- within a function print(name) (Ex.) name = "Johnny" <---- Global Scope def display_name(): name = "Appleseed" <---- Local Scope print(name)

What is an IF statement used for?

An IF statement is a block of code that sets a condition and will execute ONLY if it's condition is TRUE.

What is an index operator "[ ]" used for?

An index operator is used to give access to a sequence's element (str, list, tuples)

CQ: How do you find if the value of a variable contains only letters?

If the variable and value in use is the following: name = "Johnny Appleseed" We'll use the following line of code: print(name.isalpha()) note: short for "is alphabetical" produces: False Why because it counts the space in between Johnny and Appleseed as a non alphabetical character. Now, if we remove the space and use the following: name = "JohnnyAppleseed" And use the same code as before: print(name.isalpha()) produces: True

CQ: How do you find how many specific letters is in a variable? For example, how many letter E's are is in the value of the following variable? name = "Johnny Appleseed"

If the variable and value in use is the following: name = "Johnny Appleseed" We'll use the following line of code: print(name.count("e")) produces: 3

CQ: How do you find the length of a variable?

If the variable and value in use is the following: name = "Johnny" We'll use the following line of code. print(len(name)) ----- 6

CQ: How do you find or print specific characters in a variable?

If the variable and value in use is the following: name = "Johnny" We'll use the following line of code: print(name.find("h")) = 2 note: dont forget to add "" to text. The reason it comes back as the number "2" is is because based on the order it is number two in the name johnny. Now, you might be thinking wait no it's actually 3. However, in coding the first letter will always be counted as 0. (Ex.): name = "Johnny" = 012345 012345

CQ: How do you capitalize a value in a variable that is lowercase?

If the variable and value in use is the following: name = "john" We'll use the following line of code: print(name.capitalize()) produces: John note: There's no need to add anything to the parenthesis as it will result in error. This line of code is for capitalizing the first letter of the value in a container.

CQ: How do you make a value in a variable that is lowercase all uppercase?

If the variable and value in use is the following: name = "john" We'll use the following line of code: print(name.upper()) produces: JOHN note: There's no need to add anything to the parenthesis as it will result in error. This line of code is for capitalizing all letters of the value in a container.

CQ: What happens if you try to apply a math equation to a string? For example, use the following variables: x = "1" #(type - str) y = 2 #(type - int) z = 3.0 #(type - float) What will happen if we multiply 3 by all of them?

If we are to multiply all values within the variables listed here: print(x*3) print(y*3) print(z*3) We would get the following: 111 6 9.0 Note: Due to "x' being a string of text which is not recognized as an actual number. It will just display it three times. You can also see the difference by the color coding of each.

CQ: Using previous functions on the set from before below, how could we add another utensil to the set that is not a duplicate since sets DO NOT support duplicate values. utensils = {"fork","spoon","knife","knife","fork"} Try adding a "napkin" to the list from what we've learned before. Once finished. Try removing the "fork" from the set. Once finished. Clear everything. Now, lets create multiple sets using the previous set above. utensils = {"fork","spoon","knife","knife","fork"} dishes = {"bowl","plate","cup","cup","bowl",} Once the second set has been created, try showing both the sets together using a function. Once finished. Add the two list to one another entirely into one single list. Once finished. Find the difference between the list using a known function. Once finished. Find the similarities between the list using a known function. Done.

In order to add another non-duplicate value to the set we'll need to use the following code: utensils = {"fork","spoon","knife","knife","fork"} utensils.add("napkin") for x in utensils: print(x) ------------- In order to remove "fork" from the set. We'll use the following code: utensils = {"fork","spoon","knife","knife","fork"} utensils.add("napkin") utensils.remove("fork") for x in utensils: print(x) ------------- In order to clear everything from this set. We'll use the following code: utensils.clear() ------------- In order to show both of the two list together, we'll use the following code: utensils = {"fork","spoon","knife","knife","fork"} dishes = {"bowl","plate","cup","cup","bowl","knife",} utensils.update(dishes) for x in utensils: print(x) OR dishes.update(utensils) for x in dishes: print(x) ------------- In order to add two list to one another entirely into one single list, we'll use the following code: utensils = {"fork","spoon","knife","knife","fork"} dishes = {"bowl","plate","cup","cup","bowl","knife"} dinner_table = utensils.union(dishes) OR dinner_table = dishes.union(utensils) for x in dinner_table: print(x) ------------- Now, if we wanted to find the difference between the two list we'll use the following code: utensils = {"fork", "spoon", "knife", "knife", "fork"} dishes = {"bowl", "plate", "cup", "cup", "bowl", "knife"} print(utensils.difference(dishes)) ------------- Now, if we wanted to find the similarities between the two list we'll use the following code: utensils = {"fork", "spoon", "knife", "knife", "fork"} dishes = {"bowl", "plate", "cup", "cup", "bowl", "knife"} print(utensils.intersection(dishes))

CQ: Define a creative function that can say "Hello!" and then call upon that same function using code. Once finished. Call upon the "Hello!" function three times. Once finished. Let's add to the function and after saying "Hello!" let's add "Have a nice day!"

In order to create a function that says hello everytime it's function is called, we'll use the following code: def hello(): print("Hello!) hello() ------------ In order to call upon the function that says "Hello!" three times. We'll use the following code: def hello(): print("Hello!) hello() hello() hello() ------------ In order to call upon the function that says "Hello!" three times and add "Have a nice day!". We'll use the following code: def hello(): print("Hello!") print("Have a nice day!") OR def hello(): print("Hello! Have a nice day!") hello() Note: "hello()" functions the same way as print because in this function print is already in the block of code. So, we can just enter "hello()" and it will run the outer block and then the inner block.

CQ: Using the index operator, see if you can change the first name in the variable listed below from lower case to upper case. name = "johnny Appleseed" Once finished. Create a substring from name listed above. So that when the name is printed only the first name is shown or listed. Once finished. Add to this code and make it so that the first name appears in all caps. Once finished. Add to this code and make it so that the last name appears but in all lowercase. Once finished. Add to thise code and make it so that the last character of the full name appears.

In order to change the first letter in the first name from lower case to upper case using the index operator. We'll use the following code: name = "johnny Appleseed" if(name[0].islower()): name = name.capitalize() print(name) ------------ In order to create a substring from the name so that the first name appears, we'll use the following code: first_name = name[0:6].upper() print(first_name) Note: Keep in mind, if your index starts with zero you can just remove it and will still perform and run like normal. For example, instead of the code above, we could get the same result by using the following code: first_name = name[:6].upper() ------------ In order to create a substring from the name so that the last name appears, we'll use the following code: last_name = name[7:16].lower OR last_name = name[7:].lower print(last_name) Note: Keep in mind, much like before if it's the last word you can just remove or leave out the last number and will still perform and run like normal since it will automatically assume the range in the index. ------------ Lastly, if you'd like to access the last character in the first or last name or even the full name we'll use negative numbers to begin from the back. (See question # for reference.) See the following code: last_character = name[-1] print(last_character)

CQ: Try using code to check somebody's age by using a variety of IF statements for someone 21 years old and over, another for someone who is 100 years old and over, and one for someone who is age ZERO. Use the following code in place: age = int(input("How old are you?: "))

In order to check the users age through IF statements we'll start by using the following code: IF age >= 21: print("you are an adult!") ELSE: print("You are a child!") Note: Just as IF statements will execute if it's condition is TRUE. We can use ELSE statements that will execute if the condition is FALSE.

CQ: Using a nested loop, make sure Bill, Bob, & Barry all gets a pen, a booklet, and a flask each at the upcoming event using code. Bill Bob Barry Once finished. Using a nested loop, program the code to print 4 weeks with 7 days within each week using code. Note: Text based nested loop and number(int) nested loops are usually done differently.

In order to code the program to automatically give Bill, Bob, & Barry each a pen, a booklet, and a flask using a nested loop. We'll use the following code: attendees = ("Bill", "Bob", "Barry") goodies = ("Pen", "Booklet", "Flask") for x in (attendees): print(x) for y in (goodies): print(y, end=", ") print() ------------- In order to code the program to print 4 weeks with 7 days within each week. We'll use the following code: weeks = 4 days = 7 for x in range(weeks): | print("week: " +str(x+1)) | for y in range(days): | | print("days: " +str(y+1)) | | | print()

CQ: Using a break statement, try to prompt the user to enter the secret password and only break the loop if the password entered is correct. Once the loop is broken, prompt the user to let them know the password was accepted. secret password will be "Ice Cream"

In order to code the program to break the loop only once the correct password has been entered. We'll use the following code: while True pass = input("Enter the secret password:") if pass == "Ice Cream": break

CQ: Using a pass statement, try to print all numbers from 1 to 20 except for the number 12 in the sequence.

In order to code the program to print all numbers from 1-20 excluding the number 12. We'll use the following code: for x in range(1,21): | if x == 12: | | pass | else: | | print(x, end=" ")

CQ: Using a continue statement, try to show the phone number value from the variable shown below to show the phone number without the dash symbol: "-" phone_number = "123-456-7890" You'll want to make it so that it appears like this: 1234567890

In order to code the program to show the phone number without the dashes using a continue statement. We'll use the following code: phone_number = "123-456-7890" for x in phone_number: if x == "-": continue print(x, end="")

EQ: How would you combine the two variables in Python to show the full name? first_name = "Johnny" last_name = "Appleseed"

In order to combine two variables, all we'll need to do is use a new variable using both variables in our new variable to bring them together. We'll add "+" to add to (Ex.): full_name = "first_name "+ +" last_name"

How do you take a number in a variable and convert back into a string of code?

In order to convert a line of code that's a number or decimal back into a string of code, you'll need to add "+str()" with the name of the variable inside the parenthesis. Additionally when adding to the code that's written you'll need to add a "+" in between each piece in the line. (See below.) (Ex.): age = 30 height = 5.8 "He was " +str(age)+ " and his weight was " +str(height)

CQ: How would you convert one data type to another permanently? Try this, convert the following data type values to the new ones listed below BUT do it permanently? x = "1" (type - str) y = 2 (type - int) z = 3.0 (type - float) Now convert them to the following using code: x - convert to a float y - convert to a string z - convert to a integer

In order to convert the following code permanently. You'll need to re-assign the variable to the data type you'd like it to be. We'll convert each data type using the following code: x = float(x) Now, "x" is a float. Let's convert the other two. y = str(y) and z = int(z) So now if we check this by using the following code: print(type(x)) print(type(y)) print(type(z)) You should get the following: Produces: <class 'float'> <class 'str'> <class 'int'>

CQ: How would you convert one data type to another temporarily? Try this, convert the following data type values to the new ones listed below? x = "1" (type - str) y = 2 (type - int) z = 3.0 (type - float) Now convert them to the following using code: x - convert to a float y - convert to a string z - convert to a integer

In order to convert the following code temporarily. We'll convert each data type using the following code: print(float(x)) print(str(y)) print(int(z))

CQ: Create a list of desserts listed below in Python. Desserts: Cake, Pie, Ice Cream, Donuts. Once finished. Then from the list, only print "Pie". Once finished. Then replace "Donuts" with "Pudding" through additional code, without changing the list. Make sure this time it prints in a "list format". Once finished. Add another value or item to the list of desserts using a ".function". Let's go ahead and add "Donuts" back into the list. Once finished. Let's go ahead and remove a value or item from the list using a ".function". Let's go ahead and remove "Pie". Once finished. Use another ".function" specifically for removing the last of any element or value of within a list or variable. Once finished. Next, insert "Cookies" within the list but specifically put them after "IceCream" and before "Pudding" using a ".function". Once finished. Next, try sorting the list alphabetically using a ".function". Once finished. Lastly, clear everything using a ".function". Done.

In order to create a list of desserts we'll need to use square brackets with the following code: desserts = ["Cake", "Pie", "Ice Cream", "Donuts"] In order to print "Pie" by itself from the list, we'll use the following code: print(desserts[1]) -------------- In order to replace "Donuts" with "Pudding" we'll use the following code: desserts = ["Cake", "Pie", "Ice Cream", "Donuts"] desserts[3] = "Pudding" for x in desserts: print(x) -------------- In order to add "Donuts" back in through a function we can use the following code: desserts.append("Donuts") for x in desserts: print(x) -------------- In order to remove desserts.remove("Pie") for x in desserts: print(x) -------------- In order to remove the last thing from the list specifically, we'll use the following code: desserts.pop() for x in desserts: print(x) Note: If you would like to remove or pop something specific within the list, you can enter a number in the parenthesis of the ".pop()"which correlates to the order of the list and where each item or value is located. Otherwise if nothing is input it will default to the last thing in the list. -------------- In order to add something within a list especially between two existing items or values we'll use the following code: desserts.insert(2) for x in desserts: print(x) Note: Just a heads up when you add in the number it will insert your new value or item before the value you pick in the list. -------------- In order to sort the items we have left alphabetically we will use the following code: desserts.sort() for x in desserts: print(x) -------------- Lastly, in order to clear everything we'll use one last commonly used function to clear everything with the following code: desserts.clear() for x in desserts: print(x)

CQ: Create a FOR loop that will count up from 0 to 10. Once finished. See if you can do it reversed making it count down from 10 to 0. Once finished. Try creating a timer from a starting range of 50 and ends with 100. Once finished Now create a timer that starts from 0 again but counts up to 50 in a series of 2. Once finished Lastly, create a countdown of 10 second that counts down one by one until it says Happy New Year.

In order to create a timer that counts up from 0 to 10. We'll use the following code: FOR i IN range(0,11): print(i) or FOR i IN range(0,10): print(i+1) Note: We'll use letters when indexing such as "IJK" or "XYZ" in coding are the most common. Note: Remember when indexing we must include an extra number for the ending since everything starts with 0 instead of 1 or what we can do in this case is add a 1 to the variable "i" like this "i+1". ------------ In order to create a timer that counts down from 10 to 0. We'll use the following code: for x in reversed(range(0,11)): print(m) -------------- In order to create a timer that starts at 50 and goes to 100. We'll use the following code: FOR x IN range(50,101): print(x) -------------- In order to create a timer that starts at 0 and goes to 50 in a series of 2. We'll use the following code: FOR x IN range(0,51,2): print(x) Note: For this section we'll add a third comma which will make it so that the range is counted in patterns of 2, 3, 4 and so on for pretty much whatever we set it to. Keep in mind in setting it to 1 it's going to count normal since it's the default. --------------- In order to create a timer that counts down or up. We'll use the following code: import time FOR x in range(10,0,-1): print(x) time.sleep(1) print("Happy New Year") Note: range(x-start., y-stop, z-step) We'll need to import time similarly to when we imported math in questions before. Once time is imported we'll set a starting range for x-seconds and a stopping range for y-seconds that count down ("-1") at a rate of z-seconds or up ("+1") at a rate of z-seconds - Remember, positive is always going up, while negative is always going down. Next, we'll print seconds and then after we'll type in "time.sleep(1)" to tell the system when it prints the range of seconds to do it one by one instead of just all at once since we're going for a real countdown here. Once you type in "time.sleep" you'll be prompted with parenthesis "( )" to tell the system how fast in seconds do you want the program to count up or down through the timer so we'll do 1 for 1 second per number. Please note, you can make this count faster by typing in 0.5 or just .5 in the parenthesis.

CQ: As a test to make sure you understand this concept create a first and last name for Johnny Appleseeds that use the same variable with one outside the function and one within. Keep in mind they will need to be printed differently. You should get the following: Johnny Appleseed

In order to create a variable with the same name that runs different code. We'll use the following code: name = "Johnny" def display_name(): name = "Appleseed" print(name) print(name) display_name()

CQ: Create a nested function that ask for a number entered and then take that number through this nested function: 1. Number converts to a float then 2. Number converts to an absolute value then 2. Number is rounded up or down depending Once finished. Create the exact same nested function again but do it through one line of code with no line breaks.

In order to create nested function that takes in information such as a number and goes through each of it's nested functions as mentioned in the question we'll use the following code: num = input("Enter a whole number: ") num = float(num) num = abs(num) num = round(num) print(num) Let's say for example, we used -8.2 after running the program and being prompted by the input. The number entered would go through the following nested functions: float would keep it as -8.2 abs would change it to 8.2 round would change it to 8 therefore it would be 8 after the nested functions have run their course. Let's use another number for an example. Let's use -6. float would change it to -6.0 abs would change it to 6.0 round would change it to 6 ------------ Another way of performing this code but through one line or string of code is through the following code: print(round(abs(float(input("Enter a whole number: "))))) Very similar to the first code we wrote just all in one string.

CQ: Try printing your name in a string vertically using a FOR loop like we did previously with the range of numbers? Once finished. Then make it so the code will print the name horizontally like normal.

In order to create our name in a string using a FOR loop. We'll need to use the following code: FOR x in "Johnny Appleseed" print(x) In order to get our name in a string horizontally using a FOR loop. We'll need to use the following code: FOR x in "Johnny Appleseed" print(x, end="")

CQ: Next using functions, we can also send our function some information from arguments and have it do something with that information. Let's have our function say "Hello!" to somebody's name let's use Bill in our argument. Once finished. Let's say "Hello" to Bob & Barry in our argument since they feel left out. Once finished. Next, let's send two values or two pieces of information to our function and define each within our argument and have it do something with that information. Let's have the function say hello to Johnny Appleseed using separate First Name and Last name within the function. Once finished. Next, let's add a third parameter to our function to mention Johnny Appleseed's age in a new line that says "You are 21 years old" using a age of 21 in our argument. Once finished.

In order to have our function use information that we give it such as somebody's name we'll use the following code: def hello(name): print("Hello! " +name +" Have a nice day!") Next, instead of us accepting information like an input, we can manually type in what we want it say by using the following code: "hello(Bill)" This will call the function and use Bills name. ------------ Next in order to call the function for Bob & Barry, we'll use the following code: def hello(name): print("Hello! " +name +" Have a nice day!") "hello(Bill)" "hello(Bob)" "hello(Barry)" Note: By you typing in a name in the brackets of "Hello( )" you're defining name above within the function. Another way of doing this, is by defining the name of Bill, Bob, & Barry separately and putting their key variable within the Hello function parenthesis separately. (See below.) Man1 = "Bill" Man2 = "Bob" Man3 = "Barry" hello(Man1) hello(Man2) hello(Man3) Keep in mind, this does require an extra step when compared to before. ------------ In order to send over two pieces of information or two values to our function to say Hello to Johnny Appleseed. We'll use the following code: def hello(first_name, last_name): print("Hello! " +first_name " " +last_name +" Have a nice day!") hello(Johnny, Appleseed) ------------ In order to add a third value such as age we'll use the following code: def hello(first_name, last_name, age): print("Hello! " +first_name +" " +last_name +", Have a nice day!") print("You are " +str(age) +" years old.") hello("Johnny", "Appleseed", 21)

CQ: Using unique : key value pairs, make a dictionary using a set to list each country and their capital below: USA, Washington DC Russia, Moscow China, Beijing India, New Dehli One finished. Next, print the capital of ONLY "Moscow" from "Russia". Once finished. Use a function to what countries or capital are within the list. Check to see if Germany or it's capital is within the list. Once finished. Use a function to print or show only the keys. Once finished. Use a function to print or show only the value pairs. Once finished. Use a function to print or show both the keys and the value pairs. Once finished. Next, try to print each country and capital in a neat list using a FOR loop. Once finished. Let's use a function to go ahead and add Germany, Berlin to the list. Once finished. Let's pretend that the USA has decided to relocate and has changed it's capital from Washington DC to Las Vegas. Using a function update the USA's capital to show Las Vegas instead of Washington DC. Once finished. Almost done! Once finished let's try removing a value using a function. Let's go ahead and remove India from the list. Once finished. Lastly, using a function erase everything and wipe the screen clean. DONE!

In order to print each state with their capital using a set in a dictionary format we'll use the following code: capitals = {"USA" : "Washington DC", "Russia": "Moscow", "China": "Beijing", "India": "New Dehli"} for x in capitals: print(x) ------------ Now, in order to print a specific countries capital, we'll use the following code: print(capitals["Russia"]) ------------ In order to see what countries and capitals are present within the list above that was created we'll use the following code: print(capitals.get("Germany")) Note: This a nice way of checking if there are any or certain keys within your dictionary or one that has already been created. ------------ Now, if you wanted to print or show the keys - countries instead of the value pairs - capitals. We'll use the following code: print(capitals.keys()) ------------ Next, if we wanted to show only the value pairs, we'll use the following code: print(capitals.values()) ------------ Next, if we wanted to show both the keys and the value pairs together, we'll use the following code: print(capitals.items()) ------------ Next if we wanted to put it in a list format. We'll use the following code: for key, value in capitals.items(): print(key, value) ------------ Next, if we wanted to add Germany, Berlin capital to the list. We'll use the following code: capitals.update({"Germany,": "Berlin"}) ------------ If we'd like to update any key or value pairs we can use the following code: capitals.update({"USA,": "Las Vegas"}) ------------ Next if we would like to remove any key value pairs from the list, specifically "India" we'll use the following code: capitals.pop("India") ------------ Lastly, to clear everything we'll use the following code: capitals.clear()

CQ: Using the curated 2D list below: beverages = ["coffee","soda","tea"] dinner = ["pizza","salad","pasta"] dessert = ["cake","cookies","icecream"] Use code to show specifically the "Soda" from the first list using square brackets specifically. Once finished. Use code to show specifically the "Pizza" from the second list using square brackets specifically. Once finished. Use code to show specifically the "IceCream" from the third list using square brackets specifically.

In order to print something specifically from the compiled list with square brackets. We'll use the following code: everything = [beverages, dinner, dessert] print(everything[0][1]) -------------- In order to print something specifically from the compiled list within the dinner list. We'll use the following code: everything = [beverages, dinner, dessert] print(everything[1][0]) -------------- In order to print something specifically from the compiled list within the dinner list. We'll use the following code: everything = [beverages, dinner, dessert] print(everything[2][2])

CQ: Use a keyword argument within a function that doesn't need to be in a particular order. Let's re-create the positional argument below and turn into a keyword argument by purposely putting each argument in a different order than what's inside the function. Let's go ahead and use this order: Appleseed, Johnny, Green --------- (Ref.): Positional argument: def hello(first_name, middle_name, last_name): print("Hello! " +first_name +" " +middle_name +" " +last_name +" Have a nice day!") hello(Johnny, Green, Appleseed)

In order to re-create the positional argument into a keyword argument we'll use the following code: def hello(first_name, middle_name, last_name): print("Hello! " +first_name +" " +middle_name +" " +last_name +" Have a nice day!") hello(last_name="Appleseed",first_name="Johnny",middle_name="Green")

CQ: Try removing everything but the name of from the website link from the value in the variable. use the following variable: website = "https://google.com"

In order to remove everything but the name of the website we'll use the slice option. For "Slice" it's a little bit different so we'll use a comma instead of a colon for slice unlike the indexing. We'll use the following code: Note: remember there's no need for a starting point, we only need a stopping point because the slice function will up to whatever the stopping point is. Also the cool part about slice is we dont need to count an extra space like we do when we are indexing. Remember, if we are counting from the right it's positive, if we're counting from the left it's negative. (See below.) -------- ---- website = "https://google.com" + - then we'll define what we're slicing. name_only = slice(8,-4 ) And lastly, we'll bring it together. print(website[name_only])

CQ: Using the tuple list below, lets use another ".function" to see how many times the word "Johnny" appears within our list. student = ("Johnny","21","male") Once finished. Next, lets use another function to see where "male" is indexed within the list. Once finished. Using tuples, let's use an IF statement to call out if Johnny is in the list.

In order to use a function to count certain words on the tuple shown in the example on coding question. We'll use the following code: print(student.count("Johnny")) -------------- In order to see where male is indexed within the list we'll use the following code: print(student.index("male")) -------------- IF "Johnny" in student: print("Johnny Is Here")

CQ: Using a while loop, continually ask somebody to enter their name until a name or characters are input? Then program it to say Hi back with the name or characters entered.

In order to use a while loop to ask for somebody's name continually until something is entered, We'll use the following code: name = "" <------ this means names blank or has no value or you can use the following: name = input("Please enter your name: ") WHILE LEN(name) == 0: name = input("Please enter your name: ") print("Hello " +name)

CQ: Now, write a line of code to find the lowest value between the values listed in each variable? use the following variable: x = 5 y = 10 z = 20

In order to write a line of code that can find the smallest value in each variable, We'll use the following code: print(min(x, y, z)) Note: We'll use each variable we're comparing followed by a comma for the code to look through each value & find the largest value. Note: "max" short for maximum or largest.

CQ: Write a line of code to find the square root of the following number in the variable? use the following variable: number = 5

In order to write a line of code that can find the square root of the following number in the variable, We'll use the following code: Note: You'll always need to import math if your're using it in your coding. import math then print(math.sqrt(number)) Note: "sqrt" short for square root.

CQ: Try creating a substring based off of the first word or name in the sentence. use the following variable: name = "Johnny Appleseed" Once finished. Try creating a substring based off of the last word or name in the sentence. Once finished. Next, create a weird name from the variable by leaving the first and last name in but making it so it skips every other letter. Lastly, reverse the name or text of the value in the variable by making it read

In order to write a line of code that can slice a specific part of the name such as "Johnny" by itself, We'll use the following code: first_name = name[0:6] or first_name = name[:6] Then... print(first_name) Now, in order to write a line of code that can slice the last word or name such as "Applseed". We'll use the following code: last_name = name[7:17] or last_name = name[7:] Then... print(last_name) Note: For slicing we'll use the colon to snip a part of the text in the variable by listing the number the letter starts with which is always "0" and "6" since we'll always take an extra character at the end or you can also see it as there's 6 letters in "Johnny" but we still always start with zero. Next, in order to create a weird name we'll need to add a third colon instead of just the two we've been using previously. We'll use the following code: funny_name = name[0:16:2] or funny_name = name[::2] print(funny_name) Note: As you can see the program will skip every other letter in "Johnny Appleseed". "Johnny Appleseed" "J h n p l s e " Lastly, in order to create a reversed name we'll use negative numbers. Similar to first puzzle just counting starting from the last letter instead of the first. reversed_name=[-1:-17:-1] or reversed_name=[::-1] print(reversed_name) Note: When counting backwards we'll always count in the negatives. Due to counting in the negatives there's no need to count zero since -0 isn't an actual number so we'll default into -1 as the first letter reversed counting backwards in the last colon.

CQ: How would you write a line of code that contains a string, a int, and a float with variables that are already set? use the following variables: x = "1" #(type - str) y = 2 #(type - int) z = 3.0 #(type - float) Now write a line of code that contains each.

In order to write a line of code that contains each type in a string. We'll use the following code: print("x is " +x) print("y is " +str(y)) print("z is " +str(z)) print("This code begins with " +x +", then comes " +str(y) +", and lastly " +str(x) +".") Note: The reason X is missing "str(variable)" is due to the fact that it's already a string(str) so we don't need to add anything.

CQ: How can you ask for somebody's height in decimal form and prompt them to enter it using code? Once finished. Then code the program to say their height back with the height entered by the user. Once finished. To take this a bit farther make it so that it adds two inches to the height when it mentions the height entered.

In order to write a line of code that prompts a user to enter their height in decimal form, We'll use the following code: height = float(input("What is your height? ")) In order to print a response with the height entered we'll use the following code: print("You are " +str(height) +" ft. tall.") In order to add an extra 2 inches to the height in the response we'll use the following code: print("You are " +str(height+.2) +" ft. tall.")

CQ: How can you ask for somebody's age and prompt them to enter it using code? Once finished. Then code the program to say their age back with the age entered by the user. Once finished. To take this a bit farther make it so that it doubles their age when it mentions the age entered.

In order to write a line of code that prompts a user to enter their name, we'll use the following code: age = input("Please enter your age: ") In order to print a response with the name entered we'll use the following code: print("Hi, you are " +age +" years old.") In order to double the age in the response we'll use the following code: print("Hi, you are " +str(age*2) +" years old.")

CQ: How can you ask for somebody's name and prompt them to enter it using code? Then code the program to say hello back with the name entered by user.

In order to write a line of code that prompts a user to enter their name, we'll use the following code: name = input("Please enter your name: ") In order to print a response with the name entered we'll use the following code: print("Hi nice to meet you " +name)

CQ: How could you raise base power of the following number in the variable by 2? use the following variable: number = 5

In order to write a line of code that raises the base power of the following number in the variable by 2, We'll use the following code: print(pow(number, 2)) Note: We'll use the variable followed by a comma followed by how much we're raising the base power by. Note: "pow" short for power.

CQ: How would you round the following number in the variable using code? use the following variable: pi = 3.14 Once finished. Try SPECIFICALLY rounding the number UP using code. Once finished. Try SPECIFICALLY rounding the number DOWN using code.

In order to write a line of code that rounds the number to the nearest ten, We'll use the following code: print(round(pi)) Now, in order to round the number up we'll use the following code: Note: You'll need to import math for this step. import math then print.(math.ceil(pi)) Now, in order to round the number down we'll use the following code: print.(math.floor(pi))

What is the standard operating procedure when it comes to local and global functions?

L.E.G.B Rule or L = Local E = Enclosing G = Global B = Built-in The rule is you use any local variables first, followed by enclosed variables, followed by global variables, and last built in variables when it comes to variable scopes.

If we wanted to make it so a password had to be at least minimum 8 characters long how would we go about coding that into the program?

Passwords are a good example of where the length operator come in handy, if we wanted to make it so a password had to be at least 8 characters long on a website, we could use the following code: password = input("Please enter a sufficient password: ") WHILE len(password) <= 7: password = input("Please enter a sufficient password: ") print("Password Accepted.") or password = input("Please enter a sufficient password: ") WHILE NOT len(password) >= 8: password = input("Please enter a sufficient password: ") print("Password Accepted.") Note: We'll want to use a WHILE loop since an IF or ELIF statement will only do it a set number of times as they are listed. Which means if we were to try and use an IF statement after a user entered a password under 8 characters a number of times, eventually the system would just accept it. Whereas, with a WHILE loop it will do it infinitely until the characters entered are 8 or more.

What line of code will define a specific code type?

print(type(name_of_variable)) (Ex.): active = False print(type(active)) ______________________________________________ <class 'bool'> ______________________________________________ The program runner will bring back "Bool" which is short for Boolean since this is a "bool" type.


Set pelajaran terkait

Legal Dimensions of Nursing Practice

View Set

Pathophysiology Chapter 7 Fluid and Fluid Imbalances

View Set

APUSH SEM 1 FINALS - Questions & Terms

View Set

Respiratory Medsurg Course point

View Set

ARTH 102: Renaissance - Contemporary Review Set

View Set

Ap statistics Unit 7 Progress Check: MCQ Part B

View Set