DEV Community

elsie-n
elsie-n

Posted on • Updated on

Introduction to Python

What is python?
Python is a high-level, general purpose, interpreted programming language meaning:

  • It is easy to learn
  • Can be used in various domains, i.e web applications,automation,data science, machine learning and AI, the targeted language like SQL which can be used for querying data from relational databases.
  • It is an interpreted language,turns the source code, line by line, once at a time, into the machine code.

Why Python

  • Python increases your productivity. Python allows you to solve complex problems in less time and fewer lines of code. It’s quick to make a prototype in Python.
  • Python becomes a solution in many areas across industries, from web applications to data science and machine learning.
  • Python is quite easy to learn in comparison with other programming languages. Python syntax is clear and beautiful.
  • Python has a large ecosystem that includes lots of libraries and frameworks.
  • Python is cross-platform. Python programs can run on Windows, Linux, and macOS.
  • Python has a huge community. Whenever you get stuck, you can get help from an active community.
  • Python developers are in high demand.

Installation
To download the latest version click [(https://www.python.org/downloads/)], run the program and install.

Python Basics
Fundamentals

Whitespaces and Indentations

Unlike other programming languages ,Python uses whitespace and indentation to construct the code structure to separate statements instead of single colon(;)
This whitespaces should be uniform otherwise an error occurs while running the code.

def studentcode():
    i = 1
    max = 10
    while (i < max):
        print(i)
        i = i + 1

# call function studentcode 
studentcode()
Enter fullscreen mode Exit fullscreen mode

Comments

Comments are part of the code that does not get executed rather are as important since they describe why a piece of code was written.
In Python there are two ways of writing comments :
a single line comment begins with a hash (#) symbol followed by the comment.
# call function studentcode
multiline comments (""" comment """)

"""
def studentcode():
    i = 1
    max = 10
    while (i < max):
        print(i)
        i = i + 1

# call function studentcode 
studentcode()"""

Enter fullscreen mode Exit fullscreen mode

Identifiers

This are names that identify variables, functions, modules, classes, and other objects in Python, they are case sensitive and cannot use keywords.
some features to consider while choosing variables(containers for storing data values) include;

  • Variable names are case sensitive;studentcode is different from Studentcode
  • A variable name can only contain alphanumeric characters and underscores.
  • A variable name cannot start with a number, it must start with a letters or an underscore character.
  • Variable names cannot contain spaces. To separate words in variables, you use underscores.
  • String variables are declared either by using a single/double quotes. code = 'studentcode' code = "studentcode" Bonus Too get the data type of a variable
type ()function
 code = 56
print(type(code))

Enter fullscreen mode Exit fullscreen mode

Strings

strings are declared using single or double quotes.
To concatenate strings use (+)

print "This is" +" a good string"

Enter fullscreen mode Exit fullscreen mode

To access a specific element in a string use index of that particular string

str = "Python String"
print(str[0]) # P
print(str[1]) # y

Enter fullscreen mode Exit fullscreen mode
+---+---+---+---+---+---+---+---+---+---+---+---+---+
| P | y | t | h | o | n |   | S | t | r | i | n | g | 
+---+---+---+---+---+---+---+---+---+---+---+---+---+
  0   1   2   3   4   5   6   7   8   9   10  11  12
-12  -11  -10 -9  -8  -7  -6  -5  -4  -3  -2  -1   0 

Enter fullscreen mode Exit fullscreen mode

To get the length of a string, you use the len() function.

str = "Python String"
str_len = len(str)
print(str_len)
Enter fullscreen mode Exit fullscreen mode

Numbers

Python supports integers int(),float float() and complex numbers.
There are different types of operations;
Arithmetic Operators
Comparison Operators
Logical Operators
The different Arithmetic operators used include :

print(5 + 2)  # 7 (addition)
print(5 - 2)  # 3 (subtraction)
print(5 * 2)  # 10 (multiplication)
print(5 / 2.0)  # 2.5 (division)
print(2 ** 8)  # 256 (exponent)
print(5 % 2)  # 1 (remainder of the division)
print(5 // 2)  # 2 (floor division)
Enter fullscreen mode Exit fullscreen mode

notice to get float when dividing you should indicate either of the numbers as a float type or both,i.e

print(5 / 2.0)  # 2.5 float
print(5.0 / 2.0)  # 2.5 float
print float(5)/2 #2.5 float
Enter fullscreen mode Exit fullscreen mode

Also some of the different Comparison operators include;
Equal to (==)
Not equal to (!=)
less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)

Logical operators are and/or/not;

And checks if both the statements are true
Or checks if either of the statements is true
Not which gives the opposite of the given condition.

a = 5 
    b = 2 
# True if both conditions are true  
print(a > 3 and a < 7)  

# True if one condition is true  
print(a > 6 or b < 7)  

# True if given condition is false (inverse of given condition)  
print(not(a > 3))  

Enter fullscreen mode Exit fullscreen mode

Boolean

Checks if a statement given a condition is true or false .

x = "Elsie"
if a is "Elsie" 
   ("true")
 else 
 print "False"
Enter fullscreen mode Exit fullscreen mode

List
Python uses the square brackets ([]) to indicate a list and a comma(,) to separate the elements in the list.

students = ['Elsie', 'Judy', 'Lawrence']
To get rid of the quotes and commas while printing

students = ['Elsie', 'Judy', 'Lawrence']
 print "".join(students)
#or 
 print "...".join(students)
Enter fullscreen mode Exit fullscreen mode

Tuple
Tuples are just like lists, but immutable (cannot be modified). They are surrounded by ()
students = ('Elsie', 'Judy', 'Lawrence')

Dictionaries
A Python dictionary is a collection of key-value pairs where each key is associated with a value. Python uses the curly braces {} to define a dictionary. Inside the curly braces, you can place zero, one, or many key-value pairs.

person = {
    'first_name': 'John',
    'last_name': 'Doe',
    'age': 25,
    'favorite_colors': ['blue', 'green'],
    'active': True
}
print(person['first_name']) #retrieves the first name
print(person['last_name']) #retrieves the last name

Enter fullscreen mode Exit fullscreen mode

Control flow
Some of the control flow options include:

  • if statements; if statement if…else statement nested if if ladder
  • for loop
  • while loop
  • break & clause
  • ternary operator

if statement
There are different kinds of if statements

  • if statement This checks if a statement satisfies one condition and prints.
student_mark = input('Enter your marks:')
  if int(student_marks) >= 60:
    print("pass")

Enter fullscreen mode Exit fullscreen mode
  • if…else Use the if...else statement when you want to run another code block if the condition is not True.
student_mark = input('Enter your marks:')
  if int(student_marks) >= 60:
    print("pass")
  else 
    print ("fail")

Enter fullscreen mode Exit fullscreen mode

for loop
The for loop enables you to execute a block of code multiple times.

for index in range(n):
    statement
Enter fullscreen mode Exit fullscreen mode

The index is called a loop counter .And n is the number of times that the loop will execute the statement.

While loop
While statement allows you to execute a code block repeatedly as long as a condition is True, checks the condition at the beginning of each iteration

max = 5
counter = 0

while counter < max:
    print(counter)
    counter += 1
Enter fullscreen mode Exit fullscreen mode

Break
While using the if or loop statements one would want to terminate prematurely to do this use break

break

Functions
A function is a named code block that performs a job or returns a value. This enables one to perform a task multiple times without rewriting the code all over again. Use def to define a new function.

def students():

Top comments (0)