Comput 101

studied byStudied by 0 people
0.0(0)
Get a hint
Hint

Relational Operators (Comparison Operators)

1 / 31

encourage image

There's no tags or description

Looks like no one added any tags here yet for you.

32 Terms

1

Relational Operators (Comparison Operators)

  • These operators are used to compare values and return a Boolean result (True or False). They are commonly used in conditional statements (if, elif, else) and loops (while, for) to make decisions based on comparisons. [1-3]

  • Examples:== (equal to)

  • != (not equal to)

  • > (greater than)

  • < (less than)

  • >= (greater than or equal to)

  • <= (less than or equal to)

New cards
2

Arithmetic Operators

These operators perform mathematical operations on numeric operands.

  • Examples:+ (addition)

  • - (subtraction)

  • * (multiplication)

  • / (division)

  • % (modulus, gives the remainder of a division)

  • ** (exponentiation)

  • // (floor division, gives the integer quotient of a division)

New cards
3

Assignment Operators

These operators assign values to variables

  • Examples:= (assignment)

  • += (add and assign)

  • -= (subtract and assign)

  • *= (multiply and assign)

  • /= (divide and assign)

  • %= (modulus and assign)

  • **= (exponentiation and assign)

New cards
4

range() Function

The range() function in Python is a built-in function that generates a sequence of numbers. It's frequently used in conjunction with for loops to control the number of times the loop iterates. The sources highlight the use of range() with for loops for numerical iteration.

New cards
5

Syntax of the range() Function

  • Start (optional): This argument defines the starting value of the generated sequence. It's important to note that the start value is inclusive, meaning the sequence will include this value. If you omit the start argument, the function defaults to a starting value of 0.

  • stop (required): This argument sets the ending value of the sequence. Unlike the start value, the stop value is exclusive, meaning the sequence will not include this value. The range() function will generate numbers up to, but not including, the stop value.

  • step (optional): This argument determines the interval or difference between each number in the sequence. If you don't specify a step value, the function defaults to a step of 1

New cards
6

Examples of the range() Function (from the sources)

  • range(5): This will generate the sequence: 0, 1, 2, 3, 4. Notice that the sequence starts at 0 (the default start value) and goes up to, but doesn't include, 5.

  • range(1, 6): This will generate the sequence: 1, 2, 3, 4, 5. In this case, we've specified a start value of 1, so the sequence begins at 1 and continues up to (but doesn't include) 6.

  • range(2, 11, 2): This will generate the sequence: 2, 4, 6, 8, 10. Here, we've set a step value of 2, resulting in a sequence of even numbers.

New cards
7

For Loops in Python

For Loops are a fundamental control flow mechanism in Python that enable you to iterate over a sequence of elements and execute a block of code for each element in that sequence. The sources emphasize that For Loops are particularly well-suited for situations where you know the number of iterations in advance, or when you need to process each item in a collection of items.

New cards
8

Syntax of For Loops

  • for keyword: This keyword signals the start of the for loop.

  • item: This is a variable that takes on the value of the current element from the sequence being iterated over. You can choose any valid variable name here.

  • in keyword: This keyword connects the item variable with the sequence.

  • sequence: This represents the collection of items that you want to iterate through. Common examples include lists, tuples, strings, and ranges generated by the range() function.

  • :: The colon marks the end of the for loop header.

  • Indented Code Block: The block of code that you want to execute for each item in the sequence must be indented consistently. Python uses indentation to define blocks of code.

New cards
9

How For Loops Work

  • Initialization: At the beginning of the loop, the item variable is assigned the value of the first element in the sequence.

  • Code Execution: The code block within the loop is then executed with the item variable holding the value of the current element.

  • Iteration: After the code block executes, the item variable automatically takes on the value of the next element in the sequence.

  • Loop Continuation: Steps 2 and 3 repeat until all elements in the sequence have been processed

New cards
10

Examples of For Loops

  • Iterating through a list:

  • numbers = [1-5]

  • for num in numbers:

  •    print(num)

  • This loop will print each number in the numbers list.

  • Iterating through a String:

  • message = "Hello"

  • for letter in message:

  •    print(letter)

  • This loop will print each character in the message string.

  • Using range() for Numerical Iteration:

  • for i in range(1, 6):

  •    print(i)

  • This loop uses the range(1, 6) function to generate a sequence of numbers from 1 to 5 (6 is exclusive). The loop iterates over this sequence, printing each number.

New cards
11

Key Advantages of For Loops

  • Readability and Clarity: For Loops often lead to more readable and understandable code, especially when dealing with sequences, compared to using while loops for the same tasks.

  • Conciseness: For Loops can express iteration over a sequence in a more concise manner.

  • Automatic Iteration: For Loops handle the iteration process automatically, eliminating the need to manually manage loop counters or conditions, which can help prevent errors like infinite loops

