python-reference
Python Basics Tutorial
This tutorial covers the fundamental concepts of Python programming, designed for mid-level undergraduate students with no prior Python experience.
1. Variables and Data Types
Quick Reference:
- Variables are created by assigning a value
- Basic data types: int, float, str, bool
Example:
Exercise 1:
Remember to use the appropriate data type for each variable. Use an integer for age and a float for height.
To print multiple variables, separate them with commas inside the print function.
age = 20
height = 1.75
print(age, height)Exercise 2:
Use quotes (single or double) to create a string variable.
Use an f-string (formatted string) to include variables in the output. Variables go inside curly braces {}.
full_name = "John Doe"
is_programmer = True
print(f"My name is {full_name} and it is {is_programmer} that I am a programmer.")2. Basic Operations
Quick Reference:
- Arithmetic: +, -, *, /, // (integer division), % (modulo), ** (exponentiation)
- Comparison: ==, !=, <, >, <=, >=
- Logical: and, or, not
Example:
Exercise 1:
Use the * operator to multiply the length and width.
length = 7
width = 5
area = length * width
print(area)Exercise 2:
A number is even if it’s divisible by 2 (i.e., number % 2 == 0). A number is positive if it’s greater than 0.
Use the and operator to combine the two conditions.
number = 6 # You can change this to any integer
is_even = number % 2 == 0
is_positive = number > 0
print(f"The number {number} is both even and positive: {is_even and is_positive}")3. Control Flow
Quick Reference:
- if, elif, else for conditional execution
- for loops for iteration
- while loops for conditional iteration
Example:
Exercise 1:
A number is prime if it’s only divisible by 1 and itself. Check for divisibility using the modulo operator (%).
If you find any divisor other than 1 and the number itself, the number is not prime.
def is_prime(n):
if n < 2:
return False
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
return True
# Test the function
print(is_prime(17))
print(is_prime(4))Exercise 2:
Use the modulo operator (%) to check if a number is even.
Increment the counter in each iteration, and increment the even_count only when an even number is found.
counter = 0
even_count = 0
while even_count < 5:
if counter % 2 == 0:
print(counter)
even_count += 1
counter += 1This concludes the basic Python tutorial. Practice these concepts and explore more advanced topics to improve your Python skills!