Python Basics¶
Functions¶
Basic Structure¶
Default Arguments¶
Functions as First-Class Citizens¶
In Python, functions are first-class citizens. This means you can use functions as variables, pass them as arguments to other functions, and return them from functions.
def greet(name):
return f"Hello, {name}!"
def caller(func, arg):
return func(arg)
print(caller(greet, "Alice")) # Output: Hello, Alice!
Data Types¶
Common Data Types:
int
(e.g.,age = 25
)float
(e.g.,height = 5.9
)bool
(e.g.,is_student = True
)str
(e.g.,name = "Alice"
)list
(e.g.,nums = [3, 1, 4]
)NoneType
(e.g.,status = None
)
Example:
name = "Alice"
age = 25
print(name + " is " + str(age) + " years old.")
print(f"{name} is {age} years old.")
Type Conversion¶
Python provides functions to convert data between types:
Logical Operators¶
and
: ReturnsTrue
if both conditions areTrue
.or
: ReturnsTrue
if at least one condition isTrue
.not
: Inverts a boolean value.
Truthy and Falsey¶
if []: # An empty list is False
print("This won't print.")
if [1, 2]: # A non-empty list is True
print("This will print.")
input()
¶
The input()
function allows users to provide input to the program during runtime:
name = input("What is your name? ")
print(f"Hello, {name}!")
age = int(input("Enter your age: "))
print(f"You will be {age + 1} next year!")
File Handling¶
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)