codingstreets
Search
Close this search box.

Learning Python: Python Basics

learning-python-python-basics
Photo by Andrea Piacquadio on Pexels.com

Python is a popular high-level programming language known for its simple syntax, versatility, and extensive standard library. Created in the late 1980s, it is widely used for scripting, automation, data analysis, web development, machine learning, and scientific computing. Python’s design philosophy emphasizes code readability, making it an excellent choice for beginners. With a vast community of users and developers, Python offers many resources, including third-party libraries and tools, making it a go-to language for many industries.

Overall, Python is a versatile and powerful language widely used in industry, academia, and open-source projects. Its ease of use, broad applicability, and extensive community make it a popular choice for developers of all levels.

This article covers the basics of Python, a popular high-level programming language known for its versatility and simplicity. It explains Python’s syntax, function, standard library, etc. With its broad community of users and developers, Python offers numerous resources, making it an excellent choice for beginners and professionals.

Also, take a look at the Python Tutorial

Table of Contents

What is a Variable? 

In Python, variables are used to store values or data, and they are assigned using the “=” operator. 

Rules to Define Variables Name

  1. Variable names should start with either letter (A, a, Z, z) or an underscore(_). They cannot start with a number.
  2. Variable names can be letters (uppercase or lowercase), numbers, and underscores.
  3. Variable names are case-sensitive since letters can contain uppercase or lowercase letters. So “myVar” and “myvar” are two different variables.
  4. Variable names cannot use Python-reserved keywords such as “if”, “break”, “else”, and “while”, etc.

Here are some examples of valid variable names in Python:

				
					my_variable = 10
x = "Hello World"
first_name = "John"
My_variable = 10
				
			

And here are some examples of invalid variable names in Python:

				
					2nd_variable = 5   # Variable names cannot start with a number
last-name = "Smith"   # Variable names cannot contain hyphens
if = 20   # "if" is a reserved keyword in Python
				
			

It’s important to follow these rules when defining variable names in Python to avoid errors and make your code more readable and maintainable.

Python Data Types 

In Python, the `type()` function is used to determine the data type of a variable or value. It takes a single argument, which can be any object, and returns the type of that object as a string.

Here’s an example of using the `type()` function:

				
					x = 3.14
y = "Hello"
z = [1, 2, 3]

print(type(x))   # Output: <class 'float'>
print(type(y))   # Output: <class 'str'>
print(type(z))   # Output: <class 'list'>
				
			

In this example, the `type()` function is used to determine the data type of three variables: `x`, `y`, and `z`. The output shows that `x` is of type `float`, `y` is of type `str`, and `z` is of type `list`.

The `type()` function can be helpful when working with variables of unknown data types. It can also be used to conditionally execute code based on the data type of a variable or value.

In Python, data types refer to the different categories of values or objects that can be stored and manipulated in a program. Here are the main data types in Python:

In Python, data types refer to the different categories of values or objects that can be stored and manipulated in a program. Here are the main data types in Python:

Numeric types:

    – `int`: integer values, such as 3 or -17

    – `float`: floating-point values, such as 3.14 or -0.25

    – `complex`: complex numbers, such as 2+3j or -1+4j

Boolean type:

    – `bool`: Boolean values, `True` or `False`

Sequence types:

    – `str`: strings, such as “hello” or “123”

    – `list`: ordered collections of values, such as [1, 2, 3] or [‘apple’, ‘banana’, ‘orange’]

    – `tuple`: ordered collections of values, similar to lists but immutable, such as (1, 2, 3) or (‘apple’, ‘banana’, ‘orange’)

Mapping type:

    – `dict`: unordered collections of key-value pairs, such as {‘name’: ‘John’, ‘age’: 30}

Set types:

    – `set`: unordered collections of unique values, such as {1, 2, 3} or {‘apple’, ‘banana’, ‘orange’}

Other types:

    – `bytes`: immutable sequences of bytes, such as b’hello’

    – `bytearray`: mutable sequences of bytes, such as bytearray(b’hello’)

    – `NoneType`: a special type representing the absence of a value, denoted by `None`    

Python is a dynamically-typed language, which means that variables can hold values of any type, and the type of a variable is determined at runtime. This makes Python code more flexible and easier to write but also requires extra care when working with variables to avoid type errors.

Python print() function

In Python, the `print()` function is used to display output on the terminal. It takes one or more arguments, which can be of any data type, and prints them to the terminal.

Here are some examples of using the `print()` function:

				
					print("Hello, world!")   # Output: Hello, world!
print(40)   # Output: 40
print(1.17)   # Output: 1.17
print("I like to learn", "Python language")   # Output: I like to learn Python language
				
			

