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

Additional Documentation

Example:

Exercise 1:

Hint 1

Remember to use the appropriate data type for each variable. Use an integer for age and a float for height.

Hint 2

To print multiple variables, separate them with commas inside the print function.

Fully worked solution:
age = 20
height = 1.75
print(age, height)

Exercise 2:

Hint 1

Use quotes (single or double) to create a string variable.

Hint 2

Use an f-string (formatted string) to include variables in the output. Variables go inside curly braces {}.

Fully worked solution:
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

Additional Documentation

Example:

Exercise 1:

Hint

Use the * operator to multiply the length and width.

Fully worked solution:
length = 7
width = 5
area = length * width
print(area)

Exercise 2:

Hint 1

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.

Hint 2

Use the and operator to combine the two conditions.

Fully worked solution:
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

Additional Documentation

Example:

Exercise 1:

Hint 1

A number is prime if it’s only divisible by 1 and itself. Check for divisibility using the modulo operator (%).

Hint 2

If you find any divisor other than 1 and the number itself, the number is not prime.

Fully worked solution:
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:

Hint 1

Use the modulo operator (%) to check if a number is even.

Hint 2

Increment the counter in each iteration, and increment the even_count only when an even number is found.

Fully worked solution:
counter = 0
even_count = 0

while even_count < 5:
    if counter % 2 == 0:
        print(counter)
        even_count += 1
    counter += 1

This concludes the basic Python tutorial. Practice these concepts and explore more advanced topics to improve your Python skills!