0% found this document useful (0 votes)
4 views19 pages

Python

The document provides a comprehensive introduction to Python programming, focusing on key concepts such as variables, data types (numbers, booleans, strings), arithmetic operators, and comparison operators. It covers the syntax and usage of conditional statements, functions, and built-in functions, emphasizing the importance of indentation and logical flow in code. Additionally, it explains the differences between print and return, as well as the organization of functions and nested functions for better code structure.

Uploaded by

Rafael Rodrigues
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Python

The document provides a comprehensive introduction to Python programming, focusing on key concepts such as variables, data types (numbers, booleans, strings), arithmetic operators, and comparison operators. It covers the syntax and usage of conditional statements, functions, and built-in functions, emphasizing the importance of indentation and logical flow in code. Additionally, it explains the differences between print and return, as well as the organization of functions and nested functions for better code structure.

Uploaded by

Rafael Rodrigues
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON

VARIABLES

 Introduction to coding with a focus on variables.


 Variables store information and represent data input.
 Assigning a value to a variable: X = 5.
 Execute commands to carry out operations: Shift + Enter.
 Display variable values: Type the variable name and execute.
 Python is case-sensitive: Y is different from y.
 Use the print command for better logical flow: print(Y).
 Assign multiple values to multiple variables: X, Y = 1, 2.
 Ensure the number of variables matches the number of values to avoid errors.

NUMBERS AND BOOLEAN

 Numeric values in programming: Integers and floating points (floats).


 Integers: Positive or negative whole numbers without decimals.
o Example: x1 = 5.
 Use type(variable) to verify the variable type.
o Example: type(x1) returns int.
 type() can also be applied directly to values.
o Example: type(-6) returns int.
 Floats: Real numbers with decimal points.
o Example: x2 = 4.75. type(x2) returns float.
 Convert between types:
o int() transforms a float into an integer.
 Example: int(4.75) returns 4.
o float() transforms an integer into a float.
 Example: float(4) returns 4.0.
 Boolean values: True or False (capitalized).
o Example: x3 = True.
o type(x3) returns bool.

STRINGS

 Strings: Text values composed of a sequence of characters.


 Creating a string: Use single or double quotation marks around the text.
 Example: 'George' or "George".
 Using the print command displays text without quotes.
 Assigning a string to a variable: Example: X4 = "George".
 Combining numerical values and strings: Use the + sign.
o Example: y = 10, print(y + " dollars") - Error, because y is an integer and
"dollars" is a string.
 Convert numerical values to strings using the str() function.
o Example: print(str(y) + " dollars").
 Python automatically determines the type of data (integer, float, boolean, or
string).
 Using apostrophes in strings: Use double quotes around the text with an
apostrophe or use a backslash before the apostrophe.
 Example: "I'm fine." or I\'m fine.
 Combining strings: Use a plus sign or a comma for the print command.
 Example: 'Red' + ' car' or print('Red', 'car') (with a trailing comma).
 Pythonic syntax: Important to respect while coding.

ARITHMETIC OPERATORS AND THE DOUBLE EQUALITY SIGN

Arithmetic Operators:

 Addition (+) and Subtraction (-): Operands (e.g., 1 + 2).


 Division (/):
