Python Coding: Problem Solving & Understanding

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

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 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.):

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 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 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 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 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 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 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.

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 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)

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: 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.

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 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: (x,y,z) range(start., stop, 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.

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: 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 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: 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: 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))

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 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

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 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.

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.


संबंधित स्टडी सेट्स

Daftar kata 13: Binatang peliharaan dan binatang kesayangan - Pets & favourite animals

View Set

The nursing assistant in long-term care

View Set

Abeka - History of the World Quiz 11

View Set

Inspector Calls Combination - with explaination

View Set

Qualitative Methods - 8. Ethnography

View Set