andrewthenerd

a nerd enjoying life

professional -> software development -> python -> get started with python

Python

Contents

  1. Variables and Simple Data Types
    1. Variables
    2. Naming Convention
    3. Strings
    4. Integers
    5. Floats
    6. Multiple Assignment
    7. Constants
  2. Input and Output
    1. input() function
    2. print() function
    3. f-strings
  3. Comments and Indentation
    1. Comments
    2. Indentation
  4. Operators
    1. Arithmetic Operators
    2. Comparaison Operators
    3. Assignment Operators
    4. Logical Operators
    5. Bitwise Operators
    6. Membership Operators
    7. Identity Operators
  5. Control Flow
    1. If-else Statements
    2. for loop
    3. while loop
    4. Break, continue, and pass
  6. Data Structures
    1. Tuples
    2. Lists
    3. Sets
    4. Dictionaries
    5. X Data Struture Methods
  7. Functions
    1. X Defining and calling functions
    2. X Arguments and return values
    3. X Default arguments
    4. X *args and **kwargs
    5. X Lambda functions

Variables and Simple Data Types

Variables

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".

Naming Convention

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.

Strings

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

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

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

Multiple Assignment

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

Constants

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

Input and Output

input() function

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

f-strings are a method of merging and formatting information into strings. There are a number of ways this is done.

Basic f-string Format

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.")

Multiple Values

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.

Embedded Expresions

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.

Number Formatting

Decimal Places

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. "

Padding

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.

Width and Alignment

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***

Positive and Negative

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

Big Number Comma

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

Binary, Octal, Hexidecimal

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

Combining Fomatting

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

Comments and Indentation

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

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}")

Indentation

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

Operators

Arithmetic Operators

Athrimetic operators are used in Python to perform mathematical operations on values. These operators can work with both integers and floats.

Comparaison Operators

These operators return a Boolean value (True or False) depending on the condition of the comparaison.

Assignment Operators

These operators combine assignment with specific operations, making your code shorter and more efficient.

Logical Operators

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.

Bitwise Operators

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:

Membership Operators

In Python, membership operators test whether a value exists in a sequence (e.g., list, string, tuple):

Identity Operators

In Python, identity operators check whether two objects reference the same memory location:

Control Flow

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.

If-else statements

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")

For loop

Iterates over a sequence.

for i in range(3):
    print(i) # Output: 0, 1, 2

While loop

Repeats as long as a condition is true.

i = 0
while i < 3:
    print(i)
    i += 1

break, continue, and pass

Special commands to control loop execution.

for i in range(5):
    if i == 2:
        continue # Skip 2
    elif i == 4:
        break # Exit loop
    print(i) # Output: 0, 1, 3

Data Structures

Tuples

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

Lists

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']

Sets

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}

Dictionaries

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

Data structure methods

Here are the methods for each data structure in Python:

Functions

Defining and calling functions

Arguments and return values

Default arguments

*args and **kwargs

Lambda functions