Articles From Brendan Scott
Filter Results
Article / Updated 10-04-2023
Programming is an important skill. Python will serve you well for years to come. The tables here give you the core words, built-ins, standard library functions, and operators that you'll use most when you're coding with Python. Python Core Words KeywordSummaryExample and Logical operator to test whether two things are both True. andx>2 and x<10 as Assign a file object to a variable. Used with with.Let your code refer to a module under a different name (also called an alias). Used with import. with open(<name of file>,<file mode>) as <object name>:import cPickle as pickle break Stop execution of a loop. for i in range(10): if i%2 ==0: break class Define a custom object. class <name of class>(object): ""Your docstring"" class MyClass(object): ""A cool function."" continue Skip balance of loop and begin a new iteration. for i in range(10): if i%2 ==0: continue def Define a function. def <name of function>(): ""Your docstring"" def my_function(): ""This does... "" elif Add conditional test to an if clause. See if. else Add an alternative code block. See if. for Create a loop which iterates through elements of a list (or other iterable). for <dummy variable name> in <sequence>:for i in range(10): from Import specific functions from a module without importing the whole module. from <module name> import <name of function or object>from random import randint global Make a variable global in scope. (If a variable is defined in the main section, you can change its value within a function.) global x if Create a condition. If the condition is True, the associated code block is executed. Otherwise, any elif commands are processed. If there are none, or none are satisfied, execute the else block if there is one. if : [elif : , ...][else: ]if x == 1: print("x is 1")elif x == 2: print("x is 2")elif x > 3: print("x is greater than 3")else print("x is not greater than 3, nor is it 1 one or 2") import Use code defined in another file without retyping it. import <name of module>import random in Used to test whether a given value is one of the elements of an object. 1 in range(10) is Used to test whether names reference the same object. x = Nonex is None # faster thanx == None lambda Shorthand function definition. Usually used where a function needs to be passed as an argument to another function. lamda :times = lambda x, y: x*ycommand=lambda x: self.draw_line(self.control_points) not Logical negation, used to negate a logical condition. Don't use for testing greater than, less than, or equal. 10 not in range(10) or Logical operator to test whether at least one of two things is True. orx<2 or x>10 pass Placeholder keyword. Does nothing but stop Python complaining that a code block is empty. for i in range (10): pass print Output text to a terminal. print("Hello World!") return Return from the execution of a function. If a value is specified, return that value, otherwise return None. return return x+2 while Execute a code block while the associated condition is True. while :while True: pass with Get Python to manage a resource (like a file) for you. with open(,) as : Extend Python's core functionality with these built-ins. Python Built-ins Built-inNotesExample False Value, returned by a logical operation or directly assigned. ok_to_continue = Falseage = 16old_enough = age >=21(evaluates comparison age>=21 and assigns the result to old_enough) None Value used when representing the absence of a value or to initialise a variable which will be changed later. Returned by functions which do not explicitly return a value. x = None True Value, returned by a logical operation. ok_to_continue = Trueage = 16old_enough = age >=21(evaluates comparison age>=21 and assigns the result to old_enough) __name__ Constant, shows module name. If it's not "__main__", the code is being used in an import. if __name__=="__main__": dir List attributes of an item. dir(<object name>) enumerate Iterate through a sequence and number each item. enumerate('Hello') exit Exit Python (Command Line) interpreter. exit() float Convert a number into a decimal, usually so that division works properly. 1/float(2) getattr Get an attribute of an object by a name. Useful for introspection. getattr(<name of object>, <name of attribute>) help Get Python docstring on object. help(<name of object>)help(getattr) id Show the location in the computer's RAM where an object is stored. id(<name of object>)id(help) int Convert a string into an integer number. int('0') len Get the number of elements in a sequence. len([0,1]) object A base on which other classes can inherit from. class CustomObject(object): open Open a file on disk, return a file object. open(, )open('mydatafile.txt', 'r') # read(opens a file to read data from)open('mydatafile.txt', 'w') # write(creates a new file to write to, destroys any existing file with the same name)open('mydatafile.txt', 'a') # append(adds to an existing file if any, or createsa new one if none existing already) print Reimplementation of print keyword, but as a function.Need to import from the future to use it (srsly!) from future import print_functionprint ('Hello World!') range Gives numbers between the lower and upper limits specified (including the lower, but excluding the upper limit). A step may be specified. range(10)range(5,10)range(1,10,2) raw_input Get some text as a string from the user, with an optional prompt. prompt = 'What is your guess? 'players_guess = raw_input(prompt) str Convert an object (usually a number) into a string (usually for printing). str(0) type Give the type of the specified object. type(0)type('0')type([])type({})type(()) Use the work that others have already done. Try these modules from the Python standard library. Selected Functions from the Standard Library ModuleWhat It DoesSample Functions/Objects os.path Functions relating to files and file paths. os.path.exists() pickle, cPickle Save and load objects to/from a file. pickle.load(), pickle.dump(, ) random Various functions relating to random numbers. random.choice(), random.randint(, ), random.shuffle() String Stuff relating to strings. string.printable sys Various functions related to your computer system. sys.exit() Time Time-related functions. time.time() Tkinter User interface widgets and associated constants. Tkinter.ALLTkinter.BOTHTkinter.CENTERTkinter.ENDTkinter.HORIZONTALTkinter.LEFTTkinter.NWTkinter.RIGHTTkinter.TOPTkinter.YTkinter.Button(,text=)Tkinter.Canvas(, width=, height=)Tkinter.Checkbutton(, text=)Tkinter.Entry(, width=),Tkinter.Frame()Tkinter.IntVar()Tkinter.Label(, text = )Tkinter.mainloop()Tkinter.Menu()Tkinter.OptionMenu(, None, None)Tkinter.Scale(, from_=, to=)Tkinter.Scrollbar()Tkinter.StringVar()Tkinter.Tk() Add, subtract, divide, multiply, and more using these operators. Python Operators OperatorNameEffectExamples + Plus Add two numbers.Join two strings together. Add: >>> 1+12Join: >>> 'a'+'b''ab' – Minus Subtract a number from another.Can't use for strings. >>> 1-10 * Times Multiply two numbers.Make copies of a string. Multiply: >>> 2*24Copy: >>> 'a'*2'aa' / Divide Divide one number by another.Can't use for strings. 1/2 # integer division:Answer will be rounded down.1/2.0 # decimal division1/float(2) # decimal division % Remainder (Modulo) Give the remainder when dividing the left number by the right number.Formatting operator for strings. >>> 10%31 ** Power x**y means raise x to the power of y.Can't use for strings. >>> 3**29 = Assignment Assign the value on the right to the variable on the left. >>> a = 1 == Equality Is the left side equal to the right side? Is True if so; is False otherwise. >>> 1 == 1True>>> 'a' == 'a'True != Not equal Is the left side not equal to the right side? Is True if so; is False otherwise. >>> 1 != 1False>>> 1 != 2True>>> 'a' != 'a'True > Greater than Is the left side greater than the right side?>= means greater than or equal to >>> 2 > 1True < Less than Is the left side less than the right side?<= means less than or equal to >>> 1 < 2True & (or and) And Are both left and right True?Typically used for complex conditions where you want to do something if everything is True:while im_hungry and you_have_food: >>> True & TrueTrue>>> True and FalseFalse >>> True & (1 == 2)False | (or or) Or Is either left or right True?Typically used for complex conditions where you want at least one thing to be True:while im_bored or youre_bored: >>> True | FalseTrue>>> True or FalseTrue>>> False | FalseFalse>>> (1 == 1) | FalseTrue
View ArticleArticle / Updated 08-10-2023
Tradition dictates that Hello World! be the first program that you write when you're learning a new programming language like Python. You're following in the footsteps of many great programmers when you create this project. To create your Hello World! program, follow these steps: Open your Start menu and choose Python (command line). You should get a prompt that looks like >>>. At the moment, you're doing everything in interactive mode in the Python interpreter. That's where the >>> comes in. Python shows you >>> when you're supposed to type something. At the prompt, type the following. Use a single quote at the start and the end — it's beside the Enter key: print('Hello World!') Press the Enter key. Python runs the code you typed. You see the output shown in Figure 1. Congratulations — you've written your first program. Welcome to the Python-programmers-in-training club. If you don't see what's in Figure 1, check that you typed in the text from Step 2 exactly as it's written: Check that the parentheses and single quotes are in the right places. Check that for each opening parenthesis there is a closing parenthesis. (Otherwise, you're left hanging. Check that for each opening quote there's a closing quote. Programming languages have their own grammar and punctuation rules. These rules are the language's syntax. Humans, can work most stuff out even if perfect not you're is grammar (See? You figured out what that sentence was trying to say), but Python pretty much freaks out if you get the syntax wrong.
View ArticleArticle / Updated 08-10-2023
The Python interpreter takes in each line and operates on it immediately (more or less) after you press the Enter key. In Hello World! you use Python's print feature. print takes what's inside the parentheses and outputs it to the command line (also called the console). Python is sensitive to both the grammar and punctuation. If you misspell something, the program won't work. If Python is expecting special characters and you don't put them in, then Python will fail. Some Python issues are shown here. Can you work out how you would fix them? >>> pritn('Hello World!') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pritn' is not defined Here's another: >>> print('Hello World!) File "<stdin>", line 1 print('Hello World!) SyntaxError: EOL while scanning string literal Here's another: >>> print 'Hello World!') File "<stdin>", line 1 print 'Hello World!') ^ SyntaxError: invalid syntax Python tries to give you the reason it failed (that is, NameError and SyntaxError). Check each of these things: Opening parenthesis has a closing parenthesis Every opening quote mark has a matching closing quote mark All commands are correctly spelled
View ArticleArticle / Updated 10-19-2022
Whether you use a Mac, Windows, or Linux OS (operating system), you can find and install Python on your computer. The following sections give you instructions for each OS. How to install Python on Mac OSX To find and start Python on Mac OSX computers, follow these steps: Press Cmd+spacebar to open Spotlight. Type the word terminal. Or, from the Finder, select Finder→Go→Utilities→Terminal. The Terminal window opens. In the terminal, type python. The Python interpreter that's built in to Mac OSX opens. How to install Python on Windows Unfortunately, Python doesn't come on Windows. If you're running Windows, then you need to download and install Python by following the instructions here. Installing Python on Windows isn't difficult. If you can download a file from a website, you have the skills to install Python. Fortunately, the Python Foundation (the peeps who guide the development of Python) makes installable files available from its website. Firefox and Internet Explorer responded differently to the Python download website, so the instructions are based on which of these browsers you use. If you use a whole other browser altogether, try the Internet Explorer instructions. Installing with Firefox To install Python on a Windows machine with Firefox, follow these steps: Visit www.python.org/downloads. Click the button that says Download Python 2.7.9. Or, if it's there, click a more recent version number that starts with 2.7. Clicking this button automatically downloads and saves an msi file for you. If not, try the instructions for Internet Explorer. See Figure 1. Figure 1: Download Python with Firefox. When the download's complete, click the icon for Firefox's download tool. Click the file called python-2.7.9.msi (or the more recent version, if you downloaded one). Python 2.7.9 installs on your computer. Installing with Internet Explorer To install Python on a Windows machine with Internet Explorer, follow these steps: Visit www.python.org/downloads. From the menu bar, select Downloads→Windows. You can see the menu options in Figure 2. Figure 2: Download Python with Internet Explorer. Scroll down to the heading Python 2.7.9-2014-12-10. Or scroll to a more recent version, which starts with Python 2.7, if one is available. Under this heading, click the link titled Download Windows x86 MSI Installer. See Figure 3. This is a link for a 32-bit installation, which makes things work better with third-party libraries. Use the 32-bit installer even if you have a 64-bit machine and even if you have no idea what this paragraph is talking about. Figure 3: Python x86 MSI Installer. If you're asked to choose whether to run or save the file, choose Run. This downloads python2.7.9.msi and starts running the installer. If you get a security warning when the installer begins (or at random times during the installation), choose Run. Accept the default installation options that the installer provides. How to install Python for Linux If you're running Linux, confirm that you have version 2.7.9 of Python installed, rather than version 3. This shouldn't be a problem because Python 2.7 is installed by default in recent versions of OpenSuSE, Ubuntu, and Red Hat Fedora. In the nutty odd case when someone has Python 3 but not Python 2.7, read your distribution's documentation for how to use the package manager and get Python 2.7 and IDLE.
View ArticleCheat Sheet / Updated 02-24-2022
Python coding helps you with things you do every day, like math homework. Python programming can also help with things like making web pages: Thank goodness for widgets and keywords!
View Cheat SheetArticle / Updated 09-19-2019
Yard signs are a good way to spread your campaign brand, have supporters show their enthusiasm, and make your opponents nervous. Yard signs are an essential part of your campaign marketing, but by themselves they don’t win elections. Invest in yard signs as part of your campaign strategy. Don’t bother counting your opponent’s yard signs, because elections are won by votes and not the number of yard signs littering lawns and highways. Check with the rules of your region with regard to yard sign placement. For example, you may be prohibited from setting a yard sign on public property in the public right-of-way. Yard signs may also require a permit in some jurisdictions. Make a note when the permit allows you to set out — and remove — yard signs on your campaign calendar. Yard sign wars are a real thing. They’re a great example of how even a local, nonpartisan election can rack up the immaturity points on both sides: Your opponent’s supporters will damage and steal your yard signs. They will stick their yard signs one inch in front of yours. They will illegally place their yard signs. And your supporters may do the same things to the other yard signs. Just let it go. Yard sign wars don’t win campaigns, and complaining about stolen yard signs makes you come across as desperate. Philosophy behind yard signs Yard signs are about name recognition. The sign’s design should be tied to your campaign branding. A car driving by at 35 MPH should be able to identify your campaign based on the yard sign, which is yet another impression in the minds of the voter. On a practical level, yard signs are pretty much for supporters. They make wonderful handouts for meet-and-greet fundraising events. People are proud to show whom they’ve voting for, and having a yard sign makes them happy. I provide yard signs primarily for my supporters. Rarely, if ever, is the sight of a yard sign the deciding factor in someone voting for you or, better, switching over from voting for your opponent. Otherwise, I don’t believe yard signs have any impact on the election whatsoever. Make yard signs available For a typical local election, print about 100 yard signs per 2,000 potential voters. If you run out, you can print more. Have them available always, ready for supporters. If you can organize volunteers to set yard signs, hand them a bunch and let them have at it — after fully informing them of the various yard sign rules and regulation. Let other supporters know where they can pick up a yard sign. Specifically, send them to various meet-and-greet events to obtain one. That way, you draw more attendance at such events. Yard sign details Yard signs are about campaign marketing. The key element is your name. You can also add the position you seek. Required are any disclaimers, such as the campaign committee, treasurer, or other legally required details that must be printed on all your campaign material. A typical yard sign measures 24-by-18 inches. Larger sizes are available, though you should check the restrictions on yard sign sizes for your locale. The traditional yard sign is printed on a coated cardboard material. It’s weather resistant. Don’t go cheap and get a noncoated yard sign, because it will fade and flop in the weather. One important part about the yard sign is the mounting mechanism. Most signs are mounted on wires stuck into the ground. Called H-wires, these have an additional cost beyond the yard sign expense. Larger yard signs may require you to purchase wooden stakes or other methods to mount the signs. Yard sign do’s and don’ts Keep the information on your yard sign minimal: Your branding and name should stick out the most. If you add too much detail, the yard sign looks cluttered. No one can read your 24-word campaign slogan in inch-high letters on a yard sign. No one wants to. The following figure lists good and bad examples of yard signs. Here’s a summary: Avoid putting the election date on a yard sign. If you win, or if you lose and want to run again, you can re-use the same yard sign, but only if it doesn’t have a date on it. Use the word Vote on the sign instead of Elect. If you win, you can reuse a yard sign with the word Vote on it; otherwise, you must fix Elect to say Re-elect. Or, you can avoid both terms; it’s a campaign sign, and people aren’t that slow. Print the yard sign on both sides. Yes, it’s cheaper to use just one side. Good yard sign placement mandates that the sign be visible to both lanes of traffic. Placement of political yard signs It helps to have some hardy volunteers plant your yard signs. Yes, you’ll do your share of yard sign duty; keep signs in your car and at the ready. Also include some tools to help you hammer and dig, because not every location has the best soil. Track the location of your yard signs as well as possible. You must collect them after the campaign — and you do want to keep them should you choose to run again. Further, you don’t want your yard signs lingering long after the campaign. You’re the candidate, so these rogue yard signs are your responsibility. It’s your name on them, after all. Rules exist for planting yard signs. Ensure that you know the rules and have informed your volunteers. Double your yard sign visibility It’s possible to increase your yard sign visibility without overspending. The trick is to relocate the signs, especially during the last two weeks of the campaign. Most people tune out yard signs they’ve already seen. They recognize the bouquet of yard signs at major intersections, which eventually blend into the landscaping. However, if you go out and move the yard signs (keeping them in allowed locations), passersby will notice something different. Effectively, you’ve re-exposed the same people to a “new” yard sign without spending more money.
View ArticleArticle / Updated 03-26-2016
Python can do fractions so you can check your homework answers. Use the fractions module, and its Fraction object, specifying the numerator and denominator. To get one-half, type fractions.Fraction(1, 2). For four-fifths, type fractions.Fraction(4, 5): >>> import fractions >>> one_half = fractions.Fraction(1, 2) >>> one_fifth = fractions.Fraction(1, 5) Fractions can do normal fraction calculations (including multiplication and division) for you: >>> one_half+one_fifth Fraction(7, 10) >>> one_half-one_fifth Fraction(3, 10) >>> one_half*one_fifth Fraction(1, 10) >>> one_half/one_fifth Fraction(5, 2)
View ArticleArticle / Updated 03-26-2016
Tkinter in Python comes with a lot of good widgets. Widgets are standard graphical user interface (GUI) elements, like different kinds of buttons and menus. Most of the Tkinter widgets are given here. Label Widget A Label widget shows text to the user. You can update the widget programmatically to, for example, provide a readout or status bar. import Tkinter parent_widget = Tkinter.Tk() label_widget = Tkinter.Label(parent_widget, text="A Label") label_widget.pack() Tkinter.mainloop() Button Widget A Button can be on and off. When a user clicks it, the button emits an event. Images can be displayed on buttons. import Tkinter parent_widget = Tkinter.Tk() button_widget = Tkinter.Button(parent_widget, text="A Button") button_widget.pack() Tkinter.mainloop() Entry Widget An Entry widget gets text input from the user. import Tkinter parent_widget = Tkinter.Tk() entry_widget = Tkinter.Entry(parent_widget) entry_widget.insert(0, "Type your text here") entry_widget.pack() Tkinter.mainloop() Radiobutton Widget A Radiobutton lets you put buttons together, so that only one of them can be clicked. If one button is on and the user clicks another, the first is set to off. Use Tkinter variables (mainly Tkinter.IntVar and Tkinter.StringVar) to access its state. import Tkinter parent_widget = Tkinter.Tk() v = Tkinter.IntVar() v.set(1) # need to use v.set and v.get to # set and get the value of this variable radiobutton_widget1 = Tkinter.Radiobutton(parent_widget, text="Radiobutton 1", variable=v, value=1) radiobutton_widget2 = Tkinter.Radiobutton(parent_widget, text="Radiobutton 2", variable=v, value=2) radiobutton_widget1.pack() radiobutton_widget2.pack() Tkinter.mainloop() Radiobutton Widget (Alternate) You can display a Radiobutton without the dot indicator. In that case it displays its state by being sunken or raised. import Tkinter parent_widget = Tkinter.Tk() v = Tkinter.IntVar() v.set(1) radiobutton_widget1 = Tkinter.Radiobutton(parent_widget, text="Radiobutton 1", variable=v, value=1, indicatoron=False) radiobutton_widget2 = Tkinter.Radiobutton(parent_widget, text="Radiobutton 2", variable=v, value=2, indicatoron=False) radiobutton_widget1.pack() radiobutton_widget2.pack() Tkinter.mainloop() Checkbutton Widget A Checkbutton records on/off or true/false status. Like a Radiobutton, a Checkbutton widget can be displayed without its check mark, and you need to use a Tkinter variable to access its state. import Tkinter parent_widget = Tkinter.Tk() checkbutton_widget = Tkinter.Checkbutton(parent_widget, text="Checkbutton") checkbutton_widget.select() checkbutton_widget.pack() Tkinter.mainloop() Scale Widget: Horizontal Use a Scale widget when you want a slider that goes from one value to another. You can set the start and end values, as well as the step. For example, you can have a slider that has only the even values between 2 and 100. Access its current value by its get method; set its current value by its set method. import Tkinter parent_widget = Tkinter.Tk() scale_widget = Tkinter.Scale(parent_widget, from_=0, to=100, orient=Tkinter.HORIZONTAL) scale_widget.set(25) scale_widget.pack() Tkinter.mainloop() Scale Widget: Vertical A Scale widget can be vertical (up and down). import Tkinter parent_widget = Tkinter.Tk() scale_widget = Tkinter.Scale(parent_widget, from_=0, to=100, orient=Tkinter.VERTICAL) scale_widget.set(25) scale_widget.pack() Tkinter.mainloop() Text Widget Use a Text widget to show large areas of text. The Text widget lets the user edit and search. import Tkinter parent_widget = Tkinter.Tk() text_widget = Tkinter.Text(parent_widget, width=20, height=3) text_widget.insert(Tkinter.END, "Text Widgetn20 characters widen3 lines high") text_widget.pack() Tkinter.mainloop() LabelFrame Widget The LabelFrame acts as a parent widget for other widgets, displaying them with a title and an outline. LabelFrame has to have a child widget before you can see it. import Tkinter parent_widget = Tkinter.Tk() labelframe_widget = Tkinter.LabelFrame(parent_widget, text="LabelFrame") label_widget=Tkinter.Label(labelframe_widget, text="Child widget of the LabelFrame") labelframe_widget.pack(padx=10, pady=10) label_widget.pack() Tkinter.mainloop() Canvas Widget You use a Canvas widget to draw on. It supports different drawing methods. import Tkinter parent_widget = Tkinter.Tk() canvas_widget = Tkinter.Canvas(parent_widget bg="blue", width=100, height= 50) canvas_widget.pack() Tkinter.mainloop() Listbox Widget Listbox lets the user choose from one set of options or displays a list of items. import Tkinter parent_widget = Tkinter.Tk() listbox_entries = ["Entry 1", "Entry 2", "Entry 3", "Entry 4"] listbox_widget = Tkinter.Listbox(parent_widget) for entry in listbox_entries: listbox_widget.insert(Tkinter.END, entry) listbox_widget.pack() Tkinter.mainloop() Menu Widget The Menu widget can create a menu bar. Creating menus can be hard, especially if you want drop-down menus. To do that, you use a separate Menu widget for each drop-down menu you're creating. import Tkinter parent_widget = Tkinter.Tk() def menu_callback(): print("I'm in the menu callback!") def submenu_callback(): print("I'm in the submenu callback!") menu_widget = Tkinter.Menu(parent_widget) submenu_widget = Tkinter.Menu(menu_widget, tearoff=False) submenu_widget.add_command(label="Submenu Item1", command=submenu_callback) submenu_widget.add_command(label="Submenu Item2", command=submenu_callback) menu_widget.add_cascade(label="Item1", menu=submenu_widget) menu_widget.add_command(label="Item2", command=menu_callback) menu_widget.add_command(label="Item3", command=menu_callback) parent_widget.config(menu=menu_widget) Tkinter.mainloop() OptionMenu Widget The OptionMenu widget lets the user choose from a list of options. To use the OptionMenu the right way, you'll probably need to bind it to a separate callback that updates other information based on the user's selection. Get the currently selected value with its get method. import Tkinter parent_widget = Tkinter.Tk() control_variable = Tkinter.StringVar(parent_widget) OPTION_TUPLE = ("Option 1", "Option 2", "Option 3") optionmenu_widget = Tkinter.OptionMenu(parent_widget, control_variable, *OPTION_TUPLE) optionmenu_widget.pack() Tkinter.mainloop()
View ArticleArticle / Updated 03-26-2016
Usually you get called rude if you interrupt. Not in programming. Are you ready to create a program that never finishes by itself (called an infinite loop)? This section shows you how to force it to stop. Forcing a stop is useful when your program locks up and won't respond. The trick is to press Ctrl+C (the Ctrl key and the C key at the same time; don't press the Shift key). Make sure the Python window is active (by clicking the window) when you do — or you might close the wrong program! Here's how you write an infinite loop program: Type while True: and press Enter. Press the spacebar four times. Type pass. Press Enter twice. This is what you'll see: >>> while True: … pass … The Python interpreter is unresponsive. If you try to get it to assign or print something, nothing happens. It lays there like a lump. The usual >>> prompt isn’t there. You may also hear your computer laboring. Quick: Press Ctrl+C to break out of the loop and get control back. You get this when you do it: >>> while True: … pass … ^CTraceback (most recent call last): File "<stdin>", line 1, in <module> KeyboardInterrupt >>>
View ArticleArticle / Updated 03-26-2016
Functions are extremely useful and powerful tools in your programming toolbox because they allow you to separate your program into meaningful blocks. All the built-ins in Python are functions, as is everything in the standard library. The rules for naming a function are a lot like rules for naming a variable: They must start with a letter or an underscore: _. They should be lowercase. They can have numbers. They can be any length (within reason), but keep them short. They can't be the same as a Python keyword. They can have the same name as an existing function (including a built-in), but avoid this for now. The function print_hello_world is very basic. It only does one thing. It can't respond to different circumstances because no information is passing into the function when you call it. This is fine if you need to do the same thing all the time. Functions are even more powerful, though, because you can communicate with them and they can do different things depending on the information. You could change this function and send it different messages to print.
View Article