In the first example, the `print()` function is used to print a string literal, which is enclosed in double quotes. In the second example, the `print()` function is used to print an integer, and in the third example, it’s used to print a float. In the fourth example, the `print()` function is used to print multiple arguments separated by a comma, which are automatically separated by a space.

The `print()` function can also be used with special characters and formatting options to control the output. For example, the newline character `\n` can be used to start a new line:

				
					print("Hello,\nworld!")

#Output:

Hello,
world!
				
			

The `print()` function is a commonly used function in Python, and it’s used in almost all programs to display output to the user or to help with debugging.

Python Binary Operators

In Python, binary operators are operators that work on two operands or values. They are called binary operators because they take two inputs, which can be either variables or literals. Here are some examples of commonly used binary operators in Python:

Arithmetic operators:

+: addition

				
					num = 1+1
print(num)   #output: 2
				
			

-: subtraction

				
					num = 1-1
print(num)   #output: 0
				
			

*: multiplication

				
					num = 1*1
print(num)   #output: 1
				
			

/: division (returns a float)

				
					num = 11/2
print(num)   #output: 5.5
				
			

//: floor division (returns an integer)

				
					num = 11//2
print(num)   #output: 5
				
			

%: modulo (returns the remainder)

				
					num = 11%2
print(num)   #output: 1
				
			

**: exponentiation (raise the power of the left operand to the number of right operands)

				
					num = 5**2
print(num)   #output: 25
				
			

Comparison operators:

==: equal to

				
					num1 = 11
num2 = 11
print(num1==num2)   #output: True, since both variables contain the same values.
				
			

!=: not equal to

				
					num1 = 10
num2 = 11
print(num1!=num2)   #output: True, since both variables contain different values.
				
			

<: less than

				
					num1 = 11
num2 = 10
print(num1<num2)   #output: False
				
			

>: greater than

				
					num1 = 11
num2 = 10
print(num1>num2)   #output: True
				
			

<=: less than or equal to

				
					num1 = 11
num2 = 10
print(num1<=num2)   #output: False. Since neither num1 nor num2 is less than each and equal to the other 

				
			

>=: greater than or equal to

				
					num1 = 11
num2 = 10
print(num1>=num2)   #output: True. Since num1>num2
				
			

There are some more important binary operators in Python, which we will discuss in upcoming tutorials in detail.

Python Control Flow

Control flow refers to the order in which statements are executed in a program. In Python, control flow is managed through various control structures, such as conditional statements and loops, that allow the program to make decisions and repeat certain blocks of code.

Conditional statements, such as `if`, `elif`, and `else`, allow the program to execute certain blocks of code based on whether a certain condition is true or false. For example:

				
					if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")
				
			

In this example, the program will check whether the variable `x` is greater than zero, equal to zero, or less than zero, and execute the appropriate block of code based on the condition.

Loops, such as `for` and `while`, allow the program to repeat a block of code multiple times. For example:

				
					for i in range(10):
    print(i)
				
			

In this example, the program will repeat the block of code `print(i)` 10 times, with `i` taking on the values `0` through `9`.

Control flow also includes other flow control statements, such as `break`, `continue`, and `pass`, that allows the program to manipulate the order in which statements are executed. For example:

				
					while True:
    x = input("Enter a number: ")
    if x == "quit":
        break
    elif x == "skip":
        continue
    else:
        print(int(x) ** 2)
				
			

In this example, the program will ask the user to enter a number repeatedly, until the user enters the word “quit”. If the user enters the word “skip”, the program will go back to the start of the loop without executing the rest of the block of code. Otherwise, the program will square the entered number and print the result.

Let’s look at another example

				
					i = 0
while i < 10:
    print(i)
    i = i+1
				
			

In this example, the program will start to execute the number from 0 and keep incrementing the current value of i by 1 each time; until i == 10. Once the i == 10, the condition i < 10 will be false therefore loop will be broken.

Understanding control flow is essential for writing effective programs in Python, as it allows you to create programs that can make decisions and repeat certain blocks of code based on specific conditions.

Python Data Structure

A data structure in Python is a way of organizing and storing data in a specific format so that it can be accessed and manipulated efficiently. Python provides several built-in data structures, including:

Lists: Lists are mutable data structures that can store a collection of items of different data types. They are denoted by square brackets [] and can be accessed by their index.

				
					x = [1, 2, 3, 4, 5]
print(x)                 #output: [1, 2, 3, 4, 5]
				
			

#access the index number of element 2.

				
					x = [1, 2, 3, 4, 5]
print(x[2])              #output: 1
				
			

#change the element at index number 0.

				
					x = [1, 2, 3, 4, 5]
x[0] = 6
print(x)       #output: [6, 2, 3, 4, 5]
				
			

Tuples: Tuples are immutable data structures that can store a collection of items of different data types. They are denoted by parentheses () and can be accessed by their index.

				
					x = (1, 2, 3, 4, 5)
