Scarica Python basics , le basi per programmare in python e più Esercizi in PDF di Informatica gestionale solo su Docsity!
Python summary
L1 (print):
print('I'm here!') # Error! Invalid syntax... print("I'm here!")
- QUOTES print('The title of our textbook is "Starting Out with Python".') OR print('''I'm reading a book titled "Starting Out with Python".''')
- PRINT ON DIFF. LINES >>> print("Prima riga\nSeconda riga\necc ecc...")
output
Prima riga Seconda riga ecc ecc... Or print("First line") print("Second line") print("Third line") Or print('''First line Second line Third line''') Other examples: eggs = "Meglio un uovo oggi..." >>> bacon = "o una gallina domani?" >>> eggs + bacon 'Meglio un uovo oggi...o una gallina domani?' >>> eggs + " " + bacon 'Meglio un uovo oggi... o una gallina domani?'
print('One', end=', ') <----- print('Two', end=', ') print('Three', end='.')
One, Two, Three. print('One', 'Two', 'Three', sep=', ', end='.')
One, Two, Three. Escape Character Effect \n Causes output to be advanced to the next line \t Causes output to skip to the next horizontal tab position ' Causes a single quote mark to be printed " Causes a double quote mark to be printed \ Causes a backslash character to be printed
- PRINT ON SAME LINE print('Mon\tTues\tWed') print('Thur\tFri\tSat') Mon Tues Wed Thur Fri Sat
- f F-strings (or formatted string literals) are a special type of string literal that allow you to format values in a variety of ways. An f-string is a string literal that is enclosed in quotation marks( virgolette)and prefixed with the letter f. An f-string can contain placeholders for variables and other expressions. val = 10 print(f'The value is {val + 2 }.')
It is important to understand that the val variable is not changed. <---
The expression val + 2 simply gives us the value 12.
VARIABLES
A variable is a name that represents a storage location in the
computer’s memory. Programs use variables to store data in memory.
When a variable represents a value in the computer’s memory, we say
that the variable references the value.
- The equal sign = is known as the ****assignment****
operator. After an assignment statement executes, the variable
listed on the left side of the = operator will reference the
value given on the right side of the = operator.
25 = temperature # Error! Invalid syntax... <---
- The id function returns a unique id for the specified object,
which is is assigned when the object is created.
The id is the object's memory address, and may change each time the
program runs.
Variable naming rules:
- You cannot use one of Python’s keywords as a variable name.
- A variable name cannot contain spaces.
- The first character must be one of the letters a through z, A
through Z, or an underscore character (_).
- After the first character you may use the letters a through z or A
through Z, the digits 0 through 9, or underscores.
- Uppercase and lowercase characters are distinct.
Because different types of numbers are stored and manipulated in
different ways, Python uses data types to categorize values in
memory. When an integer is stored in memory, it is classified as
Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool
type(hours)
- The next statement uses nested function calls. The value that is returned from the input function is passed as an argument to the float function.
The float value that is returned from the float() function is assigned
to the pay_ rate variable
pay_rate = float(input('What is your hourly pay rate? ')) Nested functions are often useful to write more compact code and avoid variables. However, for the sake of readability, we should avoid nesting more than two functions. Performing calculations Python has numerous operators that can be used to perform mathematical calculations. A math expression performs a calculation and gives a value. The values on the right and left of the operator are called operands.
+ (Addition): a + b
- (Subtraction): a - b
* (Multiplication): a * b
/ (Division): a / b (result is always a float)
// (Floor Division): a // b (integer result)
% (Modulus): a % b (remainder)
** (Exponentiation): a ** b
my_number = 5 * 2.0 # The int 5 is implicitly converted to float <--- print(my_number)
- Python also allows you to break any part of a statement that is enclosed in parentheses into multiple lines without using the line continuation character.
- If a programming statement is too long might become difficult to read. Python allows you to break a statement into multiple lines by using the line continuation character, which is a backslash .
F = float(input("Enter the future value you want in the account: ")) r = float(input("Enter the annual interest rate: ")) n = int(input("Enter the number of years you want to wait: ")) P = F / ( 1 + r) ** n print('You need to deposit',P,'dollars')
- LIST x = ["apple", "banana", "cherry"] Lists are used to store multiple items in a single variable. Operation Description Example Create a List Creates a list with specified values. my_list = [1, 2, 3, 4] Access Elements Accesses an element of the list by its index (indexes start at 0). print(my_list[0]) Modify an Element Modifies an element in the list at a given index. my_list[1] = 10 Add an Element Adds an element to the end of the list. my_list.append(5) Insert an Element Inserts an element at a specified position in the list. my_list.insert(1, 7) Remove an Element Removes an element from the list, by value or by index. my_list.remove(3) Extend the List Adds elements from another list to the end of the current list. my_list.extend([6, 7]) Remove by Index Removes and returns an element by index. my_list.pop(2) Slicing Creates a sublist from the list, from a start index to an end index. sub_list = my_list[1:3] Iterate over the List Loops through all elements in the list. for item in my_list: print(item) Check Membership Checks if an element is present in the list. if 3 in my_list: print("Found!") List Length Returns the number of elements in the list. print(len(my_list)) Sort the List Sorts the list elements in ascending order. my_list.sort() Reverse the List Reverses the order of elements in the list. my_list.reverse()
Chloe 3 Aubrey girl_names = ['Joanne', 'Karen', 'Lori'] boy_names = ['Chris', 'Jerry', 'Will'] all_names = girl_names + boy_names print(all_names) ['Joanne', 'Karen', 'Lori', 'Chris', 'Jerry', 'Will'] Note: Keep in mind that you can concatenate lists only with other lists.
How to know the type of your variable?
>>> val = 9.
We use type()
>>> type(val)
class 'float'
Python Conditions and If statements Python supports the usual logical conditions from mathematics:
- Equals: a == b
- Not Equals: a != b
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b An "if statement" is written by using the if keyword. (AND / OR)
Syntax
if condition:
# Code block to execute if condition is True
elif another_condition:
# Code block to execute if another_condition is True
else:
# Code block to execute if all conditions are False
Key Points
1. if checks a condition.
2. elif adds additional conditions (optional, can have multiple).
3. else executes if none of the if/elif conditions are True (optional).
Examples: x = 10 if x > 15: print("x is greater than 15") elif x == 10: print("x is 10") else: print("x is less than 10")
One line if else statement:
result = "Positive" if x > 0 else "Non-positive" ---
print(result)
sales = 60000. if sales >= 50000.0: sales_quota_met = True else: sales_quota_met = False if sales_quota_met:
Calculate a series of commissions.
while keep_going:
Get a salesperson's sales and commission rate.
sales = float(input('Enter the amount of sales: ')) comm_rate = float(input('Enter the commission rate: '))
Calculate the commission.
commission = sales * comm_rate
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified
number.
- A function is a group of statements that exist within a program for the
purpose of performing a specific task.
def my_function():
print('Hello! This my function!')
my_function()
def get_max_list(listA, listB): n = len(listA) listC = [max(listA[i], listB[i]) for i in range(n)] return listC def main(): listA = [- 1 , 0 , 4 , 8 , 9.4] listB = [- 3 , 0 , 5 , 8.2, 9.38] listC = get_max_list(listA, listB) print(listC) main()
A function definition specifies what a function does, but it does not cause the
function to execute. To execute a function, you must call it. When a function is
called, the interpreter jumps to that function and executes the statements in
its block. Then, when the end of the block is reached, the interpreter jumps
back to the part of the program that called the function, and the program
resumes execution at that point. When this happens, we say that the
function returns. A function can return data as a result.
Key Points
1. End a Function : The return statement ends the execution of the
function. Any code after return in the same block will not be executed.
2. Return a Value : You can return a single value, multiple values, or no
value at all.
3. Default Return Value : If no return statement is provided, the function
returns None by default.
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
Python range() Function Syntax
The range() function returns a sequence of numbers and is immutable.
The range() function can be represented in three different ways, or you can think of them as three range() parameters:
- range(stop_value): By default, the starting point here is zero.
- range(start_value, stop_value): This generates the sequence based on the
start and stop value.
- range(start_value, stop_value, step_size): It generates the sequence by
incrementing the start value using the step size until it reaches the
stop value.
→range(10) #it should return a lower and an upper bound value. In Python, the range() function generates a sequence of numbers from the starting value (which is 0 by default) up to, but not including, the specified end value. In this code snippet, range(10) generates a sequence of numbers from 0 to 9 (inclusive), which represents the lower and upper bound values of the sequence. →range(0, 10) This code uses the built-in Python function range() to generate a sequence of numbers from 0 to 9 (inclusive). The range() function takes two arguments: the starting number (0 in this case) and the ending number (10 in this case). However, the ending number is not included in the sequence, so the sequence only goes up to 9. This sequence can be used in a loop or other operations that require a sequence of numbers.
→for seq in range(10):
print(seq)
This code snippet is simply printing the numbers 0 through 9 in sequence. It does not require any specific programming language as it is just a sequence of numbers.
RANDOM
import random # Random float between 0.0 and 1.
random_number = random.random() print(random_number)
randint
randint is a function inside the random module that returns a random integer
in a specified range, including both endpoints.
Example:
import random
# Random integer between 1 and 10 (both inclusive)
random_integer = random.randint(1, 10)
print(random_integer)