Python for Beginners with Examples

Matthew Bilo
October 22, 2019
Last updated on
June 25, 2024

Introduction to Python

Python is an object oriented programming language which was designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It is designed exclusively for rapid prototyping of complex applications.

This programming language has interfaces to many OS system calls and libraries and is extensible to C or C++. It is used by many large companies including NASA, Google, YouTube, BitTorrent, etc. It contains exceptions, modules, advanced data types, dynamic typing, classes, and more. It is portable and can be used as an extension language. It works well on almost all operating systems including Unix, Mac, DOS and Windows.

It is the most preferred programming language in Artificial Intelligence (AI), Natural Language Generation, Neural Networks as well as other advanced fields of Computer Science.

Features of Python Programming Language

The following are the features of Python programming language.

  • Easy to learn and use
  • Developer-friendly
  • More understandable and readable
  • Makes debugging easier
  • Works well on different platforms such as Windows, Linux, Unix and Macintosh etc.
  • Supports object oriented language and concepts of classes and objects come into existence
  • Has a large and broad library
  • Provides rich set of module and functions for rapid application development
  • Can be easily integrated with languages like C, C++, JAVA, etc.
  • Helps programmers to program video games, build Artificial Intelligence algorithms and program various scientific programs such as statistical models

This tutorial covers some of the important topics of Python Programming such as installation, creating first program, print function, Main function, Variables and various String Operators.

Read Also: My Fun & Easy Approach to Learning Python

How to Install Python

The following steps will help you install Python and PyCharm.

PyCharm - It is a cross-platform editor that provides all the tools you need to develop Python.

To download the python: Visit the official website of Python: http://www.python.org/downloads/ and choose your version

After downloading, run the exe to install Python.

Click on Install Now.

To download Pycharm : Visit the website https://www.jetbrains.com/pycharm/download/ and click the "DOWNLOAD" link under the Community Section.

When download completes, run the exe for install PyCharm.

Creating Your First Program

To create first program -> Open PyCharmEditor and to create a new project -> click on "Create New Project".

At that time New Project window will appear. In the location field, you need to select the location where you want the project to be created. If you don't want to change the location then keep it as it is, but you need to change the name.

Then Click the "Create" Button

Next Go to the "File" menu and select "New". Then, select "Python File".

At that time, a pop up window will appear. You need to type the name of the file and click"OK".

Type a simple program - print('Hello World!').

Go to the "Run" menu and select "Run" to run your program.

If you haven't installed Pycharm Editor, you can still run the code from the command prompt. You need to enter the correct path of a file in command prompt to run the program.

How to Print in Python

You need to use the print() function

Example:

print("Good Morning")

How to print blank lines

If you want to print 8 blank lines in your Python program. You can type

print(8 * "\n")

or:

print("\n\n\n\n\n\n\n\n\n")

The code is

print("LifeisBeautiful")

print(8 * "\n")

print("Life isBeautiful")

How to print end command

Python's print() function ends with a newline. This function comes with a parameter called 'end.' The default value of this parameter is '\n,' i.e., the new line character. It is also possible to end a print statement with any character or string using this parameter.

For example:

print("Life is", end=' ')

print("Beautiful", end='!')

The output is

LifeisBeautiful!

Python Main function

The following is the example of Python Main Function

def main():
 print "hello world!"
 print "Beautiful"

Here, the first print function is defined within a main function that is "Hello World" and the other is independent which is "Beautiful". When you run the function def main ():

Only python "Beautiful" prints out.

In order to get the output "hello world", you need to call the code by if name== "main", after defining the main function and then run the code. Now, you will get the output "hello world!"

Example:

def main():
 print("Hello World!")

if __name__== "__main__":
 main()
 print("Beautiful")

This example is for Python 3 codes.

For Python 2, you need to consider the following code

def main():
 print "Hello World!"

if __name__== "__main__":
 main()
 print "Beautiful"

In Python 3, the following code also works

def main():
 print("Hello World!")

main()
print("Beautiful")

Python 3 is the latest generation of the language which was introduced in 2008. Many programmers still use Python 2.7 which is the final update to Python 2, which was released in 2010. In fact, there is slight difference between the two.

Variables in Python

Variables are reserved memory locations to store values. All values in Python have a data type. Various data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. It is possible to declare variables by any name or even alphabets like a, aa, abc, etc.

Declaring a variable

Here, we will declare variable "c" and print it.

c=500

print c

Now, we will re-declare a variable

In Python, it is possible to re-declare the variable even after you have declared it once.

In this example, we have a variable a that is initialized to 0.

Later, we re-assign the value "Beautiful" to variable a

Example

a=0
print a

a='Beautiful'
print a

How to Concatenate Variables

We can concatenate different data types like string and number together. For example, "Beautiful" with the number "99".

The code is

a="Beautiful"
b=99

print(a + str(b))

After declaring the integer as string, it concatenate both "Beautiful" + str("99")= "Beautiful99" in the output.

Python Strings: Replace, Join, Split, Reverse, Uppercase & Lowercase

OperatorDescriptionExample        []    This is Slice. It gives the letter from the given index    a[1] will return "e" from the word Beautiful as such ( 0=B, 1=e, 2=a, 3=u,4=t, etc)    x="Beautiful"print x[1]        [:]    This is range slice. It gives the characters from the given range    x [1:3] it will give "ea" from the word Beautiful. It will not consider 0 which is B    X=”Beautiful”print x[1:3]        in    Membership-returns true if a letter exist in the given string    “e” is present in word Beautiful. Therefore it will return 1 (True)    x="Beautiful"print "e" in x        not in    Membership-returns true, if a letter exist is not in the given string    Membership-returns true, if a letter exist is not in the given string            r/R    This is raw string that suppresses actual meaning of escape characters.    Print r'\n' prints \n and print R'/n' prints \n            % - Used for string format    %r inserts the canonical string representation of the object and %s inserts the presentation string representation of the object    The output will be "Beautiful99".    name = 'Beautiful'number = 99print'%s %d' %(name,number)        +    Concatenates two strings strings                *    Repeat    If a=Beautiful and b=99 then a+b= "Beautiful99". Likewise, if you are using a*2, it will return "BeautifulBeautiful"  

replace() Method - It returns a copy of the string in which the values of old string have been replaced with the new value.

oldstring='I like Coffee'
newstring=oldstring.replace('like', 'love')
print(newstring)

Upper and lower case strings

string="python tutorials"
print(string.upper())

# Similarly, you can also do for other function like capitalize

string="python tutorials"
print(string.capitalize())

Converting string to lower case

string="PYTHON TUTORIALS"
print(string.lower())

Join function

If you want to add a colon (:) after every character in the string "Beautiful", then use the following code

print(":".join("Beautiful"))

Reversing String

It is used to reverse a string.

For example,

string="56789"
print(''.join(reversed(string)))

Split Strings

It is used to split a string.

The code is:

word="beautiful lifebeautiful"
print(word.split(' '))

Instead of space (' ') we can replace it with ('r') and it will split the string wherever 'r' is mentioned in the string

word="beautifullifebeautiful"
print(word.split('r'))

Conclusion

Python is a magnificent language. Its syntax is simple and code length is short which makes it easy to understand and write. If you are a beginner in programming, then Python is an awesome choice. This powerful language is not only good for learning programming, but also a good language to have in your arsenal.

Related Python courses in Hong Kong

Need more advice?

If you are at a choice point in your career and need someone to help you navigate professional challenges. You can make an appointment to our complimentary 1-on-1 Career Consultation and receive personalised career advice.