Basic syntax

Python Mastery: From Beginner to Expert - Sykalo Eugene 2023

Basic syntax
Basics of Python

Introduction to Python syntax

Python is a high-level, object-oriented programming language that is easy to learn and use. Its syntax is designed to be intuitive and readable, making it a popular choice for both beginners and experienced programmers.

The syntax of Python is based on the use of whitespace and indentation to delimit code blocks. This is different from many other programming languages, which use braces or keywords to define blocks of code. The use of whitespace and indentation in Python makes the code more readable and easier to understand.

In addition to its unique syntax, Python also has a large standard library that provides a wide range of tools and modules for developers. This library includes modules for working with databases, web development, scientific computing, and much more.

One of the key features of Python syntax is its use of dynamic typing. This means that variables do not need to be explicitly declared with a data type, as the type is inferred at runtime. This makes the language more flexible and easier to use, as developers do not need to worry about type mismatches or conversions.

Variables and Data Types in Python

Variables are used in Python to store data values. Unlike other programming languages, Python does not require you to explicitly declare the data type of a variable. The data type is inferred automatically based on the value assigned to the variable.

Basic Data Types

Python has several built-in data types. The most commonly used data types include:

  • Integers: Integers are whole numbers, such as 1, 2, 3, and so on. They can be positive, negative, or zero.
  • Floats: Floats are numbers with a decimal point, such as 1.23, 3.14, and so on.
  • Strings: Strings are sequences of characters, such as "hello", "world", and so on.
  • Booleans: Booleans are values that can be either True or False.

Type Conversion

In Python, you can convert one data type to another using type conversion. This is useful when you need to change the data type of a variable for a specific operation. The most commonly used type conversion functions include:

  • int(): Converts a value to an integer.
  • float(): Converts a value to a float.
  • str(): Converts a value to a string.
  • bool(): Converts a value to a boolean.

Variables and Assignments

In Python, you can assign a value to a variable using the equals sign (=). For example:

x = 5

This assigns the value 5 to the variable x. You can also assign multiple values to multiple variables in a single line, like this:

x, y, z = 1, 2, 3

This assigns the value 1 to x, the value 2 to y, and the value 3 to z.

Variable Names

In Python, variable names can contain letters, numbers, and underscores, but they cannot start with a number. Variable names are case-sensitive, which means that "myVariable" and "myvariable" are two different variables.

Operators in Python

Operators are used in Python to perform operations on variables and values. There are several types of operators in Python, including arithmetic operators, comparison operators, logical operators, and bitwise operators.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations, such as addition, subtraction, multiplication, and division. The most commonly used arithmetic operators in Python include:

  • +: Addition
  • ****: Subtraction
  • \: Multiplication
  • /: Division
  • %: Modulus (returns the remainder of a division)
  • //: Floor division (returns the quotient of a division, rounded down to the nearest integer)
  • \\: Exponentiation (raises a number to a power)

Comparison Operators

Comparison operators are used to compare two values and return a Boolean value (True or False). The most commonly used comparison operators in Python include:

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to

Logical Operators

Logical operators are used to combine Boolean values and return a Boolean value as a result. The most commonly used logical operators in Python include:

  • and: Returns True if both operands are True
  • or: Returns True if either operand is True
  • not: Returns the opposite Boolean value of the operand

Bitwise Operators

Bitwise operators are used to perform bitwise operations on binary numbers. The most commonly used bitwise operators in Python include:

  • &: Bitwise AND
  • |: Bitwise OR
  • ^: Bitwise XOR
  • ~: Bitwise NOT
  • <<: Bitwise left shift
  • >>: Bitwise right shift

Understanding operators is essential for programming in Python. By using operators, you can perform a wide range of operations on variables and values in your programs.

Control statements (if, elif, else)

In Python, control statements are used to control the flow of execution of a program. The most commonly used control statements in Python include if, elif, and else.

if statement

The if statement is used to execute a block of code if a condition is true. The basic syntax of an if statement is as follows:

if condition:
 # code to be executed if condition is true

For example:

x = 5

if x > 0:
 print("x is positive")

In this example, if the value of x is greater than 0, the program will print the message "x is positive".

else statement

The else statement is used to execute a block of code if the condition in an if statement is false. The basic syntax of an else statement is as follows:

if condition:
 # code to be executed if condition is true
