Python Code Examples – Sample Script Coding Tutorial for Beginners

Hi! Welcome. If you are learning Python, then this article is for you. You will find a thorough description of Python syntax and lots of code examples to guide you during your coding journey.

What we will cover:

Are you ready? Let's begin! 🔅

💡 Tip: throughout this article, I will use <> to indicate that this part of the syntax will be replaced by the element described by the text. For example, <var> means that this will be replaced by a variable when we write the code.

🔹 Variable Definitions in Python

The most basic building-block of any programming language is the concept of a variable, a name and place in memory that we reserve for a value.

In Python, we use this syntax to create a variable and assign a value to this variable:

For example:

If the name of a variable has more than one word, then the Style Guide for Python Code recommends separating words with an underscore "as necessary to improve readability."

💡 Tip: The Style Guide for Python Code (PEP 8) has great suggestions that you should follow to write clean Python code.

🔸 Hello, World! Program in Python

Before we start diving into the data types and data structures that you can use in Python, let's see how you can write your first Python program.

You just need to call the print() function and write "Hello, World!" within parentheses:

You will see this message after running the program:

💡 Tip: Writing a "Hello, World!" program is a tradition in the developer community. Most developers start learning how to code by writing this program.

Great. You just wrote your first Python program. Now let's start learning about the data types and built-in data structures that you can use in Python.

🔹 Data Types and Built-in Data Structures in Python

We have several basic data types and built-in data structures that we can work with in our programs. Each one has its own particular applications. Let's see them in detail.

Numeric Data Types in Python: Integers, Floats, and Complex

These are the numeric types that you can work with in Python:

Integers are numbers without decimals. You can check if a number is an integer with the type() function. If the output is <class 'int'> , then the number is an integer.

Floats are numbers with decimals. You can detect them visually by locating the decimal point. If we call type() to check the data type of these values, we will see this as the output:

Here we have some examples:

Complex numbers have a real part and an imaginary part denoted with j . You can create complex numbers in Python with complex() . The first argument will be the real part and the second argument will be the imaginary part.

These are some examples:

Strings in Python

Strings incredibly helpful in Python. They contain a sequence of characters and they are usually used to represent text in the code.

We can use both single quotes '' or double quotes "" to define a string. They are both valid and equivalent, but you should choose one of them and use it consistently throughout the program.

💡 Tip: Yes! You used a string when you wrote the "Hello, World!" program. Whenever you see a value surrounded by single or double quotes in Python, that is a string.

Strings can contain any character that we can type in our keyboard, including numbers, symbols, and other special characters.

💡 Tip: Spaces are also counted as characters in a string.

Quotes Within Strings

If we define a string with double quotes "" , then we can use single quotes within the string. For example:

If we define a string with single quotes '' , then we can use double quotes within the string. For example:

String Indexing

We can use indices to access the characters of a string in our Python program. An index is an integer that represents a specific position in the string. They are associated to the character at that position.

This is a diagram of the string "Hello" :

💡 Tip: Indices start from 0 and they are incremented by 1 for each character to the right.

We can also use negative indices to access these characters:

💡 Tip: we commonly use -1 to access the last character of a string.

String Slicing

We may also need to get a slice of a string or a subset of its characters. We can do so with string slicing.

This is the general syntax:

start is the index of the first character that will be included in the slice. By default, it's 0 .

We can specify two parameters to use the default value of step , which is 1 . This will include all the characters between start and stop (not inclusive):

💡 Tip: Notice that if the value of a parameter goes beyond the valid range of indices, the slice will still be presented. This is how the creators of Python implemented this feature of string slicing.

If we customize the step , we will "jump" from one index to the next according to this value.

We can also use a negative step to go from right to left:

And we can omit a parameter to use its default value. We just have to include the corresponding colon ( : ) if we omit start , stop , or both:

💡 Tip: The last example is one of the most common ways to reverse a string.

In Python 3.6 and more recent versions, we can use a type of string called f-string that helps us format our strings much more easily.

To define an f-string, we just add an f before the single or double quotes. Then, within the string, we surround the variables or expressions with curly braces {} . This replaces their value in the string when we run the program.

The output is:

Here we have an example where we calculate the value of an expression and replace the result in the string:

The values are replaced in the output:

We can also call methods within the curly braces and the value returned will be replaced in the string when we run the program:

String Methods

Strings have methods, which represent common functionality that has been implemented by Python developers, so we can use it in our programs directly. They are very helpful to perform common operations.

This is the general syntax to call a string method:

To learn more about Python methods, I would recommend reading this article from the Python documentation.

💡 Tip: All string methods return copies of the string. They do not modify the string because strings are immutable in Python.

Booleans in Python

Boolean values are True and False in Python. They must start with an uppercase letter to be recognized as a boolean value.

If we write them in lowercase, we will get an error:

Lists in Python

Now that we've covered the basic data types in Python, let's start covering the built-in data structures. First, we have lists.

To define a list, we use square brackets [] with the elements separated by a comma.

💡 Tip: It's recommended to add a space after each comma to make the code more readable.

For example, here we have examples of lists:

Lists can contain values of different data types, so this would be a valid list in Python:

We can also assign a list to a variable:

Nested Lists

Lists can contain values of any data type, even other lists. These inner lists are called nested lists .

In this example, [1, 2, 3] and [4, 5, 6] are nested lists.

Here we have other valid examples:

We can access the nested lists using their corresponding index:

Nested lists could be used to represent, for example, the structure of a simple 2D game board where each number could represent a different element or tile:

List Length

We can use the len() function to get the length of a list (the number of elements it contains).

Update a Value in a List

We can update the value at a particular index with this syntax:

Add a Value to a List

We can add a new value to the end of a list with the .append() method.

Remove a Value from a List

We can remove a value from a list with the .remove() method.

💡 Tip: This will only remove the first occurrence of the element. For example, if we try to remove the number 3 from a list that has two number 3s, the second number will not be removed:

List Indexing

We can index a list just like we index strings, with indices that start from 0 :

List Slicing

We can also get a slice of a list using the same syntax that we used with strings and we can omit the parameters to use their default values. Now, instead of adding characters to the slice, we will be adding the elements of the list.

List Methods

Python also has list methods already implemented to help us perform common list operations. Here are some examples of the most commonly used list methods:

To learn more about list methods, I would recommend reading this article from the Python documentation.

Tuples in Python

To define a tuple in Python, we use parentheses () and separate the elements with a comma. It is recommended to add a space after each comma to make the code more readable.

We can assign tuples to variables:

Tuple Indexing

We can access each element of a tuple with its corresponding index:

We can also use negative indices:

Tuple Length

To find the length of a tuple, we use the len() function, passing the tuple as argument:

Nested Tuples

Tuples can contain values of any data type, even lists and other tuples. These inner tuples are called nested tuples .

In this example, we have a nested tuple (4, 5, 6) and a list. You can access these nested data structures with their corresponding index.

Tuple Slicing

We can slice a tuple just like we sliced lists and strings. The same principle and rules apply.

Tuple Methods

There are two built-in tuple methods in Python:

💡 Tip: tuples are immutable. They cannot be modified, so we can't add, update, or remove elements from the tuple. If we need to do so, then we need to create a new copy of the tuple.

Tuple Assignment

In Python, we have a really cool feature called Tuple Assignment. With this type of assignment, we can assign values to multiple variables on the same line.

The values are assigned to their corresponding variables in the order that they appear. For example, in a, b = 1, 2 the value 1 is assigned to the variable a and the value 2 is assigned to the variable b .

💡 Tip: Tuple assignment is commonly used to swap the values of two variables:

Dictionaries in Python

Now let's start diving into dictionaries. This built-in data structure lets us create pairs of values where one value is associated with another one.

To define a dictionary in Python, we use curly brackets {} with the key-value pairs separated by a comma.

The key is separated from the value with a colon : , like this:

You can assign the dictionary to a variable:

The keys of a dictionary must be of an immutable data type. For example, they can be strings, numbers, or tuples but not lists since lists are mutable.

The values of a dictionary can be of any data type, so we can assign strings, numbers, lists, tuple, sets, and even other dictionaries as the values. Here we have some examples:

Dictionary Length

To get the number of key-value pairs, we use the len() function:

Get a Value in a Dictionary

To get a value in a dictionary, we use its key with this syntax:

This expression will be replaced by the value that corresponds to the key.

The output is the value associated to "a" :

Update a Value in a Dictionary

To update the value associated with an existing key, we use the same syntax but now we add an assignment operator and the value:

Now the dictionary is:

Add a Key-Value Pair to a Dictionary

The keys of a dictionary have to be unique. To add a new key-value pair we use the same syntax that we use to update a value, but now the key has to be new.

Now the dictionary has a new key-value pair:

Delete a Key-Value Pair in a Dictionary

To delete a key-value pair, we use the del statement:

Dictionary Methods

These are some examples of the most commonly used dictionary methods:

To learn more about dictionary methods, I recommend reading this article from the documentation.

🔸 Python Operators

Great. Now you know the syntax of the basic data types and built-in data structures in Python, so let's start diving into operators in Python. They are essential to perform operations and to form expressions.

Arithmetic Operators in Python

These operators are:

Addition: +

💡 Tip: The last two examples are curious, right? This operator behaves differently based on the data type of the operands.

When they are strings, this operator concatenates the strings and when they are Boolean values, it performs a particular operation.

In Python, True is equivalent to 1 and False is equivalent to 0 . This is why the result is 1 + 0 = 1

Subtraction: -

Multiplication: *.

💡 Tip: you can "multiply" a string by an integer to repeat the string a given number of times.

Exponentiation: **

Division: /.

💡 Tip: this operator returns a float as the result, even if the decimal part is .0

If you try to divide by 0 , you will get a ZeroDivisionError :

Integer Division: //

This operator returns an integer if the operands are integers. If they are floats, the result will be a float with .0 as the decimal part because it truncates the decimal part.

Comparison Operators

These comparison operators make expressions that evaluate to either True or False . Here we have are some examples:

We can also use them to compare strings based on their alphabetical order:

We typically use them to compare the values of two or more variables:

💡 Tip: notice that the comparison operator is == while the assignment operator is = . Their effect is different. == returns True or False while = assigns a value to a variable.

Comparison Operator Chaining

In Python, we can use something called "comparison operator chaining" in which we chain the comparison operators to make more than one comparison more concisely.

For example, this checks if a is less than b and if b is less than c :

Logical Operators

There are three logical operators in Python: and , or , and not . Each one of these operators has its own truth table and they are essential to work with conditionals.

The and operator:

The or operator:

The not operator:

These operator are used to form more complex expressions that combine different operators and variables.

Assignment Operators

Assignment operators are used to assign a value to a variable.

They are: = , += , -= , *= , %= , /= , //= , **=

💡 Tips: these operators perform bitwise operations before assigning the result to the variable: &= , |= , ^= , >>= , <<= .

Membership Operators

You can check if an element is in a sequence or not with the operators: in and not in . The result will be either True or False .

We typically use them with variables that store sequences, like in this example:

🔹 Conditionals in Python

Now let's see how we can write conditionals to make certain parts of our code run (or not) based on whether a condition is True or False .

if statements in Python

This is the syntax of a basic if statement:

If the condition is True , the code will run. Else, if it's False , the code will not run.

💡 Tip: there is a colon ( : ) at the end of the first line and the code is indented. This is essential in Python to make the code belong to the conditional.

False Condition

The condition is x > 9 and the code is print("Hello, World!") .

In this case, the condition is False , so there is no output.

True Condition

Here we have another example. Now the condition is True :

Code After the Conditional

Here we have an example with code that runs after the conditional has been completed. Notice that the last line is not indented, which means that it doesn't belong to the conditional.

In this example, the condition x > 9 is False , so the first print statement doesn't run but the last print statement runs because it is not part of the conditional, so the output is:

However, if the condition is True , like in this example:

The output will be:

Examples of Conditionals

This is another example of a conditional:

In this case, the output will be:

But if we change the value of favorite_season :

There will be no output because the condition will be False .

if/else statements in Python

We can add an else clause to the conditional if we need to specify what should happen when the condition is False .

💡 Tip: notice that the two code blocks are indented ( if and else ). This is essential for Python to be able to differentiate between the code that belongs to the main program and the code that belongs to the conditional.

Let's see an example with the else clause:

When the condition of the if clause is True , this clause runs. The else clause doesn't run.

Now the else clause runs because the condition is False .

Now the output is:

if/elif/else statements in Python

To customize our conditionals even further, we can add one or more elif clauses to check and handle multiple conditions. Only the code of the first condition that evaluates to True will run.

💡 Tip: elif has to be written after if and before else .

First Condition True

We have two conditions x < 9 and x < 15 . Only the code block from the first condition that is True from top to bottom will be executed.

In this case, the output is:

Because the first condition is True : x < 9 .

Second Condition True

If the first condition is False , then the second condition will be checked.

In this example, the first condition x < 9 is False but the second condition x < 15 is True , so the code that belongs to this clause will run.

All Conditions are False

