Day 2: Python syntax, variables, and data types
Basic Python syntax: indentation, comments, and statements:
Python is a popular programming language known for its simplicity and ease of use. In this guide, we will cover some basic Python syntax, including indentation, comments, and statements.
Indentation
Unlike many other programming languages, Python uses indentation to indicate the block of code. This means that the number of spaces or tabs used to indent a line of code determines which statements are grouped together. For example, a block of code that is indented four spaces from the left margin is considered to be part of the same block.
Indentation is significant in Python because it helps to make the code more readable and consistent. It also ensures that the code is properly structured and that the logic is easy to follow.
Comments
Comments are used in Python to provide documentation and make the code more readable. Single-line comments start with the hash symbol (#), and multi-line comments are enclosed in triple quotes (”’ or “””).
Here’s an example of a single-line comment:
# This is a comment
And here’s an example of a multi-line comment:
''' This is a
multi-line comment '''
Statements
Statements are used in Python to perform operations and control the flow of a program. A statement is a complete unit of execution that can be a simple assignment, a function call, a loop, or a conditional statement.
Here’s an example of a simple assignment statement:
x = 5
And here’s an example of a conditional statement:
if x < 10:
print("x is less than 10")
else:
print("x is greater than or equal to 10")
In this example, the if statement checks whether x is less than 10, and the else statement executes if the condition is false.
Statements are executed in order, from top to bottom, unless control statements like if, while, or for are used to alter the flow of the program.
Congratulations! You now know some basic Python syntax, including indentation, comments, and statements. Happy coding!
Variables: assignment, naming conventions, and scope:
In Python, variables are used to store data values. In this guide, we will cover how to assign values to variables, follow Python’s naming conventions for variables and constants, and understand variable scope, global variables, and local variables.
Assigning values to variables and understanding their mutable nature
In Python, values can be assigned to variables using the assignment operator (=). For example:
x = 5
This assigns the value 5 to the variable x. Variables in Python are mutable, which means that their values can be changed during the program’s execution. For example:
x = 5
x = 10
This assigns the value 5 to x, and then changes it to 10 on the next line.
Following Python’s naming conventions for variables and constants
Python has specific naming conventions for variables and constants to make the code more readable and maintainable. Here are some general guidelines for naming variables and constants:
- Use lowercase letters for variables and uppercase letters for constants.
- Separate words in variable and constant names with underscores.
- Use descriptive names that reflect the purpose of the variable or constant.
For example:
# Variables
my_variable = 5
user_name = "John Smith"
# Constants
MAX_VALUE = 100
PI = 3.14159
Understanding variable scope, global variables, and local variables
In Python, variables have different scopes, which determines where in the code they can be accessed. A variable’s scope is determined by where it is defined in the code.
Global variables are variables that are defined outside of any function or class. They can be accessed from anywhere in the code, including inside functions and classes. Here’s an example of a global variable:
x = 5
def my_function():
print(x)
my_function() # Output: 5
Local variables are variables that are defined inside a function or class. They can only be accessed from within that function or class. Here’s an example of a local variable:
def my_function():
x = 5
print(x)
my_function() # Output: 5
In this example, x is a local variable that is only accessible from within the my_function() function.
It’s important to note that global variables can be accessed from within a function, but if you want to modify the value of a global variable from within a function, you need to use the global keyword. For example:
x = 5
def my_function():
global x
x = 10
my_function()
print(x) # Output: 10
In this example, we use the global keyword to modify the value of the global variable x from within the my_function() function.
Congratulations! You now know how to assign values to variables, follow Python’s naming conventions for variables and constants, and understand variable scope, global variables, and local variables. Happy coding!
Data types: integers, floats, strings, and booleans:
In Python, there are several built-in data types for working with different kinds of data. In this guide, we will cover how to work with integers and floats for numerical operations, manipulate strings and use common string methods, and use booleans and logical operators for decision-making.
Integers and Floats
Integers and floats are used for numerical operations in Python. Integers are whole numbers, while floats are decimal numbers. Here are some examples:
x = 5 # integer
y = 2.5 # float
You can perform basic mathematical operations with integers and floats, such as addition, subtraction, multiplication, and division. For example:
a = 5
b = 2
c = a + b
d = a - b
e = a * b
f = a / b
print(c, d, e, f) # Output: 7 3 10 2.5
Strings
Strings are used for working with text in Python. They are created by enclosing text in quotes, either single quotes or double quotes. Here are some examples:
name = 'John'
greeting = "Hello, world!"
You can manipulate strings using various string methods, such as upper(), lower(), strip(), and split(). For example:
text = " hello world! "
print(text.upper()) # Output: " HELLO WORLD! "
print(text.lower()) # Output: " hello world! "
print(text.strip()) # Output: "hello world!"
print(text.split()) # Output: ["hello", "world!"]
Booleans and Logical Operators
Booleans are used for decision-making in Python. They have two possible values: True and False. Here are some examples:
is_sunny = True is_raining = False
You can use logical operators such as and, or, and not to combine and manipulate booleans. For example:
is_sunny = True
is_warm = True
if is_sunny and is_warm: print("It's a great day!")
else: print("It's not a great day.")
In this example, the and operator is used to combine two booleans (is_sunny and is_warm) into a single boolean expression. The if statement then uses the boolean expression to decide what to print.
Congratulations! You now know how to work with integers and floats for numerical operations, manipulate strings and use common string methods, and use booleans and logical operators for decision-making. Happy coding!
Type conversion and type checking:
In Python, you can convert between different data types using built-in functions, perform type checking with the type() function and isinstance() method, and understand implicit and explicit type conversion.
Converting between different data types using built-in functions
Python provides several built-in functions to convert between different data types. Here are some common conversion functions:
- int(): converts a value to an integer
- float(): converts a value to a floating-point number
- str(): converts a value to a string
- bool(): converts a value to a boolean
Here are some examples:
x = 5
y = 2.5
z = "10"
# convert integer to float
a = float(x)
print(a) # Output: 5.0
# convert float to integer
b = int(y)
print(b) # Output: 2
# convert string to integer
c = int(z)
print(c) # Output: 10
# convert integer to boolean
d = bool(x)
print(d) # Output: True
Performing type checking with the type() function and isinstance() method
You can use the type() function to determine the data type of a value. Here’s an example:
x = 5
y = 2.5
z = "hello"
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'str'>
You can also use the isinstance() method to check whether a value is of a certain data type. Here’s an example:
x = 5
y = 2.5
z = "hello"
print(isinstance(x, int)) # Output: True
print(isinstance(y, float)) # Output: True
print(isinstance(z, str)) # Output: True
Understanding implicit and explicit type conversion in Python
In Python, you can perform both implicit and explicit type conversion. Implicit type conversion is performed automatically by Python when necessary, while explicit type conversion is performed using the built-in conversion functions.
Here’s an example of implicit type conversion:
x = 5
y = 2.5
z = x + y
print(z) # Output: 7.5
In this example, Python automatically converts x from an integer to a float to perform the addition with y.
Here’s an example of explicit type conversion:
<code>x = "5"
y = int(x)
print(y) # Output: 5</code>
In this example, we use the int() function to explicitly convert the string “5” to an integer.
Congratulations! You now know how to convert between different data types using built-in functions, perform type checking with the type() function and isinstance() method, and understand implicit and explicit type conversion in Python. Happy coding!
On Day 2, students will learn the fundamentals of Python syntax, variables, and data types. They will explore Python’s unique indentation-based syntax, learn how to use comments and statements effectively, and understand the process of assigning values to variables. Students will also become familiar with Python’s various data types, such as integers, floats, strings, and booleans, and learn how to perform type conversion and type checking. By the end of the day, students should have a strong foundation in Python programming and be ready to tackle more advanced concepts in the curriculum.