From Just another day in the life of a linux sysadmin
Jump to navigation Jump to search


Python Notes

I would highly recommend using a code based editor like pycharm while learning python. It's free and can be a huge help at pointing out coding errors and easing your coding experience by aiding you while you type (it immediately adds closing parenthesis, brackets and quotes and knows when to indent automatically within loops and can list your variables as you type them and a plethora of other handy tools).

You can get pycharm here for free by downloading the community edition:

Wiki formatting for code examples

There are two ways python code can be displayed for this wiki, either showing it as code in a script, or code typed into a python REPL (read evaluate print loop) which is basically just a terminal that is running python that functions as a live script. You hit enter and it runs whatever line of code you input, but it also lets you stack commands so you can set a variable and then use that in the next line of code. The way you can tell if something is in script format is it is just lines of code. If it is run in the REPL you will see >>> indicating the python prompt:

IE: Scripts that you run as a whole:

line of code
line of code
  indented code

Python REPL:

>>> foo = 123
>>> bar = "hello world"
>>> foo
>>> bar
'hello world'

Notice the output of the REPL is not preceded by the >>> python prompt. This shows where code / input is and what the output would be after running (hitting enter), and would be displayed on the next line. The point in clarifying this is that while most python is written in a script and then run, it is easier within a wiki to use the REPL format as it tells the reader that all the previous code used in other examples relative to the section still applies without having to keep repeating the same lines of code if I were to show a script example.

Variable Types

Python variable types do not need to be set in your code as some languages require but can be called using the type tool if you are not sure.


foo = 123 #this is an auto integer
bar = "hello world" #this is a string due to the quotes

You can find out what a variable is set to using the type tool

foo = 123

the output after running this

<class 'int'>
bar = "hello world"

the output after running this:

<class 'str'>

Data Types

You may want to investigate what data types are if you are unfamiliar. This is important in every coding language and references what type of data is being used or referenced. For example a data type may be an integer meaning a number on the 10 base t spectrum, or a string meaning a line of alphabetic characters (usually), it could be numerical in output or both. If you want to do math you want integers and decimals (floating point numerals) if you expect some form of mathematical output. There are multiple types of ways data can be input and read. We need to understand that certain data can only be used in certain ways and displayed as such. The computer needs to be told that your data will be used as a certain type as it can not do math on letters and does not assume a number will be used as for math.


Indentations are important and the location of the start of a line of code can imply it is within a function or loop


 #comments are just fine anywhere on the line its only running code that needs to be located after the functions start location

 foo = 123 #this will error if on the same line as the function it is within
  bar = "hello world" #when using the tab or indent key (not spaces) this WILL read as a part of the main function


Python Basics

Creating lists

a collection of pieces of data in order is a list and is set using square brackets []

list = []

Lists can be used in your program to define what answers you expect so user input can be error checked and various other reasons. For example if you are creating a rock paper scissors game you only want the options a player can use to be rock, paper or scissors:

rolls = ["rock", "paper", "scissors"]

this list can now be used when calling for input or writing a function to ensure only these options are selected (more on this later).

Importing modules / libraries

Python comes with a slew of tools you can use with precoded modules. You can use these in your scripts via calling them with the import command

import sys
import Date

Printing data to screen

The print statement and say statement can be used to write to the users screen. Newer versions of python have different requirements than older versions but will usually tell you if you mess up.

>>> print "hello"
  File "<stdin>", line 1
    print "hello"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?
>>> print("hello")

Some versions allowed simply quotes after the print statement but it is best practice to use parenthesis and quotes as later versions do not.

Input data from a user

input("Question you want to ask")

setting a variable to this input allows you to call it later

name = input("What is your name?")

The output would be whatever you put in:

 >>> name = input("What is your name?")
What is your name?Joel
>>> name

Notice the output shows the string in quotes indicating this is a string. If you ask a question and expect a numerical answer you will want to change the type of that answer to an integer if you plan on manipulating that data. Here's what happens if you don't:

>>> age = input("What is your age?")
What is your age?37
>>> age
>>> next_age = age + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

So anytime you want to input data that is not going to be a string you need to define the type by setting it as that type after input or by setting the input as that type.

setting the input as a variable that is an integer

>>> intage = int(age)
>>> age
>>> intage

You can see that now that this is defined as an integer you can manipulate that data (applying math to integers etc)

>>> next_age = intage + 1
>>> next_age

Alternatively you can just set the input as an integer using input and int in separate parenthesis:

>>> age2 = int(input("What is your age?: "))
What is your age?: 37
>>> age2

Verifying / validating input from a user