If all conditions all False , then the else clause will run:

Multiple elif Clauses

We can add as many elif clauses as needed. This is an example of a conditional with two elif clauses:

Each condition will be checked and only the code block of the first condition that evaluates to True will run. If none of them are True , the else clause will run.

🔸 For Loops in Python

Now you know how to write conditionals in Python, so let's start diving into loops. For loops are amazing programming structures that you can use to repeat a code block a specific number of times.

This is the basic syntax to write a for loop in Python:

The iterable can be a list, tuple, dictionary, string, the sequence returned by range, a file, or any other type of iterable in Python. We will start with range() .

The range() function in Python

This function returns a sequence of integers that we can use to determine how many iterations (repetitions) of the loop will be completed. The loop will complete one iteration per integer.

💡 Tip: Each integer is assigned to the loop variable one at a time per iteration.

This is the general syntax to write a for loop with range() :

As you can see, the range function has three parameters:

You can pass 1, 2, or 3 arguments to range() :

Here we have some examples with one parameter :

💡 Tip: the loop variable is updated automatically.

In the example below, we repeat a string as many times as indicated by the value of the loop variable:

We can also use for loops with built-in data structures such as lists:

💡 Tip: when you use range(len(<seq>)) , you get a sequence of numbers that goes from 0 up to len(<seq>)-1 . This represents the sequence of valid indices.

These are some examples with two parameters :

Now the list is: ['a', 'b', 'cc', 'd']

These are some examples with three parameters :

How to Iterate over Iterables in Python

We can iterate directly over iterables such as lists, tuples, dictionaries, strings, and files using for loops. We will get each one of their elements one at a time per iteration. This is very helpful to work with them directly.

Let's see some examples:

Iterate Over a String

If we iterate over a string, its characters will be assigned to the loop variable one by one (including spaces and symbols).

We can also iterate over modified copies of the string by calling a string method where we specify the iterable in the for loop. This will assign the copy of the string as the iterable that will be used for the iterations, like this:

Iterate Over Lists and Tuples

Iterate over the keys, values, and key-value pairs of dictionaries.

We can iterate over the keys, values, and key-value pairs of a dictionary by calling specific dictionary methods. Let's see how.

To iterate over the keys , we write:

We just write the name of the variable that stores the dictionary as the iterable.

💡 Tip: you can also write <dictionary_variable>.keys() but writing the name of the variable directly is more concise and it works exactly the same.

💡 Tip: you can assign any valid name to the loop variable.

To iterate over the values , we use:

To iterate over the key-value pairs , we use:

💡 Tip: we are defining two loop variables because we want to assign the key and the value to variables that we can use in the loop.

If we define only one loop variable, this variable will contain a tuple with the key-value pair:

Break and Continue in Python

Now you know how to iterate over sequences in Python. We also have loop control statements to customize what happens when the loop runs: break and continue .

The Break Statement

The break statement is used to stop the loop immediately.

When a break statement is found, the loop stops and the program returns to its normal execution beyond the loop.

In the example below, we stop the loop when an even element is found.

The Continue Statement

The continue statement is used to skip the rest of the current iteration.

When it is found during the execution of the loop, the current iteration stops and a new one begins with the updated value of the loop variable.

In the example below, we skip the current iteration if the element is even and we only print the value if the element is odd:

The zip() function in Python

zip() is an amazing built-in function that we can use in Python to iterate over multiple sequences at once, getting their corresponding elements in each iteration.

We just need to pass the sequences as arguments to the zip() function and use this result in the loop.

The enumerate() Function in Python

You can also keep track of a counter while the loop runs with the enum() function. It is commonly used to iterate over a sequence and get the corresponding index.

💡 Tip: By default, the counter starts at 0 .

If you start the counter from 0 , you can use the index and the current value in the same iteration to modify the sequence:

You can start the counter from a different number by passing a second argument to enumerate() :

The else Clause

For loops also have an else clause. You can add this clause to the loop if you want to run a specific block of code when the loop completes all its iterations without finding the break statement.

💡 Tip: if break is found, the else clause doesn't run and if break is not found, the else clause runs.

In the example below, we try to find an element greater than 6 in the list. That element is not found, so break doesn't run and the else clause runs.

However, if the break statement runs, the else clause doesn't run. We can see this in the example below:

🔹 While Loops in Python

While loops are similar to for loops in that they let us repeat a block of code. The difference is that while loops run while a condition is True .

In a while loop, we define the condition, not the number of iterations. The loop stops when the condition is False .

This is the general syntax of a while loop:

💡 Tip: in while loops, you must update the variables that are part of the condition to make sure that the condition will eventually become False .

Break and Continue

We can also use break and continue with while loops and they both work exactly the same:

We can also add an else clause to a while loop. If break is found, the else clause doesn't run but if the break statement is not found, the else clause runs.

In the example below, the break statement is not found because none of the numbers are even before the condition becomes False , so the else clause runs.

This is the output:

But in this version of the example, the break statement is found and the else clause doesn't run:

Infinite While Loops

When we write and work with while loops, we can have something called an "infinite loop." If the condition is never False , the loop will never stop without external intervention.

This usually happens when the variables in the condition are not updated properly during the execution of the loop.

💡 Tip: you must make the necessary updates to these variables to make sure that the condition will eventually evaluate to False .

💡 Tip: to stop this process, type CTRL + C . You should see a KeyboardInterrupt message.

🔸 Nested Loops in Python

We can write for loops within for loops and while loops within while loops. These inner loops are called nested loops.

💡 Tip: the inner loop runs for each iteration of the outer loop.

Nested For Loops in Python

If we add print statements, we can see what is happening behind the scenes:

The inner loop completes two iterations per iteration of the outer loop. The loop variables are updated when a new iteration starts.

This is another example:

Nested While Loops in Python

Here we have an example of nested while loops. In this case, we have to update the variables that are part of each condition to guarantee that the loops will stop.

💡 Tip: we can also have for loops within while loops and while loops within for loops.

🔹 Functions in Python

In Python, we can define functions to make our code reusable, more readable, and organized. This is the basic syntax of a Python function:

💡 Tip: a function can have zero, one, or multiple parameters.

Function with No Parameters in Python

A function with no parameters has an empty pair of parentheses after its name in the function definition. For example:

This is the output when we call the function:

💡 Tip: You have to write an empty pair of parentheses after the name of the function to call it.

Function with One Parameter in Python

A function with one or more parameters has a list of parameters surrounded by parentheses after its name in the function definition:

When we call the function, we just need to pass one value as argument and that value will be replaced where we use the parameter in the function definition:

Here we have another example – a function that prints a pattern made with asterisks. You have to specify how many rows you want to print:

You can see the different outputs for different values of num_rows :

Functions with Two or More Parameters in Python

To define two or more parameters, we just separate them with a comma:

Now when we call the function, we must pass two arguments:

We can adapt the function that we just saw with one parameter to work with two parameters and print a pattern with a customized character:

You can see the output with the customized character is that we call the function passing the two arguments:

How to Return a Value in Python

Awesome. Now you know how to define a function, so let's see how you can work with return statements.

We will often need to return a value from a function. We can do this with the return statement in Python. We just need to write this in the function definition:

💡 Tip: the function stops immediately when return is found and the value is returned.

Here we have an example:

Now we can call the function and assign the result to a variable because the result is returned by the function:

We can also use return with a conditional to return a value based on whether a condition is True or False .

In this example, the function returns the first even element found in the sequence:

If we call the function, we can see the expected results:

💡 Tip: if a function doesn't have a return statement or doesn't find one during its execution, it returns None by default.

The Style Guide for Python Code recommends using return statements consistently. It mentions that we should:

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable)

Default Arguments in Python

We can assign default arguments for the parameters of our function. To do this, we just need to write <parameter>=<value> in the list of parameters.

💡 Tip: The Style Guide for Python Code mentions that we shouldn't "use spaces around the = sign when used to indicate a keyword argument."

In this example, we assign the default value 5 to the parameter b . If we omit this value when we call the function, the default value will be used.

If we call the function without this argument, you can see the output:

We confirm that the default argument 5 was used in the operation.

But we can also assign a custom value for b by passing a second argument:

💡 Tip: parameters with default arguments have to be defined at the end of the list of parameters. Else, you will see this error: SyntaxError: non-default argument follows default argument .

Here we have another example with the function that we wrote to print a pattern. We assign the default value "*" to the char parameter.

Now we have the option to use the default value or customize it:

🔸 Recursion in Python

A recursive function is a function that calls itself. These functions have a base case that stops the recursive process and a recursive case that continues the recursive process by making another recursive call.

Here we have some examples in Python:

🔹 Exception Handling in Python

An error or unexpected event that that occurs while a program is running is called an exception . Thanks to the elements that we will see in just a moment, we can avoid terminating the program abruptly when this occurs.

Let's see the types of exceptions in Python and how we can handle them.

Common Exceptions in Python

This is a list of common exceptions in Python and why they occur:

In the example below, we will get a RecursionError . The factorial function is implemented recursively but the argument passed to the recursive call is n instead of n-1 . Unless the value is already 0 or 1 , the base case will not be reached because the argument is not being decremented, so the process will continue and we will get this error.

💡 Tip: to learn more about these exceptions, I recommend reading this article from the documentation.

try / except in Python

We can use try/except in Python to catch the exceptions when they occur and handle them appropriately. This way, the program can terminate appropriately or even recover from the exception.

This is the basic syntax:

For example, if we take user input to access an element in a list, the input might not be a valid index, so an exception could be raised:

If we enter an invalid value like 15, the output will be:

Because the except clause runs. However, if the value is valid, the code in try will run as expected.

Here we have another example:

How to Catch a Specific Type of Exception in Python

Instead of catching and handling all possible exceptions that could occur in the try clause, we could catch and handle a specific type of exception. We just need to specify the type of the exception after the except keyword:

How to Assign a Name to the Exception Object in Python

We can specify a name for the exception object by assigning it to a variable that we can use in the except clause. This will let us access its description and attributes.

We only need to add as <name> , like this:

This is the output if we enter 15 as the index:

This is the output if we enter the value 0 for b :

try / except / else in Python

We can add an else clause to this structure after except if we want to choose what happens when no exceptions occur during the execution of the try clause:

If we enter the values 5 and 0 for a and b respectively, the output is:

But if both values are valid, for example 5 and 4 for a and b respectively, the else clause runs after try is completed and we see:

try / except / else / finally in Python

We can also add a finally clause if we need to run code that should always run, even if an exception is raised in try .

If both values are valid, the output is the result of the division and:

And if an exception is raised because b is 0 , we see:

The finally clause always runs.

💡 Tip: this clause can be used, for example, to close files even if the code throws an exception.

🔸 Object-Oriented Programming in Python

In Object-Oriented Programming (OOP), we define classes that act as blueprints to create objects in Python with attributes and methods (functionality associated with the objects).

This is a general syntax to define a class:

💡 Tip: self refers to an instance of the class (an object created with the class blueprint).

As you can see, a class can have many different elements so let's analyze them in detail:

Class Header

The first line of the class definition has the class keyword and the name of the class:

💡 Tip: If the class inherits attributes and methods from another class, we will see the name of the class within parentheses:

In Python, we write class name in Upper Camel Case (also known as Pascal Case), in which each word starts with an uppercase letter. For example: FamilyMember

__init__ and instance attributes

We are going to use the class to create object in Python, just like we build real houses from blueprints.

The objects will have attributes that we define in the class. Usually, we initialize these attributes in __init__ . This is a method that runs when we create an instance of the class.

We specify as many parameters as needed to customize the values of the attributes of the object that will be created.

Here is an example of a Dog class with this method:

💡 Tip: notice the double leading and trailing underscore in the name __init__ .

How to Create an Instance

To create an instance of Dog , we need to specify the name and age of the dog instance to assign these values to the attributes:

Great. Now we have our instance ready to be used in the program.

Some classes will not require any arguments to create an instance. In that case, we just write empty parentheses. For example:

To create an instance:

💡 Tip: self is like a parameter that acts "behind the scenes", so even if you see it in the method definition, you shouldn't consider it when you pass the arguments.

Default Arguments

We can also assign default values for the attributes and give the option to the user if they would like to customize the value.

In this case, we would write <attribute>=<value> in the list of parameters.

This is an example:

Now we can create a Circle instance with the default value for the radius by omitting the value or customize it by passing a value:

How to Get an Instance Attribute

To access an instance attribute, we use this syntax:

How to Update an Instance Attribute

To update an instance attribute, we use this syntax:

How to Remove an Instance Attribute

To remove an instance attribute, we use this syntax:

How to Delete an Instance

Similarly, we can delete an instance using del :

Public vs. Non-Public Attributes in Python

In Python, we don't have access modifiers to functionally restrict access to the instance attributes, so we rely on naming conventions to specify this.

For example, by adding a leading underscore, we can signal to other developers that an attribute is meant to be non-public.

The Python documentation mentions:

