Want to create interactive content? It’s easy in Genially!
MODULE II: BASIC VARIABLES
Jared Carvente
Created on July 24, 2023
Start designing with a free template
Discover more than 1500 professional designs like these:
Transcript
MODULE II: BASIC VARIABLES
Welcome to this module!, click on start or check each section separately
Strings
What is a variable?
Numerical variables
Naming rules
Logical variables
Start
WHAT IS A VARIABLE?
In programming, a variable is a named storage location in a computer's memory that holds a value or data. It acts as a container to store and manipulate data during the execution of a program. Variables are fundamental to programming, as they allow programmers to work with and manipulate data dynamically. When you create a variable, you give it a unique name, which is used to access and refer to the data stored in that memory location. The value assigned to a variable can be changed or updated during the execution of the program, making variables very flexible and essential for writing dynamic and interactive code. Python is a dynamically-typed language, which means you don't need to explicitly specify the data type of a variable during declaration; Python infers it based on the value assigned to the variable. To create a variable in Python, you simply assign a value to a name using the equal sign (=) assignment operator. Here's the basic syntax: In Python, variables can be used in various ways, such as performing calculations, storing user inputs, holding results of operations, and more. They are essential components of Python programs, providing a way to store and manage data dynamically during program execution.
variable_name = value
STRINGS
You can create strings like this:
# Using single quotes str1 = 'Hello, World!' # Using double quotes str2 = "This is a string." # Using triple quotes for multi-line strings str3 = '''Python is a versatile programming language. You can do a lot of amazing things with it!''' # Using triple quotes for multi-line strings (alternative syntax) str4 = """Another way to create a multi-line string. Both single quotes and double quotes can be used for this."""
In Python, a string is a sequence of characters enclosed within either single quotes (' '), double quotes (" "). Strings are used to represent textual data and are one of the fundamental data types in Python. They allow you to store and manipulate textual information such as words, sentences, paragraphs, or any other sequence of characters.
BE CAREFUL! . Strings in Python are immutable, meaning once you create a string, you cannot change its individual characters. However, you can manipulate strings by creating new strings with the desired modifications.
PRINT FUNCTION
Look at these examples:
In Python, the print() function is used to display output to the console or standard output. It allows you to print text, variables, and other data to the screen, making it a fundamental tool for debugging, displaying results, and interacting with users in Python programs.
Syntax:
print(value1, value2, ..., sep=' ', end='\n')
STRINGS INDEXING
Strings in Python are sequences of characters enclosed within single quotes, double quotes, or triple quotes. The sequence nature of strings means that they are ordered collections of elements, where each element represents a single character. This ordering allows you to access individual characters within a string using indexing. In this example, we access the first character of 'Hello,Python' variable using index 0, and it returns 'H'. Similarly, indexing with 6 gives us the character 'P'. Python also allows negative indexing, which counts characters from the end of the string. So, index -1 represents the last character, -2 represents the second-to-last character, and so on. In the second example, using -1 returns 'n' at the end of the string, while -2 returns the character 'o'. Based on the previous explanation, run this code , and analyze what happens.
STRINGS SLICING
You can use string slicing to access a range of characters within a string. Slicing allows you to specify a start index and an end index (exclusive), separating them with a colon ':'. The result will be a new string that includes characters from the start index up to, but not including, the end index. In the example shown in the previous slide, my_string[0:5] returns a new string that includes characters from index 0 up to (but not including) index 5, giving us 'Hello'. In the second example, my_string[6:] includes all characters from index 6 to the end of the string, resulting in 'Python'. Finally, my_string[:5] starts from the beginning of the string and goes up to (but not including) index 5, producing 'Hello'. Keep in mind that strings are immutable in Python, so you can't change individual characters using indexing or slicing. If you need to modify a string, you'll have to create a new one with the desired changes.
Run this code, analyze what is happening and then, write your preferred motto and get a part of it using slicing.
ENTER VALUES TO A VARIABLE: THE INPUT FUNCTION
Try these examples clicking on the run icon ,you can modify the code as you like for further practice
The input() function in Python is used to receive input from the user during the execution of a program. It allows the program to pause and wait for the user to enter some data, which can then be stored in a variable or used for further processing within the program. The input() function treats all user input as strings, so if you need to perform numerical operations with the input, you may need to convert the data to the appropriate data type.
Syntax:
user_input = input(prompt)
STRING MANIPULATION: METHODS
In Python, a string is represented as a class, so its methods are built-in functions that allow you to perform various operations and manipulations on strings. These methods are part of the string class, and you can access them using dot notation on a string object. Since strings are immutable in Python, most string methods return a new modified string rather than changing the original one. The most common methods are shown as follows:
To use these methods follow this syntax:
new_string= old_string.method()
Upper and lower case
Length of the string
Do you want to learn more methods? Click on this link and scroll down to find a section called "Built-in String Methods" : https://www.tutorialspoint.com/python/python_strings.htm
Ask for the string´s features
Concatenation and repetition
NUMERICAL VARIABLES
In Python, numerical variables are used to store numeric data, such as integers, floating-point numbers, or complex numbers. Python provides various data types to handle numerical values, and they are essential for performing mathematical operations, calculations, and data manipulation tasks. Here are the common numerical data types in Python:
- Integer (int): Integers represent whole numbers without any decimal points. For example: 1, 5, -10, 100, etc. Python automatically detects the data type if you assign a number without a decimal point to a variable.
- Floating-point number (float): Floating-point numbers represent numbers with decimal points. For example: 3.14, -0.5, 10.75, etc.
- Complex number (complex): Complex numbers consist of a real part and an imaginary part. They are represented with the format real + imagj, where real and imag are floating-point numbers. For example: 3 + 2j, 1.5 - 4j, etc.
#Integer variable integer_number=25 print(integer_number) # Output: 25 #Float variable floating_number=13.7 print(integer_number) # Output: 13.7 #Complex variable complex_number=2.6+ 6.0j print(integer_number) # Output: (2.6+6.0j)
OPERATORS
Operators are symbols or special characters used to perform various operations on data. Operators allow you to manipulate variables, perform arithmetic, compare values, assign values, and more.
Let´s start with the first two types of operators, the following ones will be explained later:
SYNTAX
variable1 OPERATOR variable 2
Assignment operators
Arithmetical operators
gives a...
result
Order of operations
BUILT-IN ARITHMETIC FUNCTIONS
Python provides various built-in functions to perform common numerical operations. Run this code, analyze it carefully . Using numerical variables, input function, mathematical operators and functions, code a mathematical formula which yields a result based on user-introduced values. Display the result using the print function to verify that the formula was written carefully .
ARITHMETICAL OPERATIONS
Look at these examples:
In Python, the print() function is used to display output to the console or standard output. It allows you to print text, variables, and other data to the screen, making it a fundamental tool for debugging, displaying results, and interacting with users in Python programs.
Syntax:
print(value1, value2, ..., sep=' ', end='\n')
BE CAREFUL!: VARIABLE NAMING RULES
There are certain rules which should be taken care while naming a Python variable:
- A variable name must start with a letter or the underscore character
- A variable name cannot start with a number or any special character like $, (, * % etc.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Python variable names are case-sensitive which means Name and NAME are two different variables in Python.
- Python reserved keywords cannot be used to name a variable, for example , the words if, True and int cannot be used as a variable name.
CONGRATULATIONS!
Good job!, keep doing your best and complete the review quizz.
Assignment operators
Assignment operators are used to assign values to variables.
- =: Simple assignment
- +=: Add and assign
- -=: Subtract and assign
- *=: Multiply and assign
- /=: Divide and assign
- //=: Floor divide and assign
- %=: Modulus and assign
- **=: Exponentiation and assign
len(string)
It is a function that returns the length of the string
my_string='Oxford' print( len(my_string) ) #what you will see in the output 6 #other example print(len('hello world')) #what you will see in the output 11 #as you can see, blank spaces are also included for counting
Order of the operations
Python also follows the standard order of operations (PEMDAS/BODMAS), where operations inside parentheses are performed first, followed by exponents, multiplication, division, floor division, and finally, addition and subtraction. Watch this video to learn more about this topic:
upper() and lower()
Convert all characters in a string to either uppercase or lowercase.
#UPPER CASE message = "hello, world!" print(message.upper()) # Output: "HELLO, WORLD!" #LOWER CASE message = "Hello, World!" print(message.lower()) # Output: "hello, world!"
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod.
Check for features
You can get many characteristics of the strings using methods that will return a false or true statement depending the composition of the string, for example:
startswith(prefix): Checks if a string starts with a specified prefix and indicates if it is true or false.
message = "Hello, World!" print(message.startswith("Hello")) # Output: True print(message.startswith("world")) # Output: False
Other useful resources when using print function
Click on the topics to learn more about them
- Raw strings
- F-strings
Arithmetic operators
Arithmetic operators are used for mathematical computations.
- +: Addition
- -: Subtraction
- *: Multiplication
- /: Division
- //: Floor Division (division with the result rounded down to the nearest integer)
- %: Modulus (remainder after division)
- **: Exponentiation (raise a number to a power)
Concatenation and repetition of strings
+ and * operators
In Python, it is common to concatenate two strings to get a new one, that is possible with the '+' operator. Likewise, sometimes it is useful to get a string that contains another string repeated n-times, that is possible using the '*' operator. See the next examples:
a='Hello'b='World' print(a+b) #Output: HelloWorld print (a*2) #Output: HelloHello
Other useful resources when using print function
Click on the topics to learn more about them
- Raw strings
- F-strings