a nerd enjoying life
professional -> software development -> python -> get started with python
So, what is a variable? You can think of a variable as an identifier to a value. It's a storage area in memory on the computer where the value is held until it is needed. In Python the type of vaiable is dynamic, which means it's type is assigned when a value is assigned to it.
max_score = 600
round_name = "Portsmouth"
So the variable max_score has been assigned, using the = operator, a type of integer with the value 600. The variable round_name has been assigned the type of string with the value "Portsmouth".
The naming convention that is preferred to be used in Python is snake_case. So make variable names descriptive, so that when code is being read the use of the variable can be determined by the name. For example:
Other naming conventions include camelCase and PascalCase, but although Python would have no problem using these as variable formats, it is not what is expecetd by the community standards.
A string can vary from an empty string, thorugh to a whole book (limited only by the memory of the computer the code is being run on). A simple string can be declared with single quotes encapsulating the string, or a double quote if the string contains a single quote, through to triple quotes.
simple_string = 'A simple example.'
#using double quotes to encapsualte a single quote
longer_string = "This is Bob's book"
#triple quotes for more complex strings
book_title = '''"A Grand Adventure with Alice's Dog and Donkey"'''
The putput to the screen will be:
A simple example.
This is Bob's book
"A Grand Adventure with Alice's Dog and Donkey"
Integers are any whole number, either positive or negative, including zero. Python does not limit the maximum value an integer can have, but the larger the number the more memory will be used and impact performance. Examples of integers are:
minimum_allowed_temp = -200
freezing_point = 0
maximum_allowed_temp = 120
Floats can take a range of numbers from negative to positive. However, there is a limitation on the number of significant digits after the decimal point, and is typically 15 to 17. To find the minimum and maximum values that your system can hold. Examples of floats are:
#accuracy to 5 decimal places
pi = 3.14159
print(pi)
#very large number
mass_of_the_sun = 1.989e30
print(mass_of_the_sun)
#very small number
mass_of_an_electron = 9.10938356e-31
print(mass_of_an_electron)
The output of this would be:
3.14159
1.989e+30
9.10938356e-31
If you have several variables that you need to assign, then there is a shorthand to include them all on the same line.
integer_1, float_2, string_last = 2, 8.56, "hello there"
print(integer_1)
print(float_2)
print(string_last)
The output will look like:
2
8.56
hello there
There is not a constant type in Python. In order to express a variable that should be treated as a constant the convention is to use UPPERCASE when declaring a variable.
To futher manage constants should be put into a separate module called, say, constants.py that are imported. Developers then know it is convention to not modify imported values (although Python does not prevent a developer from doing it.). An example constants.py would be:
MAXIMUM_SCORE = 600
TOTAL_ARROWS = 60
To then use these values they can be imported, so you would add something similar to this code.
from constants import MAXIMUM_SCORE
print(MAXIMUM_SCORE) # Output: 600
The input() function is used to get a string input from the user. The function can be called with an optional single arument, that is used as a prompt to the user.
string_one = input() string_two = input("Please enter a value:")
In the first line, the code will just get the computer to present a cursor, but no information given to the user as to what is expected. In the second use the string Please enter a value: will be shown.
There is no specific way to, for example, to force a user to input a number. The input function always returns a string, so the code will have to look at the value entered and convert it to an integer. to do this the int() function is used.
string_value = input("Please enter a value:")
print("Value that was input:", string_value)
value_1 = string_value * 10
print("Input * 10:", value_1)
value_2 = int(string_value) * 10
print("Input as integer * 10:", value_2)
Please enter a value:12
Value that was input: 12
Input * 10: 12121212121212121212
Input as integer * 10: 120
When this code is run you will see that value_1 will just end up being 10 times the string that was entered, as string_value is a string, so the code just assumes you want repeat it. In the second instance the int(string_value) converts the string entered into an integer. Note: if a non-integer is entered this will cause an error, which will need to be trapped to prevent the program crashing.
The input() function is used to to display information to the screen. There are several different ways to use it, and how it can format the data that it displays.
print(100)
float_value = 12.456
print(float_value)
print("Hello World!")
This is the simplest way in which to use the print() function. Just using it to output a value, whether it is just the value, or a variable.
Apart from a quick check to see what a value is, this is not of much use, we need a bit more information for the end user to make sense of what is going on. Typically output would be a combination of some fixed text, merged with information the program has generated. Since version 3.6 the more powerful way of doing this is usinf f-strings
f-strings are a method of merging and formatting information into strings. There are a number of ways this is done.
In this case the string is preceeded with f, or F, and the variable is placed within braces within the string that the value is to be merged.
total_arrows = 72
sentance = f"There are {total_arrows} arrows in a National round."
print(sentance)
The output will be:
There are 72 arrows in a National round.
To save on code the f-string can be placed within the print() function, so the code above will look like:
total_arrows = 72
print(f"There are {total_arrows} arrows in a National round.")
Just as a single variable can be embedded in a string, more can be added, just include them as required.
total_arrows = 72
score = 596
result_string = f"You scored {score} with {total_arrows} arrows."
print(result_string)
You scored 596 with 72 arrows.
f-strings can contain expressions, making it useful to display information without having to calculate them, and allocate to another variable before merging. In the example below two variables are divided within the brace, and this calculated value displayed.
total_arrows = 72
score = 596
result_string = f"You scored {score} with {total_arrows} arrows, giving an average of {score / total_arrows} per arrow."
print(result_string)
You scored 596 with 72 arrows, giving an average of 8.277777777777779 per arrow.
The number of digits after a decimal point can be more than required for accuracy. So in the example above 8.28, 2 dicimal points, would be more than enough. To achieve this .2f can be added as a formatter.
Example: f"{value:.2f}"
result_string = f"You scored {score} with {total_arrows} arrows, giving an average of {score / total_arrows:.2f} per arrow."
You scored 596 with 72 arrows, giving an average of 8.28 per arrow.
So when formatting is required you have the value being formatted, then a colon, followed by the formatting type. In this case .2f means the value will be represented by 2 digits after a decimal point. "
With a number you may want to add leading zeros so that all numbers look the same format over multiple lines. If the variable is already that length, or more, then none of the required padding is needed.
Example: f"{value:05}"
small_number = 23
large_number = 467125
print(f"The small number is {small_number:08}, and the large number is {large_number:08}."")
The small number is 00000023, and the larger number is 00467125.
Padding with zeros is useful, but sometimes you may want to pad with a different character, for example a space, and pad on the right instead of the left, or even centre the variable to fit in a particular width. For this, the f-string format string will have 3 components; the character to use, the alignment type (< ^ >), and the length.
example_number = 5612
print(f"{example_number:*<10}")
print(f"{example_number:*>10}")
print(f"{example_number:*^10}")
5126******
******5126
***5126***
By default a negative number always has the - displayed. However, for positive numbers, the default is to not show the + in front of the number. In order to force the symbol to be displayed for both positive and negative numbers the + format can be included. Just because a + is used as a format doesn't change a negative to a positive.
f"{value:+}"
value_positive = 25
value_negative = -34
print(f"Default display is {value_positive} and {value_negative}")
print(f"Sign formatted is {value_positive:+} and {value_negative:+}")
Default display is 25 and -34
Sign formatted is +25 and -34
In f-strings, the comma (,) is used as a thousands separator to make large numbers more readable by grouping digits into thousands. This formatting works for both integers and floats.
f"{value:,}"
large_integer = 4627891023456
large_float = 9834.2678902
print(f"{large_integer:,}")
print(f"{large_float:,}")
4,627,891,023,456
9,834.2678902
In f-strings, use :b for binary, :o for octal, and :x or :X for hexadecimal (lowercase or uppercase) to display integers in these numeral systems.
value = 42
print(f"Binary: {value:b}, Octal: {value:o}, Hex: {value:x}, Upper Hex: {value:X}")
Binary: 101010, Octal: 52, Hex: 2a, Upper Hex: 2A
Formatting can be combined together to produce an output as required. So, for example you could combine the decimal place (.) and comma (,) format, along with padding.
value_1 = 1245
value_2 = 2236.2267
value_3 = 72.8
print(f"{value_1:.>10,.2f}")
print(f"{value_2:.>10,.2f}")
print(f"{value_3:>10,.2f}") #pad with space (note: no full-stop)
..1,245.00
..2,236.23
72.80
With simple code, as we have looked at so far, comments and indentation are either not required or necessary. However, mvoing forward with more complex code the need to use them will be required.
Comments act a prompt or reminder to a human reading the code as to why something has been done, or the purpose of the code. It is not used by the Python interpreter, and will just skip over it, until the end of the comment information.
A single line of comment will just be marked with the # character
A comment can be added after a statement, so you could have a variable declaration, and a comment after it.
There is no standard way of multiple lines of comment. One way is to just to add a # to each line. Alternatively have the lines encapsulated within triple quotes (either single or double), because the string literal is not allocated to a varibale the Python interpreter will just ignore it.
#declaration of variables
integer_1 = 452
string_1 = "Hi there" #A typical string declaration
"""
Start of the code where we do stuff
Here we are just printing the variables
"""
print(f"{integer_1} and {string_1}")
Although they haven't been covered yet, indentation defines the block structure of code (e.g., for loops, functions, conditionals). The Python interpreter will enforces indentation to improve readability. If indentation is included where is it expected this will raise an IndentationError from the interpreter.
The industry standard is to use 4 spaces per indentation level, but whatever indentation you use ensure it is consistent.
total_sum = 100
#simple if else
if total_sum < 100:
print(f"You only have {total_sum}") # Indented block
else:
print("Wow, what a total!")
If the above code the indentation is ommitted on the final line, and the code looked like:
if total_sum < 100:
print(f"You only have {total_sum}") # Indented block
else:
print("Wow, what a total!")
The interpreter would produce a similar output as follows, indicating an indentation error
File "example_code.py", line 6
print("Wow, what a total!")
^
IndentationError: expected an indented block after 'else' statement on line 5
Athrimetic operators are used in Python to perform mathematical operations on values. These operators can work with both integers and floats.
Adds two numbers together.
print(5 + 3) # Output: 8
Subtracts the right number from the left.
print(10 - 4) # Output: 6
Multiplies two numbers.
print(6 * 7) # Output: 42
Divides the left number by the right and returns a float.
print(10 / 2) # Output: 5.0
Divides the left number by the right and returns the largest whole number (integer) less than or equal to the result.
print(10 // 3) # Output: 3
Returns the remainder of the division.
print(10 % 3) # Output: 1
Raises the left number to the power of the right number.
print(2 ** 3) # Output: 8
These operators return a Boolean value (True or False) depending on the condition of the comparaison.
Checks if two values are equal.
print(5 == 5) # Output: True
Checks if two values are not equal.
print(5 != 3) # Output: True
Checks if the left value is greater than the right value.
print(7 > 3) # Output: True
Checks if the left value is less than the right value.
print(3 < 7) # Output: True
Checks if the left value is greater than or equal to the right value.
print(5 >= 5) # Output: True
Checks if the left value is less than or equal to the right value.
print(3 <= 5) # Output: True
These operators combine assignment with specific operations, making your code shorter and more efficient.
Assigns a value to a variable.
x = 5
print(x) # Output: 5
Adds a value to the variable and assigns the result.
x = 5
x += 3
print(x) # Output: 8
Subtracts a value from the variable and assigns the result.
x = 5
x -= 2
print(x) # Output: 3
Multiplies the variable by a value and assigns the result.
x = 4
x *= 2
print(x) # Output: 8
Divides the variable by a value and assigns the result as a float.
x = 10
x /= 2
print(x) # Output: 5.0
Performs floor division and assigns the result.
x = 10
x //= 3
print(x) # Output: 3
Finds the remainder and assigns the result.
x = 10
x %= 3
print(x) # Output: 1
Raises the variable to a power and assigns the result.
x = 2
x **= 3
print(x) # Output: 8
Performs bitwise AND on the variable and assigns the result.
x = 5 # 0101 in binary
x &= 3 # 0011 in binary
print(x) # Output: 1
Performs bitwise OR on the variable and assigns the result.
x = 5 # 0101 in binary
x |= 3 # 0011 in binary
print(x) # Output: 7
Performs bitwise XOR on the variable and assigns the result.
x = 5 # 0101 in binary
x ^= 3 # 0011 in binary
print(x) # Output: 6
Shifts the bits of the variable to the left and assigns the result.
x = 3 # 0011 in binary
x <<= 2
print(x) # Output: 12 (1100 in binary)
Shifts the bits of the variable to the right and assigns the result.
x = 8 # 1000 in binary
x >>= 2
print(x) # Output: 2 (0010 in binary)
Logical operators are typically used in conditional statements and expressions to combine or modify conditions. Here’s a description of each logical operator in Python.
Returns True if both conditions are true.
print(True and False) # Output: False
Returns True if at least one condition is true.
print(True or False) # Output: True
Reverses the logical value of a condition.
print(not True) # Output: False
x = 5
print(x > 3 and x < 10) # Output: True (both conditions are true)
print(x < 3 or x > 10) # Output: False (neither condition is true)
print(not (x > 3)) # Output: False (negates the truth value)
Bitwise operators in Python perform operations directly on binary representations of integers, allowing for manipulation of individual bits. Here’s an example for each operator:
Sets each bit to 1 if both bits are 1.
print(5 & 3) # Output: 1 (0101 & 0011 = 0001)
Sets each bit to 1 if at least one bit is 1.
print(5 | 3) # Output: 7 (0101 | 0011 = 0111)
Sets each bit to 1 if only one of the bits is 1.
print(5 ^ 3) # Output: 6 (0101 ^ 0011 = 0110)
Inverts all the bits (1’s complement).
print(~5) # Output: -6 (~0101 = 1010 in 2's complement)
Shifts bits to the left by the specified number of positions (equivalent to multiplying by 2^n).
print(5 << 1) # Output: 10 (0101 << 1 = 1010)
Shifts bits to the right by the specified number of positions
(equivalent to dividing by 2^n).print(5 >> 1) # Output: 2 (0101 >> 1 = 0010)
In Python, membership operators test whether a value exists in a sequence (e.g., list, string, tuple):
Returns True if the specified value exists in the sequence.
print(3 in [1, 2, 3]) # Output: True
Returns True if the specified value does not exist in the sequence.
print(4 not in [1, 2, 3]) # Output: True
In Python, identity operators check whether two objects reference the same memory location:
Returns True if two objects refer to the same memory location.
a = [1, 2, 3]
b = a
print(a is b) # Output: True
Returns True if two objects do not refer to the same memory location.
a = [1, 2, 3]
b = [1, 2, 3]
print(a is not b) # Output: True (different memory locations)
Now there is the basic elements of variables and logic, some structure to process control flow can be added. Control flow manages the order in which instructions are executed. So far instructions have just been sequential, but loops and conditional statements will add more functionality to code.
Used to make decisions based on conditions.
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
Iterates over a sequence.
for i in range(3):
print(i) # Output: 0, 1, 2
Repeats as long as a condition is true.
i = 0
while i < 3:
print(i)
i += 1
Special commands to control loop execution.
Exits the loop.
Skips the current iteration.
Does nothing, acts as a placeholder.
for i in range(5):
if i == 2:
continue # Skip 2
elif i == 4:
break # Exit loop
print(i) # Output: 0, 1, 3
A tuple is a list of fixed elements, and is immutable (cannot be changed after creation).
Tuples should be used when data is fixed because it uses less memory compared to lists, so has improved performance.
Due to tuples being immutable, there are only two methods available; count() and index(). See below for an explaination of these.
days_of_week = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
print(days_of_week[2]) #Ouput: Wed
A list has a number of elements that are mutable (can be modified after creation).
Lists will use up more memory than a tuple, but have more methods available because they are mutable. These methods are; append(), extend(), insert(), remove(), pop(), clear(), index(), count(), sort(), reverse(), and copy()
entrants = ["Bob", "Alice"]
print(entrants) #Ouput: ['Bob', 'Alice']
entrants.append("Carl")
print(entrants) #Ouput: ['Bob', 'Alice', 'Carl']
entrants.sort()
print(entrants) #Ouput: ['Alice', 'Bob', 'Carl']
A set in Python is an unordered collection of unique, immutable elements, often used for membership testing and mathematical operations like union and intersection.
my_set = {1, 2, 3, 3} print(my_set) # Output: {1, 2, 3}
A dictionary in Python is an unordered collection of key-value pairs, where keys are unique and used to access their corresponding values.
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Output: Alice
Here are the methods for each data structure in Python:
A count of the number of elements matching the value requested. It requires exactly one value, otherwise there will be a TypeError.
example_tuple = (2, 1, 2, 1, 3, 3, 2)
print(example_tuple.count(2)) #Ouput: 3
The index() method returns the index value of the first occurence in the tuple. It requires exactly one value, otherwise there will be a TypeError.
index()
example_tuple = (2, 1, 2, 1, 3, 3, 2)
print(example_tuple.index(2)) #Ouput: 0
append()