Use one leading underscore only for non-public methods and instance variables. Always decide whether a class's methods and instance variables (collectively: "attributes") should be public or non-public. If in doubt, choose non-public; it's easier to make it public later than to make a public attribute non-public. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won't change or even be removed. - source

However, as the documentation also mentions:

We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work). - source

💡 Tip: technically, we can still access and modify the attribute if we add the leading underscore to its name, but we shouldn't.

Class Attributes in Python

Class attributes are shared by all instances of the class. They all have access to this attribute and they will also be affected by any changes made to these attributes.

💡 Tip: usually, they are written before the __init__ method.

How to Get a Class Attribute

To get the value of a class attribute, we use this syntax:

💡 Tip: You can use this syntax within the class as well.

How to Update a Class Attribute

To update a class attribute, we use this syntax:

How to Delete a Class Attribute

We use del to delete a class attribute. For example:

How to Define Methods

Methods represent the functionality of the instances of the class.

💡 Tip: Instance methods can work with the attributes of the instance that is calling the method if we write self.<attribute> in the method definition.

This is the basic syntax of a method in a class. They are usually located below __init__ :

They may have zero, one, or more parameters if needed (just like functions!) but instance methods must always have self as the first parameter.

For example, here is a bark method with no parameters (in addition to self ):

To call this method, we use this syntax:

Here we have a Player class with an increment_speed method with one parameter:

To call the method:

💡 Tip: to add more parameters, just separate them with a comma. It is recommended to add a space after the comma.

Properties, Getters and Setters in Python

Getters and setters are methods that we can define to get and set the value of an instance attribute, respectively. They work as intermediaries to "protect" the attributes from direct changes.

In Python, we typically use properties instead of getters and setters. Let's see how we can use them.

To define a property, we write a method with this syntax:

This method will act as a getter, so it will be called when we try to access the value of the attribute.

Now, we may also want to define a setter:

And a deleter to delete the attribute:

💡 Tip: you can write any code that you need in these methods to get, set, and delete an attribute. It is recommended to keep them as simple as possible.

If we add descriptive print statements, we can see that they are called when we perform their operation:

🔹 How to Work with Files in Python

Working with files is very important to create powerful programs. Let's see how you can do this in Python.

How to Read Files in Python

In Python, it's recommended to use a with statement to work with files because it opens them only while we need them and it closes them automatically when the process is completed.

To read a file, we use this syntax:

We can also specify that we want to open the file in read mode with an "r" :

But this is already the default mode to open a file, so we can omit it like in the first example.

💡 Tip: that's right! We can iterate over the lines of the file using a for loop. The file path can be relative to the Python script that we are running or it can be an absolute path.

How to Write to a File in Python

There are two ways to write to a file. You can either replace the entire content of the file before adding the new content, or append to the existing content.

To replace the content completely, we use the "w" mode, so we pass this string as the second argument to open() . We call the .write() method on the file object passing the content that we want to write as argument.

When you run the program, a new file will be created if it doesn't exist already in the path that we specified.

This will be the content of the file:

How to Append to a File in Python

However, if you want to append the content, then you need to use the "a" mode:

This small change will keep the existing content of the file and it will add the new content to the end.

If we run the program again, these strings will be added to the end of the file:

How to Delete a File in Python

To delete a file with our script, we can use the os module. It is recommended to check with a conditional if the file exists before calling the remove() function from this module:

You might have noticed the first line that says import os . This is an import statement. Let's see why they are helpful and how you can work with them.

🔸 Import Statements in Python

Organizing your code into multiple files as your program grows in size and complexity is good practice. But we need to find a way to combine these files to make the program work correctly, and that is exactly what import statements do.

By writing an import statement, we can import a module (a file that contains Python definitions and statements) into another file.

These are various alternatives for import statements:

First Alternative:

💡 Tip: math is a built-in Python module.

If we use this import statement, we will need to add the name of the module before the name of the function or element that we are referring to in our code:

We explicitly mention in our code the module that the element belongs to.

Second Alternative:

In our code, we can use the new name that we assigned instead of the original name of the module:

Third Alternative:

With this import statement, we can call the function directly without specifiying the name of the module:

Fourth Alternative:

With this import statement, we can assign a new name to the element imported from the module:

Fifth Alternative:

This statement imports all the elements of the module and you can refer to them directly by their name without specifying the name of the module.

💡 Tip: this type of import statement can make it more difficult for us to know which elements belong to which module, particularly when we are importing elements from multiple modules.

According to the Style Guide for Python Code :

Wildcard imports (from <module> import *) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools.

🔹 List and Dictionary Comprehension in Python

A really nice feature of Python that you should know about is list and dictionary comprehension. This is just a way to create lists and dictionaries more compactly.

List Comprehension in Python

The syntax used to define list comprehensions usually follows one of these four patterns:

💡 Tip: you should only use them when they do not make your code more difficult to read and understand.

List Comprehensions vs. Generator Expressions in Python

List comprehensions are defined with square brackets [] . This is different from generator expressions, which are defined with parentheses () . They look similar but they are quite different. Let's see why.

We can check this with the sys module. In the example below, you can see that their size in memory is very different:

We can use generator expressions to iterate in a for loop and get the elements one at a time. But if we need to store the elements in a list, then we should use list comprehension.

Dictionary Comprehension in Python

Now let's dive into dictionary comprehension. The basic syntax that we need to use to define a dictionary comprehension is:

Here we have some examples of dictionary comprehension:

This is an example with a conditional where we take an existing dictionary and create a new dictionary with only the students who earned a passing grade greater than or equal to 60:

I really hope you liked this article and found it helpful. Now you know how to write and work with the most important elements of Python.

⭐ Subscribe to my YouTube channel and follow me on Twitter to find more coding tutorials and tips. Check out my online course Python Exercises for Beginners: Solve 100+ Coding Challenges

Developer, technical writer, and content creator @freeCodeCamp. I run the freeCodeCamp.org Español YouTube channel.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Article Categories

Book categories, collections.

Write a Simple Program in Python

Python for kids for dummies.

Book image

Sign up for the Dummies Beta Program to try Dummies' newest way to learn.

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:

Press the Enter key.

Python runs the code you typed.

writing program in python

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.

About This Article

This article is from the book:.

About the book author:

Brendan Scott is a dad who loves Python and wants kids to get some of its magic too. He started pythonforkids.brendanscott.com to help teach his oldest child to code. He maintains it to help other young people learn Python.

This article can be found in the category:

Learn Python interactively.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials.

Learn Python Interactively

Python Introduction

Python Flow Control

Python Functions

Python Datatypes

Python Files

Python Object & Class

Python Advanced Topics

Python Date and time

Related Topics

Python IDEs and Code Editors

Python Main function

Python Programming

How to Get Started With Python?

In this tutorial, you will learn to install and run Python on your computer. Once we do that, we will also write our first Python program.

Video: Introduction to Python

Python is a cross-platform programming language, which means that it can run on multiple platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET virtual machines. It is free and open-source.

Even though most of today's Linux and Mac have Python pre-installed in it, the version might be out-of-date. So, it is always a good idea to install the most current version.

The Easiest Way to Run Python

The easiest way to run Python is by using Thonny IDE .

The Thonny IDE comes with the latest version of Python bundled in it. So you don't have to install Python separately.

Follow the following steps to run Python on your computer.

Run Python on your computer

If you don't want to use Thonny, here's how you can install and run Python on your computer.

Install Python on your computer

Once you finish the installation process, you can run Python.

1. Run Python in Immediate mode

Once Python is installed, typing python in the command line will invoke the interpreter in immediate mode. We can directly type in Python code, and press Enter to get the output.

Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a calculator. To exit this mode, type quit() and press enter.

Run Python in Immediate mode

2. Run Python in the Integrated Development Environment (IDE)

We can use any text editing software to write a Python script file.

We just need to save it with the .py extension. But using an IDE can make our life a lot easier. IDE is a piece of software that provides useful features like code hinting, syntax highlighting and checking, file explorers, etc. to the programmer for application development.

By the way, when you install Python, an IDE named IDLE is also installed. You can use it to run Python on your computer. It's a decent IDE for beginners.

When you open IDLE, an interactive Python Shell is opened.

Python IDLE

Now you can create a new file and save it with .py extension. For example, hello.py

Write Python code in the file and save it. To run the file, go to Run > Run Module or simply click F5 .

Run Python programs in IDLE

Now that we have Python up and running, we can write our first Python program.

Let's create a very simple program called Hello World . A "Hello, World!" is a simple program that outputs Hello, World! on the screen. Since it's a very simple program, it's often used to introduce a new programming language to beginners.

Type the following code in any text editor or an IDE and save it as hello_world.py

Then, run the file. You will get the following output.

Congratulations! You just wrote your first program in Python.

As you can see, this was a pretty easy task. This is the beauty of the Python programming language.

Table of Contents

Sorry about that.

Related Tutorials

Python Tutorial

Try PRO for FREE

writing program in python

Code Like A Girl

Gabriela Dijkhoffz

Jun 12, 2018

Ch 1 — Intro to Python: Writing Your First Program

Welcome back! By now, you should have installed Virtual Box and have Ubuntu 18.04 running on your virtual machine. Ubuntu 18.04 already has Python3 installed, so you don’t have to worry about that. You should also have Atom downloaded on your virtual machine. If you haven’t done these things, refer back to my previous article where I explained how to do these things.

Some Background on Programming

Assuming you may be an absolute beginner, let’s start by asking the question: What is programming? Programming is basically talking to your computer and asking it to perform certain actions. This is done through Terminal, in which you can directly write commands to your computer, as well as run programs you write in a text editor. The big issue here is that the computer doesn’t speak English, Spanish, or any language traditionally used to communicate between humans. Different programming languages like Python, C, Java, etc. have been created to develop complex programs, as well as perform simple commands that computers can understand. It’s common to be confused and frustrated when learning a programming language for the first time because it requires us to approach problems in a different way. In many introductory Computer Science courses, professors will ask students to explain how to make a peanut butter and jelly sandwich. The students will respond with simple commands such as, “open the bag of bread, then take out two slices, spread peanut butter on one slice, spread peanut butter on the other”, etc. The issue here is that they’re assuming the person listening understands that to spread the peanut butter, you need to open the jar, insert the knife, get some peanut butter, grab a slice of bread, and evenly spread throughout. When writing code, think of your computer as something that will only do exactly what you tell it to, in the order you tell it to. This takes some getting used to, but before you know it, you’ll automatically start thinking this way and your mind will be set to solve problems efficiently.

Writing Our First Program

When learning a new programming language, it’s traditional for the first program to be the “Hello World” program. This program prints out the outputs the words “Hello World” into Terminal. The book advises us to do a slight variation of this, but it’s still the same concept.

With Python, we can either write a program in a text editor and then run it on Terminal or we can use Python’s Interactive Interpreter and type commands directly in Terminal. First, we will write in the Python Interpreter. To do this, open Terminal, type in the following, and click enter:

This is what should come up. We can now write directly into the Python Interpreter and if used properly, it should be able to run code one line at a time and in the order we write them. For example, let’s try the “Hello World” program.

Here we see the print() function. Anything inside the parentheses and between the quotes will display in the Terminal. If we leave it blank, it won’t print anything.

What is a String?

In this example, “Hello World” is the String being printed by the print() function. A String can be printed using single quotes (‘Hello World’) or double quotes (“Hello World”).

To use quotes inside of Strings , we can start the String with single quotes and have the double quote inside the String or vice versa.

Writing Code in Atom

Now that we’ve explored the Python Interpreter, we can start to write our code in the text editor and actually run it in Terminal. This way, we can write more complex code all in one place, rather than asking the interpreter to do what we want it to do, one line at a time.

To start, you should create a folder where you can save your code in order to keep it organized. It’s important to note the path to this folder because when you run your code on Terminal, you must be in the right directory to find the files.

To create a folder, click the files icon on the left side of your desktop.

Next, click “Desktop” on the left side and then right click in the blank space. Select, “New Folder”.

Finally, give your folder a name and click “Create”.

Next, you can open Atom. For this tutorial and the ones to come, we will be using Atom as our text editor. A good tip for using Atom, when you create a new file, save it immediately. This way, it will color code your code (this is called syntax highlighting ) and help with formatting (this will make more sense later).

When you open Atom, click “File” on the top left corner and click “New File” or use the keyboard shortcut Ctrl + N to create a new file.

Next, click “File” again, but this time select “Save As” or press Ctrl + Shift + S on your keyboard to save the file in the folder you created.

In this screen, find the folder you created. I saved mine in the Desktop, so I selected “Desktop” then “Python Practice”. Next, I named the file on the top input box. When naming a Python file, you have to make sure you use the format “filename.py”. The .py at the end represents the Python file extension.

Now we can write the same program we wrote on the interpreter, but on Atom instead.

I used the same print() function and entered a String between the quotes just like we did previously. You may have noticed there’s a blue dot on the file tab next to the name. This dot means that you edited the file and haven’t saved it. If you click on “File” and select “Save” or press Ctrl + S on your keyboard, it will save the file and the blue dot will go away. This is something important to do as you go because if you want to run your program and check if it’s working right, it will only run the last saved version.