New cards
12

When to Choose a For Loop

  • Iterating over a sequence (list, tuple, string, range) where you want to process each element.

  • Situations where the number of iterations is known in advance.

  • When you want to avoid the risk of creating accidental infinite loops.

New cards
13

While Loops in Python - purpose

  • while loops are particularly useful when you want to repeatedly execute a block of code as long as a specific condition remains True. This is in contrast to for loops, which are often preferred when you know the number of iterations in advance.

New cards
14

While Loops Syntax and Structure

  • while condition:

  •    # Code to be executed while the condition is true

  • Let's break this down:

  • condition: This is a Boolean expression that determines whether the loop continues to execute. Before each iteration of the loop, Python evaluates this condition. If it evaluates to True, the code block within the loop is executed. If it evaluates to False, the loop terminates, and the program continues with the code that comes after the loop.

  • Code to be executed: This indented block of code represents the actions that will be performed repeatedly as long as the condition remains True.

New cards
15

Example of an Infinite Loop

  • a = 1

  • while a <= 10:

  •    print(a)

  • In this example, the variable a is initialized to 1. The while loop's condition (a <= 10) is True because 1 is less than or equal to 10. However, there's no code within the loop's body to modify the value of a. As a result, the condition will always remain True, leading to an infinite loop that prints the value 1 endlessly. The sources point out that you would typically need to interrupt the execution (e.g., using Ctrl+C) to stop such a loop.

New cards
16

Avoiding Infinite Loops:

  • To prevent infinite loops, you need to include code within the loop that updates the variable(s) used in the condition.

  • Example (from source):num = 1

  • while num <= 20:

  •    print(num)

  •    num += 1

  • Here, the loop is designed to print numbers from 1 to 20. The line num += 1 is crucial. It increments the value of num by 1 in each iteration. Eventually, num will become 21, causing the condition num <= 20 to evaluate to False, thus terminating the loop.

  • Illustrative Example (from source):

  • concat_str = ""  # Initialize an empty string

  • usr_input = input("Enter a string (or 'quit' to exit): ")

  • while usr_input != "quit":

  •    concat_str += usr_input # Concatenate the user's input to the existing string

  •    usr_input = input("Enter a string (or 'quit' to exit): ")

  • print("Concatenated string:", concat_str)

  • In this example, the loop continues to prompt the user for input until the user enters the string "quit". Once "quit" is entered, the condition usr_input != "quit" becomes False, and the loop ends.

New cards
17

Purpose of Relational Operators

  • relational operators are used to compare values in Python. They are essential for creating conditions in conditional statements (like if, elif, and else) and in loops, allowing you to control the flow of your program's execution based on the outcome of these comparisons.

  • The key thing to remember about relational operators is that they always return a Boolean value, which is either True or False. This Boolean result indicates whether the comparison made by the operator holds true or not

New cards
18

int(...):

  • The int() function attempts to convert a value into an integer.

  • Converting from Strings: It can convert strings representing whole numbers into their corresponding integer values. For example, int("25") would return the integer 25.

  • Converting from Floats: When converting from a float to an integer using int(), the decimal part of the float is truncated. It does not round the number. For instance, int(3.75) would result in 3.

  • Limitations: If you try to convert a string that doesn't represent a whole number (e.g., "3.14" or "hello") using int(), it will raise a ValueError.

New cards
19

float(...)

  • The float() function converts a value to a floating-point number.

  • Converting from Strings: It can convert strings that represent numbers (including those with decimal points) into their corresponding float values. For example, float("3.5") would return the float 3.5.

  • Limitations: Similar to int(), using float() on a string that doesn't represent a valid number will result in a ValueError

New cards
20

str(...)

  • The str() function converts a value to a string. This is particularly useful when you want to combine numeric data with text.

  • Converting from Numbers: It converts numeric values (both integers and floats) into their string representations. For example, str(42) would result in the string "42".

  • Concatenation with Strings: You can then use the + operator to concatenate this string with other strings. For instance, str(42) + " days" would produce the string "42 days".

New cards
21

Combining Data in Output

  • Let's say you want to display a message that includes both text and a numeric value. You can use str() to convert the numeric value to a string and then use the + operator for concatenation.

  • age = 25

  • message = "You are " + str(age) + " years old."

  • print(message)  # Output: You are 25 years old.

New cards
22

Input Validation

  •  Imagine you're getting input from a user that's expected to be a number. You can use int() or float() to convert the input (which is initially a string) to a numeric type. However, it's important to handle potential ValueError exceptions in case the user enters invalid input.

  • while True:

  •    try:

  •        age = int(input("Enter your age: "))

  •        break  # Exit the loop if conversion is successful

  •    except ValueError:

  •        print("Invalid input. Please enter a whole number.")

