basic functions
basic functions
Let’s dive into some more useful Python functions that you'll use frequently as you start
coding. These functions will help you work with data, interact with the user, and perform common tasks.
The `input()` function allows you to get input from the user, which can be really useful for interactive
programs. It always returns the input as a string.
```python
name = input("What is your name? ") # Prompts the user for input
```
- The `input()` function will show the message inside the parentheses to the user and wait for them to
type something. Once they do, it returns their input as a string.
If you want to turn a string (like the one from `input()`) into a number so you can perform math, you can
use `int()` (for integers) or `float()` (for decimal numbers).
```python
```
- `int()` will convert strings like `"5"` into the number `5`.
The `len()` function is used to find the length of a string or the number of items in a list.
```python
word = "Python"
print(len(fruits)) # This will print 3, because there are 3 items in the list
```
Sometimes you might want to convert a number or other data type into a string (for example, when
you’re combining it with other text). You can use the `str()` function for that.
```python
age = 25
message = "Your age is " + str(age) # Convert the number to a string before combining
print(message)
```
### 5. **`max()` and `min()` – Finding the Largest and Smallest Values**
If you have a list of numbers, you can use `max()` to find the largest value and `min()` to find the
smallest.
```python
```
### 6. **`type()` – Checking the Type of a Value**
If you’re not sure what type of data something is, you can use `type()` to find out. This can be helpful
when debugging or working with user input.
```python
number = 42
text = "Hello!"
```
If you have a decimal number and want to round it, `round()` is useful. You can also specify how many
decimal places you want to round to.
```python
pi = 3.14159
```
The `abs()` function returns the absolute value of a number, which means it removes the negative sign if
the number is negative.
```python
negative_number = -5
```
### 9. **`sum()` – Adding Up Numbers in a List**
If you have a list of numbers and want to find the total, you can use `sum()`.
```python
numbers = [1, 2, 3, 4, 5]
```
```python
for i in range(5):
print(i)
```
```python
print(i)
```
This will print `1, 3, 5, 7, 9` because it starts at `1` and goes up to `10` in steps of `2`.
---
4. Converts their age into a string and displays a message with that string.
---
Let me know if you need help or clarification on anything, or if you're ready to move on to new
concepts!