Python Basics II Flashcards
How can you turn a list into a set?
With the set function, for example set([1,2,3,3]} will return {1,2,3}
How do you add an element to a set?
Use the add method, for example, {1,2,3}.add(4) gives {1,2,3,4}
What are the basic comparison operators?
> , <, ==, >=, <=, !=
For example
{1,1} == {1}
returns True
How do you do negation (not equal)?
Precede with an exclamation point, for example, 1 != 2 returns true
How are the “and” and “or” operators represented?
With the words and and or, for example,
1<2 and 2<3
Keep in mind Python is case-sensitive. If you write AND instead of and, you will get an error.
What is the syntax for conditional logic (If, then, else)?
It uses colon and indent format. For example,
if 1==1:
print(‘they are equal’)
else:
print(‘they are not equal’)
What is the syntax for multiple conditions
Use elif, for example,
if 1==12:
print(‘they are equal’)
elif 1<12:
print(‘middle’)
else:
print(‘they are not equal’)
How do you get Python to perform multiple actions when the condition is true?
Just keep listing the actions in the indented block. You do not need a Begin-End block, such as in other languages. Esample:
if 1==1:
print(‘they are equal’)
print(‘this too’)
print(‘and this’)
elif 1<12:
print(‘middle’)
else:
print(‘they are not equal’)
How do you name a variable embedded in a string?
By putting the variable name inside of the braces. For example,
‘This is var1 {x} and this is var2 {y}’.format(y=’World’, x=’Hello’)
Which returns,
‘This is var1 Hello and this is var2 World’
Does the add method work for lists?
No, it only works for sets.