-
Notifications
You must be signed in to change notification settings - Fork 1
Python Tips and Tricks
"Python Programmer's Glossary Bible" By Joseph C. Richardson
Hello and welcome to the knowledge of programming, with Python. Python is an object oriented programming language, such as C++. Python’s object oriented programming language makes Python very easy to understand, especially if you are coming from another type of computer programming language like C++; Python and C++ are very similar to each other. And as a matter of fact, Python derived from C++. However, with object oriented programming languages, there are no line numbers to type and there are no such things as ‘gosubroutine’ or ‘goto’ commands. Instead, Python uses ‘functions’ to call for subroutines. Functions can also do much more than simply call for subroutines; we will get into functions later. Python is very picky about how you place your programming statements. Python executes/runs its programs from the top of the programming list, downward. If you don’t have some program statements on the right line of the program list, then Python will bypass those commands, or even execute them at the wrong time. It’s very important on how you type your Python programs. One other thing Python is very, very picky about, with Python programming it is imperative to properly ‘indent’ your code; you may need some practice to get comfortable with how to properly indent your code, without creating indentation errors and not knowing why. To remedy such unwanted indentation errors from occurring, simply press the ‘ENTER’ key after each line of code you type. The cursor will automatically indent for you on the next line; all you do is type your code and let the cursor do the indents for you each time you press the ‘ENTER’ key. Note: all indentations must be exactly in-line, or an ‘unexpected indent syntax error’ dialog box will occur. See example below:
Here are some examples of line-indentations in Python, which always proceeds right after the use of a colon (:). For example, consider the following with yellow highlighted colons (:) showing where they are.
- for key,value in dictionary_list.items():
- print(key,value[0])
- def my_second_function():
- print('My second function.')
- class Dunder_str:
-
- def __init__(self,num1,num2):
- self.num1=num1
- while True:
-
- while True:
- os.system('cls')
- if Boole==True:
-
- if not Boole:
- print(Boole)
For those such was myself, who are quite new to object oriented programming, it takes about a good year or more to fully start to understand it. But with a little bit of practice and patience each and every single day, your Python programming skills will get sharper as you learn. You will make all kinds of mistakes along the way, but that’s also part of learning anything new. So let’s get started and take the journey into the knowledge of Python Object Oriented Programming Language with my "Python Programmer's Glossary Bible". Because great programming always starts with a great programmer’s manual.
Tips & Tricks for Novice Programmers: For those who are very new to programming, here are some very important things to keep in mind. When writing programs always create nice, clean and meaningful code; don’t create strings that are hard to understand. For example, create a string like this: name = ‘Jim’, not like this: n = ‘Jim’. Use meaningful names for strings of all types, such as character strings, integer strings, including tuples, lists and dictionaries alike. Creating meaningful strings also reduces accidental syntax errors from occurring in your programming code. Another very important thing to keep in mind is commenting your programming code so that you and other programmers, who are sharing the same project will be able to tell what parts of the programming code are doing what and such. Comments start with the '#' number sign followed by the commented word, or words. For example, # This is a print statement’s string variable ‘name’. Here is another example of what a comment might look like, # This loop counts all the items in the names list. Comments help the programmer express in meaningful ways how the program works and other programmers can easily pick up the pieces when they take over the nightshift. Another type of comment is with the use of three single quote marks (''') at the beginning of the comment statement and at the end of the comment statement. This type of comment can hold complete paragraphs, whereas the '#' comment statement can only hold words on a single line. The two examples of comments are as follows: # This is a comment statement on a single line. ''' This is a commented paragraph statement, which can hold a complete paragraph about the program and how it works. You can use as many lines of commented words as you please. ''' Note: comments do not execute/run, while a program is executing or running. Comments are ignored by the program; only the programmers know that comments exist within the programming code. As you study the "Python Programmer's Glossary Bible", you will constantly notice how everything written is in the form of these, two types of comment statements.
Case Sensitivity Case sensitivity in programming of every kind is very important to understand. This means that text must be typed correctly. For example, if you type a string's variable name with a capital letter, then you will also have to keep using that string's variable name with a capital letter. Likewise, if you type a string's variable name with a small letter, then you will also have to keep using that string's variable name with a small letter. However, programmers understand case sensitivity as 'Uppercase' and 'Lowercase', which simply means 'Caps and Non-Caps.
For example, take a close look at these two string variable names. (A='Value') and (a='Value'). Both of these strings are exactly the same, but with one exception, the variable name 'A' is also shown as 'a' in the other string variable name example. To gain a much better understanding of case sensitivity in programming, here are two examples of yellow, highlighted string variable names, which involve case sensitivity in the Python code. For example, consider the following:
Correct case sensitivity
A='Value' print(A)
a='Value' print(a)
incorrect case sensitivity
A='Value' print(a)
a='Value' print(A)
If you take a close look at these two Python program examples below, you will clearly see how case sensitivity works. Both variable names are of the letter 'A' and 'a', but Python thinks they are different variable names, that belong to different values. So it's very important that you always keep string variable names with different, unique letters to avoid any potential naming errors, which may occur, such as in these two illustrated Python program examples below.
A=" I'm the Value for uppercase A " print(A)
a=" I'm the Value for lowercase a " print(a)
However, case sensitivity doesn't stop at string variable names alone, input statements are also governed by case sensitivity, so are classes and functions alike. Some Python commands start with an uppercase letter, such as 'Canvas, Label, Entry, Tk(), True, False. And some, such as class functions always start with a capital letter in the variable name as a standard, but lowercase letters can also be used in class variable names as well. Note: most, basic string variable names are usually written as lowercase letters as a standard, but uppercase letters can also be written as well.
DRY (Don't Repeat Yourself) When it comes to programming, especially those who are brand new to programming will often write repetitious code, without realizing it. Repetitious code simply means using the same code, or command statements over and over again. For example, consider the following:
Don't Repeat Yourself! print("Hello Sun!") print("Hello Moon!") print("Hello Stars!") print("Hello World!")
Keep it DRY! words_tuple=("Hello Sun!","Hello Moon!","Hello Stars!","Hello World!")
- for words in words_tuple:
- print(words)
Single-Line Multiple Command Statements Python supports single-line multiple command statements, which means most command statements can be written on the same line using commas (,) as command-line separators. For example, consider the following:
print("Hello Sun!") print("Hello Moon!") print("Hello Stars!") print("Hello World!")
print("Hello Sun!"),print("Hello Moon!"),print("Hello Stars!"),print("Hello World!")
Python supports single-line multiple strings, which means multiple strings can be written on the same line using semicolons (;) as string separators. For example, consider the following:
string_1=' "Python' string_2="Programmer's" string_3='Glossary' string_4='Bible" '
string_1=' "Python';string_2="Programmer's";string_3='Glossary';string_4='Bible" '
print(string_1,string_2,string_3,string_4)
Python supports single-line multiple import function statements, which means multiple import function statements can be written on the same line using semicolons (;) as import function statement separators. For example, consider the following:
import os import time import math from math import* import winsound
import os;import time;import math;from math import*;import winsound
import os,time,math,winsound;from math import*
Note: to keep things simple, especially for the novice programmer, all program statements and program examples will remain on separate command lines. To the novice programmer, this is especially important to be able to mitigate any programming errors, which will occur from time to time as you write programs, especially complex programs. However, it is good practice to keep nice, neat program code on separate command lines to make it easy to understand; professional programmers prefer such.
Writing Dirty Code Programming Now, let's talk 'dirty'. I mean, let's talk about 'dirty code programming' and why you shouldn't do it. What dirty code programming simply means, is how you write it. For example, if you create a print string that looks like this:
d='dirty';c='code';p='programming';print(d,c,p,'is very hard to understand!')
As you can see, dirty code programming makes it very hard to understand what's happening in the program. Now consider the following:
program='Programming' nice='Nice,' clean='Clean' code='Code'
print(program,nice,clean,code,'is much easier to understand.')
Here is another example of clean code programming, using semicolons (;) to separate strings on the same line.
program='Programming';nice='Nice,';clean='Clean';code='Code.'
print(program,nice,clean,code,'is much easier to understand.')
Notice how both program examples are very easy to understand, whereas the dirty code program example is very hard to understand. Also notice how it's less likely to create text errors and syntax errors using a clean code programming style approach, whereas dirty code leaves programs vulnerable to text errors and syntax errors alike. Now that you have a general idea of what Python programming is all about, let's get started with some simple 'print' statement program examples.
Print Statement Examples: ''' Print statement values are encased with round brackets '()' on each end of the 'print' statement's value. Quotation marks (" ") denote what kind of 'print' statement value it is. If the value is a string, then no quotation marks are used inside the 'print' statement's value. However, quotation marks are used within the 'print' statement's string value instead. Note: double quotation marks (" ") or single quotation marks (' ') can be used in 'print' statements, string values, tuples and lists alike. If the value is not a string, then quotation marks are used inside the 'print' statement's value itself, such as these two 'print' statement examples below. ''' # Print statement examples:
# Double Quotation marks (" ")
print("Hello World!")
# Single Quotation marks (' ')
print('Hello World!')
# Print statement string examples:
# Double Quotation marks (" ")
my_string_example="Hello World!"
print(my_string_example)
# Single Quotation marks (' ')
my_string_example='Hello World!'
print(my_string_example)
Fancy Print Statement Examples: ''' All 'print' statements and all 'input' statements also support the 'n' line-break implementer, which acts like a normal line-break in between sentences. The 'n' line-break implementer can also be implemented into string values, tuple values and list values alike. From here on, the 'n' line-break implementer will be implemented into all 'print' statements, 'input' statements, string values, tuple values and list values. The 'n' line-break implementer makes the screen printout much more cleaner and nicer looking with actual line-breaks in between sentences. Note: two 'nn' or more 'nnn' line-break implementers can be implemented at once within a single 'print' statement. ''' # Here are some 'print' statement examlples of the 'n' line-break implementer.
print('nHello World!')
print('nnHello World!')
print('nnnHello World!')
print('nnnnHello World!')
print('Hello world!nHello world!nHello world!nHello world!')
# The upper() fuction turns the words 'hello world!' into the words 'HELLO WORLD!' # example:
print('nhello world!'.upper())
# The title() function turns the words 'hello world!' into the words 'Hello World!' # example:
print('nhello world!'.title())
# The lower() function turns the words 'HELLO WORLD!' into the words 'hello world!' # example:
print('nHELLO WORLD!'.lower())
# Make 'print' statement values in reverse by omitting the slice '[::]' emitter.
print('nHello World!'[::-1])
# Try these 'print' statement value in reverse program examples, while using other # combined functions.
print('nhello world!'[::-1].upper())
print('nhello world!'[::-1].title())
print('nHELLO WORLD!'[::-1].lower())
# The slice [::] emitter can be omitted into tuples, lists, dictionaries and 'print' # statements, such as in these 'print' statement program examples:
# The slice [::] emitter takes one to three positive or negative values. The 'print' # statement's string value 'HELLO WORLD!' is sliced. When slicing a 'print' statement's # string value, the values can be sliced from left to right, or from right to left. For # example, the 'print' string value 'HELLO WORLD!' looks like these sliced 'print' string # value examples:
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 # H,E,L,L,O, ,W,O,L,R,D,!
# -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1 # H,E,L,L,O, ,W,O,L,R,D,!
# [ start value : end value : step value ]
# Note: step values must start at 1 not 0
# empty slice: no values
print('HELLO WORLD!'[:])
# Screen output: HELLO WORLD!
# slice start value 0
print('HELLO WORLD!'[0:])
# Screen output: HELLO WORLD!
# slice end value -1
print('HELLO WORLD! '[:-1])
# Screen output: HELLO WORLD!
# slice start and slice end values 1 and -2
print('HELLO WORLD! '[1:-2])
# Screen output: ELLO WORLD
# slice start, slice end and slice step 2
print('HELLO WORLD!'[0:-1:2])
# Screen output: HLOWRD
# In this example, the start and end slice emitter values are positive. Notice how the # screen output shows 'HE'.
# slice start and slice end values 0 and 2
print('HELLO WORLD! '[0:2])
# Screen output: HE
# In this example, the start and end slice emitter values are negative. Notice how the # screen output shows 'D!'.
# slice start and slice end values -3 and -1
print('HELLO WORLD! '[-3:-1])
# Screen output: D!
# Make this 'print' statement print 'Hello World!' 3 times.
print('Hello World! '*3)
# Make this 'print' statement print 'Hello World!' go in the top, middle of the screen. # Note: use an emty space in between the single quotation marks (' '*45)
print(' '*45+'Hello World!')
# Try these 'print' statement program examples:
print('Hello World! '*3+'Python')
print('Python '*3+'Hello World!')
print('Python '*45+'Hello World!')
print('Python '*45)
# The 'len' function counts how many characters, including spaces there are inside of # a 'print' statement. The length of these two words "Hello World!", including the # space in between 'Hello' and 'World!' are counted. For example: "Hello World!" # including one space is twelve characters long. The printout on the screen will only # show the number "12", not the actual words "Hello World!".
print(len('nHello World!'))