Let’s try running this program now. Switch screens to Terminal.

As mentioned before, to run a program, we have to make sure Terminal is in the correct directory to find the file. To do this, we are going to type the following into Terminal and click enter. If you named your directory something different, then replace your directory path below.

Now let’s break this down, “ cd ” means change directory. If we were to type “ cd ~ ” by itself and click enter, it would take us back to the home directory. In the commands above, I changed the directory to Desktop and the folder Python Practice inside the Desktop folder. To do this easily, first type cd. Then when you’re going to type Desktop, just type “Des” then hit tab and it should finish the word for you. Same with the next folder, type Python then hit tab, and it should finish typing it.

This can be used a lot, especially when you know the name of the file or folder you’re looking for and if you’re sure there isn’t another file or folder that could come up with that name. To learn more about the “ cd ~ ” command, check out this article .

You may have also noticed the random backslash ( \ ) after the word “Python” in the previous command. This character is used when writing code in Python and when typing in the Terminal. It is considered an escape character , meaning it causes the Terminal to ignore the following space as code. Instead, it treats it as part of the directory name. This is specific to the example above, however, backslashes can be used to escape other characters, but for brevity I’m just covering this example.

After you enter the above, it will change the directory and will now appear in bold blue letters as pictured. Since we are in the correct directory, we can run files in the Python Practice folder. To do this, you will type in the following and press enter (if you named your file differently, use filename.py as the format to run your program):

Yay! We wrote a program to print the words “Hello World!”. This might seem like it’s not a big deal, but this is the first step to writing many more complex programs that do so many cool things, I promise!!

Proper Coding Habits

Now that we wrote our first program, let’s talk about some proper habits to develop while writing code.

When you write any program, you should always start with a comment that describes the program. This is important because later on, when you have a million Python programs that are thousands of lines long, you might not remember exactly what it was for.

In addition, comments help other programmers understand your code. In the working world, developers have to modify other developers’ code. Imagine how hard this could be if their code is disorganized and has no comments explaining what it does. If you want to make a comment about a certain line or section of code, make sure to write the comment before the line of code you are talking about.

To make comments on your programs, type in “#” at the beginning of the line, and everything for the rest of that line will be considered a comment. Comments are ignored by the Python Interpreter and aren’t executed as code.

If you were to run the example above, it would only print the words “Hello World!” and ignore the comments. Try it!

Now that we’ve learned a little bit about writing programs in Python, the Python Interpreter, and Terminal, I’m going to attempt and show the End-of-Chapter challenges provided by the book: Python Programming for the Absolute Beginner.

Challenge 1

Create an error of your very own by entering your favorite ice cream flavor in interactive mode. Then, make up for your misdeed and enter a statement that prints the name of your favorite ice cream.

To start, I’ll open Terminal and start the Python Interpreter or Interactive mode and type in my favorite ice cream flavor.

As seen above, I typed in “chocolate” into the Python Interpreter and pressed enter. This created a NameError which means that I entered a Variable that hasn’t been previously defined. You can learn more about Python Debugging and errors in this article .

Now, let’s fix the error and instead print the name of my favorite ice cream flavor.

This time, I wrote the following code to print the word “Chocolate”.

To exit the interpreter, enter “ exit() ” and press enter.

First challenge done!

Challenge 2

Write and save a program that prints out your name and waits for the user to press the Enter key before the program ends.

The input() Function

To do this challenge, we’re going to learn about the input() function. The input() function is similar to the print() function because it outputs to the Terminal anything you write in between the parentheses and quotes, but it requires user input (typing something in and pressing enter) to move forward with the program or end the program if it’s the last line. Here’s an example:

As you can see, this program didn’t end until I pressed enter. The first picture, shows the screen before I pressed enter and the second picture shows it after.

Now, let’s actually write the program the challenge asked us to.

Try it yourself!

Yay, it’s done!

Challenge 3

Write a program that prints your favorite quote. It should give credit to the person who said it on the next line.

For this challenge you can start by finding a quote along with the author.

Notice that the String in the first print() function is split into two with a comma. I used this feature because when I wrote the quote, the line was too long and splitting it into two lines makes the code easier to read. This is also an example of how to have quotes inside Strings .

When I run the program, it still outputs to Terminal all in one line because the comma just combines both Strings into one call of the print() function.

To get the author in the next line, I just had to call the print() function again in the next line with the String “-John Woods”. It’s good to note that if you wanted to add an extra line in between these two, you can add \n at at end of a String before the end quotes. “ \n ” means insert new line, for example:

The only thing I changed in the code above is the “ \n ” at the end of the quote and after the author’s name.

This is useful to separate the output so it’s more organized and easier to read.

And… This is all for Chapter 1. You learned about the Python Interpreter, writing Python programs in Atom and running them in Terminal, some Terminal commands and syntax, Strings , the print() and input() functions, and some good programming habits!

If you want to see more, tune in for my next article on Chapter 2 in which you will learn more about Strings, Variables, more on the input() function, and doing math in your programs.

Follow me on Twitter @Gdijkhoffz for updates on my articles and cool programming stuff!

Thanks for reading :)

More from Code Like A Girl

Welcome to Code Like A Girl, a space that celebrates redefining society's perceptions of women in technology. Share your story with us!

About Help Terms Privacy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

Gabriela Dijkhoffz

software engineer || 🇻🇪

Text to speech

Programming for Data Science with Python

How To Write Your First Python Application

This blog was last updated on July 13, 2021.

Python is one of the fastest-growing programming languages across the world. Given its incredible versatility, Python can solve many types of software problems. With that said, it shouldn’t come as a surprise that Python is an indispensable tool for data specialists, analysts, and machine learning engineers, among many other professionals.

In this article, we’ll walk you through writing your first Python application. In doing so, we’ll create a simple Python program covering rudimentary Python syntax before connecting the program to a database. Let’s get started.

Why Learn Python

Python is a powerful and in-demand programming language . In recent years, the language has been steadily climbing RedMonk’s “annual programming language rankings ,” a list based on rankings from GitHub and StackOverflow. As of the January 2021 rankings, Python was in second place — one spot higher than the year prior.

There are many reasons for Python’s success, including the language’s remarkable versatility and simplicity. Python is a great programming language to learn first due to its intuitive syntax that resembles that of the English language and a relatively shallow learning curve.

Although Python has established itself as the standard language of artificial intelligence and data science, it’s also widely used in web development, scientific computing and software development. What’s more, Python boasts a vast community of collaborators who constantly enrich its already vast ecosystem and keep its many libraries up-to-date.

All of these reasons make Python a great starting point for any aspiring programmer. Without further ado, let’s start writing our first Python program.

Setting Up Python

To be able to run the code in this article, you’ll need to have Python 3 installed on your computer. To check whether you already have Python 3 on your machine, follow the instructions below depending on your operating system.

In an active Python prompt, you can type in “exit()” to close it and go back to the command line.

A working Python 3 prompt on Windows.

A working Python 3 prompt on Windows.

The Python 2 prompt on macOS.

The Python 2 prompt on macOS.

The Python 3 prompt that we’re looking for on macOS.

The Python 3 prompt that we’re looking for on macOS.

Creating Our First .py File

With Python installed, we can now write and run our first Python program.

All Python files end with the “.py” extension. You can create, edit, and save Python files with any text editor. 

To create your first Python file, navigate to the folder that you would like to create your file in and create a file called test.py . Next, open this file up in a text editor and type in the following code:

Save your file, and in the terminal, navigate to the file’s location. Then, run the file by calling python test.py . This line instructs your Python interpreter to execute the command you just wrote. You should see the correct output:

Note : remember to use “python3” instead of “python” if needed to get to the Python 3 executable.  Some of the examples will not work with Python 2.

This hello-world program works, but let’s make it more interesting.

To start, let’s add a variable and a conditional statement to our program. We want the variable to store our first name — that we’ll provide to the program dynamically, and the conditional statement to check if the name provided matches the one we defined in the program. Depending on the result of the conditional statement, the program will print out a greeting message or ask for another name.

Note that, unlike many other languages, Python uses whitespace indentation as a delimiter for code blocks instead of the traditional curly braces or keywords. This allows Python to have extremely readable code. Keep this in mind as you write your program. It will help you avoid issues caused by missing line breaks or indentation.

Let’s run our program and see the output:

As the next step, let’s edit the name variable to store another name to see whether our condition is really working:

If you run the program again, you should see the following output:

As expected, since the two names are not the same, the program executes the statement captured by the “else” branch of the condition.

Writing a Simple Function

Let’s take our basic program logic and turn it into a function. 

Our function will accept a single argument called “name.” The program will then ask whether the provided name is the name of the person interacting with the program. The user may answer affirmatively with a “yes,” which will prompt the program to print a greeting message. Any other answer will be interpreted as negative and the program will thus print another message.

This function might be implemented in the following way:

Let’s examine this new program component by component.

We begin by defining the function (if this part is confusing, check out our article on function definition in Python ). In short, Python functions are prefaced using the def keyword followed by the function’s name; in this example, we’ll call our function “ checkName” . 

Inside the function, we declare a variable “ answer” . Using Python’s “input” function, we ask the user whether the name being printed out is theirs and the user provides their answer by typing it into the terminal. We store the answer into a variable and perform the conditional check.

Note that the conditional now calls the “ lower()” method on the answer. We use this method simply to ensure that the answer is lowercase so that it’s always evaluated identically regardless of how the user types it in — whether as “yes,” “YES,” “yEs” or “Yes.” 

At the end of the file, we call the function, passing our name as the parameter. With this function call in place, we should be able to run our script and walk through both conditionals:

Note : if you are getting a NameError with the message “name ‘yes’ is not defined”, you are running the program using Python 2 instead of Python 3. Make sure that you have installed Python 3 and are using it.

Let’s take our function a step further and allow our user to enter their name even if it’s not the one the program expected. Implementing such functionality will take only one additional line and one changed line.

The new changes are right after the “else” statement. Instead of apologizing to the user, the program now asks for the user’s name and greets them. Running the program should look something like this:

Having written a simple function and used variables, user input and conditional statements, let’s connect to a simple SQLite database to store and retrieve information.

Creating and Accessing Database Tables 

SQLite is a simple database that stores records in a file on disk. It’s got fewer features than production-grade database systems like MySQL and PostgreSQL, but SQLite is an easier database to start learning with.

Note : Most of the feature differences between SQLite and other systems are in the areas of complex data types, performance, and reliability . Such functionality is valuable for production systems, but we aren’t going to cover it in this article. The SQL syntax that we’re using in the examples in this article is very similar to what you can use with MySQL or PostgreSQL.

Creating a Table and Inserting Our First Record

To begin working with SQLite, we’ll open the Python interpreter and create a new database called “example.db”. Then, we’ll create a new table in our database, called “users”, and add a record for Keenan.

We start by importing the “sqlite3” library:

Next, we select the database to connect to. Because SQLite is file-based, the name we specify in this step is the name of the file where all the data will be stored. SQLite will create the file if it doesn’t exist:

After we’ve selected the right database, we’ll need to define a database cursor. This cursor will help us send queries to the SQLite database and process their results:

We can now use the cursor to run SQL queries against our “example.db” database.

Let’s create our desired “users” table with two values for each record: an ID number, and a first name. The ID number will serve as a primary key, meaning that each user record will have a different identifier, to help us distinguish them. To make sure there are no errors creating the table, we’ll run another query first — to drop any existing versions of the table with the same name:

At this point, we have a “users” table that we can start inserting values into. Time to add our first record , for Keenan:

We will now use the “commit” function to ensure that all changes have been saved to our new “users“ table, and will then close our connection to the “example.db” database:

Here is the full sequence of the commands we’ve run just now, all in one snippet:

We now have a SQLite database in the “example.db” file in our current directory, and it should contain a single record for Keenan. In the next section, we’ll retrieve that the data is stored correctly.

Retrieving a Database Record

After we’ve inserted our first record, it’s a good idea to verify that the data got stored correctly. To query the contents of the database, we’ll use the Python interpreter once again.

We start by importing the “sqlite3” library, the same way we did in the previous section. We then select the “example.db” database and create a cursor to help us send queries to it:

We can now use the cursor to execute a SQL Select statement to get all users from the “users” table and print their data one by one. Because the cursor can contain multiple results, we will need to iterate over them using the Python “for” statement:.

Note : when entering the commands from this snippet, make sure that you type in four spaces before the “print” statement. Indentation of code using spaces helps the Python interpreter understand how the “print” statement relates to the “for” statement above.

The output shows us that the record for Keenan that we entered in the previous section is present in the database and that its user ID is 1.

It’s interesting to note that we didn’t specify which identifier we want Keenan to get — the database decided that for us due to our use of the Primary Key statement on the “id” column. When we define a numeric column and make it a primary key, the database will pick a higher ID number for each new record.

With the database created and working, and with the first user record correctly stored, we can now upgrade our “checkName” function to return the person’s ID from our database if there is a record for their name.

