Python Syntax

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

The elif keyword is pythons way of saying _____________

"if the previous conditions were not true, then try this condition".

What are the 4 data structures in python that store multiple items to one variable?

1. sets 2. tuples 3. lists 4. dictionary

Define list comprehension.

A list comprehension allows you to generate code with less lines.

How does a list comprehension work?

A list comprehension combines the for loop and the creation of new elements into one line, and automatically appends each new element.

How do we combine strings and numbers in Python?

By using the format method. Use the format() method to insert numbers into strings: age = 36 txt = "My name is John, and I am {}" print(txt.format(age))

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert. An example of an illegal character is a double quote inside a string that is surrounded by double quotes: Example You will get an error if you use double quotes inside a string that is surrounded by double quotes: txt = "We are the so-called "Vikings" from the north." #produces an error

Correct way to write it: txt = "We are the so-called \"Vikings\" from the north."

What's a dictionary?

Dictionaries are Python's implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. x = {"name" : "John", "age" : 36} print(type(x))

What are dictionaries used for?

Dictionaries are used to store data in Key:value pairs. JavaScript calls them associative arrays.

How do I check if a list item exists?

EXAMPLE thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list")

Short Hand If ... Else If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

Example One line if else statement: a = 2b = 330 print("A") if a > b else print("B")

If you have only one statement to execute, you can put it on the same line as the if statement.

Example One line if statement: if a > b: print("a is greater than b")

What's the output? b = "Hello, World!" print(b[:5])

Hello

What are some instances when I might want to run all entries in a list to perform the same task with each item?

In a game, I might want to move every element on the screen by the same amount. I might want to perform the same operation on a list of numbers.

What does this varaible declaration do? x = y = z = "Orange"

It assigns the string orange tow all 3 varialbes.

What does this code do? squares = [] for value in range(1,11): square = value **2 squares.append(square) print(squares)

It prints the square root of each number starting at 1 and ending at 10. **is the symbol for square root.

what does .title() do?

It turns the first letter of each word into a capital letter where specified. name = "diane" print(name) OUTPUT Diane

What does this code do: fruits = ["Apple", "Bannana", "Cherry"] x, y, z = fruits print(x) # Apple print(y) #Bannana print(z) #Cherry

It's an alternative to: print(fruits[0]) print(fruits[1]) print(fruits[2])

What is casting?

It's when you specify the data type of a variable.

What's the data type of the code below? x = ["apple", "banana", "cherry"] print(type(x))

List aka array in JavaScript

What do Python lists do?

Lists are used to store multiple items in a single variable fruit = ["apple", "bannana"]

What does negative indexing mean in a list?

Negative indexing means start from the end -1 refers to the last item, -2 refers to the second last item etc.

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders: What's the output? quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price))

OUTPUT: I want to pay 49.95 dollars for 3 pieces of item 567

What does slicing a string mean?

Returning a range of characters within a string.

Do lists allow duplicate items?

Since lists are indexed, lists can have items with the same value.

How do i search from the end of a list?

Specify negative indexes. Example This example returns the items from "orange" (-4) to, but NOT including "mango" (-1): thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]print(thislist[-4:-1])

Python Indentation example: if 5>2: print("Five is greater than two!")

The indentation is not there to make the code look better. It's part of the if statement.

Checking user input requires checking usernames when they log in to a website.

True

White space is NOT ignored in Python.

True

You aren't required to specify type when declaring a variable.

True x = 4 # is type int x = 'Sally' #is type string

Are tuples changeable?

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

When do you use a tuple?

When you want to store a set of values that should not be changed throughout the life of a program.

How do I get the type of a variable?

X = 5 y = "John" print(type(x)) print(type(y))

Can list items be of any data type?

Yes

How do I assign a multiline string to a variable?

a = """Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua.""" print(a) #use triple quotes on each end of the string.

How do I access a single letter of a string?

a = "Hello, World!"print(a[1]) OUTPUT: e

