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.

  • Chat on IRC
  • Python >>>
  • About >>>
  • Getting Started

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!

  • PRO Courses Guides New Tech Help Pro Expert Videos About wikiHow Pro Upgrade Sign In
  • EXPLORE Tech Help Pro About Us Random Article Quizzes Request a New Article Community Dashboard This Or That Game Popular Categories Arts and Entertainment Artwork Books Movies Computers and Electronics Computers Phone Skills Technology Hacks Health Men's Health Mental Health Women's Health Relationships Dating Love Relationship Issues Hobbies and Crafts Crafts Drawing Games Education & Communication Communication Skills Personal Development Studying Personal Care and Style Fashion Hair Care Personal Hygiene Youth Personal Care School Stuff Dating All Categories Arts and Entertainment Finance and Business Home and Garden Relationship Quizzes Cars & Other Vehicles Food and Entertaining Personal Care and Style Sports and Fitness Computers and Electronics Health Pets and Animals Travel Education & Communication Hobbies and Crafts Philosophy and Religion Work World Family Life Holidays and Traditions Relationships Youth
  • Browse Articles
  • Learn Something New
  • Quizzes Hot
  • This Or That Game New
  • Train Your Brain
  • Explore More
  • Support wikiHow
  • About wikiHow
  • Log in / Sign up
  • Computers and Electronics
  • Programming

How to Write a Basic Python Program

Last Updated: January 17, 2024

Installing Dependencies

Downloading and installing python, writing the script, running the script, expert interview, things you'll need.

This article was co-authored by Kevin Burnett . Kevin Burnett is a Software Developer with over 20 years of professional experience. He spent the majority of his career at Rosetta Stone, a language-learning software company. He has experience with both front and back-end development and works primarily in Ruby, Python, and JavaScript. This article has been viewed 32,105 times.

Python is a high-level programming language. The language utilizes a straightforward syntax which can make it easy for new users to get started.

Step 1 Open the Terminal.

  • command -options filename.ext
  • The "sudo" command gives permission to the terminal to modify your computer. This is necessary to install any program. You will be required to enter your password.
  • The "apt-get install" command tells the computer to install the package "build-essential" which is required to install Python.
  • sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
  • These are programs that Python uses to run correctly. They are also known as “dependencies”.

Step 1 Download the latest version of Python from the Internet.

  • cd ~/Downloads/
  • The "cd" command changes to the correct working directory so the computer can find and put programs in the right place.
  • wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz

Step 2 Decompress the Python file using the following command:

  • tar -xvf Python-2.7.5.tgz
  • cd Python-2.7.5
  • Once again, we need to change the working directory. This time, we change to the newly created Python directory.

Step 3 Use the .

  • ./configure

Step 4 Use the make command.

  • sudo make install

Step 1 Open a text editor.

  • Any text editor that can save files with a ".py" extension will do. Ubuntu 12.04 or greater is packaged with the Gedit editor.

Step 2 Type print 'Hello, World!'In Python, whatever is enclosed in quotes after the word print will be printed out to the screen.

  • In Python, whatever is enclosed in quotes after the word print will be printed out to the screen.

Step 3 Save the file as

  • Be careful that the file is not saved as "hello_world.py.txt".

Step 1 Open the Terminal again.

  • Remember to use the "cd" command to change directories.
  • If you need a list of all subdirectories at your current location, use the "ls" command. "ls" stands for "list subdirectories".

Step 3 Run the script:

  • python hello_world.py

Community Q&A

Simeon Watson

  • Ubuntu 12.04 or greater
  • Your account password

write program python

Thanks for reading our article! If you’d like to learn more about programming languages, check out our in-depth interview with Kevin Burnett .

You Might Also Like

Update Pip

About This Article

Kevin Burnett

  • Send fan mail to authors

Is this article up to date?

Am I a Narcissist or an Empath Quiz

Featured Articles

Make Blueberry Pancakes

Trending Articles

How to Take the Perfect Thirst Trap

Watch Articles

Wrap a Round Gift

  • Terms of Use
  • Privacy Policy
  • Do Not Sell or Share My Info
  • Not Selling Info

wikiHow Tech Help:

Tech troubles got you down? We've got the tips you need

Python Land

Your First Python Program

If you followed the Python tutorial from the start, you’ve learned a lot by now. We’ve covered key topics, like booleans and conditional programming , strings , and functions . What we haven’t done yet, is create an actual program. So let’s wrap this up by combining what we learned into a nice little program. We will create your first Python program together.

Table of Contents

  • 1 Entering the code in the REPL
  • 2 Analyzing your first Python program
  • 3 Assignment: adapt your first Python program
  • 4 And now what?

Entering the code in the REPL

Let me share the program first. Please analyze it thoroughly before you continue reading. There’s one function you don’t know yet (input), but that I’ll explain shortly:

Now it’s time to try this program yourself. If you simply copy and paste the above code into the REPL, you’ll notice that it won’t work. What does work is:

  • First copy the function say_hi(name) and hit enter. Now the REPL knows this function.
  • After that, copy and paste the name = input("Your name: ") and hit enter again. It will ask for your name, so enter it.
  • Finally, you can copy and paste the say_hi(name) line and see what happens!

In the REPL, it should end up looking like the following:

If you still have problems, here’s a version in my online Python interpreter , that you can run right from this page. Note that input() doesn’t work in this system, so we just call say_hi() with a predefined string instead:

Analyzing your first Python program

Let’s go over the code step by step.

Asking for input with Python

I managed to cram in one more new thing, the built-in function  input() . It does exactly what you expect it to do: ask for input and assign that input to a variable. If you give input a string as an argument, it will print it as a prefix. In this case, it will print ‘Your name: ‘ and wait for you to enter your name.

The say_hi function with one argument

The say_hi(name) Python function that we defined, takes one argument, the name, and prints the name to the screen. The function does not return anything. It doesn’t need to, since it does all the printing work itself.

An if .. else block

Our function only greets us if the name is not an empty string. Why’s that?

When someone just hits enter when asked for input, the input() function returns an empty string. You can check for yourself in the REPL:

Just hit enter when asked for input, and you’ll see that the call to input() results in an empty string. So to not make a fool of ourselves, we won’t greet someone showing such rude behavior. We do this by checking if the input is equal to an empty string using an if-else block .

Finally, with Python’s for loop , we print each letter of the entered name on a new line, just because we can.

Assignment: adapt your first Python program

Since we defined a function, say_hi(name) , we can reuse this function. You can repeatedly ask for a name and repeatedly call say_hi. Here’s a little assignment:

And now what?

At this point, using the interactive Python shell starts to work against us. Chances are you’ve been fiddling a lot to get this first Python program working, mainly because of indentation issues. Luckily, we can also store our Python programs in files, as you’ll learn in the next section: creating Python programs . But before we do so, we’ll first dive into Python comments .

For now: congratulations. If you followed along, you should have a basic understanding of programming with Python. You created your first Python program! I recommend you to keep experimenting inside the REPL. You may need to re-read some or all of the sections. That’s OK and perfectly normal.

The most important piece of advice I’d like to give at this point is that you don’t learn programming by reading alone, just like you don’t become a doctor just by reading. You’ll have to get your hands dirty and practice.

If you feel ready, continue with the next chapter!

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Course for Beginners

Related articles

  • PyInstaller: Create An Executable From Python Code
  • How to Migrate To Python 3
  • Python Iterator: Example Code and How it Works
  • VSCode GUI tour: Explore The Elements of This Powerful IDE

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, learn python.

Python is a popular programming language.

Python can be used on a server to create web applications.

Learning by Examples

With our "Try it Yourself" editor, you can edit Python code and view the result.

Click on the "Try it Yourself" button to see how it works.

Python File Handling

In our File Handling section you will learn how to open, read, write, and delete files.

Python Database Handling

In our database section you will learn how to access and work with MySQL and MongoDB databases:

Python MySQL Tutorial

Python MongoDB Tutorial

Python Exercises

Test yourself with exercises.

Insert the missing part of the code below to output "Hello World".

Start the Exercise

Advertisement

Learn by examples! This tutorial supplements all explanations with clarifying examples.

See All Python Examples

