import numpy as np arr = np.array([1, 2, 3, 4, 5]) print(arr)
zeros_array = np.zeros((3, 4)) 3x4 Array with zeroes ones_array = np.ones((2, 2)) 2x2 Array with ones range_array = np.arange(0, 10, 2) Output: [0 2 4 6 8]
arr1=np.array([1,2,3]) arr2=np.array([4,5,6]) sum_array = arr1 + arr2 Array adding the two arrays element wise print(sum_array)
product_array = arr1 * arr2 Multiplication of two arrays print(product_array)
sin_array = np.sin(arr1) Each element has a sine function applied to it log_array = np.log(arr1) Apply the natural logarithm
arr2D = np.array([[1, 2, 3],[4, 5, 6]]) print(arr2D)
element = arr2D[1, 2] Selecting the 2nd row, 3rd column element print(element)
subarray = arr2D[0:1, 1:3] Copies elements of first row, 2nd to 3rd column print(subarray)
arr1D = np.array([1, 2, 3, 4, 5, 6]) arr2D = arr1D.reshape((2, 3)) Two dimensional array of two rows and three columns print(arr2D)
arr2D = np.array([[1, 2], [3, 4]]) result = arr2D + 5 Add 5 to every element in the array print(result)
def add(a, b): return a + b; def subtract(a, b): return a - b;
import math_operations result = math_operations.add(5, 3) print(result) Output: 8
import math_operations result = math_operations.subtract(10, 5)
from math_operations import add result = add(3, 4)
import math_operations as math_ops result = math_ops.add(7, 8)
import datetime current_time = datetime.datetime.now() print(current_time)
pip install requests
import requests response = requests.get("https://www.example.com") print(response.text)
python3 -m venv myenv
source myenv/bin/activate On macOS/Linux myenvScriptsactivate On Windows pip install requests
def __init__(self, name, age): self.name = name self.age = age function that rudimentary implements the characteristics of a dog def speak(self): return f"{self.name} says woof!"
dog1 = Dog("Buddy", 3) print(dog1.name) Output: Buddy print(dog1.speak()) Output: Buddy says woof.
class Dog: species = "Canine" Class variable def __init__(self, name, age): self.name = name Instance variable self.age = age Instance variable
class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound." class Dog(Animal): Dog is a subclass of Animal def speak(self): Overriding the speak method return f"{self.name} barks." class Cat(Animal): Cat is a subclass of Animal def speak(self): Overriding the speak method return f"{self.name} meows."
class BankAccount: def __init__(self, owner: str, balance): self.owner = owner self.__balance = balance Private variable def deposit(self, amount): if amount > 0: self.__balance += amount def withdraw(self, amount): if amount > 0 and amount <= self.__balance: self.__balance -= amount def get_balance(self): return self.__balance
try: This code could potentially lead to an Exception risky_code ( ) except ExceptionType: print("An error occurred.") else: print("Did something go wrong?")
try: a = 1 5/0 except NameError: print('Exception occurred')
try: a = 0 if a == 0: raise ZeroDivisionError("Division by zero") else: 2/a except ZeroDivisionError: print ('error is raised') finally: print ('Don't divide a number by zero')
import pdb; pdb.set_trace()
import logging Setting up the logging configuration logging.basicConfig(level=logging.DEBUG) Logging a debug message logging.debug("This is a debug message.") Logging an info message logging.info("This is an info message.")
with open('example.txt', 'r') as file: content = file.read() print(content)
try: with open('example.txt', 'r') as file: content = file.read() print(content) except FileNotFoundError: print("The file does not exist.")
fruits = ['apple', 'banana', 'cherry'] fruits.append('orange') Adds 'orange' to the end of the list fruits[1] = 'blueberry' Changes 'banana' to 'blueberry'
colors = ('red', 'green', 'blue')
colors[1] = 'yellow' This will cause an error since the tuples have been assigned and are thus immutable
person = {'name': 'John', 'age': 30, 'city': 'New York'} print(person['name']) Output will be 'John'
person['age'] = 31 Sets the value of age to 31 person['job'] = 'Engineer' Sets the job for the person as a key-value pair
del person['city'] The key city and its value are removed
def function_name(parameter1, parameter2, …): Code block that performs an operation On the parameters return result }
def add_numbers(a, b): return a + b This is called the function. Invoking the function with an argument result= add_numbers(5, 3) print(f'the result is: {result}') The output is logically expected to be equal to 8
x = 10 Variable which is Global def print_global(): print(x) Global variable is being Accessed Inside A Function print_global() Result will be 10
def add_two_numbers(a: int, b: int) -> int: sum_result: int = a + b return sum_result
x = 10 def global_x_addition(): global x x = 20 global_x_addition() print(x)
if condition: //code block to be executed if that condition turns to be True
age = 20; if age >= 18: print("You are eligible to vote")
number = -5 if number >= 0: print("the number is positive") else: print("the number is negative")
score = 85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") else: print("Grade: F")
for item in sequence: Code block to execute for each item
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
while expression: code which is carried out provided the expression evaluates to True
count = 1 while count <= 5: print(count) count += 1
age = 25
count = 10
height = 5.9
name = "Alice"
is_sunny = True
fruits = ["apple", "banana", "cherry"]
person = {"name": "Alice", "age": 25}
coordinates = (10, 20)
+ (Addition) – (Subtraction) (Multiplication) / (Division) // (Floor Division) % (Modulus) (Exponentiation)
a = 5 b = 3 print(a + b) # Output: 8
== (Equal to) != (Not equal to) > (Greater than) < (Less than) >= (Greater than or equal to) <= (Less than or equal to)
x = 10 y = 5 print(x > y) # Output: True
print(x < 10 and y > 5) # Output: True
x=5 x +=3 # Creates the value of x at 8
fruits = [ "apple", "banana", "cherry"] print( "banana" in fruits ) # Output: true
pip install
pip install numpy
import numpy as np
python -m venv venv
venvScriptsactivate
source venv/bin/activate
deactivate
您有什么意见或建议,欢迎给我们留言。
分享好文,绿手指(GFinger)养花助手见证你的成长。
请前往电脑端操作