Chapter 3: The world of variables and operators Flashcards
What is a variable?
Data that we need to store and manipulate in our programs
Example of a variable
UserAge (variable) = 0 (initial value)
Do you have to give a variable an initial value every time it is created?
YEAH!!
Can you change the value of a variable later in the program?
Yes
Can multiple variables be defined in one go?
Yes
Example of multiple variables
userAge, userName = 33, ‘Amrapali’
What is Table, chair = ‘brown’, ‘black’ is equivalent to?
Table = Brown Table = Black
What can a variable name in Python contain?
A variable name in Python can contain
1) Letter (a-z, A-Z)
2) Numbers
3) Underscores
Can the first character be a number?
No, the first character cannot be a number. variable name as 2username is invalid.
Example of variable names
userAge, user_age, userAge2
What words cannot be named as usernames?
Words which have a preassigned meaning to them cannot be used as variable names like input and print.
Is username same as userName?
No, because the variable names are case-sensitive
What are the two naming conventions for variables?
1) Camel case notation
2) Using underscores
What is camel case notation? Provide examples
Writing compound words with mixed casing. For example thisIsAVariableName
Example of underscore usage in naming a variable
this _is_a_variable_name
What is unique about ‘=’ in Python and math?
It has a different meaning in Python and math.
What is the ‘=’ sign called in programming?
It is called the assignment operator
What does the assignment operator mean?
It means we are assigning the value on the right side of the = sign to the variable on the left
If you type the below code into your IDLE editor X= 5 Y= 10 X=Y print ("X=", X) print ("Y=", Y)
What will be the output? Explain.
X= 10
Y= 10
Because, the third line assigns Y’s value to X
What are the basic operators in Python?
Addition, subtraction, multiplication, division, floor division, modulus and exponent
Provide examples of all the basic operators
x=5
y=2
Addition:
x+y=7
Subtraction:
x-y=3
Multiplication:
x*y= 10
Division:
x/y= 2.5
Floor Division:
x//y=2 (it rounds down the answer to the nearest whole number)
Modulus:
x%y=1 (gives the remainder when 5 is divided by 2)
Exponent:
x**y=25 (5 to the power 2)
What are the other assignment operators beside “=’?
+=, -= and *=
What does += implies?
If x= 10 then x+=2 i.e. x= x+2
the output will be x= 12
What does x-= implies?
If x= 10 then x-=2 i.e. x=x-2
the output will be x= 8
What will be the output of below code? x=10 x+=2 print(x) x-=2 print(x)
For the first print(x) will be 12 and the next one 10. This is because post executing the first print command x now has the value of 12 and the next -= function actually subtracts 2 from 12 thus giving us 10. This is an example of the fact that computer executes sequentially. If you want the subtraction answer as 8 you need to define the variable again.