Let's be honest users are not perfect and often make mistakes when asking for input or just don't know what is expected if not spelled out for them. This is where lists and validating input can be very important if you want your program to run properly. Usually when inputting data you want a specific answer in a specific format. This could be a date or string of text. Considering that the format of that data can vary we need to ensure we only input what we want. This can be done by setting a list of potential answers and then checking to see if the input was in the list:

rolls = ['rock', 'paper', 'scissors']
roll1 = get_roll(player_1, rolls)
roll2 = random.choice(rolls)

Here we have set a list called rolls and two variables roll1 and roll2. Roll1 calls a function called get_roll which requires the player_1 data and the list data we set in rolls so these are passed to the function in the parentheses when calling the function (more on this later). Roll2 uses the "random" prewritten function (this would be imported earlier in your script) and allows for a choice of any item in the list rolls.

You can also manipulate the input afterwards to ensure it does not contain capital letters or extra spaces or fits a certain date format etc:

roll1 = roll1.lower().strip()

This will take the input variable roll1 and ensure it is only lowercase (lower) and remove any extra spaces (strip).

Using Loops and comparisons

You can repeat operations in python as in most any language using loops and can determine things in your code using if statements. The basic functionality is the same as usual but python does require a colon after the first line when using loops or if comparisons as well as indents after calling the loop and if statement (with further indenting for nested loops or loops within loops):

while attempts < attempt_limit:
    guess_text = input("How many?")
    guess = int(guess_text)

    if mm_count == guess:
        print(f"You win! It was {guess}")
    elif guess < mm_count:
        print("Sorry that's too low")
        print("Sorry that's too high!")

    attempts += 1

You can use an if statement to determine if a variable has data or not. Python considers all data that is empty to be false and any variable that contains data to be true. If you need to find out if a variable has data or not you can simply ask if it is true:

age =37
intage = int(age)
if age == True:

You could do as the above but you can simplify this:

if age:
   print("There is data")
   print("No Data")

Similarly you can test if it is not true (False)

if not age:

Working with variables

Setting a variable in python is as easy as declaring the name of the variable an equals sign and its value

variable = value
age = 37
intage = int(37)

Using or calling that variable in text requires curly brackets as well as a format indicator that tells python you will be including a variable which is just a simple f:

print(f"My age is {age}")

You can add to numerical variable using the += short key this is used for incrementing in loops often:

attempts = attempts + 1
attempts += 1

Working with Functions

Functions allow you to clean up your code so it's not just a slew of endless lines. This can make debugging easier as you can seperate code functionalities into segments. To create a function you define it using def:

 def show_header():

    print("Rock Paper Scissors Roshambo v1")

This is a very simple way of taking the segment of code that displays a few print statements for a basic game and encapsulating them into a function. In pycharm you can collapse and expand these functions to make viewing your code easier on the eyes. You can then call this function later in your script when you want to display this. Because there is no way to close the functions any code after the function would be considered a part if it so you will need to put remaining lines of code within a function as well. This doesn't mean everything needs its own separate function as most coders will just create a function called main and include any other lines of code here. Main is also where you can call your other functions:

def main():

def show_header():

    print("Rock Paper Scissors Roshambo v1")

if __name__ == '__main__':

Notice the if statement at the end. This tells python not to run the main function unless called directly so other functions can be defined without ending the program. Essentially it says only run the main function when running the script as a whole. This is required when using a main function that calls other functions.

You will notice each function is followed by parenthesis, these allow you to pass variables into the function that were created elsewhere. As it sits the function only "knows" what you tell it and is seperate from the main script so it does not know if you created variables elsewhere. Using a variable in a function is sometimes called a local variable and one that is used thru the whole script is called a global variable. In python you don't set global variables but rather pass previously created variables into the function itself:

def check_for_winning_throw(player_1, player_2, roll1, roll2):

This function tests to see who wins and that requires knowing who the players are and what they rolled so these variables are passed along when defining the function within its parenthesis. Once you have written your function you will want to provide the data that it finds to your script. This is done using the return statement.

def get_roll(player_name, rolls):
    input(f"{player_name}, What is your roll? [rock, paper, scissors]: ")
    # this takes input and forced lowercase and removes spaces
    roll = roll.lower().strip()
    if roll not in rolls:
        print(f"Sorry {player_name}, {roll} is not a valid play!")
        #this tells the function invalid data was provided so nothing is returned
        return None
    #this passes the roll data back to the function so when its called this is what it provides
    return roll

Return can also be used when invalid data is input and there is no data to return to the program. In this example the function that returns the roll data will be set to return none when a mistake is entered (see above) and when testing for a valid roll in the play game function (which is not set to return anything) return is used by itself to exit the function:

    if not roll1:
        print("Cant play that, exiting")