print(x)          #output: (1, 2, 3, 4, 5)
				
			

#return an error since the tuple is immutable

				
					x = (1, 2, 3, 4, 5)
x[0] = 6
print(x)

#output
TypeError: 'tuple' object does not support item assignment.
				
			

Sets: Sets are mutable data structures that can store a collection of unique items. They are denoted by curly braces {} and can be used to perform mathematical set operations such as union and intersection.

				
					x = {1, 2, 3, 4, 5}
print(x)           #output: {1, 2, 3, 4, 5}
				
			

#find the common element in both the set

				
					x = {1, 2, 3, 4, 5}
y = {1, 6, 7, 8, 9}
common_element = x.intersection(y)
print(common_element)                   #output: {1}
				
			

#add set y element in the set x

				
					x = {1, 2, 3, 4, 5}
y = {6, 7, 8, 9}
add_element = x.union(y)
print(add_element)          #output: {1, 2, 3, 4, 5, 6, 7, 8, 9}

				
			

Dictionaries: Dictionaries are mutable data structures that store key-value pairs. They are denoted by curly braces {} and can be accessed by their keys.

				
					x = {'Name':'John', 'Age':20, 'Class':'XII'}
print(x)                                                

#output:  {'Name':'John', 'Age':20, 'Class':'XII'} 
				
			

#updated the existing value with the new value

				
					x = {'Name':'John', 'Age':20, 'Class':'XII'}
x['Name'] = 'Smith'
print(x)

#output:  {'Name': 'Smith', 'Age': 20, 'Class': 'XII'}

				
			

#added new pair of key-value at the end

				
					x = {'Name':'John', 'Age':20, 'Class':'XII'}
x['City'] = 'NY'
print(x)

#output:  {'Name': 'John', 'Age': 20, 'Class': 'XII', 'City': 'NY'}
				
			

Strings: Strings are immutable data structures that can store a collection of characters or text. They are denoted by either single or double quotes and can be accessed by their index.

#single quote

				
					x = 'I like programming.'
print(x)                    #output: 'I like programming.'

				
			

#double quote

				
					x = "I like programming."
print(x)                  #output: "I like programming."
				
			

#accessed the element from index number 2 to 7

				
					x = "I like programming."
print(x[2:7])               #output: like
				
			

#return an error since String is immutable

				
					x = "I like programming."
x[0] = "You"
print(x)

#output:  TypeError: 'str' object does not support item assignment
				
			

Python def function

In Python, def is a keyword used to define a function. A function is a reusable block of code that performs a specific task. Defining a function allows you to encapsulate a block of code and give it a name, making it easier to call and use that code multiple times throughout your program.

Here is the basic syntax for defining a function in Python:

				
					def function_name(parameter1, parameter2, ...):
    # function body
    # do something with the parameters
    # return a value (optional)
				
			

In this example, function_name is the name of the function, parameter1, parameter2, etc. are the parameters that the function takes as inputs, and the function body contains the code that will be executed each time the function is called.

#created a function

				
					def my_function():
    print("I am a programmer.")
my_function()
				
			
				
					def add_numbers(x, y):
    result = x + y
    return result

sum = add_numbers(5, 7)
print(sum)
				
			

This will call the add_numbers function with the arguments 5 and 7, and store the result in the variable sum. The print statement will then output the value of sum, which in this case is 12.

Python lambda function

In Python, a lambda function is a small anonymous function that can be defined without a name using the lambda keyword. Lambda functions are often used as a quick way to define simple functions that can be used as arguments to higher-order functions such as map(), filter(), and reduce().

Syntax:

				
					lambda arguments: expression
				
			

In this syntax, arguments represent the function’s arguments (which are optional), and expression represents the result of the function.

				
					sum = lambda x, y: x + y
				
			

Once this lambda function has been defined, you can call it like this:

				
					result = sum(5, 7)
print(result)       #Output: 12
				
			

Lambda functions can also be used as arguments to higher-order functions. For example, here is an example of using a lambda function with the map() function to convert a list of integers to a list of their squares:

				
					numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x**2, numbers)
print(list(squares))                   # Output: [1, 4, 9, 16, 25]
				
			

In this example, the lambda function lambda x: x**2 is applied to each element of the numbers list using the map() function, resulting in a new list containing the squares of the original numbers.

Conclusion

In conclusion, Python is a high-level, interpreted, and general-purpose programming language that is easy to learn and use. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than in other languages. Python has a vast standard library and a large and active community of users and developers. It is suitable for various applications, including scripting, automation, data analysis, web development, machine learning, and scientific computing. Its versatility, simplicity, and extensive resources make it a popular language among developers of all levels.

Recent Articles