DEV Community

Cover image for Python Basics, Operators and Conditional Statements
Young Odhiambo
Young Odhiambo

Posted on

Python Basics, Operators and Conditional Statements

Introduction

Python is a high-level programming language with a simple and readable syntax. It uses an intuitive syntax that closely resembles English, making it the perfect starting point for beginners.

Common Uses

Python is a versatile, high-level programming language used widely for artificial intelligence, web development, data analysis, and task automation:

  1. Web Development: Building server-side applications with frameworks like Django and FastAPI.
  2. Data Science & Machine Learning: Processing numbers and training models using Pandas, NumPy, and PyTorch.
  3. Automation: Writing simple scripts to handle repetitive daily file management or data entry tasks

Getting Started

Print()

print() is a built-in function that outputs text or variables to the screen

print("Hello world")
Enter fullscreen mode Exit fullscreen mode

Output

Hello world
Enter fullscreen mode Exit fullscreen mode

Comments in Python

Comments are lines in a program that are not executed by the interpreter. They are used to explain code and make it easier to read and understand.

# Single line comment

"""
This is a 
multi- line comment
or doctrines

"""
Enter fullscreen mode Exit fullscreen mode
  • # : Denotes a single-line comment.​
  • """ """ or ''' ''' : Triple quotes are used for multi-line comments or docstrings.

Variables

Variables are names that store data in memory. They are created when a value is assigned, with the name referencing that value. It can be text, integer or a float.

# create variables
name = 'Mosses Njuguna'
age = 25
city = 'Nairobi'

# use the variable in print
print(name)
print(age)
print(city)
Enter fullscreen mode Exit fullscreen mode

Output

Mosses Njuguna
25
Nairobi
Enter fullscreen mode Exit fullscreen mode

Data Types in Python

Data types define the kind of data a variable can hold and determine the operations that can be performed on it.

Example of data types in python are:

1. string (str)

  • Strings are surrounded by either single quatation marks or double quatation.
name = 'Fatuma Waridi'
city = 'Nairobi'
Enter fullscreen mode Exit fullscreen mode

2. integer (int)

  • Whole numbers, no quattion
age = 22
score = 87
Enter fullscreen mode Exit fullscreen mode

3. float

  • Float are numbers containing a decimal point, also they are not put inside quatations.
height = 1.68
balance = 15750.50
Enter fullscreen mode Exit fullscreen mode

4. Boleans (bol)

  • These are True of False values. The are also not put inside the quatations and the first letters must be capital.
is_student = True
has_id_card = False
Enter fullscreen mode Exit fullscreen mode

Type Casting in Python

Type casting is the process of changing a variable from one data type to another in Python.

# converting string to integer
text_number = '42'
real_number = int(text_number)
print(real_number + 8)

# converting number to a string
age = 24
age_str = str(age)
print(age_str)

# convert a string to a float
txt_price = '99.99'
price = float(txt_price)
print(price)
Enter fullscreen mode Exit fullscreen mode

F-String

F-strings (formatted string literals) allow you to embed variables and expressions directly inside strings.

name = 'Mosses'
age = 29
city = 'Nairobi'

print(f'{name} is {age} years old and lives in {city}')
Enter fullscreen mode Exit fullscreen mode

Input()

The input() function is used to take input from the user. By default, the value entered by the user is stored as a string.

# ask the user for their name

name = input('what is your name')
print(f'Hello {name}')
Enter fullscreen mode Exit fullscreen mode

Python Operators

Operators in Python are symbols used to perform operations on values and variables, such as calculations, comparisons, and logical checks.

1. Arithmetic Operators

These are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.

a = 15
b = 4

print("Addition:      ", a + b)
print("Subtraction:   ", a - b)
print("Multiplication:", a * b)
print("Division:      ", a / b)
print("Floor division:", a // b)
print("Modulus:       ", a % b)
print("Power:         ", a ** b)

Enter fullscreen mode Exit fullscreen mode

Output

Addition:       19
Subtraction:    11
Multiplication: 60
Division:       3.75
Floor division: 3
Modulus:        3
Power:          50625
Enter fullscreen mode Exit fullscreen mode

2. Comparison Operators

These are used to compare two values. They return a Boolean value either True or False depending on whether the comparison is correct.

a = 10
b = 20

print(a == b)   # False, because 10 is not equal to 20
print(a != b)   # True, because 10 is not equal to 20
print(a > b)    # False, 10 is not greater than 20
print(a < b)    # True, 10 is less than 20
print(a >= b)   # False, 10 is not greater than or equal to 20
print(a <= b)   # True, 10 is less than or equal to 20
Enter fullscreen mode Exit fullscreen mode

Output

False
True
False
True
False
True
Enter fullscreen mode Exit fullscreen mode

3. Logical Operators

It perform Logical AND, Logical OR and Logical NOT operations. It is used to combine conditional statements.
Types of logical operators are: AND, OR, NOT​.

a = True
b = False
print(a and b) 
print(a or b) 
print(not a)
Enter fullscreen mode Exit fullscreen mode

Output

False
True
False
Enter fullscreen mode Exit fullscreen mode

4. Membership Operators

Used to test if a sequence (like a string, list, or tuple) is present in an object.
in : Returns True if a sequence with the specified value is present in the object (e.g., 'a' in 'apple' → True).

not in : Returns True if a sequence with the specified value is not present in the object.

Python If Else Statements - Conditional Statements

If-Else statements are conditional statements used to perform decision-making in a program. They allow different blocks of code to execute based on whether a condition is True or False.

1. If Statement

The if statement is used to execute a block of code only when a given condition is True. If the condition is False, the code inside the if block is skipped.

age = 20

if age >= 18:
    print('Your an adult') # runs because the condition is True
Enter fullscreen mode Exit fullscreen mode

2. if-Else Statement

The if-else statement is used to execute one block of code when a condition is True and another block when the condition is False.

age = 16

if age >= 18:
    print("You're eligible to vote")

else:
    print("You're not eligible to vote")  # runs the esle statement because the condition is False
Enter fullscreen mode Exit fullscreen mode

3. Nested If-Else Statement

A nested if-else statement is an if-else structure placed inside another if or else block. It is used to check multiple conditions step by step and execute code based on those conditions.

age = 20
citizenship = 'Kenyan'

if citizenship == 'Kenyan':
    print('Can own a kenyan ID')

    if age >= 18:
        print("You're eligible to have an ID")
    else:
        print("You've not attained the minimum age to have an ID")

else:
    print("You can't own a Kenyan ID")
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding Python basics, variables, data types, input/output, operators, and conditional statements provides a strong foundation for programming. These concepts make it possible to write programs that store and process information, perform calculations, make decisions, and respond to user input.

Top comments (0)