Python Quiz

Test your Python skills with a quiz.

My Learning

Track your progress with the free "My Learning" program here at W3Schools.

Log in to your account, and start earning points!

This is an optional feature. You can study at W3Schools without using My Learning.

write program python

You will also find complete function and method references:

Reference Overview

Built-in Functions

String Methods

List/Array Methods

Dictionary Methods

Tuple Methods

Set Methods

File Methods

Python Keywords

Python Exceptions

Python Glossary

Random Module

Requests Module

Math Module

CMath Module

Download Python

Download Python from the official Python web site: https://python.org

Python Exam - Get Your Diploma!

Kickstart your career.

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

  • Python »
  • 3.12.2 Documentation »
  • The Python Tutorial »
  • 7. Input and Output
  • Theme Auto Light Dark |

7. Input and Output ¶

There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities.

7.1. Fancier Output Formatting ¶

So far we’ve encountered two ways of writing values: expression statements and the print() function. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout . See the Library Reference for more information on this.)

Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.

To use formatted string literals , begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.

The str.format() method of strings requires more manual effort. You’ll still use { and } to mark where a variable will be substituted and can provide detailed formatting directives, but you’ll also need to provide the information to be formatted.

Finally, you can do all the string handling yourself by using string slicing and concatenation operations to create any layout you can imagine. The string type has some methods that perform useful operations for padding strings to a given column width.

When you don’t need fancy output but just want a quick display of some variables for debugging purposes, you can convert any value to a string with the repr() or str() functions.

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr() . Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings, in particular, have two distinct representations.

Some examples:

The string module contains a Template class that offers yet another way to substitute values into strings, using placeholders like $x and replacing them with values from a dictionary, but offers much less control of the formatting.

7.1.1. Formatted String Literals ¶

Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression} .

An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal:

Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.

Other modifiers can be used to convert the value before it is formatted. '!a' applies ascii() , '!s' applies str() , and '!r' applies repr() :

The = specifier can be used to expand an expression to the text of the expression, an equal sign, then the representation of the evaluated expression:

See self-documenting expressions for more information on the = specifier. For a reference on these format specifications, see the reference guide for the Format Specification Mini-Language .

7.1.2. The String format() Method ¶

Basic usage of the str.format() method looks like this:

The brackets and characters within them (called format fields) are replaced with the objects passed into the str.format() method. A number in the brackets can be used to refer to the position of the object passed into the str.format() method.

If keyword arguments are used in the str.format() method, their values are referred to by using the name of the argument.

Positional and keyword arguments can be arbitrarily combined:

If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys.

This could also be done by passing the table dictionary as keyword arguments with the ** notation.

This is particularly useful in combination with the built-in function vars() , which returns a dictionary containing all local variables.

As an example, the following lines produce a tidily aligned set of columns giving integers and their squares and cubes:

For a complete overview of string formatting with str.format() , see Format String Syntax .

7.1.3. Manual String Formatting ¶

Here’s the same table of squares and cubes, formatted manually:

(Note that the one space between each column was added by the way print() works: it always adds spaces between its arguments.)

The str.rjust() method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods str.ljust() and str.center() . These methods do not write anything, they just return a new string. If the input string is too long, they don’t truncate it, but return it unchanged; this will mess up your column lay-out but that’s usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in x.ljust(n)[:n] .)

There is another method, str.zfill() , which pads a numeric string on the left with zeros. It understands about plus and minus signs:

7.1.4. Old string formatting ¶

The % operator (modulo) can also be used for string formatting. Given 'string' % values , instances of % in string are replaced with zero or more elements of values . This operation is commonly known as string interpolation. For example:

More information can be found in the printf-style String Formatting section.

7.2. Reading and Writing Files ¶

open() returns a file object , and is most commonly used with two positional arguments and one keyword argument: open(filename, mode, encoding=None)

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

Normally, files are opened in text mode , that means, you read and write strings from and to the file, which are encoded in a specific encoding . If encoding is not specified, the default is platform dependent (see open() ). Because UTF-8 is the modern de-facto standard, encoding="utf-8" is recommended unless you know that you need to use a different encoding. Appending a 'b' to the mode opens the file in binary mode . Binary mode data is read and written as bytes objects. You can not specify encoding when opening file in binary mode.

In text mode, the default when reading is to convert platform-specific line endings ( \n on Unix, \r\n on Windows) to just \n . When writing in text mode, the default is to convert occurrences of \n back to platform-specific line endings. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try - finally blocks:

If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it.

Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

After a file object is closed, either by a with statement or by calling f.close() , attempts to use the file object will automatically fail.

7.2.1. Methods of File Objects ¶

The rest of the examples in this section will assume that a file object called f has already been created.

To read a file’s contents, call f.read(size) , which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ( '' ).

f.readline() reads a single line from the file; a newline character ( \n ) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n' , a string containing only a single newline.

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:

If you want to read all the lines of a file in a list you can also use list(f) or f.readlines() .

f.write(string) writes the contents of string to the file, returning the number of characters written.

Other types of objects need to be converted – either to a string (in text mode) or a bytes object (in binary mode) – before writing them:

f.tell() returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode.

To change the file object’s position, use f.seek(offset, whence) . The position is computed from adding offset to a reference point; the reference point is selected by the whence argument. A whence value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. whence can be omitted and defaults to 0, using the beginning of the file as the reference point.

In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2) ) and the only valid offset values are those returned from the f.tell() , or zero. Any other offset value produces undefined behaviour.

File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects.

7.2.2. Saving structured data with json ¶

Strings can easily be written to and read from a file. Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int() , which takes a string like '123' and returns its numeric value 123. When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated.

Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation) . The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing . Reconstructing the data from the string representation is called deserializing . Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.

The JSON format is commonly used by modern applications to allow for data exchange. Many programmers are already familiar with it, which makes it a good choice for interoperability.

If you have an object x , you can view its JSON string representation with a simple line of code:

Another variant of the dumps() function, called dump() , simply serializes the object to a text file . So if f is a text file object opened for writing, we can do this:

To decode the object again, if f is a binary file or text file object which has been opened for reading:

JSON files must be encoded in UTF-8. Use encoding="utf-8" when opening JSON file as a text file for both of reading and writing.

This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. The reference for the json module contains an explanation of this.

pickle - the pickle module

Contrary to JSON , pickle is a protocol which allows the serialization of arbitrarily complex Python objects. As such, it is specific to Python and cannot be used to communicate with applications written in other languages. It is also insecure by default: deserializing pickle data coming from an untrusted source can execute arbitrary code, if the data was crafted by a skilled attacker.

Table of Contents

  • 7.1.1. Formatted String Literals
  • 7.1.2. The String format() Method
  • 7.1.3. Manual String Formatting
  • 7.1.4. Old string formatting
  • 7.2.1. Methods of File Objects
  • 7.2.2. Saving structured data with json

Previous topic

8. Errors and Exceptions

  • Report a Bug
  • Show Source

The Python Code Example Handbook – Simple Python Program Examples for Beginners

Python is a high-level, general purpose, interpreted programming language. It's well-known for being very easy to learn yet powerful, and it has many uses in many different fields.

If you're someone trying to get started with Python, it's easy to get lost among all the excellent learning resources on the internet.

Now this article isn't trying to be another head in that crowd. Rather, here I'll introduce you to Python basics and I'll point you in the right direction.

In this article, I'll introduce to the fundamentals of the Python programming language with the help of a ton of code examples. I'll explain them in great detail and include links for further study.

Once I've introduced you to the language at a basic level, I'll suggest you some excellent learning resources and explain how to make the best of them.

While I'll explain the code examples thoroughly, I'm assuming that you're familiar with common programming concepts such as expressions, statements, variables, functions, and so on. So I'll not spend time explaining these programming concepts in detail – rather I'll focus on Python's way of implementing/using them.

Without any further ado, let's jump in!

Table of Contents

High level overview of python, how to write hello, world in python, variables in python, data types in python.

  • How to Write Comments in Python

Strings in Python

Numbers in python, how to handle user input in python.

  • if-else-elif in Python

match-case in Python

Lists and tuples in python, loops in python, dictionaries in python, functions in python, additional python learning resources.