Using Database Records in Our Python Program

Let’s have a look at how we could access database records in our “ test.py” file. We’ll update the “checkName” function code to check whether the person’s name is already in our SQLite database. If it is, we will greet them, and if it’s not, we will tell them that that they are not in the database yet:

Let’s run our new program and see what happens when we enter a name that isn’t yet present in the database:

And now let’s try this for Keenan who already has a database record:

We get the message with Keenan’s ID back, as expected.

Learn To Code With Udacity

Congratulations, you’ve just built a simple Python application that’s communicating with your database, storing variables, getting user input and running conditional statements.

You could expand your program by asking the user their name and storing it in the database if there isn’t a record for them already. You could also tweak the “print” statements to clean up unnecessary whitespace in the program’s output.

If you want to learn more about how to write a Python application, consider enrolling in a Udacity Nanodegree program, where you’ll complete hands-on projects and get valuable career support. We offer an Introduction to Programming program, which is great for beginners to HTML, CSS, JavaScript and/or Python. If you’re particularly interested in Python, check out our Python for Data Science program, which provides a more specialized approach to mastering the language.

Enroll in our Introduction to Programming Nanodegree program today!

Udacity Team

Popular Nanodegrees

Data scientist nanodegree, self-driving car engineer, data analyst nanodegree, android basics nanodegree, intro to programming nanodegree, ai for trading, predictive analytics for business nanodegree, ai for business leaders, data structures & algorithms, school of artificial intelligence, school of cyber security, school of data science, school of business, school of autonomous systems, school of executive leadership, school of programming and development, related articles, multiple inheritance in c++.

writing program in python

Python Ordered Sets: An Overview

writing program in python

Implementing Dijkstra’s Algorithm in Python

writing program in python

Python Match-Case Statement: Example & Alternatives

[et_bloom_locked optin_id=”optin_4″]

Click below to download your preferred Career Guide

Web Developer Career Guide Cloud Career Guide Data Career Guide Robotics Career Guide

[/et_bloom_locked]

Notice: While JavaScript is not essential for this website, your interaction with the content will be limited. Please turn JavaScript on for the full experience.

Notice: Your browser is ancient . Please upgrade to a different browser to experience a better web.

Python For Beginners

Welcome! Are you completely new to programming ? If not then we presume you will be looking for information about why and how to get started with Python. Fortunately an experienced programmer in any programming language (whatever it may be) can pick up Python very quickly. It's also easy for beginners to use and learn, so jump in !

Installing Python is generally easy, and nowadays many Linux and UNIX distributions include a recent Python. Even some Windows computers (notably those from HP) now come with Python already installed. If you do need to install Python and aren't confident about the task you can find a few notes on the BeginnersGuide/Download wiki page, but installation is unremarkable on most platforms.

Before getting started, you may want to find out which IDEs and text editors are tailored to make Python editing easy, browse the list of introductory books , or look at code samples that you might find helpful.

There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be useful if English is not your first language.

The online documentation is your first port of call for definitive information. There is a fairly brief tutorial that gives you basic information about the language and gets you started. You can follow this by looking at the library reference for a full description of Python's many libraries and the language reference for a complete (though somewhat dry) explanation of Python's syntax. If you are looking for common Python recipes and patterns, you can browse the ActiveState Python Cookbook

Looking for Something Specific?

If you want to know whether a particular application, or a library with particular functionality, is available in Python there are a number of possible sources of information. The Python web site provides a Python Package Index (also known as the Cheese Shop , a reference to the Monty Python script of that name). There is also a search page for a number of sources of Python-related information. Failing that, just Google for a phrase including the word ''python'' and you may well get the result you need. If all else fails, ask on the python newsgroup and there's a good chance someone will put you on the right track.

Frequently Asked Questions

If you have a question, it's a good idea to try the FAQ , which answers the most commonly asked questions about Python.

Looking to Help?

If you want to help to develop Python, take a look at the developer area for further information. Please note that you don't have to be an expert programmer to help. The documentation is just as important as the compiler, and still needs plenty of work!

How to Use Python: Your First Steps

How to Use Python: Your First Steps

Table of Contents

Why You Should Use Python

Installing python from binaries, running your python interpreter, built-in data types, conditionals, syntax errors, semantic errors, how to get help in python, repls (read-evaluate-print loops), code editors, ides (integrated development environments), python code style, the standard library, the python package index and pip, coding is like riding a bike, advising new python coders, code an example: count to 10, test your knowledge.

Are you looking for a place to learn the basics of how to use Python from a beginner’s perspective ? Do you want to get up and running with Python but don’t know where to start? If so, then this tutorial is for you. This tutorial focuses on the essentials you need to know to start programming with Python.

In this tutorial, you’ll learn:

You’ll also have the opportunity to create your first Python program and run it on your computer . Finally, you’ll have a chance to evaluate your progress with a quiz that’ll give you an idea of how much you’ve learned.

Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

The Python Logo. The Python logo is a trademark of the Python Software Foundation.

Python, named after the British comedy group Monty Python , is a high-level , interpreted , interactive , and object-oriented programming language. Its flexibility allows you to do many things , both big and small. With Python, you can write basic programs and scripts and also to create complex and large-scale enterprise solutions. Here’s a sampling of its uses:

You can find Python everywhere in the world of computer programming. For example, Python is the foundation of some of the world’s most popular websites , including Reddit, Dropbox, and YouTube, to name a few. The Python web framework Django powers both Instagram and Pinterest .

Python has a bunch of features that make it attractive as your first programming language:

Compared to other programming languages, Python has the following features:

There’s a lot more to learn about Python. But by now, you should have a better idea of why Python is so popular and why you should consider learning to program with it.

How to Download and Install Python

Python works on Linux, Mac, Windows , and several other platforms. It comes preinstalled on macOS and on most Linux distributions. However, if you want to be up to date, then you probably need to download and install the latest version. You also have the choice of using different Python versions in different projects if you want to.

To check what Python version has been installed globally in your operating system, open the terminal or command line and run the following command:

This command prints the version of your system’s default Python 3 installation. Note that you use python3 instead of python because some operating systems still include Python 2 as their default Python installation.

Regardless of your operating system, you can download an appropriate version of Python from the official site . Go there and grab the appropriate 32-bit or 64-bit version for your operating system and processor.

Selecting and downloading a Python binary from the language’s official site is often a good choice. However, there are some OS-specific alternatives:

You can also use the Anaconda distribution to install Python along with a rich set of packages and libraries, or you can use Miniconda if you want to install only the packages you need.

Note: There are several options for managing Python versions and environments. Choosing the right tools for this task can be overwhelming when you’re starting with the language.

For a guide on this subject, check out An Effective Python Environment: Making Yourself at Home .

For further instructions on installing Python on different platforms, you can check out Python 3 Installation & Setup Guide .

You can do a quick test to ensure Python is installed correctly. Fire up your terminal or command line and run the python3 command. That should open a Python interactive session, and your command prompt should look similar to this:

While you’re here, you might as well run your first line of code:

That’s it! You’ve just written your first Python program! When you’re done, you can use exit() or quit() to leave the interactive session, or you can use the following key combinations:

Keep your terminal or command line open. You still have more to do and learn! You’ll start by learning the basics of Python syntax.

The Basic Python Syntax

The Python syntax is clear, concise, and focused on readability. Readability is arguably one of the more attractive features of the language itself. It makes Python ideal for people who are learning to program. In this section, you’ll learn about several important components of the Python syntax:

This knowledge will help you get up and running with Python. You’ll be able to create your own programs in almost no time.