else:
 # code to be executed if condition is false

For example:

x = -5

if x > 0:
 print("x is positive")
else:
 print("x is not positive")

In this example, if the value of x is greater than 0, the program will print the message "x is positive". If the value of x is not greater than 0, the program will print the message "x is not positive".

elif statement

The elif statement is used to check for multiple conditions. The basic syntax of an elif statement is as follows:

if condition1:
 # code to be executed if condition1 is true
elif condition2:
 # code to be executed if condition2 is true
else:
 # code to be executed if all conditions are false

For example:

x = 0

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

In this example, if the value of x is greater than 0, the program will print the message "x is positive". If the value of x is less than 0, the program will print the message "x is negative". If the value of x is equal to 0, the program will print the message "x is zero".

Control statements are essential for programming in Python. By using control statements, you can control the flow of execution of your program and make it more flexible and powerful.

Loops (for loop and while loop)

Loops are used in Python to execute a block of code repeatedly. There are two types of loops in Python: the for loop and the while loop.

for loop

The for loop is used to iterate over a sequence of values. The basic syntax of a for loop is as follows:

for variable in sequence:
 # code to be executed for each value in sequence

For example:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
 print(fruit)

In this example, the for loop iterates over the list of fruits and prints each fruit.

while loop

The while loop is used to execute a block of code repeatedly as long as a certain condition is true. The basic syntax of a while loop is as follows:

while condition:
 # code to be executed as long as condition is true

For example:

i = 1

while i <= 5:
 print(i)
 i += 1

In this example, the while loop prints the values of i from 1 to 5.

break and continue statements

In Python, the break statement is used to exit a loop prematurely. The continue statement is used to skip over an iteration of a loop. For example:

i = 0

while i < 10:
 i += 1
 if i == 5:
 continue
 print(i)
 if i == 8:
 break

In this example, the loop prints the values of i from 1 to 4, skips over the value of 5, prints the values of i from 6 to 8, and then exits the loop.

Loops are essential for programming in Python. By using loops, you can execute a block of code repeatedly and make your programs more flexible and powerful.

Functions in Python

Functions are a key concept in Python programming. A function is a block of code that performs a specific task. Functions can be used to break up a large program into smaller, more manageable pieces, making it easier to read and maintain.

Defining Functions

To define a function in Python, you use the def keyword followed by the name of the function, a set of parentheses, and a colon. For example:

def greet(name):
 print("Hello, " + name + "!")

This defines a function called greet that takes one argument, name. When the function is called, it will print a greeting message to the console.

Calling Functions

To call a function in Python, you simply write the name of the function followed by a set of parentheses containing any arguments that the function requires. For example:

greet("John")

This calls the greet function and passes in the argument "John". The function will then print the message "Hello, John!" to the console.

Returning Values

Functions can also return values back to the calling code. To do this, you use the return keyword followed by the value that you want to return. For example:

def add_numbers(x, y):
 return x + y

This defines a function called add_numbers that takes two arguments, x and y, and returns their sum. To call this function and get the result, you would write:

result = add_numbers(3, 5)
print(result)

This would call the add_numbers function with the arguments 3 and 5, and store the result in the result variable. The program would then print the value 8 to the console.

Default Arguments

In Python, you can define default values for function arguments. This means that if an argument is not provided when the function is called, it will default to a specified value. To define a default argument, you simply provide a value for the argument in the function definition. For example:

def greet(name="World"):
 print("Hello, " + name + "!")

This defines a function called greet that takes one argument, name, with a default value of "World". If the function is called without an argument, it will use the default value. For example:

greet()

This would call the greet function with the default argument, and print the message "Hello, World!" to the console.

Variable Arguments

In Python, you can also define functions that take a variable number of arguments. To do this, you use the *args syntax in the function definition. For example:

def add_numbers(*args):
 result = 0
 for num in args:
 result += num
 return result

This defines a function called add_numbers that takes any number of arguments, and returns their sum. To call this function with multiple arguments, you would write:

result = add_numbers(1, 2, 3, 4, 5)
print(result)

This would call the add_numbers function with the arguments 1, 2, 3, 4, and 5, and store the result in the result variable. The program would then print the value 15 to the console.

Functions are an essential part of programming in Python. By using functions, you can break up a large program into smaller, more manageable pieces, making it easier to read and maintain.