Before I jump into coding, you'll need to have Python installed and ready to go on your system. Depending on the system you're running – Windows, macOS or Linux – the installation process will differ.

If you're on Windows, my fellow freeCodeCamp author Md. Fahim Bin Amin has written an excellent guide on How to Install Python on Windows . Another author Dillion Megida has written another excellent article on How to Install Python 3 on Mac .

Some platforms, such as some of the modern Linux distributions, come with a fairly up-to-date version of Python pre-installed. So if you're on Linux, execute the following command to check your version of Python:

Having any version of Python 3 installed on your system will suffice. Apart from Python, you'll also need a code editor or IDE well suited for writing Python code.

In my Python IDE – Best IDEs and Editors for Python article I've listed three of the best code editors and IDEs that you may use for writing Python code.

So if you have Python and a code editor or IDE ready to go, let's move on to writing your first piece of Python code.

Somewhere in your computer, create a new file named program.py and put the following code in it:

To run this code, open your terminal inside the directory where you've put the program.py file and execute the following command:

The output of the code will be whatever you've passed as the parameter of the print() function, which in the case of this code snippet is:

As you may have already guessed, print() is a built-in Python function that prints whatever you give it on the console. The function can print strings, numbers, expressions – more or less anything that you can throw at it.

The first statement prints out the string Hello, World! just like before. The second one prints out a number and the third one prints out the result of the 5 + 5 expression:

One thing that you may or may not have noticed is that the three print statements have been outputted in three separate lines. Whereas in other languages such as C/C++/C#/Java you have to append a newline character explicitly.

As it turns out, print() functions as newline character by default and you can override this default behavior as follows:

Now the output of the program will be:

Which means any string you pass as the value of the end parameter will be used as the terminating character of the printed line.

Here, I've used | as the terminating character of the first two statements. However, I've used the default newline character as the terminating character of the last statement.

You can learn more about the print() function by playing around with it or by reading the official docs on the function.

To declare a variable in Python, you start by writing out the name of the variable, then an equals sign, followed by the value of the variable:

Output of this code will be:

As you can see, there is no special keyword for declaring a variable. Python is smart enough to get the type of the variable from the value you're assigning.

In the example above, the name variable contains the Farhan string. Since the word Farhan is within quotes, Python will treat this variable as a string.

In Python, you can concatenate two strings using the plus sign. That's what we've done in the print() statement above. But if you change the code as follows:

And try to run this program, you'll face the following problem:

As you can see, strings can be concatenated with strings only, and the age variable is an integer. There is a better way of embedding variables within string statements.

I hope you've noticed the f in the beginning of the strings inside the print() statements. This f turns the strings into f-strings. These strings are evaluated at runtime, so inside a f-string, you can put any valid Python statement within curly braces. This makes embedding variables or even simple logic within strings very easy.

You can re-declare your variables anywhere within the program. You can even change their types if you wish to.

This is a completely valid program and the value of a will be printed as 10 since you've overridden the initial value on the second line.

In Python, there four main literal types that you need to be aware of:

Integers and floating points are self-explanatory. A boolean can be either true or false , and strings in Python can be enclosed within either single quotes or double quotes. I prefer using single quotes. You may use the one you like but try not to mix both types of quotes together.

Comments in Python

Comments in Python start with a hash symbol:

Comments written using a hash can only be single line. If you want to write multi-line comment in Python, you'll have to use quotes as follows:

Commenting your code as needed is a good way of documenting it. But make sure you're not adding comments where the code can be easily understood by just looking at it.

Strings in Python are ordered collections of Unicode characters. Strings can not be modified at runtime. You've already seen how to declare a string. In this section you'll learn about common string operations.

In a string, each character will have an index. And like arrays, string indexes are zero-based.

These characters can be accessed using these indexes as follows:

The output of this program will be as follows:

Another fun thing that you can do using these indexes is slicing. Assume that you want to take out a part from a string.

The output of this program will be:

In this example, name[0:3] means print starting from index 0 to index 3 . Now you may think that h is at index 3 and you'll be right about that. But the thing about slicing is, it doesn't include the character at the ending index.

If you'd like to learn more about slicing, there is an article titled How to Substring a String in Python that you may find useful.

You can use the len() function to figure out the length of a string as follows:

Output from this program will be 6 since there are six characters in the string.

Python has a ton of string methods, but demonstrating each of them isn't possible here so I'll demonstrate some of the most common ones.

The first method is capitalize() . This method returns a copy of the given string with its first character capitalized and the rest lowercased.

Output of this code will be Python is awesome . If you want to convert the entire sentence to uppercase, there is the upper() method:

Output of this code will be PYTHON IS AWESOME . You can do the opposite using the lower() method:

The output of this code will be python is awesome . There are the isupper() and islower() methods to check whether a string is in uppercase or lowercase.

Output of this code will be as follows:

If you want to replace all occurrences of a substring within a string, you can do so by using the replace() method:

This code will replace all occurrences of python with freeCodeCamp  in the given string.

Finally, there are the split() and join() methods. The first one splits a string into a list:

The method takes a delimiter to split the string on. Here, I've used space as the delimiter. Output of this code will be ['python', 'is', 'awesome'] . This is a list. We haven't covered lists yet but we will soon. For now, understand that they're like arrays.

You can produce a new string using the elements of an iterable, that is a list, using the join() method:

I've called the join() method on a space so the result of this code will be a string joined using spaces in between as follows:

If you want to learn more about all the string methods in Python, feel free to consult the official documentation .

Numbers in Python can be of integer, floating point, and complex types. In this article, I'll only discuss operations related to the real numbers – that is, integers and floating points.

You can perform addition, subtraction, multiplication, and division operations using integers and floating point numbers like in any other programming language:

Output from this snippet of code will be as follows:

One thing to keep in mind is that even if you perform a division operation between two integers, the result will always be a floating point. If you want the result to be an integer, you can do so as follows:

This time the result will be an integer. Be careful that if there are any numbers after the decimal point, they'll be chopped off.

If you'd like to learn more about the numeric types in Python, feel free to consult the official documentation .

For taking input from the user, there is the input() function.

The output from this program will be as follows:

The input() function saves the user input as a string even if the user inputs a number. So if you're taking a number as input from the user, be sure to convert it to the appropriate data type.

if-elif-else in Python

Like any other programming language, Python has the usual if-elif-else statements.

This is a very simple calculator program. Depending on the operation you choose, the calculator will perform one of the mentioned operations.

In Python, code blocks such as the if block or the elif block or the else block start with the keyword and a colon.

Indentation is crucial in Python and if you indent code within a code block inappropriately, the code will fail to run.

In Python, a match-case is equivalent to a switch-case statement in other programming languages. The aforementioned calculator program can be rewritten using match-case as follows:

Again, depending on the value of op , one of the cases will be performed. If the input from the user doesn't match any of the cases, then the wildcard _ action will take place.

Keep in mind that match-case is available only on Python 3.10 and later versions. So if you're using an older version, you may not have this statement.

Lists in Python are a sequence of values. You can modify lists at runtime. You can create a list as follows:

Output of this program will be ['a', 'e', 'i', 'o', 'u'] . Like strings, each element in a Python list has an index and these indexes start from zero.

Like strings you can perform slicing on lists as well and the syntax for slicing a list is the same as a string.

Lists in Python have a bunch of useful methods. To add new items to a list there are the append() , extend() , and insert() methods.

The append() method appends a new item to the list and the extend() method adds multiple items:

The insert() method, on the other hand, inserts an item at a given index in the list:

The pop() method pops the last element off the list:

Output from this snippet of code will be:

The remove() method can remove a given element from the list:

This will delete the e from the list of vowels.

Finally there is the clear() method that removes all the elements from the list.

There is also the sort() method:

The sort() method sorts the list in ascending order. This method sorts the list in place. This means it doesn't return a new list, and instead sorts the original list.

If you want to reverse the list instead, there is the reverse() method:

It's also an in place method like sort. It's just the reverse (no pun intended) of the sort method. You can learn more about lists from the official documentation .

There is also an immutable sequence type called a tuple in Python. Tuples are pretty similar to lists but you can not modify a tuple.