Comments are pieces of text that live in your code but are ignored by the Python interpreter as it executes the code. You can use comments to describe the code so that you and other developers can quickly understand what the code does or why the code is written in a given way. To write a comment in Python, just add a hash mark ( # ) before your comment text:

The Python interpreter ignores the text after the hash mark and up to the end of the line. You can also add inline comments to your code. In other words, you can combine a Python expression or statement with a comment in a single line, given that the comment occupies the final part of the line:

You should use inline comments sparingly to clear up pieces of code that aren’t obvious on their own. In general, your comments should be short and to the point. PEP 8 advises keeping comments at 72 characters or less. If your comment is approaching or exceeding that length, then you might want to spread it out over multiple lines:

If you need more room for a given comment, then you can use multiple lines with a hash mark on each. This way, you can keep your comments under 72 characters in length.

In Python, variables are names attached to a particular object. They hold a reference, or pointer , to the memory address at which an object is stored. Once a variable is assigned an object, you can access the object using the variable name.

You need to define your variables in advance. Here’s the syntax:

You should use a naming scheme that makes your variables intuitive and readable. The variable name should provide some indication as to what the values assigned to it are.

Sometimes programmers use short variable names, such as x and y . These are perfectly suitable names in the context of math, algebra, and so on. In other contexts, you should avoid single-character names and use something more descriptive. That way, other developers can make an educated guess of what your variables hold. Think of others, as well as your future self, when writing your programs. Your future self will thank you.

Here are some examples of valid and invalid variable names in Python:

Your variable names can be any length and can consist of uppercase and lowercase letters ( A-Z , a-z ), digits ( 0-9 ), and also the underscore character ( _ ). In sum, variable names should be alphanumeric, but note that even though variable names can contain digits, their first character can’t be a digit.

Note: The lower_case_with_underscores naming convention, also known as snake_case , is commonly used in Python. It isn’t enforced, but it’s a widely adopted standard.

Finally, Python now offers full Unicode support , so you can also use Unicode characters in your variable names like you saw above with the variable π .

Like any other programming language, Python has a set of special words that are part of its syntax. These words are known as keywords . To get the complete list of keywords available in your current Python installation, you can run the following code in an interactive session:

Each of these keywords plays a role in Python syntax. They are reserved words that have specific meanings and purposes in the language, so you shouldn’t use them for anything but those specific purposes. For example, you shouldn’t use them as variable names in your code.

There’s another way of getting access to the whole list of Python keywords:

keyword provides a set of functions that allow you to determine if a given string is a keyword. For example, keyword.kwlist holds a list of all the current keywords in Python. These are handy when you need to manipulate keywords programmatically in your Python programs.

Python has a handful of built-in data types , such as numbers (integers, floats, complex numbers), Booleans , strings , lists, tuples , dictionaries , and sets . You can manipulate them with several tools:

In the next few sections, you’ll learn the basics of incorporating Python’s built-in data types into your programs.

Python provides integers, floating-point numbers, and complex numbers. Integers and floating-point numbers are the most commonly used numeric types in day-to-day programming, while complex numbers have specific use cases in math and science. Here’s a summary of their features:

Integer numbers have unlimited precision. Floating-point numbers’ precision information is available in sys.float_info . Complex numbers have a real part and an imaginary part, which are both floating-point numbers.

Operators represent operations, such as addition, subtraction, multiplication, division, and so on. When you combine them with numbers, they form expressions that Python can evaluate:

These operators work with two operands and are commonly known as arithmetic operators . The operands can be numbers or variables that hold numbers.

Besides operators, Python provides you with a bunch of built-in functions for manipulating numbers. These functions are always available to you. In other words, you don’t have to import them to be able to use them in your programs.

Note: There are modules available in the Python standard library , such as math , that also provide you with functions to manipulate numbers.

To use the functions associated with these modules, you first have to import the module and then access the function using module.function_name() . Alternatively, you can import a function directly from the module using from module import function_name .

Given an integer number or a string representing a number as an argument, float() returns a floating-point number:

With float() , you can convert integer numbers and strings representing numbers into floating-point numbers, but you can’t convert a complex number into a floating-point number.

Given a floating-point number or a string as an argument, int() returns an integer . This function doesn’t round the input up to the nearest integer. It simply truncates the input, throwing out anything after the decimal point, and returns the number. So, an input of 10.6 returns 10 instead of 11 . Similarly, 3.25 returns 3 :

Note that you can pass a string representing an integer to int() , but you can’t pass a string representing a floating-point number. Complex numbers don’t work either.

Besides these built-in functions, there are a few methods associated with each type of number. You can access them using attribute reference , also known as dot notation :

These methods can be a useful tool to learn about. In the case of integer numbers, to access their methods through a literal , you need to use a pair of parentheses. Otherwise, you get a SyntaxError .

Booleans are implemented as a subclass of integers with only two possible values in Python: True or False . Note that these values must start with a capital letter.

You use Boolean values to express the truth value of an expression or object. Booleans are handy when you’re writing predicate functions or when you’re using comparison operators , such as greater than ( > ), lower than ( < ), equal ( == ), and so on:

Comparison operators evaluate to Boolean values, True or False . Feel free to play with them in your Python interactive session.

Python provides a built-in function, bool() , that is closely related to Boolean values. Here’s how it works:

bool() takes an object as an argument and returns True or False according to the object’s truth value. To evaluate the truth value of an object, the function uses Python’s truth testing rules .

On the other hand, int() takes a Boolean value and returns 0 for False and 1 for True :

This is because Python implements its Boolean values as a subclass of int , as you saw before.

Strings are pieces of text or sequences of characters that you can define using single, double, or triple quotes:

Note that you can use different types of quotes to create string objects in Python. You can also use the backslash character ( \ ) to escape characters with special meaning, such as the quotes themselves.

Once you define your string objects, you can use the plus operator ( + ) to concatenate them in a new string:

When used on strings, the plus operator ( + ) concatenates them into a single string. Note that you need to include a blank space ( " " ) between words to have proper spacing in your resulting string. If you need to concatenate a lot of strings, then you should consider using .join() , which is more efficient. You’ll learn about .join() a little bit later in this tutorial.

Python comes with many useful built-in functions and methods for string manipulation. For example, if you pass a string as an argument to len() , then you’ll get the string’s length , or the number of characters it contains:

When you call len() using a string as an argument, you get the number of characters, including any blank spaces, in the input string.

The string class ( str ) provides a rich set of methods that are useful for manipulating and processing strings. For example, str.join() takes an iterable of strings and joins them together in a new string. The string on which you call the method plays the role of a separator:

str.upper() returns a copy of the underlying string with all the letters converted to uppercase:

str.lower() returns a copy of the underlying string with all the letters converted to lowercase:

str.format() performs a string formatting operation. This method provides a lot of flexibility for string formatting and interpolation:

You can also use an f-string to format your strings without using .format() :

Python’s f-strings are an improved string formatting syntax. They’re string literals with an f at the beginning, outside the quotes. Expressions that appear in embedded curly braces ( {} ) are replaced with their values in the formatted string.

Strings are sequences of characters. This means that you can retrieve individual characters from a string using their positional index . An index is a zero-based integer number associated with a specific position in a sequence:

An indexing operation retrieves the character at the position indicated by the given index. Note that a negative index retrieves the element in reverse order, with -1 being the index of the last character in the string.

You can also retrieve a part of a string by slicing it:

Slicing operations take the element in the form [start:end:step] . Here, start is the index of the first item to include in the slice, and end is the index of the last item, which isn’t included in the returned slice. Finally, step is an optional integer representing the number of items to jump over while extracting the items from the original string. A step of 2 , for example, will return every other element between start and stop .

Lists are usually called arrays in nearly every other programming language. In Python, lists are mutable sequences that group various objects together. To create a list, you use an assignment with a sequence of comma-separated objects in square brackets ( [] ) on its right side:

Lists can contain objects of different data types, including other lists. They can also be empty. Since lists are mutable sequences, you can modify them in place using index notation and an assignment operation.

Since lists are sequences just like strings, you can access their individual items using zero-based integer indices:

Indexing operations also work with Python lists, so you can retrieve any item in a list by using its positional index. Negative indices retrieve items in reverse order, starting from the last item.

You can also create new lists from an existing list using a slicing operation:

If you nest a list, a string, or any other sequence within another list, then you can access the inner items using multiple indices:

In this case, the first index gets the item from the container list, and the second index retrieves an item from the inner sequence.

You can also concatenate your lists using the plus operator:

Since lists are sequences of objects, you can use the same functions you use on any other sequence, such as strings.

Given a list as an argument, len() returns the list’s length, or the number of objects it contains:

You can check out the Python documentation to see all available list methods. Below is a summary of some of the most commonly used methods.

list.append() takes an object as an argument and adds it to the end of the underlying list:

list.sort() sorts the underlying list in place:

list.pop() takes an integer index as an argument, then removes and returns the item at that index in the underlying list:

Lists are quite common and versatile data structures in Python. They’re so popular that developers sometimes tend to overuse them, which can make the code inefficient.

Tuples are similar to lists, but they’re immutable sequences . This means that you can’t change them after creation. To create a tuple object, can use an assignment operation with a sequence of a comma-separated items on its right side. You commonly use parentheses to delimit a tuple, but they’re not mandatory:

If you try to change a tuple in place, then you get a TypeError indicating that tuples don’t support in-place modifications.

Just like lists, you can also do indexing and slicing with tuples:

Since tuples are sequences, you can use indices to retrieve specific items in the tuples. Note that you can also retrieve slices from a tuple with a slicing operation.

You can also add two tuples using the concatenation operator:

A concatenation operation with two tuples creates a new tuple containing all the items in the two input tuples.

Like with lists and strings, you can use some built-in functions to manipulate tuples. For example, len() returns the length of the tuple, or the number of items it contains:

With a tuple as an argument, list() returns a list with all the items in the input tuple:

Because tuples are immutable sequences, many of the methods that are available for lists don’t work on tuples. However, tuples have two built-in methods:

tuple.count() takes an object as an argument and returns the number of times the item appears in the underlying tuple. If the object isn’t in the tuple, then .count() returns 0 :

tuple.index() takes an object as an argument and returns the index of the first instance of that object in the tuple at hand. If the object isn’t in the tuple, then .index() raises a ValueError :

Tuples are quite useful data structures. They’re memory efficient, immutable, and have a lot of potential for managing data that shouldn’t be modified by the user. They can also be used as dictionary keys, which you’ll learn about in the next section.

Dictionaries

Dictionaries are a type of associative array containing a collection of key-value pairs in which each key is a hashable object that maps to an arbitrary object, the value. There are several ways to create a dictionary. Here are two of them:

The first approach uses a pair of curly brackets in which you add a comma-separated list of key-value pairs, using a colon ( : ) to separate the keys from the values. The second approach uses the built-in function dict() , which can take keyword arguments and turn them into a dictionary, with the keywords as the keys and the arguments as the values.

Note: Since Python 3.6, dictionaries have been ordered data structures . But before that, they were unordered. So, if you’re using a Python version lower than 3.6 and you need an ordered dictionary, then consider using collections.OrderedDict() .

You can retrieve the value associated with a given key using the following syntax:

This is quite similar to an indexing operation, but this time you use a key instead of an index.

You can also retrieve the keys, values, and key-value pairs in a dictionary using .keys() , .values() , and .items() , respectively:

These three methods are fundamental tools when it comes to manipulating dictionaries in Python, especially when you’re iterating through a dictionary .

Python also provides a set data structure. Sets are unordered and mutable collections of arbitrary but hashable Python objects. You can create sets in several ways. Here are two of them:

In the first example, you use curly brackets and a list of comma-separated objects to create a set. If you use set() , then you need to provide an iterable with the objects you want to include in the set. Finally, if you want to create an empty set, then you need to use set() without arguments. Using an empty pair of curly brackets creates an empty dictionary instead of a set.

One of the most common use cases of sets is to use them for removing duplicate objects from an existing iterable:

Since sets are collections of unique objects, when you create a set using set() and an iterable as an argument, the class constructor removes any duplicate objects and keeps only one instance of each in the resulting set.

Note: Python also provides an immutable variation of a set called frozenset . You can create them by calling frozenset() with an iterable as an argument. If you call frozenset() without arguments, then you’ll get an empty frozenset.

You can use some built-in functions with sets like you’ve done with other built-in data structures. For example, if you pass a set as an argument to len() , then you get the number of items in the set:

You can also use operators to manage sets in Python. In this case, most operators represent typical set operations like union ( | ), intersection ( & ), difference ( - ), and so on:

Sets provide a bunch of methods, including methods that perform set operations like those in the above example. They also provide methods to modify or update the underlying set. For example, set.add() takes an object and adds it to the set:

set.remove() takes an object and removes it from the set:

Python sets are quite useful data structures that are an important addition to the Python developer’s tool kit.

Sometimes you need to run (or not run) a given code block depending on whether certain conditions are met. In this case, conditional statements are your ally. These statements control the execution of a group of statements based on the truth value of an expression. You can create a conditional statement in Python with the if keyword and the following general syntax:

The if statement runs only one code block. In other words, if expr0 is true, then only its associated code block will run. After that, the execution jumps to the statement directly below the if statement.

The first elif clause evaluates expr1 only if expr0 is false. If expr0 is false and expr1 is true, then only the code block associated with expr1 will run, and so on. The else clause is optional and will run only if all the previously evaluated conditions are false. You can have as many elif clauses as you need, including none at all, but you can have only up to one else clause.

Here are some examples of how this works:

In the first example, age is equal to 21 , so the condition is true, and Python prints You're a legal adult to your screen. In the second example, the expression age >= 18 evaluates to False , so Python runs the code block of the else clause and prints You're NOT an adult on your screen.

In the final example, the first expression, age > 18 , is false, so the execution jumps to the elif clause. The condition in this clause is true, so Python runs the associated code block and prints You're exactly 18 years old .

If you need to repeat a piece of code several times to get a final result, then you might need to use a loop . Loops are a common way of iterating multiple times and performing some actions in each iteration . Python provides two types of loops:

Here’s the general syntax to create a for loop:

This type of loop performs as many iterations as items in iterable . Normally, you use each iteration to perform a given operation on the value of loop_var . The else clause is optional and runs when the loop finishes. The break and continue statements are also optional.

Check out the following example:

When the loop processes the last number in the tuple, the flow of execution jumps into the else clause and prints The loop wasn't interrupted on your screen. That’s because your loop wasn’t interrupted by a break statement. You commonly use an else clause in loops that have a break statement in their code block. Otherwise, there’s no need for it.

If the loop hits a break_condition , then the break statement interrupts the loop execution and jumps to the next statement below the loop without consuming the rest of the items in iterable :

When i == 3 , the loop prints Number found: 3 on your screen and then hits the break statement. This interrupts the loop, and execution jumps to the line below the loop without running the else clause. If you set number to 6 or any other number that’s not in the tuple of numbers, then the loop doesn’t hit the break statement and prints Number not found .

If the loop hits a continue_condition , then the continue statement resumes the loop without running the rest of the statements in the loop’s code block:

This time, the continue statement restarts the loop when i == 3 . That’s why you don’t see the number 3 in the output.

Both statements, break and continue , should be wrapped in a conditional. Otherwise, the loop will always break when it hits break and continue when it hits continue .

You normally use a while loop when you don’t know beforehand how many iterations you need to complete a given operation. That’s why this loop is used to perform indefinite iterations.

Here’s the general syntax for a while loop in Python:

This loop works similarly to a for loop, but it’ll keep iterating until expression is false. A common problem with this type of loop comes when you provide an expression that never evaluates to False . In this case, the loop will iterate forever.

Here’s an example of how the while loop works:

Again, the else clause is optional, and you’ll commonly use it with a break statement in the loop’s code block. Here, break and continue work the same as in a for loop.

There are situations in which you need an infinite loop . For example, GUI applications run in an infinite loop that manages the user’s events. This loop needs a break statement to terminate the loop when, for example, the user exits the application. Otherwise, the application would continue running forever.

In Python, a function is a named code block that performs actions and optionally computes the result, which is then returned to the calling code. You can use the following syntax to define a function:

The def keyword starts the function header . Then you need the name of the function and a list of arguments in parentheses. Note that the list of arguments is optional, but the parentheses are syntactically required.

The final step is to define the function’s code block, which will begin one level of indentation to the right. In this case, the return statement is also optional and is the statement that you use if you need to send a return_value back to the caller code.

Note: The full syntax to define functions and their arguments is beyond the scope of this tutorial. For an in-depth resource on this topic, check out Defining Your Own Python Function .

To use a function, you need to call it. A function call consists of the function’s name, followed by the function’s arguments in parentheses:

You can have functions that don’t require arguments when called, but the parentheses are always needed. If you forget them, then you won’t be calling the function but referencing it as a function object.

How to Handle Errors in Python

Errors are something that irritates and frustrates programmers at every level of experience. Having the ability to identify and handle them is a core skill for programmers. In Python, there are two types of code-based errors: syntax errors and exceptions .

Syntax errors occur when the syntax of your code isn’t valid in Python. They automatically stop the execution of your programs. For example, the if statement below is missing a colon at the end of the statement’s header, and Python quickly points out the error:

The missing colon at the end of the if statement is invalid Python syntax. The Python parser catches the problem and raises a SyntaxError immediately. The arrow ( ^ ) indicates where the parser found the problem.

Exceptions are raised by syntactically correct code at runtime to signal a problem during program execution. For example, consider the following math expression:

The expression 12 / 0 is syntactically correct in the eyes of the Python parser. However, it raises a ZeroDivisionError exception when the interpreter tries to actually evaluate the expression.

Note: In Python, you’ll commonly rely on exceptions to control the flow of a program. Python developers favor this coding style, known as EAFP (Easier to Ask for Forgiveness than Permission), over the coding style known as LBYL (Look Before You Leap), which is based on using if statements. For more information on these two coding styles, check out LBYL vs EAFP: Preventing or Handling Errors in Python .

Python provides several convenient built-in exceptions that allow you to catch and handle errors in your code.

Semantic errors happen as a result of one or more problems in the logic of a program. These errors can be difficult to find, debug, and fix because no error message is generated. The code runs but generates unexpected output, incorrect output, or no output at all.

A classic example of a semantic error would be an infinite loop , which most programmers experience at least once in their coding lifetime.

Like a good friend, Python is always there to help if you get stuck. Perhaps you want to know how a specific function, method, class, or object works. In this case, you can just open an interactive session and call help() . That’ll take you directly to Python’s help utility :

Once there, you can type in the name of a Python object to get helpful information about it:

When you type the name len at the help> prompt and hit Enter , you get help content related to that built-in function. To leave the content and get back to the help> prompt, you can press Q . To leave the help utility, you can type quit and hit Enter .

You can also use help() with the name of an object as an argument to get information about that object:

Speaking of dir() , you can use this function to inspect the methods and attributes that are available in a particular object:

When you call dir() with the name of a Python object as an argument, the function attempts to return a list of valid attributes for that specific object. This is a convenient way to get an idea of what a given object can do.

Tools for Coding in Python

There are three main approaches to coding in Python. You already used one of them, the Python interactive interpreter , also known as the read-evaluate-print loop (REPL) . Even though the REPL is quite useful for trying out small pieces of code and experimenting, you can’t save your code for later use.

To save and reuse your code, you need to create a Python script or module . Both of them are plain text files with a .py (or .pyw on Windows) extension. To create scripts and modules, you can use a code editor or an integrated development environment (IDE) , which are the second and third approaches to coding in Python.

Although you can create functions in an interactive session, you’ll typically use the REPL for one-line expressions and statements or for short compound statements to get quick feedback on your code. Fire up your Python interpreter and type the following:

The interpreter simply evaluates 24 + 10 , adding the two numbers, and outputs the sum, 34 . Now try one more:

Take a minute to read the output. It states some important principles in Python, which will help you write better and more Pythonic code.

So far, you’ve used the standard Python REPL , which ships with your current Python distribution. However, this isn’t the only REPL out there. Third-party REPLs provide many useful features, such as syntax highlighting, code completion, and so on. Here are some popular options:

Keep in mind that once you close the REPL session, your code is gone. In other words, the code typed into a REPL isn’t persistent, so you can’t reuse it. As a developer, you want code that you can reuse to save precious keystrokes. In this situation, code editors and IDEs come in handy.

The second approach to coding in Python is to use a code editor . Some people prefer an integrated development environment (IDE) , but a code editor is often better for learning purposes. Why? Because when you’re learning something new, you want to peel off as many layers of complexity as possible. Adding a complex IDE into the mix can make the task of learning Python more difficult.

A Python program, in its bare-bones form, consists of lines of text (code) saved in a file with a .py or .pyw extension. You can write Python code in something as basic as Notepad on Windows, but there’s no reason to put yourself through such an ordeal since there are much better options available.

At its core, a code editor should provide several features to help programmers create programs. In most cases, you can customize the code editor to suit your needs and style. So, what should you look for in a code editor? The answer to this question might depend on your personal needs, but in general, you should look for at least the following features:

Take a look at the following comparison example:

The Good Bad and Ugly

The code in the editor at the top ( Sublime Text ) is more readable due to the syntax highlighting and line numbering. The editor also identifies three errors, one of which is a showstopper. Can you figure out which one?

Meanwhile, the editor at the bottom (Notepad) doesn’t display the errors and is hard on the eyes since it’s in black and white.

Here’s a non-exhaustive list of some modern code editors that you can use:

There are many different options, both free and commercial, when it comes to code editors. Do your research and don’t be afraid to experiment! Keep in mind that your code editor should help you adhere to Python coding standards, best practices, and idioms.

An IDE is a program dedicated to software development. IDEs commonly integrate several features, such as code editing, debugging , version control, the ability to build and run your code, and so on. There are a lot of available IDEs that support Python or that are Python-specific. Here are three popular examples:

IDLE is Python’s Integrated Development and Learning Environment. You can use IDLE interactively exactly as you use the Python interpreter. You can also use it for code reuse since you can create and save your code with IDLE. If you’re interested in using IDLE, then check out Getting Started With Python IDLE .

PyCharm is a full-featured, Python-specific IDE developed by JetBrains . If you’re interested in using it, then check out PyCharm for Productive Python Development (Guide) . It’s available on all major platforms and comes in free Edu and Community versions as well as a paid Professional version.

Thonny is a beginner-friendly IDE that will enable you to start working with Python right away. If you’re thinking of using Thonny, then check out Thonny: The Beginner-Friendly Python Editor .

This list of IDEs isn’t nearly complete. It’s intended to give you some guidance on how to get the right Python IDE for you. Explore and experiment before you make your choice.

PEP 8 is the official style guide for Python code. Although it’s not required to write workable Python code, studying PEP 8 and applying it consistently in your Python code will make your programs more readable and maintainable. Luckily, you don’t need to memorize PEP 8 to give your Python code a Pythonic style.

Most code editors and IDEs that support Python internally implement automatic checks to find and point out PEP 8 violations. This will help you consistently improve the style of your code and will also reinforce PEP 8’s recommendations in your mind.

You can also take advantage of code linters , such as Flake8 , Pylint , and pycodestyle . You can even use code formatters, such as Black and isort , to consistently format your code. Some of these tools are conveniently integrated into some of the currently available code editors and IDEs.

If you want to learn more about how you can improve the quality of your code using PEP 8 and other code style best practices, then check out How to Write Beautiful Python Code With PEP 8 and Python Code Quality: Tools & Best Practices .

Get Extra Features in Python

So far, you’ve learned a few basic Python concepts and features. When you start to dive deeper into the language, you may find that you need a certain feature and decide to code it by yourself. If that’s the case, then consider that you might be reinventing the wheel.

Python’s been in use for almost three decades now. It has an incredibly large community of developers, and it’s likely that someone else has run into the same problem as you. With a little research, you may be able to find a code snippet, library, framework, or other solution that can save you a lot of time and effort.

The first place to look is the Python standard library. If you don’t find anything there, then you can also look at the Python Package Index (PyPI) . Finally, you can check out some other third-party libraries .

One of the great things about Python is the plethora of available modules, packages, and libraries both built into the Python core and made available by third-party developers. These modules, packages, and libraries can be quite helpful in your day-to-day work as a Python coder. Here are some of the most commonly used built-in modules:

For example, here you import math to use pi , find the square root of a number with sqrt() , and raise a number to a power with pow() :

Once you import math , you can use any function or object defined in that module. If you want a complete list of the functions and objects that live in math , then you can run something like dir(math) in an interactive session.

You can also import specific functions directly from math or any other module:

This kind of import statement brings the name sqrt() into your current namespace , so you can use it directly without the need to reference the containing module.

If you’re using modules, such as math or random , then make sure not to use those same names for your custom modules, functions, or objects. Otherwise, you might run into name conflicts , which can cause in unexpected behavior.

The Python package index , also known as PyPI (pronounced “pie pea eye”), is a massive repository of Python packages that includes frameworks, tools, packages, and libraries. You can install any PyPI package using pip . This is one of the recommended tools for managing third-party modules, packages, and libraries in Python.

New coders frequently hit a wall when they’re following an example and they see ModuleNotFoundError: No module named module_x when they run the code. This means that the code depends on module_x , but that module isn’t installed in the current Python environment, creating a broken dependency . Modules like module_x can be manually installed using pip .

For example, say you’re trying to run an application that uses pandas , but you don’t have this library installed on your computer. In this case, you can open your terminal and use pip like this:

This command downloads pandas and its dependencies from PyPI and installs them in your current Python environment. Once the installation is finished, you can run your application again and, if there’s no other broken dependency, the code should work.

Take Your Python Skills to the Next Level

Real Python Logo

Here at Real Python , you can find all kinds of resources that can help you out on your path to learning how to program in Python:

At Real Python , you can also find many other resources, such as books and courses , podcast episodes , Office Hours sessions , a newsletter , and so on. Some of them are totally free, others cost a modest fee supports the site and allows us to continue creating and updating content for you.

If you’re just beginning with Python, then check out the book Python Basics: A Practical Introduction to Python 3 . It’ll help you make the leap from beginner to intermediate Python developer.

Of course, there are many other courses, tutorials, and resources about Python available online. Again, this is a personal choice. Do your research before making a decision. A good source of free learning materials is the official Python documentation , which you should keep handy as a reliable and quick reference. Just be aware that the material can be less reader-friendly than what you’ll find at Real Python .

Above all, it’s important that you don’t fall into trying to find the best book or video ever and get lost in the process. Do some research. Ask around. But pick something and stick with it ! Open your code editor and start coding a Python project! Make a commitment to yourself to find a way to bring your vision to life and complete your project.

Coding is like riding a bike. You can watch people to learn how it’s done and sometimes you can get a push, but in the end, it’s a solo event. When you get stuck or need to brush up on a new concept, you can often work through the problem yourself by doing some research on Google. If you get an error message, then typing in the exact error message into Google will often bring up a result on the first page that might solve the problem.

Stack Overflow is another fundamental place to go when you’re looking for answers. The Q&A for coding has some great explanations of Python topics. Understanding slice notation and Manually raising (throwing) an exception in Python are just two truly excellent examples.

If you get stuck on a problem, then try these suggestions:

Stop coding!

Get a piece of paper and map out how to solve the problem using plain words. Use a flowchart if necessary.

Don’t use a try and except block until your code is working. The try can suppress valuable error messages that help identify problems in your code.

Use print() to quickly inspect your variables and make sure they have the expected value. This is an effective quick-and-dirty problem solver.

Use the rubber duck debugging technique. Explain your code, line by line, to the duck. You might find the solution to your problems in the process.

Use the Python Visualizer if you’re still stumped. This tool allows you to step through your code as it executes. The Python Visualizer has examples to help you if needed.

One final and important note: A frustrated brain is not going to help. When you start to get annoyed because something isn’t working, take a break to clear your mind. Go for a run or do something else. You will be amazed just how effective this can be. Often, you’ll come back with fresh eyes and see a simple typo, a misspelled keyword, or something similar.

Coders expect other coders, even beginners, to try and resolve the issue by themselves. At some point, though, you’ll need guidance. Once you’ve tried everything you can think of and have truly hit the wall, ask for help before you smash your keyboard or another inanimate object.

There are several places to get help, including code forums , Facebook groups, and the IRC channel #python , to name a few. Take a minute to read any rules or guidelines for any of the groups that you use. Make it easy for others to help you by explaining the problem and what you’ve tried. If there’s an error, then include that information as well.

Have fun coding!

Many programmers get overwhelmed when they start to solve a problem. An effective approach to help you solve a problem, regardless of size, is to logically divide the problem into smaller parts.

For example, say you need to code a program that counts from 1 to 10. Each time the count increments, you want to display its value. One approach to help in the development of a workflow is to use pseudocode :

Let's make a plan

Since you you’ll be more productive on an organized machine, first create a folder named something like python_code where you’ll store the example files. Learning to code is a hands-on adventure, so fire up your code editor and enter the following code. Don’t just copy and paste the code! Typing it yourself will be much more beneficial to your learning:

Note that lines 3 and 8 start with a hash character ( # ) followed by a space and then an explanation. Those are comments. Comments can have many purposes, but for the most part, you use them to either explain the code or summarize a specific approach you took as the developer. Do the comments in the above examples make sense to you? If not, then improve them or even remove them.

Did you notice that the examples use both a single equals sign ( = ) and a double equals sign ( == )? This can be confusing, so here’s how it works:

Save the file as count_to_ten.py in the folder you created, then exit the editor. Open a terminal or command prompt and navigate to the folder. Now run the following command:

You may need to replace python with python3 depending on your setup. The output will look something like this:

That’s it! You just wrote your first Python program. Can you explain what each line of code in the program does?

If you’ve read through this tutorial up to this point, then you might want to answer some Python-related questions and test what you’ve learned. Go ahead and test your knowledge:

Now open your text editor and create a new file called exercise.py . Copy and paste the following code into it:

Following the instructions, update the code. When you’re done, run the code from your terminal to test using the python exercise.py command. Good luck!

Now that you know the basics of Python programming, be sure to check out the wide range of Python tutorials, video courses, and resources here at Real Python to continue building your skills.

Learning how to use Python and get your programming skills to the next level is a worthwhile endeavor. Python is a popular, productive, and powerful high-level programming language that is in high demand. In this tutorial, you learned essential concepts about Python and started to apply them to your Python code.

In this tutorial, you learned:

You also created your first Python program and ran it on your computer. With all this knowledge, you can dive deeper into Python and learn a lot more of the language.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Tutorial Categories: basics python

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

Get the Python Cheat Sheet (Free PDF)

🔒 No spam. We take your privacy seriously.

writing program in python

writing program in python

The biomedical informatics hub's Introduction to Python workshop pages

© 2019. All rights reserved.

python-intro

Writing your first script, organization of scripts.

Before we write anything, let’s create a folder to hold your Python scripts.

Usually you would choose a hierarchy that’s sensible for you (for example I use Documents/programming/python in my home directory as the root for all of my Python projects!).

For the purposes of this workshop, let’s use your Desktop folder in your U drive and create a folder called

*nix users Similar to above, but place the python_workshop folder in your home folder (e.g. /home/ubuntu for openstack users). NB It’s a slightly confusing convention, but a user’s home folder is the path /home/username , not simply /home .

What is a Python Script?

A Python script is just a plain text file, and the convention is to use the extension .py (instead of e.g. .txt ) to let programs know that it holds Python code.

Python code is very close to something called pseudo-code, which is what people use when detailing the main components of an algorithm. For example, the pseudo-code for the factorial function (e.g. 3! = 3 x 2 x 1) is SET fact to n WHILE n is more than 1 SET fact to fact times (n - 1) SET n to n - 1 while the python code is fact = n while n > 1 : fact = fact * ( n - 1 ) n = n - 1 What this simple example illustrates, is that Python is extremely readable; it just takes becoming familiar with a few base syntax rules (~grammar). We’ll be speaking Python in no time!

Worked Exercise : Hello, world!

We’ll start by creating a blank Python script file.

Creating a file

We’re going to name our first script file exercise_hello_world.py and keep it inside the newly created python_workshop folder.

To do this, open Notepad++ . You should see a blank file (that may be named “new 1”, or “new 2” etc, depending on if you closed any tabs!).

Starting Notepad++

If you don’t see a blank file, select File->New from the menu bar.

Then select File->Save As , navigate to the python_workshop folder we created a few minutes ago, and set the file name to exercise_hello_world.py and click Save .

Now that we have a blank Python script file, lets start adding some code!

Initial content

First of all, enter:

replacing the text in the line starting # Author with your details.

Running the script with Python: The Terminal

Now let’s see what running this through Python does!

Start a customized command prompt ( reminder : in the Windows File Explorer, find the WinPython3 folder on the C: drive, and click on WinPython Command Prompt.exe ).

A terminal window should pop up, that looks a little bit like

Reminder: Basic terminal usage You were advised to have basic knowledge of using a terminal (Windows Command Prompt/Linux Terminal/MacOS Terminal), you are about to see out why! Here’s a recap of the things you’re most likely to need. Windows MacOS / Linux What it does `cd FOLDER_NAME` `cd FOLDER_NAME` Change directory to FOLDER_NAME `dir FOLDER_NAME` `ls FOLDER_NAME` List folder contents; if FOLDER_NAME is omitted, list current folder contents `..` `..` Reference to parent folder. E.g. `cd ..` is how you would navigate from `/a/b/c/` to `/a/b/` if you are currently in `/a/b/c/`. `mkdir FOLDER_NAME` `mkdir FOLDER_NAME` Create a folder called FOLDER_NAME
Quick note on terminology Folder and directory refer to the same thing, while full path or absolute path means the full directory location. E.g. if you’re currently in your Desktop folder, the folder is Desktop, but the full path is something like /users/joe/Desktop . If you’re on Windows the path starts with a drive letter too, like “C:” or “U:”, and the forward-slashes will be backslashes instead. Console and terminal (and sometimes shell ) are usually used interchangeably to mean the same thing; the text-based interface where commands can be entered. In windows, the built-in console is also called the “command prompt” and is started using cmd.exe . For our purposes, we’re going to be mainly interested in the terminal console which is where we type commands like cd , or dir . For interactive Python snippet testing we can also use the Interactive Python console, which is where we can directly type python commands. You might encounter this later; for now just be aware that there are these two types of console.

Now using the terminal command to change directory, cd , navigate to your Desktop directory.

You can verify that it contains your new python_workshop folder by using the windows terminal command dir :

should list

in the output.

Change directory into the python_workshop folder using

and verify that our new file is there using dir .

If you see your file ( exercise_hello_world.py ) listed, great! If not, check the previous steps carefully and/or ask a demonstrator for help.

Once the terminal is in the correct directory, we’re ready to run Python on our file.

As the terminal is preconfigured (meaning that it knows all about the Python program and where to find it) we can simply type python ... to run the Python interpreter, replacing “…” with input arguments.

In most simple use cases, we just use a single input argument; the script file name.

In advanced usage cases, we can also add in additional command line arguments to the script, but this will be covered in an advanced exercise in the follow-on workshop.

We can now type

to get Python to run our script file:

We should get no output - python has interpreted and run our script file, but as the script only contained comments , no terminal output was produced!

Comments Comments are used to make notes about things like what each few lines of code are doing. In our case, we also added an initial comment that keeps track of who wrote the script. Comments are created by using the hash symbol, # . A comment can take up a whole line as in our script above, or only part of a line; we’ll see an example of this later.

Adding functionality

Now that we have a script file that contains a couple of lines of comment, and successfully runs with Python (i.e. does nothing!), let’s add some functionality.

Switch back to the editor window (Notepad++) and add an empty line (for readability). Then, on the fourth line of the script add the text

replacing the placeholder YOURNAME with your actual name.

Answer: Hello world

Your code should look like:

which produces the output:

Switch to the terminal window, and repeat the python command

Tip On many terminals, you can press the Up arrow key to cycle through previous commands. This will save you from having to type the command each time!
Tip On several desktop environments (including Windows), you can cycle between open windows using “Alt + Tab” (or “Alt + Shift + Tab) to cycle in the other direction); this saves you from having to use the mouse between editing and running code.

Hurrah! We got Python to output text to the terminal. This may not seem like much of an achievement, but once you understand this line of code, you’re well on your way to being able to program in Python.

So let’s have a look.

Anatomy of our script

Lines 1 & 2.

As mentioned above, lines 1 and 2 are comments, which are non-executing lines of text that are used for us to be able to understand our code. They may seem pointless now, but if you give your script to a colleague who’s never touched a program before, if they read the first couple of lines they will immediately know who wrote the script, and why.

Comments become much more useful as scripts grow; “future you” may well benefit from well commented code as you look back over a script and try to remember what you were doing and why!

Our first line of Python code contains two of the major concepts of this course; a function call , and data type .

Calling a function

The function being called, or executed, is named print , and the data it is given as an argument is "Hello, world from Joe" . This data is of type string (more on ths in the next setion!).

What is a Function? A function is a self-contained piece of processing; often functions take inputs and provide return values (but they don’t have to). They provide a way to separate specific pieces of processing so that they can be reused over and over again. If you’re familiar with the concept of a function from mathematics, programming functions can be similar: for example the sin trigonometric function generates an output number (between -1 and 1) for any input angle. The print function does not generate any output values - it only causes its input to be “printed” to the terminal. For functions that do generate output values, these outputs are often captured by assigning them to variables - more on this later!

The syntax for calling a function is:

Outputting to the terminal using print

The print function is useful for providing output to the terminal - which is the most basic way of getting information out of a Python script.

The print function accepts a variety of input data types. For example we can write

i.e. a number.

You may also pass multiple, comma-separated arguments to the print function. E.g.

Now that we know how to write a script, and how to run it with Python, let’s examine in more detail what goes into the script, starting with data types.

VITAL note on whitespace in Python scripts

Guido (the creator of Python) decided that code-readability is crucial for good programming, and that unlike most other languages where badly laid out code is still valid, in Python code must be laid out in a specific way.

By layout, we are refering to the whitespace (spaces or tabs) preceding text in code, known as the indentation :

*We’ll cover in more detail what we mean by “logical blocks” later on, when we look at loops and conditional execution of code.

For example

is perfectly fine, while

would cause an indentation error.

While this feature of Python may seem petty or just irritating at first, many Python users grow to appreciate its significance in enforcing good coding practice.

previous episode

Programming with python, next episode, writing python scripts.

Overview Teaching: 20 min Exercises: 0 min Questions How can I write and save complete Python programs? Objectives Write Python commands in to a file Execute the file as a program

Up until now we have been using the IPython interpreter to get to grips with the basic use of Python. From now on, we will be focusing on saving our code in to scripts and running them from the shell by executing the python program with our script as an argument.

Switching to Shell Commands From this lesson onwards we will be switching from typing Python commands in the interpreter or a file to typing commands in a shell terminal window (such as bash). When you see a $ in front of a command that tells you to run that command in the shell rather than the Python interpreter.

Writing Your First Script

A script in python is almost exactly the same as a Shell script you’ve already met, i.e. it is a plain text file that contains lines of Python code that will be executed one after another.

To create and edit a Python script, it is almost essential to use a text editor with syntax highlighting. For this course, we recommend using VSCode as provided by Microsoft. It’s easily installed on Windows either directly or through Anaconda and macOS users can install and run it through Anaconda as well.

Choosing a Good Text Editor When we write Python scripts, it is essential that it is written in plain text - this means you can’t use a Word Processor program like MS Word as it will add quite a bit of other information to the created file that Python won’t understand. You also want to use an editor that knows about the programming language you’re using as then it can highlight different parts of the code, help with formatting and show any syntax errors. There are many options out there but possible ones are: Visual Studio Code Spyder Notepad++ PyCharm Emacs Vim

To write our first script then, start up your text editor, select ‘New File’ and create a new file called ~/Desktop/swc-python/hello.py . After this has been created and opened, type the following and save it:

As you can see, we have used the .py extension as this makes it easier to identify Python scripts from other file types.

From your shell prompt that you were running IPython in, make sure you are in the correct folder:

and then type:

Hopefully you should see what you would expect:

Congratulations! You’ve created your first Python script! Going forward in this course, we recommend writing the code in scripts and executing from the shell prompt just like this. You can continue to use the IPython interpreter if you’d prefer but as things increase in complexity, it will become harder to avoid typing errors, etc.

Documenting your Code

Now we are starting to store code, we must start documenting it as well. This is critical, not only for other users of your code but also yourself who may come back to some code at a later date and not easily remember what it did or how. This is where comments become essential — these are bits of human readable text, denoted by # , that Python will ignore but can be used to explain the meaning behind certain bits of code. Try changing the your hello.py file to the following:

If you run this, you will see the same as before but now you’ve added some information about what you were trying to achieve!

It’s not all About Comments You shouldn’t use comments as an excuse for poor variable names or code structure/formatting. Your code should be fairly readable without comments. They should help with clarifications and overall aims of a particular piece of code.
Key Points Python commands can be written and stored in a plain text file This file can then be run by using the python <scriptname> Python scripts generally use the .py extension You should try to use a syntax-highlighting text editor to edit your Python scripts Use comments to improve the readability of your code and aid understanding for both other people and yourself in the future

IMAGES

  1. Writing a Python Program

    writing program in python

  2. Ch 1

    writing program in python

  3. Helloworld to Python

    writing program in python

  4. Writing a Python Program Demo: Lesson 70

    writing program in python

  5. Python Write to File

    writing program in python

  6. Python Tutorial for beginners Session: #3 Writing Python First Program

    writing program in python

VIDEO

  1. How to write your First program in Python

  2. Python Tutorial 1

  3. Python Basics -- Part 2

  4. PYTHON PROGRAMMING : Introduction

  5. programming in python #pythonprogramming #python

  6. c++ Program to take input and Print sum of two numbers

COMMENTS

  1. How Do I Write a Dedication Ceremony Program?

    Writing a dedication ceremony program is easy if you’ve planned your event well. The form of your program book follows the outline of events you build as you develop the event.

  2. What Are Some Python Adaptations?

    Some python adaptations include a high metabolism, the enlargement of organs during feeding and heat sensitive organs. It’s these heat sensitive organs that allow pythons to identify possible prey.

  3. Can I Learn Python on My Own?

    Modern society is built on the use of computers, and programming languages are what make any computer tick. One such language is Python. It’s a high-level, open-source and general-purpose programming language that’s easy to learn, and it fe...

  4. Python Code Examples

    print("Hello, World!") You will see this message after running the program: "Hello, World!" Tip: Writing a

  5. Write a Simple Program in Python

    Open your Start menu and choose Python (command line). You should get a prompt that looks like >>>. · At the prompt, type the following. Use a

  6. How to Get Started With Python?

    Download Thonny IDE. · Run the installer to install Thonny on your computer. · Go to: File > New. Then save the file with .py extension. · Write Python code in the

  7. Writing a Python Program

    This 14-minute demo shows how to use two terminal windows to write and debug a simple Python2 program.If you're using Python3

  8. Ch 1

    When you write any program, you should always start with a comment that describes the program. This is important because later on, when you have

  9. How To Write Your First Python Application

    Open the terminal window and type in “python”. If you are getting a Python 3 prompt, you can stop here and proceed to the Create Our First .py

  10. Python For Beginners

    Are you completely new to programming? If not then we presume you will be looking for information about why and how to get started with Python.

  11. How to Use Python: Your First Steps

    You can find Python everywhere in the world of computer programming. For example, Python is the foundation of some of the world's most popular websites

  12. Writing your first Script · python-intro

    A Python script is just a plain text file, and the convention is to use the extension .py (instead of e.g. .txt ) to let programs know that it holds Python code

  13. Programming with Python: Writing Python Scripts

    A script in python is almost exactly the same as a Shell script you've already met, i.e. it is a plain text file that contains lines of Python code that will be

  14. Techniques to Write Better Python Code

    First is the use of the functional paradigm. While we know Python has constructs that allow us to write an algorithm in functional syntax, the