What is Python?
Python is an interpreted ,high-level ,general-purpose programming language used in web development, data science and creating software prototypes.
Python programs have the extension .py and can be run from the command line by typing python file_name.py.
Python Syntax Compared to other programming languages
- Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
- Python relies on indentation, for using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.
Applications of Python Programming Language
- Building desktop applications, including GUI applications, CLI tools, and even games
- Doing mathematical and scientific analysis of data
- Building web and Internet applications
- Doing computer systems administration and automating tasks
- Performing DevOps tasks
Python has a bunch of features that make it attractive as your first programming language:
Free: Python is available free of charge, even for commercial purposes.
Open source: Anyone can contribute to Python development.
Versatile: Python can help you solve problems in many fields, including scripting, data science, web development, GUI development, and more.
Powerful: You can code small scripts to automate repetitive tasks, and you can also create complex and large-scale enterprise solutions with Python.
Multiparadigm: It lets you write code in different styles, including object-oriented, imperative, and functional style.
Installation
- Download the latest version of python Here
- Double-click the installer file to launch the setup wizard.
- In the setup window, you need to check the Add Python 3.9 to PATH and click the Install Now to begin the installation. Once the setup completes, you’ll see the following window:
Verify the Installation
In the Command Prompt, type python command as follows:
If you see the output like the above screenshot, you’ve successfully installed Python on your computer.
Setup Visual Studio Code for Python
To set up VS Code,
- Download Visual Studio Code Here based on your platform.
- Launch the setup wizard and follow the steps.
- Once the installation completes, you can launch the VS code application:
Install python extension
Follow the steps below to install python extension to make VS Code work with python.
- Click on extensions tab
- Type python keyword
- Click on python extension. It will show detailed information on the right pane.
- Finally click the install button to install python extension
Now we are ready to develop the first program in Python.
Creating First Program in Python
- First, create a new folder. In this case will create folder Firstproject.
- Second, launch the VS code and open the Firstproject folder.
- Third, create a new app.py file and enter the following code and save the file:
print("Hello world")
print() is a built-in function that displays a message on the screen.
Executing the Python Hello World program
To execute the app.py file, first launch the Command Prompt on Windows or Terminal on macOS or Linux.
Then, navigate to the Firstproject folder.
After that, type the following command to execute the app.py file:
python app.py
The following output will be displayed
Hello world
Comments
Comments are pieces of text in your code but are ignored by the Python interpreter as it executes the code.
Comments are used to describe the code so that you and other developers can quickly understand what the code does or why the code is written in a given way.
To write a comment in Python, just add a hash mark (#) before your comment text:
For Example:
# This is a single line comment
'''
This is a multiline comment
'''
Variables
In Python, variables are names attached to a particular object. They hold a reference, or pointer, to the memory address at which an object is stored.
Here's the syntax
variable_name = variable_value
Always use a naming scheme that makes your variables intuitive and readable.
Variable names can be of any length and can consist of uppercase and lowercase letters (A-Z, a-z), digits (0-9), and also the underscore character (_).
Even though variable names can contain digits, their first character can’t be a digit.
Here are some examples of valid and invalid variable names in Python:
First_number = 1
print(First_number)
output: 1
1rst_num = 1
print(1rst_num )
output :Syntax Error: invalid syntax
Keywords
Just like any other programming language, Python has a set of special words that are part of its syntax. These words are known as keywords
Keywords are reserved words that have specific meanings and purposes in the language.
And you shouldn’t use them for anything but those specific purposes. For example, you shouldn’t use them as variable names in your code.
Built-In Data Types
Python has a handful of built-in data types, such as numbers (integers, floats, complex numbers), Booleans, strings, lists, tuples, dictionaries, and sets.
Numbers
Numeric literals can belong to three different numerical types;
Integers:
Are whole numbers
Examples 5,4,6
Floats:
Numbers with decimal points
Examples 3.4,5.6,8.9
Complex numbers:
Numbers with a real part and an imaginary part
Examples 1.5j,3+3.5j
Arithmetic Operators represent operations, such as addition, subtraction, multiplication, division, and so on. When you combine them with numbers, they form expressions that Python can evaluate:
# Addition
5 + 3
8
# Subtraction
>>> 5 - 3
2
Multiplication
5 * 3
15
# Division
5 / 3
1.6666666666666667
# Floor division
5 // 3
1
# Modulus (returns the remainder from division)
5 % 3
2
# Power
5 ** 3
125
Booleans
Booleans are implemented as a subclass of integers with only two possible values in Python: True or False. The two values must start with a capital letter.
Booleans are handy when you are using Comparison operators
Here is how it works
2 < 5
True
4 > 10
False
Python provides a built-in function such as bool() and int().
bool() takes an object as an argument and returns True or False according to the object’s truth value.
Here is how it works;
bool(0)
False
bool(1)
True
int() takes a Boolean value and returns 0 for False and 1 for True
int(False)
0
int(True)
1
Strings
Strings are pieces of text or sequences of characters that you can define using single, double, or triple quotes:
# Use single quotes
print('Hello there!')
'Hello there!'
#Use double quotes
greeting = "Good Morning!"
print(greeting)
'Good Morning!'
# Use triple quotes
message = """Thanks for joining us!"""
print(message)
'Thanks for joining us!'
Once you define your string objects, you can use the plus operator (+) to concatenate them in a new string:
print("Happy" + " " + "Holidays!")
'Happy Holidays!'
The string class (str) provides a rich set of methods that are useful for manipulating and processing strings. For example,
str.upper() returns a copy of the underlying string with all the letters converted to uppercase:
"Happy Holidays!".upper()
'HAPPY HOLIDAYS!'
str.join()takes an iterable of strings and joins them together in a new string.
" ".join(["Happy", "Holidays!"])
'Happy Holidays!'
Lists
Lists are used to store multiple items in a single variables.
Lists are defined in Python by enclosing a comma-separated sequence of objects in square brackets ([]), as shown below:
numbers=[1,2,3,4]
print(numbers)
output: [1, 2, 3, 4]
Lists in python have the following characteristics;
- Lists are ordered.
- Lists can contain any arbitrary objects.
- List elements can be accessed by index.
- Lists can be nested to arbitrary depth.
- Lists are mutable.
- Lists are dynamic.
Methods That Modify a List
append(object)
Appends an object to the end of a list.
numbers=[1,2,3,4]
numbers.append(5)
print(numbers)
output:[1, 2, 3, 4,5]
extend(iterable)
Adds to the end of a list, but the argument is expected to be an iterable.
a = ['a', 'b']
a.extend([1, 2, 3])
print(a)
['a', 'b', 1, 2, 3]
insert()
Inserts an object into a list at the specified index.
a = ['name', 'location', 'address','email']
a.insert(3, 20)
print(a)
['name', 'location', 'address', 20, 'email']
remove()
Removes an object from a list
a = ['name', 'location', 'email', 'address']
a.remove('email')
print(a)
['name, 'location', 'address']
Tuples
Tuples are identical to lists in all respects, except for the following properties:
- Tuples are defined by enclosing the elements in parentheses (()) instead of square brackets ([]).
- Tuples are immutable hence cannot be modified
- Execution is faster when manipulating a tuple Here is an example of a tuple:
new_tuple=(1,2,3,4)
print(new_tuple)
output: (1, 2, 3, 4)
Dictionaries
Dictionary in python is an ordered collection, used to store data values.
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value.
new_dict = {"name": "Korir", "Email": "korir@gmail.com",
"DOB": 2000}
print(new_dict["Email"])
output:"korir@gmail.com"
Top comments (0)