The output of this code will be ('a', 'e', 'i', 'o', 'u') . There are not many methods for the tuples. If you want to learn more about tuples, consult the official documentation .

You can use loops in Python to iterate over a sequence type like a list.

There is also while loop but since the for loop is what you'll be mostly using, I won't spend time explaining while loops.

Let's assume I've given you the line "the quick brown fox jumped over the lazy dog" and tell you to count the the number of occurrences for each letter. You can do this easily using a hashmap.

A hashmap is a collection of key-value pairs.

To do the task I gave you earlier, you can write the following code:

Output for this code will be as follows:

This is a dictionary. Each letter is a key and their occurrence number is the value. On the code snippet, you declare a dictionary in the second line. Estefania Cassingena Navone has written an article called Python Dictionaries 101: A Detailed Visual Introduction which you may consult to learn more about dictionaries.

The final concept that I'll discuss is functions. Functions in programming are chunks of code that perform a certain task.

In Python, you can declare a function using the def keyword followed by the function signature:

This is the same calculator program as before, but now the operations are written within separate functions.

To learn more about functions, you can read this article: Functions in Python – Explained with Code Examples by Bala Priya C .

There are a lot of other concepts that you need to learn if you want to be a great Python programmer. That's what the next section is about.

Now that you have a basic understanding of the Python programming language, I'll suggest some high quality learning resources to continue your learning journey.

Learn Python in 4 Hours

The first resource on the list is a video on the freeCodeCamp YouTube channel created by Girrafe Academy.

The instructor has created multiple courses on the channel and is known for making concise videos.

The video covers most of the important Python concepts within 4 hours. The instructor also makes simple projects along the way.

Python for Everybody

Another beginner friendly Python course in the freeCodeCamp YouTube channel is Python for Everybody. What makes this course special is that it not only targeted at Python beginners but at people who're trying to get started with programming in general.

The course is a little over 13 hours long and is taught by Charles R. Severance aka Dr. Chuck. He has authored some of the most amazing courses on the internet.

If you're patient enough to sit through a 13 hour course, Python for Everybody is one of the best Python courses online.

12 Beginner Python Projects

If you prefer a project-based approach, then this 3 hours course by Kylie Ying is highly recommended.

Kylie is a freeCodeCamp team member and knows what she's doing. In this course you'll learn to make 12 beginner friendly Python projects in increasing levels of complexity.

Learn Python by Building 5 Games

If you're into gaming and want to learn Python through building classic games, then this course should be a good fit for you.

The instructor for this course is Christian Thompson, an experienced Python programmer. If you're familiar with another programming language or you learn well by jumping into projects, dive right in.

Intermediate Python

If you've finished your first Python course and have learned all the fundamental concepts and now you're looking for the next logical step, then look no further.

Patrick Loeber has produced this 6 hour course on intermediate Python where you'll learn about a good number concepts usually not found in beginner Python courses.

Object Oriented Programming with Python

If you're struggling to understand of object oriented programming in general, this course will teach you object oriented programming with Python in 2 hours.

The course includes tons of code examples and covers all the important concepts regarding object oriented programming with Python. I'd suggest this course right after you've finished your basic course.

Python for Data Science

This is a bit of a specialized course. If you're thinking of getting into data science and want to learn about all the necessary Python stuff necessary for data science then this course will help you greatly.

Don't think that this is a quick course. In its just over 12 hour runtime, this course will teach you Python programming concepts and a bunch of tools essential for data science in great detail.

Data Structures and Algorithms in Python

Having an understanding of data structures and algorithms is essential to becoming an efficient software developer.

In this 12.5 hour course from Jovian, you'll learn about important data structures and algorithms with code examples in great detail. Regardless of what you plan to do with Python afterwards, I'd highly recommend this course.

I would like to thank you from the bottom of my heart for the time you've spent reading this article.

Although I've listed as many as good resources I could, the freeCodeCamp YouTube channel is just filled with excellent Python learning resources.

I also have a personal blog where I write about random tech stuff, so if you're interested in something like that, checkout https://farhan.dev . If you have any questions or are confused about anything – or just want to get in touch – I'm available on Twitter and LinkedIn .

Software developer with a knack for learning new things and writing about them

If you read this far, thank the author to show them you care. Say Thanks

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

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling

Python Programs

  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python

Related Articles

Basic Programs

  • How to Add Two Numbers in Python - Easy Programs
  • Find Maximum of two numbers in Python
  • Python Program to Find the Factorial of a Number
  • Python Program for Simple Interest
  • Python Program for Compound Interest
  • Python Program to Check Armstrong Number

Array Programs

  • Python Program to Find Sum of Array
  • Python Program to Find Largest Element in an Array
  • Python Program for Array Rotation
  • Python Program for Reversal algorithm for array rotation
  • Python Program to Split the array and add the first part to the end
  • Python Program for Find remainder of array multiplication divided by n
  • Python Program to check if given array is Monotonic

List Programs

  • Python program to interchange first and last elements in a list
  • Python Program to Swap Two Elements in a List
  • How To Find the Length of a List in Python
  • Check if element exists in list in Python
  • Different ways to clear a list in Python
  • Reversing a List in Python

Matrix Programs

  • Adding and Subtracting Matrices in Python
  • Python Program to Add Two Matrices
  • Python program to multiply two matrices
  • Python | Matrix Product
  • Transpose a matrix in Single line in Python
  • Python | Matrix creation of n*n
  • Python | Get Kth Column of Matrix
  • Python - Vertical Concatenation in Matrix

String Programs

  • Python Program to Check if a String is Palindrome or Not
  • Python program to check whether the string is Symmetrical or Palindrome
  • Reverse Words in a Given String in Python
  • How to Remove Letters From a String in Python
  • Check if String Contains Substring in Python
  • Python - Words Frequency in String Shorthands

Dictionary Programs

  • Python | Ways to remove a key from dictionary
  • Python | Merging two Dictionaries
  • Python - Convert key-values list to flat dictionary
  • Python - Insertion at the beginning in OrderedDict
  • Python | Check order of character in string using OrderedDict( )
  • Python dictionary with keys having multiple inputs

Tuple Programs

  • Find the size of a Tuple in Python
  • Python - Maximum and Minimum K elements in Tuple
  • Python program to create a list of tuples from given list having number and its cube in each tuple
  • Python - Adding Tuple to List and vice - versa
  • Python - Closest Pair to Kth index element in Tuple
  • Python - Join Tuples if similar initial element

Searching and Sorting Programs

  • Python Program for Linear Search
  • Python Program for Bubble Sort
  • Python Program for Selection Sort
  • Python Program for Insertion Sort
  • Python Program for Recursive Insertion Sort
  • Python Program for Binary Search (Recursive and Iterative)

Pattern Printing Programs

  • Program to print the pattern 'G'
  • Python | Print an Inverted Star Pattern
  • Python 3 | Program to print double sided stair-case pattern
  • Print with your own font using Python !!

Date-Time Programs

  • Python program to get Current Time
  • How to Get Current Date and Time using Python
  • Python | Find yesterday's, today's and tomorrow's date
  • Python program to convert time from 12 hour to 24 hour format
  • Python program to find difference between current time and given time
  • Python Program to Create a Lap Timer
  • Convert date string to timestamp in Python
  • How to convert timestamp string to datetime object in Python?
  • Find number of times every day occurs in a Year

Python Regex Programs

  • Python - Check if String Contain Only Defined Characters using Regex
  • Python program to Count Uppercase, Lowercase, special character and numeric values using Regex
  • The most occurring number in a string using Regex in python
  • Python Regex to extract maximum numeric value from a string
  • Regex in Python to put spaces between words starting with capital letters
  • Python - Check whether a string starts and ends with the same character or not (using Regular Expression)

Python File Handling Programs

  • Python program to read file word by word
  • Python program to read character by character from a file
  • Count number of lines in a text file in Python
  • How to remove lines starting with any prefix using Python?
  • Eliminating repeated lines from a file using Python
  • Read List of Dictionaries from File in Python