o Python 2: Quotient is an integer. Example: 16 / 3 results in 5.
o Python 3: Quotient is a float. Example: 16 / 3 results in 5.33.
 Obtain Remainder (%): Example: 16 % 3 results in 1.
 Obtain Quocient (//): Example: 16 % 3 results in 3.
 Multiplication (*): Example: 5 * 3 results in 15.
 Assign arithmetic operations to variables. Example: x = 5 * 3, then x results in
15.

 Exponentiation (**): Example: 5 ** 3 results in 125


 Equal sign in programming: Means "assign" or "bind to."
o Example: Assign 5 ** 3 to Y. This means Y = 125.
 Double equality sign (==): Used to check equality between values.
o Example: Y == 125 checks if Y is equal to 125 and returns True or False.
o Example: Y == 126 returns False because 125 is not equal to 126.
 Double equality sign always returns a boolean value (True or False).

DIVERSE TOPICS

 Variable reassignment:
o Initial assignment: Z = 1 results in Z = 1.
o Reassigning: Z = 3 changes Z to 3.
o Order of commands matters: The latest assignment is valid.
o Example: Adding 5 to Z after reassignment (Z = 3 + 5) results in 8.
o Example: Reassigning Z = 7 changes Z to 7.
 Python reassigns values to variables, and older commands are overwritten by
newer ones.
 Comments:
o Used to explain code; not executed by the computer.
o Begin comments with a hash sign (#).
o Comments provide clarity and structure to longer code.
 Example:
o # This is a comment
o print(7, 2) - prints 7 and 2 on the same line.
 Multiple-line comments:
o Place a hash sign (#) at the beginning of each line.
 Example:
 # First comment line
 # Second comment line
o Comments do not produce any output; only visible to the programmer.
 Using a backslash (\):
o When code lines get long, use a backslash to continue on the next line.
 Example:
 python
 2.0 * 1.5 + 5 \
 + 10
o The machine reads it as one command, improving code organization.
 Indexing:
o Technique to extract specific characters from strings.
o Use square brackets to specify the position of the character.
o Important: Python counts from zero, not one (e.g., 0, 1, 2, 3, 4...).
o Example:
 word = "Friday"
 Extract the letter 'D' using word[3] (0-based indexing).
 Syntax:
o Place the word (or string) followed by square brackets with the index
inside.
o Example: word[3] returns D, word[4] returns A.
 Indentation:
o Fundamental for communicating ideas to the machine in Python.
o Example: Define a function using def and indent the function body.
 def five(x):
 x=5
 return x
o Printing within a function: Indent the print statement to include it in the
function body.
 def five(x):
 x=5
 return x
 print(five(3)) # Outside the function body, separate command
o Align commands with def for separate blocks of code.
o Indentation clarifies the logic and organization of code.

COMPARISON AND LOGIC OPERATORS

Comparison Operators:

 == : Checks if two values are equal. Example: 10 == 10 returns True.


 != : Checks if two values are not equal. Example: 10 != 15 returns True.
 > : Checks if a value is greater than another. Example: 100 > 50 returns True.
 < : Checks if a value is less than another. Example: 100 < 50 returns False.
 >= : Checks if a value is greater than or equal to another. Example: 15 >= 10 +
10 returns False.
 <= : Checks if a value is less than or equal to another. Example: 15 <= 10 + 5
returns True.
Logical (Boolean) Operators:

 and: True if both statements are true. Examples:


o True and True returns True
o True and False returns False
 or: True if at least one statement is true. Examples:
o False or False returns False
o True or False returns True
 not: Inverts the Boolean value. Examples:
o not True returns False
o not False returns True

Example with comparison:

 (3 > 5) and (10 <= 20) returns False

Order of importance: not first, then and, finally or.

 Example: True and not True interpreted as True and False, results in False
 Example: False or not True and True interpreted as False or False and True, results in
False
 Example: True and not True or True interpreted as True and False or True, results in
True

Identity Operators:

 is: Checks if two values are the same. Example: 5 is 6 returns False
 is not: Checks if two values are not the same. Example: 5 is not 6 returns True
 Equivalent to using == and !=.

CONDITIONAL STATEMENTS

If statement:

 Used to execute code if a condition is true.


 Syntax: if condition:

if 5 == 15 / 3:
print("Hooray!")

Use double-equality sign (==) to check equality.

Colon (:) indicates the start of the code block to execute if the condition is true.

Indentation is crucial for code readability and to avoid errors.

Example of inequality:

 Syntax: if condition:
if 5 != 3 * 6:
print("Hooray!")

Logical flow:

 If the condition is true, execute the code block.


 If the condition is false, the code block is not executed.

If condition is not true, Python proceeds to the next instruction or returns nothing.

Conditional Statements: if and else.

 Assign value to x: x = 1.
 Example: Display "Case 1" if x is greater than 3, else display "Case 2".

Using two if statements:

if x > 3:
print("Case 1")
if x <= 3:
print("Case 2")

Using else for a shorter expression:

if x > 3:
print("Case 1")
else:
print("Case 2")

else executes the command if the if condition is not satisfied.

Ensure proper indentation for readability and error-free code.

if and else keywords should be on the same vertical line.

Blocks of code:

 if statement forms the first block.


 else statement forms another block.

elif statement:

 Adds a second condition to an if statement.

if y > 5:
print("Greater")
elif y < 5:
print("Less")
else:
print("Equal")

 Check if y is greater than 5, print "Greater".


 Check if y is less than 5, print "Less".
 Else, print "Equal".

You can add multiple elif statements as needed.

Example with additional elif:

 Check if y is less than 0, print "Negative".

Order of conditions matters:

 Python reads commands from top to bottom.


 Executes the first true condition and skips the rest.

Example of control flow:

 Conditions are checked in order.


 First satisfied condition is executed, others are skipped.

Importance of logical order:

 Example: Swapping elif statements can lead to different outcomes.


 Ensures correct and expected results.

Boolean values:

 Represent true or false.

Example:

 Assign x = 2.
 Use an if-else construction:

if x > 4:
print("Correct")
else:
print("Incorrect")

 The if statement attaches a Boolean value to it.


 If x > 4 is true, print "Correct".
 If x > 4 is false, print "Incorrect".

Boolean values help understand computational logic and conditionals in Python.

Control flow of If, Elif, and Else statements:

 Ensure correct syntax: colon sign and indentation.


 The order of commands leads to specific outcomes.
FUNCTIONS

 Functions:
o Define a function using the def keyword.
o Example:

def simple():
print("My first function")

o defis a keyword, not a command or function.


o Function name follows the def keyword.
o Parentheses are used after the function name.
o Parameters can be included within the parentheses if needed.
o Add a colon (:) after the function name and parentheses.
o Indent the function body for better readability.
o Call the function to execute it:

simple()

Creating a function with a parameter:

 Use the def keyword to define the function.

def plus_10(A):
return A + 10

 is followed by the function name and parentheses with the parameter.


def
 Use return to output the result.

Calling the function:

 Example: plus_10(2) returns 12.


 Example: plus_10(5) returns 15.

Parameters vs. Arguments:

 Parameters are specified in the function definition. Example: A is a parameter.


 Arguments are provided when calling the function. Example: 2 and 5 are
arguments.

Difference between print and return:

 print displays a message but does not return a value.


 return outputs the result of the function.

A function can take one or more input variables and return a single output.

Use intuitive names for functions to improve code readability and style.

Organizing function definitions:


 Use a variable to store the result before returning it.

def plus_ten(a):
result = a + 10
return result

 Call the function with an argument: plus_ten(2) returns 12.

Difference between print and return:

 print: Displays a statement/object for the programmer, useful for debugging.


 return: Specifies what the function should output, used to pass results.

Example:

 print("Outcome") and return result:

def plus_ten(a):
result = a + 10
print("Outcome")
return result

 Calling plus_ten(2) prints "Outcome" and returns 12.

Remember: A function can only return a single result.

Nested functions:

 A function can be called within another function.

Example: Calculating daily wage and adding a bonus.

 Define a function wage to calculate daily wage:

def wage(w_hours):
return w_hours * 25

 Define another function with_bonus to add a bonus:

def with_bonus(w_hours):
return wage(w_hours) + 50

 Call the functions:


o wage(8) returns 200 (base compensation).
o with_bonus(8) returns 250 (base compensation + bonus).

Nested functions can streamline calculations and improve code organization.

Combining if statements and functions:

 Define a function to calculate Johnny's savings.


 Example: add_10 function with parameter m.
 Logic:
o If m >= 100, add 10 to the saved amount.
o If m < 100, return a message to save more.
 Example:

def add_10(m):
if m >= 100:
m = m + 10
return m
else:
return "Save more"

 Call the function:


o add_10(110) returns 120.
o add_10(50) returns "Save more".

 Functions with multiple parameters:


o Define a function with multiple arguments separated by commas.

def example_function(A, B, C):


return A - B + C

o Call the function with arguments in order:

example_function(10, 3, 2) # Returns 9

o Ensure the order of arguments matches the parameters.


o Alternatively, specify the names of variables:

example_function(B=3, A=10, C=2) # Returns 9

BUILT-IN FUNCTIONS

Built-in functions:

 Installed with Python, no need to code them every time.


 Examples:
o type(variable): Returns the type of the variable.
 Example: type(10) returns int.
o int(), float(), str(): Transform arguments into integer, float, and string data
types.
 Examples: int(5.0) returns 5, float(3) returns 3.0, str(500) returns
"500".
o max(sequence): Returns the highest value in a sequence.
 Example: max(10, 20, 30) returns 30.
o min(sequence): Returns the lowest value in a sequence.
 Example: min(10, 20, 30) returns 10.
o abs(value): Returns the absolute value of its argument.
 Example: abs(-20) returns 20.
o sum(sequence): Calculates the sum of all elements in a list (it’s obligatory
to pass the arguments into a list).
 Example: sum([1, 2, 3, 4]) returns 10.
o round(value, digits): Rounds the float to a specified number of digits.
 Example: round(3.555, 2) returns 3.56, round(3.2) returns 3.0.
o pow(base, exponent): Elevates the base to the power of the exponent.
 Example: pow(2, 10) returns 1024.
o len(object): Returns the number of elements in an object.
 Example: len("mathematics") returns 11.

LISTS

 Lists:
o A sequence of data points (e.g., floats, integers, strings).
o Created using square brackets and quotation marks for strings.
o Example:

Participants = ["John", "Leila", "Gregory", "Cate"]

 Accessing list elements:


o Use square brackets with the index.
o Python counts from zero.
o Example: Participants[1] returns "Leila".
o Use negative indices to count from the end.
o Example: Participants[-1] returns "Cate".
 Replacing items in a list:
o Example: Replace "Cate" with "Maria".

Participants[3] = "Maria"

 Deleting items from a list:


o Use the del keyword.
o Example: Delete "Gregory".

del Participants[2]

 Slicing lists:
o Extract a portion of a list using square brackets and colon.
o Syntax: list[start:end], where start is the index of the first element and end
is one position above the last element.
o Example: Participants[1:3] returns ["Leila", "Maria"].
o To get the first two elements: Participants[:2].
o To get the last two elements:
 Method 1: Participants[4:].
 Method 2: Participants[-2:].

Additional methods:
 Finding the index:
o Use the index method to find the position of an element.
o Example: [Link]("Maria") returns 2.
 Creating a list of lists:
o Combine lists within a new list.
o Example:

Newcomers = ["Joshua", "Brittany"]


Bigger_List = [Participants, Newcomers]

 Sorting a list:
o Use the sort method to order elements alphabetically or numerically.
o Example: [Link]().
o To sort in reverse order: [Link](reverse=True).
o Numeric sorting example:

Numbers = [5, 3, 1, 2, 4]
[Link]() # [1, 2, 3, 4, 5]
[Link](reverse=True) # [5, 4, 3, 2, 1]

METHODS

 Appending to a list:
 Use the append method to add an element.
 Example: Add "Dwayne" to Participants.

[Link]("Dwayne")

 Extending a list:
 Use the extend method to add multiple elements.
 Example: Add "George" and "Catherine" to Participants.

[Link](["George", "Catherine"])

 Printing list elements:


 List elements are treated as string values.
 Example: Print the first participant.

print(Participants[0]) # "John"

 Using len to count elements:

 The len function counts the number of elements in an object.


 Example: Count the elements in Participants.

len(Participants) # 6

 Summary:

 Built-in functions take objects as arguments.


 Built-in methods are applied to objects using the dot operator.

TUPLES

 Immutable sequences; cannot be changed or modified.


 Syntax: Tuples use parentheses.
 Example: (40, 50, 60) creates a tuple.
 Tuple assignment: Assign values to variables.

(a, b, c) = (40, 50, 60)

 Indexing: Access values by their position.

x = (40, 50, 60)


x[0] # Returns 40

 Tuples within lists: Tuples can be elements of lists.

 Comma Separated Values (CSV):


 Split method: Assign values separated by commas.
age, years_of_school = "30,17".split(',')
print(age) # Returns "30"
print(years_of_school) # Returns "17"

 Functions returning tuples:


 Example function returning multiple values.
def square_info(side_length):
area = side_length ** 2
perimeter = 4 * side_length
return (area, perimeter)
square_info(4) # Returns (16, 16)

DICTIONARIES

 Dictionaries:

 Another way of storing data, using key-value pairs.


 Syntax: Use curly braces {}.
 Example:

animals = {"K1": "cat", "K2": "dog", "K3": "mouse"}

 Accessing values:
 Access a value by its key.
 Example: animals["K1"] returns "cat".

 Adding a new value:


 Syntax: dictionary_name[new_key] = new_value.
 Example: animals["K4"] = "parrot".
 Replacing a value:
 Use the same syntax as adding a new value.
 Example: animals["K2"] = "squirrel".

 Lists as values in dictionaries:


 Example:

departments = {"dept1": ["Peter"], "dept2": ["Jennifer", "Michael", "Tommy"]}

 Creating a dictionary with empty curly braces:

 Add keys and values one by one.


 Example:

player_positions = {}
player_positions["Center"] = "Hector"

 Using the get method:

 Avoid errors when a key does not exist.


 Example: player_positions.get("Coach") returns None.

 Iterating over a dictionary:

 Example: Calculate the total cost of items bought.

 Dictionaries used:

 prices: Contains the price of each item.

prices = {"spaghetti": 4, "lasagna": 5, "hamburger": 3}

 quantity: Contains the quantity of each item bought.

quantity = {"spaghetti": 6, "lasagna": 10, "hamburger": 0}

 Calculating total cost:

 Initialize a rolling sum money_spent to 0.


 Iterate over each item in prices.
 Multiply the price by the quantity for each item.
 Add the result to money_spent.
 Example code:

money_spent = 0
for item in prices:
money_spent += prices[item] * quantity[item]
print(money_spent) # Outputs 74

 Key observation:
 The outcome remains the same if you loop through prices or quantity since both
dictionaries contain the same keys.

FOR LOOPS

 Iteration:

o The ability to execute a certain code repeatedly.


o Example: Printing all even numbers from 0 to 20.

 For loop:

o Syntax:
for N in even:
print(N)

o Nis the loop variable; it can be named anything.


o The loop body (the code to be executed) must be indented.

 Steps:

 The loop takes an element N from the list.


 Executes the body (prints the element).
 Moves to the next element and repeats until all elements are processed.

 Printing in a single line:

 Add a comma and end parameter to the print function:

for N in even:
print(N, end=" ")

 This prints each element with a space in between on the same line (the
standard argument on end is “\”, that’s why as standard this loops jump one
line when presenting the single elements.

WHILE LOOPS

 While loop:
 Executes code repeatedly as long as a condition is true.
 Syntax:

X=0
while X <= 20:
print(X)
X=X+2

 The loop will run until X is greater than 20.


 Avoiding infinite loops:

 Ensure the loop condition can eventually become false.


 Example: Increment X within the loop.

 Incrementing:
o Adding the same number to a variable during each loop iteration.
o Example: X = X + 2 or X += 2.

 For loop vs. While loop:


o Choice depends on personal preference and use case.
o Both loops can achieve the same result.

RANGES

 Range function:
o Creates a sequence of integers.
o Syntax: range(start, stop, step).

 Parameters:
o start: First number in the list (optional; defaults to 0).
o stop: One more than the last number (required).
o step: Distance between consecutive values (optional; defaults to 1).

 Examples:
o range(10): Creates a range object with values from 0 to 9.
o To display as a list:

list(range(10)) # Returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

o range(3, 7): Creates a range object with values [3, 4, 5, 6].


o range(1, 20, 2): Creates a range object with odd numbers [1, 3, 5, 7, 9, 11,
13, 15, 17, 19].

 Converting to list:
o In Python 3, use the list function:

 list(range(3, 7)) # Returns [3, 4, 5, 6]

CONDITIONAL STATEMENTS

 Using the range function in a for loop:


o Example: Print values of 2^0 to 2^9.
o Code:

for N in range(10):
print(2 ** N, end=" ")
 Combining iteration and conditional in a loop:
o Example: Print even values between 0 and 19, and "odd" for odd numbers.
o Code:

for X in range(20):
if X % 2 == 0:
print(X, end=" ")
else:
print("odd", end=" ")

 Two main ways to program a loop:

1. Using a list directly:

X = [0, 1, 2]
for item in X:
print(item)

2. Using range and len functions:

X = [0, 1, 2]
for item in range(len(X)):
print(X[item])

 Both approaches lead to the same outcome, but the second is useful in
advanced coding.

 Counting items in a list:


 Define a function to count items less than 20.
 Example:

def count(numbers):
total = 0
for x in numbers:
if x < 20:
total += 1
return total

 Explanation:
o total starts at 0.
o For each x in the numbers list, if x < 20, increment total by 1.
o Return the total value.

 Verifying the function:


o Example list: [15, 25, 10, 30, 5].
o Call the function: count([15, 25, 10, 30, 5]) returns 3.

 Adding more items:


o Example: Adding 17 to the list.
o Adjusted list: [15, 25, 10, 30, 5, 17].
o Call the function: count([15, 25, 10, 30, 5, 17]) returns 4.
ADVANCED TOOLS

 Object-Oriented Programming (OOP):


o Concept of interacting with objects.
o Supported by languages like Java, PHP, Python, and C++.
o Allows modeling of real-world concepts through objects.

 Objects:
o Every value in Python is an object (integers, floats, strings, lists).
o Objects contain data and operations to manipulate the data.

 Classes:
o Define the rules for creating objects.
o Each object belongs to a class.
o Example: Uncle Archibald belongs to the Bike-Maker's Class, and his bike
is an object of this class.

 Attributes:
o Properties or states of an object.
o Example: A bike's color, size, and type (mountain bike or road bike).

 Methods:
o Operations or actions that can be applied to an object.
o Example: Turn left, turn right, slow down, accelerate.
o Methods are special functions that operate on objects.

 Practical example:
o Creating a list with three floats as an object.
o The list belongs to Python's List Class.
o Attributes: Type of data in the list (floats).
o Methods: Extend, index, etc.
o Methods are applied to the object using the dot operator.

 Difference between functions and methods:


o Methods are functions with the object as one of their parameters.
o Methods belong to a class/object, while functions exist independently.

 Modules:
o Pre-written code containing definitions of variables, functions, and classes.
o Can be loaded into new programs to avoid rewriting code.
o Example: A module to handle mathematical operations.

 Packages:
o A collection or directory of related Python modules.
o People in the programming community have developed many packages
tailored for various professions and specializations.
o The term "library" is often used interchangeably with "package".
 Advantages:
o Reusability: Use pre-written code without rewriting.
o Organization: Group related modules into packages.

 Python's Standard Library:


o Collection of modules available upon Python installation.
o Includes built-in functions like len and list methods.

 Broad Application:
o Not mandatory to install all available modules.
o Users can download additional modules and packages as needed.

 Modules and Packages:


o Modules: Pre-written code with variables, functions, and classes.
o Packages: Collections of related modules.
o Libraries: Another term for packages.

 Specialized Modules:
o Statisticians might use statistical modules.
o Data scientists might use packages for organizing data.

 Creating Modules:
o Typically done by specialized experts.
o Once released, modules can be improved and updated.
o Reused multiple times, enhancing efficiency.

 Four ways to import a module:

1. Import the entire module:


o Syntax: import module_name
o Example:

import math
print([Link](16)) # Outputs 4.0

2. Import specific function from module:


o Syntax: from module_name import function_name
o Example:

from math import sqrt


print(sqrt(25)) # Outputs 5.0

3. Import specific function and rename it:


o Syntax: from module_name import function_name as new_name
o Example:

from math import sqrt as s


print(s(36)) # Outputs 6.0
4. Import all functions from a module:
o Syntax: from module_name import *
o Example:

from math import *


print(sqrt(64)) # Outputs 8.0

o Warning: This method can lead to conflicts if multiple modules have


functions with the same name. It is generally avoided in professional
coding.

 Further reference:
o Use the help() function to learn more about modules and their functions.
o Example:

help(math)
help([Link])

You might also like