New cards
23

Integer (int)

  • [1-3] Integers represent whole numbers.

  • Examples: You can use integers to represent quantities like the number of students in a class (e.g., 25), the age of a person (e.g., 30), or the year in a date (e.g., 2024).

  • Operations: You can perform standard arithmetic operations on integers, such as addition (+), subtraction (-), multiplication (*), division (/), and more.

New cards
24

Float (float)

  • Floats represent numbers with decimal points.

  • Examples: You might use floats to represent values like temperatures (e.g., 98.6), prices (e.g., 19.99), or scientific measurements (e.g., 3.14159).

  • Operations: Like integers, you can use arithmetic operators on floats

New cards
25

Boolean (bool):

  • Booleans represent truth values, which can be either True or False.

  • Examples: You'd use Booleans in situations where you need to evaluate logical conditions, like checking if a user is logged in (True or False), if a file exists (True or False), or if a certain event has occurred (True or False).

  • Operations: You can combine Booleans using logical operators like and, or, and not. Interestingly, in Python, you can also treat Booleans like numbers in some contexts. True is equivalent to the integer 1, and False is equivalent to the integer 0. This allows you to use some arithmetic operators with Booleans, although it's essential to do so carefully and make sure your code remains readable.

New cards
26

String (str)

  •  Strings represent text.

  • Examples: You'd use strings to store and manipulate textual data, such as names (e.g., "Alice"), addresses (e.g., "123 Main Street"), or any other sequence of characters.

  • Operations: Common operations on strings include concatenation (joining strings using the + operator) and various built-in string methods that Python provides for tasks like searching within strings, replacing parts of strings, and changing the case of characters in strings

New cards
27

if Statement

  • The if statement is the most basic form. It checks a condition, and if the condition is true, the code block within the if statement is executed. If the condition is false, the code block is skipped. [2, 3]

  • if num > 0:

  •    print("The number is positive.")

New cards
28

if-else Statement

  • The if-else statement provides an alternative path of execution. If the if condition is true, the code block within the if statement is executed. If the condition is false, the code block within the else statement is executed. This ensures that one of the two blocks will always be executed. [3]

  • if num > 0:

  •    print("The number is positive.")

  • else:

  •    print("The number is negative or zero.")

New cards
29

if-elif-else Statement

  • The if-elif-else statement allows you to check multiple conditions in a chain. The elif stands for "else if." The conditions are evaluated in order. If an if or elif condition is true, its corresponding code block is executed, and the rest of the chain is skipped. The else block, if present, is executed only if none of the preceding if or elif conditions are true. [4]

  • if num > 0:

  •    print("The number is positive.")

  • elif num < 0:

  •    print("The number is negative.")

  • else:

  •    print("The number is zero.")

New cards
30

Lists are mutable:

  • The sources emphasize that lists in Python are mutable, which means you can modify their elements after the list has been created. [1-3] This is a key distinction from immutable data types like strings, where you cannot change individual characters directly. [2, 3]

New cards
31

Modifying elements by index:

  • You can modify an element within a list by assigning a new value to a specific index, just like you would when accessing elements. [2] For example:

  • my_list = [4-8]

  • my_list[9] = 25  # Modifies the second element (index 1)

  • print(my_list)   # Output: [4, 6-8, 10]

New cards
32

The append() method:

While not directly modifying existing elements, the append() method is another way to change a list's content. [11] It adds a new element to the end of the list, effectively modifying its structure and length

New cards

Explore top notes

note Note
studied byStudied by 10 people
... ago
5.0(2)
note Note
studied byStudied by 11 people
... ago
5.0(1)
note Note
studied byStudied by 8 people
... ago
5.0(1)
note Note
studied byStudied by 12 people
... ago
5.0(1)
note Note
studied byStudied by 3 people
... ago
5.0(1)
note Note
studied byStudied by 13 people
... ago
5.0(1)
note Note
studied byStudied by 47 people
... ago
4.7(3)
note Note
studied byStudied by 13 people
... ago
5.0(1)

Explore top flashcards

flashcards Flashcard (20)
studied byStudied by 10 people
... ago
5.0(1)
flashcards Flashcard (22)
studied byStudied by 21 people
... ago
5.0(1)
flashcards Flashcard (23)
studied byStudied by 12 people
... ago
5.0(1)
flashcards Flashcard (124)
studied byStudied by 28 people
... ago
5.0(1)
flashcards Flashcard (52)
studied byStudied by 4 people
... ago
5.0(1)
flashcards Flashcard (106)
studied byStudied by 12 people
... ago
5.0(1)
flashcards Flashcard (43)
studied byStudied by 88 people
... ago
4.3(7)
flashcards Flashcard (123)
studied byStudied by 35 people
... ago
5.0(1)
robot