More Python Programs

  • Python Program to Reverse a linked list
  • Python Program for Find largest prime factor of a number
  • Python Program for Find sum of odd factors of a number
  • Python Program for Coin Change
  • Python Program for Tower of Hanoi
  • Python Program for Sieve of Eratosthenes

Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python code examples cover a wide range of basic concepts in the Python language, including List , Strings , Dictionary , Tuple , sets, and many more. Each program example contains multiple approaches to solve the problem.

So, without wasting your time start exploring the Python programs and scale up your logical abilities in Python program.

Topics : Basic Programs Array Programs List Programs Matrix Programs String Programs Dictionary Programs Tuple Programs Searching and Sorting Programs Pattern Printing Date-Time Programs Regex Programs File Handling Programs More Python Programs     Basic Programs:

In this section, you will find all the basic Python programming examples. So, explore the section and complete the basic stage of Python programming.

  • Python program to add two numbers
  • Maximum of two numbers in Python
  • Python Program for factorial of a number
  • Python Program for simple interest
  • Python Program for compound interest
  • Python Program to check Armstrong Number
  • Python Program for Program to find area of a circle
  • Python program to print all Prime numbers in an Interval
  • Python program to check whether a number is Prime or not
  • Python Program for n-th Fibonacci number
  • Python Program for How to check if a given number is Fibonacci number?
  • Python Program for n\’th multiple of a number in Fibonacci Series
  • Program to print ASCII Value of a character
  • Python Program for Sum of squares of first n natural numbers
  • Python Program for cube sum of first n natural numbers

Array Programs:

To scale up Array logic, try out the below-listed Python array programming examples. Here, you will find all the important Python examples that are related to the Python array concept.

  • Python Program to find sum of array
  • Python Program to find largest element in an array
  • Python Program for array rotation
  • Python Program for Find reminder of array multiplication divided by n

List Programs:

Explore the below section and try out all the important Python List programming examples.

  • Python program to swap two elements in a list
  • Python | Ways to find length of list
  • Python | Ways to check if element exists in list
  • Python | Reversing a List
  • Python program to find sum of elements in list
  • Python | Multiply all numbers in the list
  • Python program to find smallest number in a list
  • Python program to find largest number in a list
  • Python program to find second largest number in a list
  • Python program to find N largest elements from a list
  • Python program to print even numbers in a list
  • Python program to print odd numbers in a List
  • Python program to print all even numbers in a range
  • Python program to print all odd numbers in a range
  • Python program to print positive numbers in a list
  • Python program to print negative numbers in a list
  • Python program to print all positive numbers in a range
  • Python program to print all negative numbers in a range
  • Remove multiple elements from a list in Python
  • Python – Remove empty List from List
  • Python | Cloning or Copying a list
  • Python | Count occurrences of an element in a list
  • Python | Remove empty tuples from a list
  • Python | Program to print duplicates from a list of integers
  • Python program to find Cumulative sum of a list
  • Break a list into chunks of size N in Python
  • Python | Sort the values of first list using second list

Matrix Programs:

Get a detailed list of Python Matrix examples and boost your understanding of matrix concepts in Python.

  • Python program to add two Matrices
  • Python program for Matrix Product
  • Python – Vertical Concatenation in Matrix

String Programs:

If you are looking for Python programming examples that are based on the Python string concept, then scroll down to the below section and practice a wide range of Python string program examples.

  • Python program to check if a string is palindrome or not
  • Reverse words in a given String in Python
  • Ways to remove i’th character from string in Python
  • Python | Check if a Substring is Present in a Given String
  • Python – Words Frequency in String Shorthands
  • Python – Convert Snake case to Pascal case
  • Find length of a string in python (4 ways)
  • Python program to print even length words in a string
  • Python program to accept the strings which contains all vowels
  • Python | Count the Number of matching characters in a pair of string
  • Remove all duplicates from a given string in Python
  • Python – Least Frequent Character in String
  • Python | Program to check if a string contains any special character
  • Generating random strings until a given string is generated
  • Find words which are greater than given length k
  • Python program for removing i-th character from a string
  • Python program to split and join a string
  • Python | Check if a given string is binary string or not
  • Python program to find uncommon words from two Strings
  • Python – Replace multiple words with K
  • Python | Permutation of a given string using inbuilt function
  • Python | Check for URL in a String
  • Execute a String of Code in Python
  • String slicing in Python to rotate a string
  • String slicing in Python to check if a string can become empty by recursive deletion
  • Python Counter| Find all duplicate characters in string
  • Python – Replace all occurrences of a substring in a string

Dictionary Programs:

In this section, you will find out all the important practice sets or examples related to the Python Dictionary concept.

  • Python – Extract Unique values dictionary values
  • Python program to find the sum of all items in a dictionary
  • Ways to sort list of dictionaries by values in Python – Using itemgetter
  • Ways to sort list of dictionaries by values in Python – Using lambda function
  • Python – Convert key-values list to flat dictionary
  • Python – Insertion at the beginning in OrderedDict
  • Dictionary and counter in Python to find winner of election
  • Python – Append Dictionary Keys and Values ( In order ) in dictionary
  • Python | Sort Python Dictionaries by Key or Value
  • Python – Sort Dictionary key and values List
  • Handling missing keys in Python dictionaries
  • Print anagrams together in Python using List and Dictionary
  • K’th Non-repeating Character in Python using List Comprehension and OrderedDict
  • Check if binary representations of two numbers are anagram
  • Python Counter to find the size of largest subset of anagram words
  • Python | Remove all duplicates words from a given sentence
  • Python Dictionary to find mirror characters in a string
  • Counting the frequencies in a list using dictionary in Python
  • Python | Convert a list of Tuples into Dictionary
  • Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
  • Python dictionary, set and counter to check if frequencies can become same
  • Scraping And Finding Ordered Words In A Dictionary using Python
  • Possible Words using given characters in Python

Tuple Programs:

Explore the wide range of Tuple programs here in this section of Python programming examples.

  • Python program to Find the size of a Tuple
  • Python – Maximum and Minimum K elements in Tuple
  • Create a list of tuples from given list having number and its cube in each tuple
  • Python – Closest Pair to Kth index element in Tuple
  • Python – Join Tuples if similar initial element
  • Python – Extract digits from Tuple list
  • Sort a list of tuples by second Item
  • Python – Flatten tuple of List to tuple
  • Python – Convert Nested Tuple to Custom Key Dictionary

Searching and Sorting Programs:

In this section, on searching and sorting examples, we have mentioned all the important example sets of Python searching and sorting to boost your Python programming concept.

  • Python Program for QuickSort
  • Python Program for Iterative Quick Sort
  • Python Program for Merge Sort
  • Python Program for Iterative Merge Sort
  • Python Program for Heap Sort
  • Python Program for Counting Sort
  • Python Program for ShellSort
  • Python Program for Topological Sorting
  • Python Program for Radix Sort
  • Python Program for Binary Insertion Sort
  • Python Program for Bitonic Sort
  • Python Program for Comb Sort
  • Python Program for Pigeonhole Sort
  • Python Program for Cocktail Sort
  • Python Program for Gnome Sort
  • Python Program for Odd-Even Sort / Brick Sort
  • Python Program for BogoSort or Permutation Sort
  • Python Program for Cycle Sort
  • Python Program for Stooge Sort

Pattern Printing Programs:

Get a complete list of Python pattern printing examples in the below section.

  • Python Program to print the pattern ‘G’
  • Python Program to print an Inverted Star Pattern
  • Python Program to print double sided stair-case pattern
  • Python Program to print with your own font

Date-Time Programs:

In this section, we have mentioned all important Python program examples that are related to the Python Date-Time concept.

  • Get Current Date and Time using Python

Python Regex Programs:

To boost Python Regex concept get a list of Python Regex programming examples below.

  • Python Program to Check if String Contain Only Defined Characters using Regex
  • Python Program to find the most occurring number in a string using Regex
  • Python Program to put spaces between words starting with capital letters using Regex
  • Python – Check whether a string starts and ends with the same character or not
  • Python regex to find sequences of one upper case letter followed by lower case letters
  • Python Program to Remove duplicate words from Sentence
  • Python | Remove all characters except letters and numbers
  • Python Regex | Program to accept string ending with alphanumeric character
  • Python Regex – Program to accept string starting with vowel
  • Python Program to check if a string starts with a substring using regex
  • Python Program to Check if an URL is valid or not using Regular Expression
  • Parsing and Processing URL using Python – Regex
  • Python Program to validate an IP address using ReGex
  • Python Program to Check if email address valid or not
  • Python program to find files having a particular extension using RegEx
  • Python program to extract IP address from file
  • Python program to check the validity of a Password
  • Categorize Password as Strong or Weak using Regex in Python

