Python is one of the most widely used programming languages. Guido van Rossum created it, and it was released in 1991. It's used for server-side web development, software development, mathematics, and system programming just to mention.
Some of the most noticeable differences between Python and other programming languages are that Python uses new lines to complete commands, rather than semicolons or parentheses (though the semicolons(;) are optional and usually not used in python), and that Python relies on indentation, using whitespace, to define scope; for example, the scope of loops, functions, and classes. Curly brackets are commonly used in other computer languages for this purpose.
Python is well-known for its general-purpose character, which makes it suitable for and the finest solution provider in practically any software development domain. Python is used in a variety of developing fields, including Data Science and Big Data Analytics. It is the most popular programming language and may be used to create any application.
A Python script which is essentially a file that contains a python code should have an extension .py and can be run from the command line by typing python file_name.py
Features of python
Python is a free and open source programming language that can be downloaded from the official website, with even its source code available.
Python is a portable programming language its code can be shared and will continue to function as intended.
Python is an expressive language, which implies it is more intelligible and readable than other programming languages.
Python is a simple language to pick up and use, just focusing more on the code rather than the language's syntax.
Python features a huge and diverse library, as well as a comprehensive set of modules and functions enabling rapid application development.
Platform Independent, write once and run anywhere
Its Dynamically typed giving the programmer additional flexibility.
Object-Oriented, python supports object oriented language and concepts of classes and objects come into existence.
Applications of python
Python is utilized in a wide range of applications. Here's a small sample:
Web and internet development
Education
Scientific and numeric
Business Applications
3D CAD Applications
Image processing Applications
Artificial Intelligence
Python installation
Here's where you can get the most recent version of Python for your operating system.
This pythontutorial.net tutorial will teach you how to set up a Python development environment using VS Code.
You can use IDEs like PyCharm or any other after installing Python.
Note
- Python 3.10 will include a lot of cool new features, but it's currently in beta. Installing it as your default Python version may not be a good choice because it isn't production-ready.
First Python Program
Lets go ahead and create our first python program to display "Hello World!" .
To begin, make a new folder called lets say , python , in which you will save your Python files.
Second, start Visual Studio Code and go to the new folder you made, python.
Third, create a new python file, say first.py, and paste the following code into it before saving it.
print ("Hello World!")
A built-in function, print() which we have used above, shows a message on the screen. It will display the message 'Hello Word!' in our case.
Executing Our First Python Program
To run the first.py file we generated earlier, use the Command Prompt on Windows or the Terminal on Mac or Linux.
Then, for our case, navigate to the folder, python , holding our file. Learn more on terminal commands here
Then, to run the app.py file, type the following command:
Python3 first.py
The following output will be displayed:
Hello World!
Comments
When writing a program, comments are crucial. It explains what happens inside a program so that someone looking at your source code doesn't have trouble deducing what's going on.
To begin creating a comment in python we utilize the hash symbol (#)
If we have comments that span multiple lines, multi-line comments we can use the hash symbol at the start of each line . Another option is to use triple quotes such as ''' or """
# This is a single line comment
'''
multiline comment
This comment is written in more than one line
'''
Variables
Variables are names that are connected to a specific object in Python. They keep a reference to the memory address where an item is stored, often known as a pointer.
The syntax is as follows:
variable_name = variable_value
Always name your variables in a way that is both intuitive and readable.
Uppercase and lowercase letters (A-Z, a-z), numerals (0-9), and the underscore character (_) can all be used in variable names.
Variable names may contain digits, but the initial character must not be a numeric.
Variables do not require declaration. Python is a dynamically typed language since their data types are deduced from their assignment statement. This means that throughout the code, different data types might be given to the same variable.
Below are examples:
first_name = "Haddasah"
print(first_name)
first-name = "Chenda"
print(first_name)
last_name = "Maghanga"
print(last_name)
Arithmetic operators
Addition, subtraction, multiplication, division, and other operations are represented by arithmetic operators. They produce expressions that Python can evaluate when combined with numbers:
print(10 + 2) # 12 (addition)
print(1 - 1) # 0 (subtraction)
print(5 * 5) # 25 (multiplication)
print(22 / 2) # 11.0 (division)
print(5 ** 3) # 125 (exponent)
print(11 % 2) # 1 (remainder of the division)
print( 5 // 3) # 1 (floor division)
Logical Conditional & Comparison Operators
Comparison Operators
Comparison_(Relational)_ Operators compare the values. It either returns True or False according to the
condition. They are as listed below: > (greater than), >= (greater than or equal to), < (less than), <= (less than or equal to), ==
(equal to), != (not equal)
a=10
b=20
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
print("a == b is ",a==b)
print("a != b is ",a!=b)
#Output
a > b is False
a >= b is False
a < b is True
a <= b is True
a == b is False
a != b is True
Note
- Chaining of relational operators is possible. In the chaining, if all comparisons returns True then only result is True. If at least one comparison returns False then the result is False
10<20 ==>True
10<20<30 ==>True
10<20<30<40 ==>True
10<20<30<40>50 ==>False
Logical Operators
They allow a program to make a decision based on multiple conditions. Each operand is
considered a condition that can be evaluated to a true or false value. They are:
and, or, not
For boolean types behavior:
➢ and ==>If both arguments are True then only result is True
➢ or ==>If atleast one arugemnt is True then result is True
➢ not ==>complement
For non boolean type’s behavior
➢ 0 means False
➢ non-zero means True
➢ empty string is always treated as False
a=10
b=20
c=0
print("a and b is ",a and b)
print("a or b is ",a or b)
print("not b is ",not b)
print("c and b is ",c and b)
print("c and b is ",c or b)
print("not c is", not c)
# Output
a and b is 20
a or b is 10
not b is False
c and b is 0
c and b is 20
not c is True
Conditional Operators
if
Decision making is required when we want to execute a code only if a certain condition is satisfied
num = 3
if num > 0:
print(num,"is a positive number.") print("This is always printed.")
# Output
3 is a positive number This is always printed
else
The if-else statement evaluates test expression and will execute body of if only when test condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
# Output
b is not greater than a
elif
The elif is short for else if. It allows us to check for multiple expressions.
Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional.
i = 20
if (i == 10):
print ("i is 10") elif (i == 15):
print ("i is 15") elif (i == 20):
print ("i is 20") else:
print ("i is not present")
# Output
i is 20
Data types
Strings
Any single characters within either single, double or triple quotes is considered as a string.
# Use single quotes
print('Good Morning Kenya!')
'Good Morning Kenya!'
#Use double quotes
community = "Lux Tech Academy"
print(community)
'Lux Tech Academy'
# Use triple quotes
message = """Thank you for reading this article"""
print(message)
'Thank you for reading this article'
After you've defined your string objects, you may concatenate them with the plus operator (+):
print("Lux" + " " + "Academy")
'Lux Academy'
The string class (str) contains a number of helpful methods for manipulating and processing strings. Below are jyst but a few examples:
- str.upper() returns a copy of the underlying string with all the letters converted to uppercase:
"Consistency is key".upper()
'CONSISTENCY IS KEY'
- str.join() takes an iterable of strings and joins them together in a new string.
" ".join(["Data", "Science"])
'Data Science'
Numbers
Python has three forms of numeric data: int, float, and complex. They don't need to be specified because they're inferred.
Integers: Are whole numbers
Examples 5,4,6Floats: Numbers with decimal points
Examples 3.4,5.6,8.9Complex numbers: Numbers with a real part and an imaginary part
Examples 1.5j,3+3.5j
pi = 3.14 #float
age = 20 #int
code = 389jL0 #complex number
Booleans
In Python, Booleans are represented as an integer subclass with only two possible values: True or False. The first letter of each value must be capitalized.
When utilizing comparison operators, Booleans come in helpful as it was seen above.
# booleans
a = True
b = False
if a is True and b is False:
print("Data Scince EastAfrica")
Lists
A list in Python is what other programming languages call an array. Multiple items can be stored in a single variable using lists.
In Python, lists are created by enclosing a comma-separated list of objects in square brackets ([]), as illustrated below:
favourite_drinks = ["water", "wine", "juice"]
print(favourite_drinks)
output: [water, wine, juice]
The following are the characteristics of Python lists:
Lists are arranged in a certain sequence.
Any object can be included in a list.
The index can be used to retrieve list elements.
Lists can be nested arbitrary deep.
Lists can be changed.
Lists are fluid.
List Modification Methods
append(object)
Appends an object to the end of a list.
winners=[Winnie,Grace,Muusi]
numbers.append(Ndanu)
print(numbers)
output:[Winnie,Grace,Muusi,Ndanu]
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 similar to lists in every way except for the features listed below:
Instead of square brackets ([]), tuples are defined by surrounding the elements in parenthesis (()).
Tuples are immutable, thus they can't be changed.
When manipulating a tuple, execution is faster. A tuple can be illustrated as follows:
#tuples
new_tuple = ("van", "car", "pat", "darn" , "run")
print(len(new_tuple)) # 5
print(new_tuple[1]) # car
print(new_tuple[1:4]) # ('car', 'pat', 'darn')
Dictionaries
In Python, a dictionary is an ordered collection that is used to hold data values.
Curly braces ( {} ) can be used to define a dictionary by enclosing a comma-separated list of key-value pairs. Each key is separated from its associated value by a colon (:).
new_dict = {"name": "Lux Academy", "Twitter Handle": "@lux_academy"}
print(new_dict["name"])
output:"Lux Academy"
Thank you very much for taking time to read this. I would really appreciate any comment in the comment section.
You can connect with me on twitter @Kai_mwanyumba
Top comments (8)
Great work!
Thank you very much , really appreciate it.
You can read mine here dev.to/torine6/python-101-introduc...
Yeah sure Torine6 a great article there , Keep it up
This is really good
Thank you very much I appreciate it 🤗
This is an amazing article! It is what actually inspired me to write mine dev.to/flaviankyande/python-101-in...
Great work there Flavian , keep it up👏👏 . Let's keep the good work going 🎊