Python

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:

https://www.jetbrains.com/pycharm/download/

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
#comments
  indented code

Python REPL:

>>> foo = 123
>>> bar = "hello world"
>>> foo
123
>>> 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.

IE:

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
type(foo)

the output after running this

<class 'int'>
bar = "hello world"
type(bar)

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.

Indents

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

IE:

 __main__
 #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

 __end_of_main__ 

Python Basics

Creating lists

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

list = []
list.append(listItem1)
list.append(listItem2)

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")
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?")
print("name")

The output would be whatever you put in:

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

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
'37'
>>> 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
'37'
>>> intage
37

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
38

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
37

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). The While loop is useful for as long as something is true or false an if statement is useful when comparing items and a for in loop is good for performing a task on a list or set of data:

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

    if mm_count == guess:
        print(f"You win! It was {guess}")
        exit
    elif guess < mm_count:
        print("Sorry that's too low")
    else:
        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")
else:
   print("No Data")

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

if not age:

If you have a large set of data you need to cycle through using a for in loop is recommended:

plays = ["Rock", "Paper", "Scissors"]

print("Available options: ", end=' ')
for p in plays:
    print(p, end=' ')
print()

Here we are using end=" " to show that we want these items on the same line versus a new line by adding a space instead of a traditional carriage return alternatively you could use commas or dashes or whatever you want here. Notice the simplicity of the loop. The p here is simply a variable name and can be anything you want for i in or for n are very common in these loops and many use the first letter of the variable or list name you are looping through. If you have a set of data that you need to perform the same task on through the list a for in loop is the way to go.

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("--------------------------------")
    print("Rock Paper Scissors Roshambo v1")
    print("--------------------------------")

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():
    show_header()

def show_header():

    print("--------------------------------")
    print("Rock Paper Scissors Roshambo v1")
    print("--------------------------------")

if __name__ == '__main__':
    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")
        return

Multiple ways to code the same thing

In python there are lots of various ways to come to the same outcome, some are better than others though and it usually takes time to figure out for yourself what that means. Usually better code boils down to the ability for you and others to understand what it is doing as easily as possible. There are other factors of course but for the most part you want to be able to come back and know what you were doing when you created your code. Lets try creating a multiple choice list multiple different ways:

rolls = ['rock', 'paper', 'scissors']
for r in rolls:
    print(r)

This will provide us with a very basic list of the items within our list rolls:

rock
paper
scissors

But what if we want this as a numerical list so you can select the roll you wanted:

rolls = ['rock', 'paper', 'scissors']
index = 1
for r in rolls:
    print(f"{index}. {r})
    index +=1

That does give us what we are looking for a numerical list:

1. Rock
2. Paper
3. Scissors

However that's not the best way this could be done:


rolls = ['rock', 'paper', 'scissors']
print("Available rolls:")
for index, r in enumerate(rolls, start=1):
    print(f"{index}. {r})
    

While this is not really "easier" to read by using the enumerate function we do not need the added code for increasing the count for the index. We can also set the starting number as indexes and lists and computers in general start counting at 0. While there are multiple ways to get a numbered list you want to understand what the code is doing without creating excess work for yourself so using built in functions is recommended as much as possible.

Data Structures

Dictionaries, Lists / Arrays and Sets are all examples of data structures in python (Lists and Arrays are the same thing. Python calls them lists other languages call them Arrays). Dictionaries are groups of data with variable data within them that include key and value pairs, Lists and Arrays are groups of data that can be sorted or looped through and can contain repeating data, sets are individual groups of data that do not repeat:

Lists

lst = [1,1,11,7]
#notice how lists and arrays can have repeating data
print(lst)

[1,1,11,7}]

#you can append to them
lst = [1,1,11,7]
lst.append(2)
print(lst)

[1,1,11,7,2]

lst = [1,1,11,7]
#you can remove them
lst.remove(11)
print(lst)

[1,1,7]

#you can organize them
lst = [2,1,11,7]
lst.sort()
print(lst)

[1,2,7,11]

Sets

#Sets are called with curly braces and do not have repeating data
st = {1, 1, 11, 7}
st.add(1)
st.add(11)
print(st)

{1, 11, 7}

Notice how even though the set was created with duplicates and duplicates were added, when printed it only includes non repeating data.

Dictionaries

Dictionaries are kind of like sets but they allow you to add a name or key and quickly search for the value associated with that key.

d = {
    'bob': 0,     #bob is the key and 0 is the value
    'sarah': 0,
}
print(d['bob'])

0

The dictionary is called with a curly brace or using dict() and the key and value are separated by colons. This way we can use these usernames and set the amount of wins they have for example and then later we can call the key from the dictionary to find the value as above, which is currently 0. We can further manipulate the value as needed:

d = {
    'bob': 0,
    'sarah': 0,
}
print(d['bob'])
d['bob'] += 1      #here we increment the value
print(d['bob'])    #here we print the value for the key of bob
print(d)           #here we print the entire dictionary

0
1
{'bob': 1, 'sarah': 0}

So you can see that appending to the dictionary changes the value for the key. You can also add non-existent keys:

d = {
    'bob': 0,
    'sarah': 0,
}
print(d['bob'])
d['bob'] += 1
print(d['bob'])
print(d)
d['michael'] = 7   #here we are adding a key and setting the value to 7
print(d)

0
1
{'bob': 1, 'sarah': 0}
{'bob': 1, 'sarah': 0, 'michael': 7}