Python File Handling Programs:

If you want to scale up your Python file handling concept, explore the below section and find out all the real-life Python programming examples on Python file handling.

  • Python – Get number of characters, words, spaces and lines in a file
  • Python program to Count the Number of occurrences of a key-value pair in a text file
  • Python | Finding ‘n’ Character Words in a Text File
  • Python Program to obtain the line number in which given word is present
  • Python Program to remove lines starting with any prefix
  • Python Program to Eliminate repeated lines from a file
  • Python Program to read List of Dictionaries from File
  • Python – Append content of one text file to another
  • Python program to copy odd lines of one file to other
  • Python Program to merge two files into a third file
  • Python program to Reverse a single line of a text file
  • Python program to reverse the content of a file and store it in another file
  • Python Program to Reverse the Content of a File using Stack

More Python Programs:

Find a more important list of Python programming examples below and upscale your Python programming skills.

  • Python Program for Efficient program to print all prime factors of a given number
  • Python Program for Product of unique prime factors of a number
  • Python Program to Check if binary representation is palindrome
  • Python Program for Basic Euclidean algorithms
  • Python Program for Extended Euclidean algorithms
  • Python Program for Maximum height when coins are arranged in a triangle
  • Python Program for Find minimum sum of factors of number
  • Python Program for Difference between sums of odd and even digits
  • Python Program for Program to Print Matrix in Z form
  • Python Program for Smallest K digit number divisible by X
  • Python Program for Print Number series without using any loop
  • Python Program for Number of stopping station problem
  • Check if a triangle of positive area is possible with the given angles
  • Python program to find the most occurring character and its count
  • Python Program for Find sum of even factors of a number
  • Python Program for Check if all digits of a number divide it
  • Check whether a number has consecutive 0’s in the given base or not
  • Python Program for Number of solutions to Modular Equations
  • Python Program for Legendre\’s Conjecture

Please Login to comment...

  • 10 Best Notion Integrations to Connect Your Apps
  • 10 ChatGPT Prompts for Financial Analysts to Streamline Analysis
  • 10 Best AI Tools for Solving Math Problems Effortlessly [Free + Paid]
  • Elicit vs. Scholarcy: Which AI Extracts Better Research Insights?
  • Dev Scripter 2024 - Biggest Technical Writing Event By GeeksforGeeks

Improve your Coding Skills with Practice

 alt=

Online Python Compiler

Online Python Compiler

About online python compiler.

Try our Online Python Compiler (Version Python v3.6.2) to Edit, Run, and Share your Python Code directly from your browser. This online development environment provides you the latest version Python v3.6.2.

How to use Online Python Compiler?

Write and execute code.

  • Write your program (or, paste it) directly under the "Source Code" tab.
  • If you want to save your program, go to the "Project" menu and save it.
  • You can directly execute your program without saving it by clicking on on "Execute" button.

The latest version of Coding Ground allows to provide program input at run time from the termnial window exactly the same way as you run your program at your own computer. So simply run a program and provide your program input (if any) from the terminal window available in the right side.

Online Python Compiler: Keyboard Shortcuts

The following are the keyword shortcut of this Online Python Compiler:

Online Python Compiler: Save and Share Python Code (Project)

Save python project online.

You can save your Python Project with us so that you can access this project later on. To save a project you will need to create a login Id with us. So before you save a project, please create a login Id using a link given at the top right corner of this page.

Share Python Project Online

You can use this feature to share your Python Code with your teachers, classmates and colleagues. Just click Share Button and it will create a short link, which can be shared through Email, WhatsApp or even through Social Media. A shared link will be deleted if it has been passive for almost 3 months.

More Features of Online Python Compiler

  • Theme – You can change the current editor's theme from the "Editor Theme" option under "Settings" menu.
  • Font Size – You can change the font size of the editor /compiler from from the "Font Size" option under "Settings" menu.
  • Tab Size – You can change the tab size from the "Tab Size" option under "Settings" Menu.
  • Show/Hide Line Numbers – You can show/hide the line number with the code from the "Show Line Numbers" or "Hide Line Numbers" option under "Settings" Menu.
  • And, many more.

Benefits of Using Online Python Compiler

There are several benefits of using the Online Python Compiler to run your Python code:

  • Platform independence: You can run your code from any device without taking care of operating systems.
  • Convenience: You don't need to install anything for using this.
  • No setup required: There is no need for additional setup to run your code.
  • Updated version: Our online compiler/editors/terminals are the latest up-to-date.

TutorialsTonight Logo

Pattern Program in Python

In this article, you will look at 30 different pattern program in Python .

Star Pattern In Python

Star pattern is a common pattern program created in any programming language. It is a pattern that consists of a series of stars that create some sort of shape.

In the image below you can see some of the star patterns.

star pattern example

There are also other types of patterns that do not use stars but numbers or alphabets. We will also look at these in brief here.

Let's start with different pattern programs using python.

pattern program in python

List of Pattern Program In Python

We are going to see the following pattern program in python here in this article.

  • Square Pattern in Python
  • Hollow Square Pattern in Python
  • Left triangle star Pattern in Python
  • Right triangle star Pattern in Python
  • Left downward triangle pattern
  • Right downward triangle pattern
  • Hollow triangle star Pattern
  • Pyramid Pattern in Python
  • Hollow Pyramid Pattern in Python
  • Reverse pyramid Pattern in Python
  • Diamond star pattern in Python
  • Hollow diamond star pattern in Python
  • Hourglass star pattern in python
  • Right Pascal star Pattern in Python
  • Left Pascal star Pattern in python
  • Heart Pattern in Python
  • Plus star pattern
  • Cross star pattern
  • Left triangle number pattern
  • Right triangle number pattern
  • Number pyramid pattern
  • Number pyramid reverse pattern
  • Hollow number pyramid pattern
  • Number diamond pattern
  • Hollow number diamond pattern
  • Alphabet pyramid pattern
  • Reverse alphabet pyramid pattern
  • Hollow alphabet pyramid pattern
  • Alphabet diamond pattern
  • Hollow alphabet diamond pattern

1. Square Pattern in Python

The square pattern is the easiest pattern program. It is a pattern that has the shape of a square made of stars.

Let's see how to create and print a square pattern.

  • Take size of the square as input from the user or just set a value.
  • Run a nested loop for the number of rows and columns.
  • Print the star in each iteration and print a new line after each row.

2. Hollow Square Pattern

The hollow square pattern is a bit more difficult pattern program than a simple square because here you will have to deal with spaces within the square.

Here are the steps to create a hollow square pattern.

  • To create hollow pattern again run a nested for loop.
  • External loop will be same as the previous square pattern but inside internal loop you will have to check the condition.
  • If its the first or last row or column then print only stars.
  • Otherwise check if its the first or last column then print star else print spaces.

3. Left Triangle Star Pattern In Python

The left triangle star pattern is a star pattern in the shape of a triangle. It is quite easy to create it.

Steps to create a left triangle star pattern:

  • Run a nested for loop where internal loop will run for number of times external loop has run.
  • Print star in each iteration of internal loop.
  • Print a new line at the end of internal loop.

4. Right Triangle Star Pattern In Python

The right triangle star pattern is a star pattern in the shape of a triangle as shown above. It is similar to the left triangle star pattern but you will have to deal with spaces.

Steps to create a right triangle star pattern:

  • Create a loop that will run for the number of rows (size).
  • Inside this we will have 2 loops, first will print spaces and second will print stars. (look at pattern above)
  • Spaces will be printed for size - i times and stars will be printed for i times. Where i is the current row.
  • Print new line at the end of both internal loops.

5. Left Downward Triangle Pattern