What does the split() method return?

a list where the text between the specified separator becomes the list items. The split() method splits the string into substrings if it finds instances of the separator: a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']

What does isinstance() function do?

can be used to determine if an object is of a certain data type x = 200 print(isinstance(x, int))

What does the word float do below? x = 5 x = float(x)

changes 5 from int to a float

name.lower()

changes all letters to lower case

name.upper()

changes all letters to upper case

How do I print a list of even numbers?

evenNumbers = list(range(2,11,2)) print(evenNumbers) OUTPUT [2,4,6,8,10]

Which data structure do you use to perform the same task with each item in a list?

for loop

Syntax for range() is?

for value in range(1,5): print(value)

How do I loop through the letters in the word "bannana"

for x in "banana": print(x) OUTPUT: B a n n a n a

How do I Check if "free" is present in the following text: txt = "The best things in life are free!"

if "free" in txt: print("Yes, 'free' is present.")

What are the 3 number types in Python?

int, float, complex

What's the syntax for writing a set?

it's a list with curly braces {}

Which function returns the length of a string?

len() a = "Hello, World!" print(len(a)) OUTPUT: 13

The only characters you are allowed when declaring a variable are__________?`

letters, numbers that aren't the first letter, and __

is this a list or a tuple? x = ["apple", "banana", "cherry"]

list

What does this code output? b = "Hello, World!" print(b[2:5])

llo

How do I convert the results of range() to a list?

numbers = list(range(1,6)) print(numbers) OUTPUT [1,2,3,4,5]

Remember both conditions have to be true for and and only _______ one condition has to be true for or.

one

Python indentation is not ________________________

optional

How do I get the characters from position 2, and all the way to the end: b = "Hello, World!"print(b[2:])

print(b[2:])

x, y, z = "Orange", "Bannana", "Cherry"

print(x) #Orange print(y) #Bannana print(z) #Cherry

Which method do I use to print a list of numbers?

range()

how do you specify a range of indexes?

range(start, end) Example thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]print(thislist[2:5]) OUTPUT cherry orange kiwi NOTE The search will start at index 2 (included) and end at index 5 (not included).

What does the strip() method do?

removes any whitespace from the beginning or the end of a string. a = " Hello, World! " print(a.strip()) # returns "Hello, World!"

What does the replace() method do?

replaces a string with another string: a = "Hello, World!" print(a.replace("H", "J"))

x = 5 What does type((x)) do?

returns <class 'int'> which tells you the data type of x.

Negative indexing means __________________________________

start from the end -1 refers to the last item, -2 refers to the second last item etc.

wHAT DO LISTS WORK WELL FOR?

storing collections of items that can change throughout the life of a program.

When we say that lists are ordered, it means that ____________________________________________________________________

the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list.

What are Boolean values used for?

to track the state of a program or a particular condition that is important in your program.

"Python " and "Python" are considered two different things.

true

The following code example would print the data type of x, what data type would that be? x = ("apple", "banana", "cherry") print(type(x))

tuple

is this a list or a tuple: x = ("apple", "banana", "cherry")

tuple

What do you use to create a list of items that do not change?

tuples

What's a tuple?

tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable.

To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

txt = "The best things in life are free!" print("expensive" not in txt) OUTPUT: true

Strings are are arrays of bytes representing __________________

unicode characters.

How do I concatenate, or combine, two strings?

use the + operator. a = "Hello" b = "World" c = a + b print(c) OUTPUT HelloWorld

Define immutable

value that can't change.


Set pelajaran terkait

CH 20 THE LYMPHATIC SYSTEM & LYMPHOID ORGANS & TISSUE

View Set

Health Problems of the Adolescent

View Set

Git Essential Training: The Basics: 1. What is Git?

View Set

XCEL Chapter 10 - Health Insurance Underwriting

View Set

Exam 3 Extra Credit Questions (Dynamic Study Modules)

View Set