A simple, book-style learning guide for Python programming fundamentals
if to choose what runs.The source chapter assumes that you have already used IPython as a calculator. Now the focus changes: instead of only evaluating expressions, you start writing actual Python statements and small scripts.
A variable is a name that refers to a value/object. You create or change a variable with the assignment symbol =.
x = 7
y = 3
x + yThe statements x = 7 and y = 3 store values for later use.
total = x + y
totalPython evaluates the right-hand side first and then assigns the result to the name on the left.
= as "is assigned". It is different from ==, which asks whether two values are equal.Python variable names may contain letters, digits and underscores, but they cannot begin with a digit. Python is case-sensitive, so number and Number are different names.
student_name = "Aman"
age2 = 20
# 2age = 20 # invalid: starts with a digitEvery Python value has a type. The built-in type() function lets you inspect it.
type(7)
type(10.5)total = x + y. Clear formatting makes code easier to read.Python provides familiar arithmetic operators plus operators that are especially useful in programming.
| Operation | Operator | Example | Meaning |
|---|---|---|---|
| Addition | + | 7 + 3 | Add two values |
| Subtraction | - | 7 - 3 | Subtract the right value |
| Multiplication | * | 7 * 3 | Multiply values |
| Exponentiation | ** | 2 ** 10 | Raise a value to a power |
| True division | / | 7 / 4 | Division producing a floating-point result |
| Floor division | // | 7 // 4 | Largest integer not greater than the result |
| Remainder | % | 17 % 5 | Remainder after division |
2 ** 10
9 ** (1 / 2)A square root can be expressed as raising a number to the power 1/2.
7 / 4
7 // 4
-13 / 4
-13 // 4/ gives the normal division result. // gives the floor of the result. With negative numbers, floor means moving to the next smaller integer, so -13 // 4 is -4.17 % 5
7.5 % 3.5The remainder operator is commonly useful when checking divisibility, such as finding whether a number is even.
8 % 2
9 % 2Programming expressions are written in a horizontal, straight-line form. For example, a fraction is written using / or //.
10 * (5 + 3)
10 * 5 + 3Parentheses can force part of an expression to be evaluated first and can make the intended calculation clearer.
| Priority | Operators | Grouping |
|---|---|---|
| Highest | () | Inside parentheses first |
| Next | ** | Right to left |
| Next | * / // % | Left to right |
| Lowest among these arithmetic operators | + - | Left to right |
2 + 3 * 4
(2 + 3) * 4Some operations cannot be completed. For example, division by zero raises ZeroDivisionError.
123 / 0Using a variable that has not been defined can raise NameError.
z + 7print and Single-/Double-Quoted StringsThe built-in print() function displays text or values.
print('Welcome to Python!')
print("Welcome to Python!")A string is a sequence of characters. You can normally delimit it with single quotes or double quotes.
print('Welcome', 'to', 'Python!')When multiple arguments are passed to print, Python separates them with spaces by default.
| Sequence | Purpose | Example |
|---|---|---|
| \n | New line | print('A\nB') |
| \t | Horizontal tab | print('A\tB') |
| \\ | Backslash character | print('C:\\Temp') |
| \" | Double quote inside a double-quoted string | print("Say \"Hi\"") |
| \' | Single quote inside a single-quoted string | print('It\'s Python') |
print('Welcome\nto\nPython!')A long string can be continued onto another source line using the continuation character \. The source chapter also notes that parentheses are the preferred way to break long code lines when possible.
print('This is a long message that is '
'split into two strings.')print('Sum is', 7 + 3)Triple-quoted strings use either ''' or """. The source chapter recommends three double quotes in its style guidance.
message = """This is a string
that spans two lines."""
print(message)Internally, a multiline string contains newline characters where the source lines were separated.
print("""Display "hi" and 'bye' in quotes""")SyntaxError. You can escape the quote or choose a different string delimiter.The built-in input() function displays a prompt and waits for the user to type something. The important point is that input() always returns a string.
name = input("What's your name? ")
print(name)value1 = input('Enter first number: ')
value2 = input('Enter second number: ')
print(value1 + value2)If the user enters 7 and 3, the values are strings, so + concatenates them.
This is string concatenation: the second string is placed after the first string.
value = int(input('Enter an integer: '))
another_value = int(input('Enter another integer: '))
print(value + another_value)price = float(input('Enter price: '))Use float() when the input may contain a decimal value.
If text cannot be converted to the requested numeric type, Python raises an exception such as ValueError.
int('hello')input() → string. If you need a number, explicitly convert it with int() or float().if Statement and Comparison OperatorsA condition is a Boolean expression that evaluates to either True or False.
7 > 4
7 < 4| Operator | Meaning | Example |
|---|---|---|
> | greater than | x > y |
< | less than | x < y |
>= | greater than or equal to | x >= y |
<= | less than or equal to | x <= y |
== | equal to | x == y |
!= | not equal to | x != y |
if number1 == number2:
print('The numbers are equal')The structure is:
if→condition→:→indented suite= when you mean ==. Read = as "assigned" and == as "is equal to".number1 = int(input('Enter first integer: '))
number2 = int(input('Enter second integer: '))
if number1 == number2:
print(number1, 'is equal to', number2)
if number1 != number2:
print(number1, 'is not equal to', number2)
if number1 < number2:
print(number1, 'is less than', number2)
if number1 > number2:
print(number1, 'is greater than', number2)
if number1 <= number2:
print(number1, 'is less than or equal to', number2)
if number1 >= number2:
print(number1, 'is greater than or equal to', number2)A comment starts with # and is ignored by Python.
# This comment explains the next statement
age = 20The source chapter also introduces a script-level docstring to describe a program's purpose:
"""Compare two integers using if statements."""Blank lines and spaces make code easier to read. Indentation is different: indentation is part of Python's syntax for an if suite.
Python allows comparisons such as:
x = 3
1 <= x <= 5This is a convenient way to ask whether a value lies within a range.
Long statements can be split across lines. The source chapter notes that using parentheses to break long lines is preferred when practical.
print('Enter two integers, and I will tell you',
'the relationships they satisfy.')Python values such as 7, 4.1 and 'dog' are objects. Every object has a type and a value.
| Value | Type |
|---|---|
7 | int |
4.1 | float |
'dog' | str |
When you assign an object to a variable, the variable name becomes associated with that object.
x = 7
x + 10Python uses dynamic typing. The type is associated with the object a variable currently refers to; the same variable name can later refer to an object of another type.
x = 7
print(type(x))
x = 4.1
print(type(x))
x = 'dog'
print(type(x))Python creates objects in memory and automatically removes objects that are no longer needed. This automatic memory cleanup is called garbage collection.
| Order | Operators |
|---|---|
| 1 | () |
| 2 | ** |
| 3 | * / // % |
| 4 | + - |
| 5 | > <= < >= |
| 6 | == != |
Data science often begins by getting to know the data. Descriptive statistics provide simple ways to summarize a collection of values.
The chapter demonstrates a simple algorithm for three values:
number1 = int(input('Enter first integer: '))
number2 = int(input('Enter second integer: '))
number3 = int(input('Enter third integer: '))
minimum = number1
if number2 < minimum:
minimum = number2
if number3 < minimum:
minimum = number3
print('Minimum value is', minimum)min() and max()Python already provides built-in functions for common tasks.
min(36, 27, 12)
max(36, 27, 12)For the values 36, 27, 12, the minimum is 12 and the maximum is 36, so the range extends from 12 through 36.
The source introduces reduction as a functional-style programming idea: many values are reduced to one result. min() and max() are examples. Other reductions encountered later include sum, average, variance and standard deviation.
This chapter builds the first practical layer of Python programming. You move from calculator-style expressions to small programs that can store, display, receive, compare and summarize data.
int and float.+, -, *, **, /, // and %.print() to display values and text.\n and \t.input() returns a string.int() or float() when required.if statements for decisions.type(), min() and max().if→Objects→StatisticsIf you remember one idea: Python programs are built by combining values, names, expressions and statements. Once you understand those building blocks, larger programs become combinations of the same ideas.
= instead of === assigns a value; == compares two values.input() returns a string even when the user types digits.ifif condition:.if suite must be indented./ and // cannot divide by zero.A variable is a name associated with an object/value so the program can refer to it later.
= and ==?= assigns a value. == tests equality and produces True or False.
7 / 4 produce?1.75. True division produces a floating-point result.
7 // 4 produce?1. Floor division gives the greatest integer that is not greater than the mathematical result.
input() need conversion for arithmetic?Because input() returns a string. Use int() or float() when numeric arithmetic is required.
Python determines the type of the object a variable refers to while the program executes, and a variable can later refer to an object of another type.
Minimum is the smallest value, maximum is the largest value, and range describes the span from the minimum to the maximum.
8 * (10 - 3) / 2 and explain the evaluation order./, // and %.if to determine whether it is greater than 100.type() to inspect an integer, float and string.min() and max() on a collection of values and describe the resulting range.