The left downward triangle pattern is the star pattern of a triangle upside down. It is very easy to create.

Run 2 nested loops where the internal loop will run size - i times and external loop will run size times. Here i is the current row.

6. Right Downward Triangle Pattern

The right downward triangle pattern is a pattern that is upside down and has perpendicular to the right side.

Steps to create a right downward triangle pattern:

  • From the above given pattern you can see that, this also requires 2 internal loop.
  • First internal loop print spaces for i times and second internal loop print stars for size - i times.
  • Here i is index of the current row.
  • Print new line everytime after the internal loop.

7. Hollow triangle star Pattern

The hollow triangle star pattern is a star pattern in the shape of the triangle made of stars but hollow.

Follow these steps:

  • You can see the pattern up there be sure to understand it. Stars are printed only in first last column of any row, except the last row.
  • Run a nested loop where external loop runs for the size of triangle.
  • Inside create internal loop. Inside it check if its first or last row then print only stars. If not print starts only at first and last column else print spaces.

8. Pyramid Pattern in python

The pyramid pattern is a very famous pattern in programming. It has the shape of an equilateral triangle and it is used to represent a pyramid. You can see the pattern up here.

The pyramid pattern has an odd number of stars in each row 1, 3, 5, 7, etc.

  • Again we need to nest the loops.
  • Create 2 internal loop, first print spaces and second print stars.
  • Print spaces for number of times equal to size - i and stars for 2 * i - 1 times.
  • Here i is the current row.

9. Hollow Pyramid Pattern In Python

The hollow pyramid pattern is a pyramid pattern made of stars but hollow. You can see the pattern up there.

Follow these steps to create hollow pyramid pattern:

  • You can observe that we have to handle spaces at 2 different places. First before printing star and second between the pyramid.
  • Create nested loop with 2 internal loops. First loop just create space, second loop print both spaces & stars with some logics.
  • The first internal loop print spaces for size - i times.
  • The second internal loop pexecutes for 2 * i - 1 times and checks if it is first or last row then print star, if not check if it is first or last column then print star else print space.

10. Reverse Pyramid Pattern In Python

The reverse pyramid pattern is the same as the pyramid pattern but it is upside down. See the pattern up there.

Just like the pyramid pattern, the reverse pyramid pattern follows the same logic. The only difference is that we have to print the spaces and stars with reverse logic.

Stay Ahead, Learn More

  • Pyramid Pattern In Python
  • Number Pattern Programs In Python
  • Alphabet Pattern Programs In Python

11. Diamond Star Pattern In Python

The diamond star pattern is a star pattern with the shape of the diamond. You can see the pattern up here.

If you look closely, you will see that the pattern is a combination of a pyramid pattern and a downward triangle star pattern. So you can create this pattern by combining both patterns.

Here is the code to create this pattern.

12. Hollow Diamond Star Pattern In Python

The hollow diamond pattern is the same as the diamond star pattern but hollow. The pattern is up here.

This one is complex because you have to deal with multiple things like spaces, stars for each row where the pattern itself is divided into two parts upper pyramid and lower pyramid.

Let's see the code.

13. Hourglass Star Pattern In Python

The hourglass pattern is a pattern with the shape of an hourglass. When you observe the pattern, you will see that it is made up of two patterns. The first pattern is a downward pyramid pattern and the second pattern is an upward triangle pattern.

You can create this pattern by combining both patterns. The code is as follows.

14. Right Pascal Star Pattern In Python

The right pascal triangle pattern is shown above. It can be clearly seen that it is made up of an upper triangle and a lower triangle.

So you can run 2 different loops one which creates the upper triangle and another which creates the lower triangle.

Here is the complete code.

15. Left Pascal Star Pattern In Python

The left pascal triangle pattern is a mirror image of the right pascal triangle pattern. The pattern is shown above.

The left pascal triangle pattern is a little bit more complicated than the right pascal triangle pattern because you will have to deal with both spaces and stars.

16. Heart pattern in python

The heart pattern is a pattern with the shape of a heart. It is quite a complex pattern. But if you observe the code carefully then you will understand it easily.

17. Plus pattern program in Python

The plus pattern is a pattern with the shape of a plus sign (+).

The complete code is given below.

18. Cross pattern program in Python

The cross pattern is a pattern with the shape of a cross sign (X).

Here is the complete code to create the cross pattern.

19. Left Number Triangle Pattern Program

The left number triangle pattern is a triangle pattern that is made of numbers and has perpendicular on its left side.

The complete code for the left number triangle pattern is given below.

20. Right Number Triangle Pattern Program

The right number triangle pattern is a triangle pattern that is made of numbers and has perpendicular on its right side.

The complete code for the right number triangle pattern is given below.

21. Number Pyramid Pattern Program In Python

The number pyramid pattern is a pattern that is made of numbers and has a pyramid shape.

The complete code for the number pyramid pattern is given below.

22. Reverse Number Pyramid Pattern Program In Python

The reverse number pyramid pattern is a number pyramid reversed 180 degrees.

The complete code for the reverse number pyramid pattern is given below.

23. Hollow Number Pyramid Pattern Program

The hollow number pyramid pattern is a number pyramid pattern that has a hollow space in the middle.

The complete code for the hollow number pyramid pattern is given below.

24. Number Diamond Pattern Program

The number diamond pattern is a diamond pattern that is made of numbers.

The complete code for the number diamond pattern is given below.

25. Hollow Number Diamond Pattern Program

The hollow number diamond pattern is a diamond pattern that is made of numbers and is hollow inside.

The complete code for the hollow number diamond pattern is given below.

Let's now create some pattern programs using alphabets instead of stars or numbers.

26. Alphabet Pyramid Pattern Program

The alphabet pyramid pattern is a pyramid pattern that is made of alphabets.

The complete code for the alphabet pyramid pattern is given below.

27. Reverse Alphabet Pyramid Pattern Program

The reverse alphabet pyramid pattern is a pyramid pattern that is made of alphabets and is upside down.

The complete code for the reverse alphabet pyramid pattern is given below.

28. Hollow Alphabet Pyramid Pattern

The hollow alphabet pyramid pattern is a pyramid pattern that is made of alphabets and is hollow inside.

The complete code for the hollow alphabet pyramid pattern is given below.

29. Alphabet Diamond Pattern Program

The alphabet diamond pattern is a diamond pattern that is made of alphabets.

The complete code for the alphabet diamond pattern is given below.

30. Hollow Alphabet Diamond Pattern

The hollow alphabet diamond pattern is a diamond pattern that is made of alphabets and is hollow inside.

The complete code for the hollow alphabet diamond pattern is given below.

After looking at 30 pattern program in python you have learned the basics of creating patterns. Now you can create your own patterns and make them look beautiful. Try the alphabet pattern program discussed in the next article.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Getting Started
  • Keywords and Identifier
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Type Conversion
  • Python I/O and Import

Python Operators

  • Python Namespace

Python Flow Control

  • Python if...else
  • Python for Loop
  • Python while Loop
  • Python break and continue
  • Python Pass

Python Functions

  • Python Function
  • Function Argument
  • Python Recursion
  • Anonymous Function
  • Global, Local and Nonlocal
  • Python Global Keyword
  • Python Modules
  • Python Package

Python Datatypes

  • Python Numbers
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary

Python Files

  • Python File Operation
  • Python Directory
  • Python Exception
  • Exception Handling
  • User-defined Exception

Python Object & Class

  • Classes & Objects
  • Python Inheritance
  • Multiple Inheritance
  • Operator Overloading

Python Advanced Topics

  • Python Iterator
  • Python Generator
  • Python Closure
  • Python Decorators
  • Python Property
  • Python RegEx
  • Python Examples

Python Date and time

  • Python datetime Module
  • Python datetime.strftime()
  • Python datetime.strptime()
  • Current date & time
  • Get current time
  • Timestamp to datetime
  • Python time Module
  • Python time.sleep()

Python Tutorials

Precedence and Associativity of Operators in Python

Python Operator Overloading

Python if...else Statement

Python 3 Tutorial

  • Python any()
  • Python Strings

Operators are special symbols that perform operations on variables and values. For example,

Here, + is an operator that adds two numbers: 5 and 6 .

  • Types of Python Operators

