Advanced Programming in Python PDF

Summary

This document provides a presentation on advanced programming concepts within the Python language, specifically focusing on built-in data types and their usage within the programming language. Various examples illustrate how different Python data types function. The summary shows the different data types and uses.

Full Transcript

Advanced Programming Built-in Data Types in Python Functions and Classes -- A Preview. Built-in Data Types in Python Numbers ► Python supports three types of numbers: ► - Integers (int) ► - Floating-point numbers (float) ► - Complex numbers (complex) ► Examples: ►...

Advanced Programming Built-in Data Types in Python Functions and Classes -- A Preview. Built-in Data Types in Python Numbers ► Python supports three types of numbers: ► - Integers (int) ► - Floating-point numbers (float) ► - Complex numbers (complex) ► Examples: ► age = 25 # Integer ► temperature = 36.6 # Float ► z = 2 + 3j # Complex number Strings ► Strings are used to store text. You can concatenate, slice, and manipulate strings. ► Examples: ► greeting = "Hello, world!" # String ► print(greeting.upper()) # HELLO, WORLD! Examples ► # String declaration greeting = "Hello, world!" print(type(greeting)) # Output: # String concatenation full_greeting = greeting + " How are you?" print(full_greeting) # Output: Hello, world! How are you? # Slicing a string print(greeting[0:5]) # Output: Hello ► It returns the substring "Hello" because: Index 0 is H, Index 1 is e, Index 2 is l, Index 3 is l, Index 4 is o. ► # String methods print(greeting.upper()) # Output: HELLO, WORLD! print(greeting.lower()) # Output: hello, world! print(greeting.split()) # Output: ['Hello,', 'world!'] Lists ► Lists are ordered collections that can store multiple items. ► Examples: ► numbers = [1, 2, 3, 4, 5] # List of integers ► mixed_list = [1, "Hello", 3.14, True] # Mixed data types Examples ► Examples: # List of integers numbers = [1, 2, 3, 4, 5] print(type(numbers)) # Output: # List with mixed data types mixed_list = [1, "Hello", 3.14, True] print(mixed_list) # Output: [1, 'Hello', 3.14, True] # Adding and removing items numbers.append(6) print(numbers) # Output: [1, 2, 3, 4, 5, 6] numbers.remove(2) print(numbers) # Output: [1, 3, 4, 5, 6] # List slicing print(numbers[1:4]) # Output: [3, 4, 5] Tuples ► Tuples are immutable lists, meaning their values cannot be changed. ► Examples: ► coordinates = (10, 20) Examples ► # Tuple declaration coordinates = (10, 20) print(type(coordinates)) # Output: # Accessing tuple elements print(coordinates) # Output: 10 # Tuples are immutable, this will raise an error # coordinates = 15 # TypeError: 'tuple' object does not support item assignment Dictionaries ► Dictionaries store key-value pairs. Keys must be unique. ► Examples: ► student = {"name": "John", "age": 22, "major": "CS"} Examples ► # Dictionary declaration student = { "name": "John", "age": 22, "major": "Computer Science" } print(type(student)) # Output: # Accessing dictionary values print(student["name"]) # Output: John # Adding a new key-value pair student["graduation_year"] = 2024 print(student) # Output: {'name': 'John', 'age': 22, 'major': 'Computer Science', 'graduation_year': 2024} # Removing a key-value pair student.pop("age") print(student) # Output: {'name': 'John', 'major': 'Computer Science', 'graduation_year': 2024} ► # Création d'un dictionnaire ► person = { ► 'name': 'Alice', ► 'age': 30, ► 'city': 'Paris' ► } ► # Accès à des éléments ► print(person['name']) # Sortie : Alice ► # Modification d'un élément ► person['age'] = 31 ► # Ajout d'un nouvel élément ► person['email'] = '[email protected]' ► # Suppression d'un élément ► del person['city'] ► # Itération sur les paires clé-valeur ► for key, value in person.items(): ► print(f"{key}: {value}") Sets ► Sets are unordered collections of unique elements. ► Examples: ► fruits = {"apple", "banana", "cherry"} Type Conversion ► Convert data using functions like int(), str(), and list(). ► Examples: ► num = int("123") # String to integer ► tup = tuple([1, 2, 3]) # List to tuple Examples ► # Set declaration fruits = {"apple", "banana", "cherry"} print(type(fruits)) # Output: # Adding and removing elements fruits.add("orange") print(fruits) # Output: {'banana', 'apple', 'orange', 'cherry'} fruits.remove("banana") print(fruits) # Output: {'apple', 'orange', 'cherry'} # Sets do not allow duplicates fruits.add("apple") print(fruits) # Output: {'apple', 'orange', 'cherry'} Variables in Python ► Python variables are dynamically typed, which means that a variable, at any given moment during the execution of a program, has a specific type assigned to it, but this type can evolve during the program's execution. In Python, the type of a variable is not declared by the user; it is defined by usage, meaning it is determined by the actual value that is stored in the variable. Example ► v = 12 # v is an integer ► print(type(v)) # ► ► v = "Hello" # v becomes a string ► print(type(v)) # ► ► v = 3.14 # v becomes a floating-point number ► print(type(v)) # ► This dynamic typing gives Python great flexibility, but it also requires the developer to be cautious about the types of variables, especially when manipulating data in operations or functions. Functions in Python Defining a Function You define a function using the def keyword, followed by the function name and parentheses. def greet(name): print(f"Hello, {name}!") Calling a Function To execute the function, you call it by its name and pass the required arguments: greet("Alice") # Output: Hello, Alice! Return Statement Functions can return values using the return statement. If no return statement is provided, the function returns None by default. def add(a, b): return a + b result = add(5, 3) print(result) # Output: 8 Default Arguments You can define default values for function parameters. If no argument is provided for that parameter, the default value is used. def greet(name="World"): print(f"Hello, {name}!") greet() # Output: Hello, World!greet("Bob") # Output: Hello, Bob! Keyword Arguments When calling a function, you can use keyword arguments to specify parameters by name: def introduce(name, age): print(f"My name is {name} and I am {age} years old.")introduce(age=30, name="Alice") # Output: My name is Alice and I am 30 years old. Variable-Length Arguments You can define functions that accept a variable number of arguments using *args for positional arguments and **kwargs for keyword arguments. def sum_all(*args): return sum(args)print(sum_all(1, 2, 3, 4)) # Output: 10 def display_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") display_info(name="Alice", age=30) # Output:# name: Alice# age: 30 def display_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") display_info(name="Alice", age=30) # Output:# name: Alice# age: 30 Lambda Functions Python also supports anonymous functions using the lambda keyword. They are often used for short, throwaway functions. square = lambda x: x * x print(square(5)) # Output: 25 Scope of Variables Variables defined inside a function are local to that function, meaning they cannot be accessed from outside the function. def my_function(): local_var = "I'm local!" print(local_var) my_function() # print(local_var) # This would raise a NameError Variable Scope Types Local Scope: Variables defined within a function are local to that function. Global Scope: Variables defined outside of any function have a global scopeand can be accessed anywhere in the program. Enclosing Scope: In nested functions, a variable defined in the enclosing function is accessible in the inner function. Built-in Scope: These are names that are pre-defined in Python (like print() and len()), accessible anywhere.

Use Quizgecko on...
Browser
Browser