Mooc,fi Flashcards
(37 cards)
Computer programs consist of
commands, each command instructing the computer to take some action. A computer executes these commands one by one. Among other things, commands can be used to perform calculations, compare things in the computer’s memory, cause changes in how the program functions, relay messages or ask for information from the program’s user.
Arithmetic operations
You can also put arithmetic operations inside a print command. print(2 + 5), Notice the lack of quotation marks around the arithmetic operations above. Quotation marks are used to signify strings.
strings
are sequences of characters. They can consist of letters, numbers and any other types of characters, such as punctuation. Strings aren’t just words as we commonly understand them, but instead a single string can be as long as multiple complete sentences. Strings are usually printed out exactly as they are written.
Commenting
Any line beginning with the pound sign #, also known as a hash or a number sign, is a comment. This means that any text on that line following the # symbol will not in any way affect how the program functions. Python will simply ignore it.
Comments are used for explaining how a program works, to both the programmer themselves, and others reading the program code.
When the program is run, the comment will not be visible to the user
Input
refers to any information a user gives to the program. Specifically, the Python command input reads in a line of input typed in by the user. It may also be used to display a message to the user, to prompt for specific input.
variable
a variable is a location for storing some value, such as a string or a number. This value can be used later, and it can also be changed.
the value stored in a variable can change. In the previous section we noticed that the new value replaces the old one.
Referencing a variable
A single variable can be referred to many times in a program
Choosing a good name for a variable
It is often useful to name variables according to what they are used for. For example, if the variable contains a word, the name word is a better choice than, say, a.
There is no set limit to the length of a variable name in Python, but there are some other limitations. A variable name should begin with a letter, and it can only contain letters, numbers and underscores _.
Lowercase and uppercase letters are different characters. The variables name, Name and NAME are all different variables. While this rule has a few exceptions, we will ignore those for now.
It is a common programming practice in Python to use only lowercase characters in variable names. If the variable name consists of multiple words, use an underscore between the words. While this rule also has a few exceptions, we will ignore those for now.
Integers
Integers are numbers that do not have a decimal or fractional part, such as -15, 0 and 1.
Notice the lack of quotation marks here. In fact, if we were to add quotation marks around the number, this would mean our variable would no longer be an integer, but a string instead. A string can contain numbers, but it is processed differently.
For integer values the + operator means addition, but for string values it means concatenation, or “stringing together”.
If we do want to print out a string and an integer in a single command, the integer can be cast as a string with the str function, and the two strings can then be combined normally.
The print command also has built-in functionalities that support combining different types of values. The simplest way is to add a comma between the values. All the values will be printed out regardless of their type
Printing with f-strings
So called f-strings are another way of formatting printouts in Python. The syntax can initially look a bit confusing, but in the end f-strings are often the simplest way of formatting text.
With f-strings the previous example would look like this:
result = 10 * 25
print(f”The result is {result}”)
A single f-string can contain multiple variables.
Floating point numbers
Floating point number or float is a term you will come across often in programming. It refers to numbers with a decimal point. They can be used much in the same way as integer values.
end = “”
For example:
print(“Hi “, end=””)
print(“there!”)
Sample output
Hi there!
Arithmetic operations
Operator Purpose Example Result
+ Addition 2 + 4 6
- Subtraction 10 - 2.5 7.5
* Multiplication -2 * 123 -246
/ Division (floating point result) 9 / 2 4.5
// Division (integer result) 9 // 2 4
% Modulo 9 % 2 1
** Exponentiation 2 ** 3 8
The order of operations is familiar from mathematics
first calculate the exponents, then multiplication and division, and finally addition and subtraction. The order can be changed with parentheses.
Operands, operators and data types
A calculation usually consists of operands and operators.
The data type of an operand usually determines the data type of the result: if two integers are added together, the result will also be an integer. If a floating point number is subtracted from another floating point number, the result is a floating point number. In fact, if a single one of the operands in an expression is a floating point number, the result will also be a floating point number, regardless of the other operands.
Division / is an exception to this rule. Its result is a floating point number, even if the operands are integers. For example 1 / 5 will result in the floating point number 0.2.
Integer division operator //
If the operands are integers, it will produce an integer. The result is rounded down to the nearest integer
x = 3
y = 2
print(f”/ operator {x/y}”)
print(f”// operator {x//y}”)
prints out
Sample output
/ operator 1.5
// operator 1
Numbers as input
We have already used the input command to read in strings from the user. The same function can be used to read in numbers, but the string produced by the function must then be converted to a numeric data type in the program code. In the previous section we cast integers as strings with the str function. The same basic principle applies here, but the name of the casting function will be different.
A string can be converted into an integer with the function int. The following program asks the user for their year of birth and stores it in the variable input_str. The program then creates another variable year, which contains the year converted into an integer. After this the calculation 2021-year is possible, using the user-supplied value.
input_str = input(“Which year were you born? “)
year = int(input_str)
print(f”Your age at the end of the year 2021: {2021 - year}” )
conditional statement
with a block of code which is executed only if the condition in the statement is true.
In a conditional statement the keyword if is followed by a condition, such as a comparison of two values. The code block following this header line is only executed if the condition is true.
age = int(input(“How old are you? “))
if age > 17:
print(“You are of age!”)
print(“Here’s a copy of GTA6 for you.”)
print(“Next customer, please!”)
Comparison operators
Operator Purpose Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
>= Greater than or equal to a >= b
< Less than a < b
<= Less than or equal to a <= b
Indentation
Python recognises that a block of code is part of a conditional statement if each line of code in the block is indented the same. That is, there should be a bit of whitespace at the beginning of every line of code within the code block. Each line should have the same amount of whitespace.
You can use the Tab key, short for tabulator key, to insert a set amount of whitespace.
Statement
A statement is a part of the program which executes something. It often, but not always, refers to a single command.
For example, print(“Hi!”) is a statement which prints out a line of text. Likewise, number = 2 is a statement which assigns a value to a variable.
A statement can also be more complicated. It can, for instance, contain other statements. The following statement spans three lines:
if name == “Anna”:
print(“Hi!”)
number = 2
In the above case there are two statements (a print statement and an assignment statement) within a conditional statement.
Block
A block is a group of consecutive statements that are at the same level in the structure of the program. For example, the block of a conditional statement contains those statements which are executed only if the condition is true.
if age > 17:
# beginning of the conditional block
print(“You are of age!”)
age = age + 1
print(“You are now one year older…”)
# end of the conditional block
print(“This here belongs to another block”)
In Python blocks are expressed by indenting all code in the block by the same amount of whitespace.
NB: the main block of a Python program must always be at the leftmost edge of the file, without indentation:
Expression
An expression is a bit of code that results in a determined data type. When the program is executed, the expression is evaluated so that it has a value that can then be used in the program.
Here are a few examples of expressions:
Expression Value Type Python data type
2 + 4 + 3 9 integer int
“abc” + “de” “abcde” string str
11 / 2 5.5 floating point number float
2 * 5 > 9 True Boolean value bool
Because all expressions have a type, they can be assigned to variables:
the variable x is assigned the value of the expression 1 + 2
x = 1 + 2
Simple expressions can be assembled together to form more complicated expressions, for example with arithmetic operations:
the variable y is assigned the value of the expression ‘3 times x plus x squared’
y = 3 * x + x**2
Function
A function executes some functionality. Functions can also take one or more arguments, which are data that can be fed to and processed by the function. Arguments are sometimes also referred to as parameters. There is a technical distinction between an argument and a parameter, but the words are often used interchangeably. For now it should suffice to remember that both terms refer to the idea of some data passed to the function.
A function is executed when it is called. That is, when the function (and its arguments, if any) is mentioned in the code. The following statement calls the print function with the argument “this is an argument”:
print(“this is an argument”)
Another function you’ve already used often is the input function, which asks the user for input. The argument of this function is the message that is shown to the user:
name = input(“Please type in your name: “)
In this case the function also returns a value. After the function has been executed, the section of code where it was called is replaced by the value it returns; it is another expression that has now been evaluated. The function input returns a string value containing whatever the user typed in at the prompt. The value a function returns is often stored in a variable so that it can be used in the program later on.