Here's a list of different types of Python operators that we will learn in this tutorial.

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Special Operators

1. Python Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,

Here, - is an arithmetic operator that subtracts two values or variables.

Example 1: Arithmetic Operators in Python

In the above example, we have used multiple arithmetic operators,

  • + to add a and b
  • - to subtract b from a
  • * to multiply a and b
  • / to divide a by b
  • // to floor divide a by b
  • % to get the remainder
  • ** to get a to the power b

2. Python Assignment Operators

Assignment operators are used to assign values to variables. For example,

Here, = is an assignment operator that assigns 5 to x .

Here's a list of different assignment operators available in Python.

Example 2: Assignment Operators

Here, we have used the += operator to assign the sum of a and b to a .

Similarly, we can use any other assignment operators as per our needs.

3. Python Comparison Operators

Comparison operators compare two values/variables and return a boolean result: True or False . For example,

Here, the > comparison operator is used to compare whether a is greater than b or not.

Example 3: Comparison Operators

Note: Comparison operators are used in decision-making and loops . We'll discuss more of the comparison operator and decision-making in later tutorials.

4. Python Logical Operators

Logical operators are used to check whether an expression is True or False . They are used in decision-making. For example,

Here, and is the logical operator AND . Since both a > 2 and b >= 6 are True , the result is True .

Example 4: Logical Operators

Note : Here is the truth table for these logical operators.

5. Python Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.

For example, 2 is 10 in binary, and 7 is 111 .

In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)

6. Python Special operators

Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.

  • Identity operators

In Python, is and is not are used to check if two values are located at the same memory location.

It's important to note that having two variables with equal values doesn't necessarily mean they are identical.

Example 4: Identity operators in Python

Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).

But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.

  • Membership operators

In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence ( string , list , tuple , set and dictionary ).

In a dictionary, we can only test for the presence of a key, not the value.

Example 5: Membership operators in Python

Here, 'H' is in message , but 'hello' is not present in message (remember, Python is case-sensitive).

Similarly, 1 is key, and 'a' is the value in dictionary dict1 . Hence, 'a' in y returns False .

  • Precedence and Associativity of operators in Python

Table of Contents

  • Introduction
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python Bitwise operators
  • Python Special operators

Video: Operators in Python

Sorry about that.

Related Tutorials

Python Tutorial

IMAGES

  1. Writing a Python Program

    write program python

  2. Python File Write

    write program python

  3. 10 Easy Steps: How to Write to a Text File in Python 2024

    write program python

  4. Write a Program to implement Python Stack

    write program python

  5. Best code writer for python

    write program python

  6. Python Programming Overview

    write program python

VIDEO

  1. what is python..? full information #coding #shortvideo #python

  2. Python

  3. Simple first program in Python

  4. Python Basics Intro

  5. Python Tutorials Part-1

  6. #2 First Program in Python

COMMENTS

  1. How to Use Python: Your First Steps

    Code Editors IDEs (Integrated Development Environments) Python Code Style Get Extra Features in Python The Standard Library The Python Package Index and pip Take Your Python Skills to the Next Level Coding Is Like Riding a Bike Advising New Python Coders Code an Example: Count to 10 Test Your Knowledge Conclusion Remove ads

  2. Python Examples

    Popular Examples Python Examples Python Program to Check Prime Number Python Examples Python Program to Add Two Numbers Python Examples Python Program to Find the Factorial of a Number Python Examples Python Program to Make a Simple Calculator All Examples Advanced Introduction Object Oriented Decision Making and Loops Functions Native Datatypes

  3. Python For Beginners

    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.

  4. How To Write Your First Python 3 Program

    To write the "Hello, World!" program, let's open up a command-line text editor such as nano and create a new file: nano hello.py

  5. The Python Tutorial

    This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well. For a description of standard objects and modules, see The Python Standard ...

  6. How to Write a Basic Python Program: 13 Steps (with Pictures)

    1 Open the Terminal. On Linux, you can press the Alt button to open a search bar. Type "terminal" and click on Terminal. 2 Know the commands. Terminal commands are shown in this document as: command -options filename.ext sudo apt-get install build-essential The "sudo" command gives permission to the terminal to modify your computer.

  7. How to Get Started With 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. Download Thonny IDE. Run the installer to install Thonny on your computer. Go to: File > New.

  8. Python Code Example Handbook

    You will see this message after running the program: "Hello, World!" 💡 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.

  9. Your First Python Program • Python Land Tutorial

    What does work is: First copy the function say_hi (name) and hit enter. Now the REPL knows this function. After that, copy and paste the name = input ("Your name: ") and hit enter again. It will ask for your name, so enter it. Finally, you can copy and paste the say_hi (name) line and see what happens!

  10. Python Tutorial

    print("Hello, World!") Try it Yourself » Click on the "Try it Yourself" button to see how it works. Python File Handling In our File Handling section you will learn how to open, read, write, and delete files. Python File Handling Python Database Handling In our database section you will learn how to access and work with MySQL and MongoDB databases:

  11. Online Python Compiler (Interpreter)

    Write and run Python code using our online compiler (interpreter). You can use Python Shell like IDLE, and take inputs from the user in our Python compiler.

  12. 7. Input and Output

    7.1.1. Formatted String Literals ¶ Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression}. An optional format specifier can follow the expression.

  13. How To Write Your First Python Application

    In the command prompt, type in "python" and press Enter. If you already have Python installed, you'll be greeted with a Python prompt. If you see a Python prompt, and the version of Python is 3 or above, you can skip the rest of the installation steps and proceed directly to the Creating Our First .py File section.

  14. The Python Code Example Handbook

    name = 'Farhan' print('My name is ' + name) Output of this code will be: My name is Farhan. As you can see, there is no special keyword for declaring a variable. Python is smart enough to get the type of the variable from the value you're assigning. In the example above, the name variable contains the Farhan string.

  15. Python Programs

    Explore the wide range of Tuple programs here in this section of Python programming examples. Python program to Find the size of a Tuple. Python - Maximum and Minimum K elements in Tuple. Create a list of tuples from given list having number and its cube in each tuple. Python - Adding Tuple to List and vice - versa.

  16. How to Write Clean Code in Python

    Write not more of a unit test than is sufficient to fail. Write not more production code than is sufficient to pass the currently failing test. So, the tests are written before the production code. This leads to the developer thinking about what the function should do. In Python, libraries like unittest or pytest can be used to test your functions.

  17. Online Python Compiler

    Free Online Python Compiler - The most user friendly Online Python Compiler and Editor which allows you to write Python Code, Compile and Execute it online. You can ...

  18. Python Functions (With Examples)

    Create a Function Let's create our first function. def greet(): print('Hello World!') Here are the different parts of the program: Create a Python Function Here, we have created a simple function named greet () that prints Hello World! Note: When writing a function, pay attention to indentation, which are the spaces at the start of a code line.

  19. How to Run a Python Script

    Whether you are a beginner or an experienced developer, Python scripting is a fundamental skill. In computing, a script is a list of commands and instructions interpreted by a specific program. The term 'script' is very generic and applies to every programming language. If the script is written in Python, it is called a Python Script.

  20. Pattern Program in Python (with 30 Examples)

    1. Square Pattern in Python ***** ***** ***** ***** ***** The square pattern is the easiest pattern program. It is a pattern that has the shape of a square made of stars. Let's see how to create and print a square pattern. Take size of the square as input from the user or just set a value. Run a nested loop for the number of rows and columns.

  21. Write a program in python that first reads in the name of an

    Write a program in python that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the ...

  22. Python Dictionary (With Examples)

    Python Dictionary. Notes: Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use mutable (changeable) objects such as lists as keys. We can also create a dictionary using a Python built-in function dict(). To learn more, visit Python dict().

  23. python

    I am using DrCacheSim (DynamoRIO) to write raw cache files for a simple program (python program which I converted into an executable program) and then simulate the cache from the raw files. The simulation in most tries works only for one of the several directories which are generated when writing cache data for the program.

  24. Python Operators (With Examples)

    6. Python Special operators. Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples. Identity operators. In Python, is and is not are used to check if two values are located at the same memory location.