Untitled Document
Untitled Document
focusing on functions, variables, conditionals, user input, and basic formatting like f-strings.
Here’s a comprehensive summary with examples to help solidify each concept:
1. Introduction to Functions
●
● The print() function displays text or variables on the screen.
2. Defining Functions
You can create your own functions using the def keyword:
python
Copy code
def greet():
print("Hello!")
3. Variables
● Variables store values that can be used and manipulated in the program.
4. User Input
Python allows you to gather user input with the input() function:
python
Copy code
name = input("What's your name? ")
print(f"Hello, {name}!")
●
○ When you run this, it asks the user for their name and greets them.
Input is always stored as a string, so if you need a number, you can convert it:
python
Copy code
age = int(input("How old are you? "))
print(f"Next year, you will be {age + 1} years old.")
5. Return Values
Functions can return values using the return statement:
python
Copy code
def square(x):
return x * x
○
● The square() function takes a number x, multiplies it by itself, and returns the result.
6. Conditionals
Conditionals are used to make decisions in your program with if, elif, and else:
python
Copy code
age = 18
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Output:
sql
Copy code
You are an adult.
●
● Conditionals allow your code to behave differently depending on the values of variables.
Example interaction:
rust
Copy code
What's your name? Alice
How old are you? 30
Hello, Alice. You are 30 years old.
9. Best Practices
● Use meaningful variable names: Choose names that describe their purpose (e.g.,
name, age).
● Keep functions small: Each function should do one thing well, making them easier to
test and maintain.
● Test your functions: Use different inputs to ensure your functions behave as expected.
● Comment your code: Use comments (#) to explain complex parts of your code.
10. Summary
● Lesson 0 is foundational for understanding how Python programs are structured using
functions, variables, and conditionals.
● Mastering these basics will help with more advanced topics in future lessons.
By grasping these core ideas, you'll have a strong foundation to build more complex programs
as you progress through CS50P. Each concept is introduced to make Python easier and more
intuitive to use, especially as you start writing your own functions and programs.
4o
ChatGPT can make mistakes. Check important info.