
































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

































Halil Özmen
about some of the features of Python. These notes are intended to be used as a check list by the instructor who teaches programming courses to students. The first ten chapters can be used in an introduction to programming course targetting students who has no programming knowledge, and the last four chapters can be used in more advanced Python programming courses.
Computer Program: A computer program is a sequence or set of instructions in a programming language for a computer to execute.
Computer Programming Process: Computer programming is the process of performing a particular computation, usually by designing and building an executable computer program. Programming involves tasks such as analysis, generating algorithms (design and implementation), profiling algorithms' accuracy and resource consumption, and the implementation of algorithms.
Programming Languages:
A programming language is a system of notation for writing computer programs. Assembly Language is any low-level programming language with a very strong correspondence between the instructions in the language and the architecture's machine code instructions. A high-level language is any programming language that enables development of a program in a much more user-friendly programming context and is generally independent of the computer's hardware architecture.
Machine Language: 01101011 01010100 10111011 11101010 00100111 ....
Assembly Language: LBL4: MOV AX, ADD R3, # CMP AL, BL JE LBL
High Level Language: a = int(input("Enter an integer number: ")) if a % 2 == 0: a = a / 2 print(a)
History of Programming Languages: (only some major languages are listed)
1951 - Assembly Language 1954 - FORTRAN 1958 - LISP 1958 - ALGOL 1959 - COBOL 1964 - BASIC 1964 - PL/I 1970 - Pascal 1972 - C
1978 - SQL (query language) 1980 - C++ 1984 - MATLAB 1990 - Python 1993 - R 1995 - Java 1995 - PHP 2002 - Scratch ....
Assembler, Compiler, Linker, Loader, Interpreter:
Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming.
Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.
Some of Python's notable features:
Some programming-language features of Python are:
To install Python, download Python installation program (python-3.14.0-amd64.exe or similar) from web site python.org , and run it. This will install Python and its environment to your computer.
https://www.programiz.com/python-programming/online-compiler/ https://www.w3schools.com/python/trypython.asp?filename=demo_compiler
Under Windows, run "IDLE (Python 3.x ... bit)" from Start menu.
The "Python 3.?.? Shell" window will be opened.
The first few lines will be similar to: Python 3.13.3 (tags/v3.13.3:6280bb5, Apr 8 2025, 14:47:33) [MSC v. 64 bit (AMD64)] on win Enter "help" below or click "Help" above for more information. >>> After the prompt >>> the user can enter Python commands (statements).
Strings:
Strings will be covered more deeply in subsequent chapters, here this is an introduction to strings. String constants are delimited with a single quote ('), double quote ("), triple single quote (''') or triple double quote ("""). a = 'Antalya' ab = "Antalya is beautiful" s1 = '40' + "8" # "408" t1 = """Ali'yi Kaan"a, \nabcd 123456 efgh""" # \n : newline. print(t1) Ali'yi Kaan"a, abcd 123456 efgh
In Python, variable names must start with an alphabetical character (A-Z, a-z) or underscore '', and can contain alphanumeric character (A-Z, a-z, 0-9) or underscore ''.
Variable names are case sensitive. Example: a and A are two different variables.
Variable names can not start with a digit and can not contain space or other special characters. Valid variables: a z A Z a8 _a8 _ _0 a1 _1a c3po C3pO
Invalid variable names: 8a a-8 a 8 a&b a^b Good variable names make programs more readable by humans. Since programs often contain many variables, well-chosen variable names can make a program more easily understandable. a = 7 pi = 3. city = "Ankara" x = 10 print('x =', x) x = 20 # value of x is changed print('x =', x) x = 3.14159 # value of x is changed again print('x =', x) x = 'Antalya' # x has been changed one more time print('x =', x) x = '30' + "4444" # x has been changed once more print('x =', x)
Expressions:
An expression contains one or more variables or constants, and may contain operators and/or parenteses. 7 + 8 7.2 ** 2
c = (a + 2) / b
a = b + (c * 2) / (a - 1) b * b – (4 % a * c / (d - 4)) ** 0.
A user variable or function name can not be same as a Python keyword, or an existing Python function name. Python Keywords (Reserved Words):
First the expression at the right hand side of = is evaluated, then the result is stored in (assigned to) the variable (or object) on the left side.
variable = expression # expression is computed, result is assigned to variable.
**a = 7 # 7 is assigned to variable a pi = 3.14159 # 3.14159 is assigned to variable pi b = a + 2 # expression a + 2 is computed, result is assigned to variable a. x, y, z = 100 / 5, -45, 0.5 # Multiple assignment statement. x, y = y, x # Swap (exchange) contents of two variables n = 88 n += b + c # Equivalent to: n = n + (b+c) n -= 7 # Equivalent to: n = n - 7 n *= 4 # Equivalent to: n = n * 4 n /= 10 # Equivalent to: n = n / 10 n %= 10 # Equivalent to: n = n % 10 n //= 10 # Equivalent to: n = n // 10 n = 2 # Equivalent to: n = n ** 2 a = "Ant" a += "alya" # Equivalent to: a = a + "alya" -> "Antalya"
We may need to get a data of a type by converting data of other type. Sometimes type conversion occurs automatically, and in some cases, we may need to use type conversion functions. Type Conversion Functions:
ascii() Returns a string containing a printable representation of an object bin() Converts an integer to a binary string bool() Converts an argument to a Boolean value chr() Returns string representation of character given by integer argument complex() Returns a complex number constructed from arguments float() Returns a floating-point object constructed from a number or string hex() Converts an integer to a hexadecimal string int() Returns an integer object constructed from a number or string oct() Converts an integer to an octal string ord() Returns integer representation of a character repr() Returns a string containing a printable representation of an object str() Returns a string version of an object type() Returns the type of an object or creates a new type object
Expression Result Expression Result int('4') int('4.88') int(8.9876) float(4) float("4.88")
**Error 8
4.**
str(4) 5 + int('10') '5' + str(10) 5 + str(10)
Error
Truth Tables of Logical (Boolean) Operators:
a b not a a and b a or b False False True False False False True True False True True False False False True True True False True True
Logical (Boolean) Expressions: not t > u t > u and v == w t > u or v == w (t > u and t <= v) or (w > t and w >= v)
not 0 not 1 not 5 not -
not 0. not 32. not -0.
Precedence of Operators:
Level Operators Meaning 1 () Parentheses 2 ****** Exponent (power) 3 +x - x ~x Unary plus, Unary minus, Bitwise NOT 4 *****^ /^ //^ %^ Multiplication, Division, Floor division, Modulus 5 +^ -^ Addition, Subtraction 6 << >> Bitwise shift operators 7 & Bitwise AND 8 ^ Bitwise XOR 9 | Bitwise OR 10 ==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators 11 not^ Logical NOT 12 and Logical AND 13 or Logical OR
The basic form of an if statement is as follows: if condition: # condition is followed by colon ':' block of statements # all block statements are indented equally
If the condition is True , then the block is executed, then execution continues after the block. If the condition is False , the block is not executed, the execution continues directly after the block.
Rules:
x = 1 if x == 1: print("x is 1.")
if n >= 10 and n <= 99: .... ....
a = 24 b = 60 if a < b: a = b + 1 print("a =", a, " b =", b)
if a >= b and c == d: .... .... if-block statements ....
The basic form of an if - else statement is as follows: if condition: # condition is followed by colon ':' if-block else: # else is followed by colon ':' else-block If the condition is True , then if-block is executed.
If the condition is False , then else-block is executed.
It is same as: if condition: if-block if not condition: else-block In either case, after if-block or else-block, the execution continues after the if-else statement. a, b = 10, 20 if a > b: print("a > b") # These two statements forms the if-block b = b * 2 else: print("a <= b") # These two statements forms the else-block a *= 2
Nested if statements are structures where there is (inner) if-statement inside another (outer) if- statement.
If there are nested if-statements only inside else-blocks, then if- elif statements can be used.
General Form of Nested if: Now let's examine the general form of nested if's. There may be nested if inside if-blocks as well as inside else-blocks. if condition-1: if condition-2: block- else: block- else: if condition-3: block- else: block-
if gender == "F": if age < 20:
else:
else: # case: gender == "M" if age < 20:
else:
Example: a = int(input("Enter a number: ")) b = int(input("Enter a number: ")) if a < 0: if b < 0: print("Both numbers are negative.") else print("Only the first number is negative.") else if b < 0: print("Only the second number is negative.") else print("None of numbers are negative.")
The loop statements are used when there is a need for repeating tasks.
Python's built-in function range() produces an object that will generate a sequence of integers. The arguments of range function are integer.
Single argument range(stop) the sequence starts at 0 and continues to the integer before stop (0 1 2 ... stop-1). Identical with: range(0, stop)
Two arguments range(start, stop) the sequence starts at "start" and continues to the integer before "stop" (till [stop - 1]).
Three arguments range(start, stop, increase/decrease)
Starts at "start", every time is increased (decreased) by "increase/decrease" and continues to the integer before "stop".
Example range() functions: range(5) # from 0 (inclusive) till 5 (exclusive):=> 0, 1, 2, 3, 4 range(2, 6) # from 2 (inclusive) till 6 (exclusive):=> 2, 3, 4, 5 range(4, 10, 2) # from 4 (inclusive) till 10 (exclusive) by 2:=> 4, 6, 8 range(4, 1, -1) # from 4 (incl.) till 1 (excl.) by -1:=> 4, 3, 2 range(12, 4, -2) # from 12 (incl.) till 4 (excl.) by -2:=> 12, 10, 8, 6
The basic forms of for statements are as follows: # To repeat loop for each number generated by range() function: for var in range(10): # ends with colon ':' block of Python statements
for var in range(4, 10): # ends with colon ':' block of Python statements
**for var in range(2, 11, 2): # ends with colon ':' block of Python statements
string = "..some string.." for ch in string: block of Python statements # eg.: print(ch)
for var in list: # ends with colon ':' block of Python statements**
Examples:
for x in range(5): # from 0 (inclusive) till 5 (exclusive) print(x)
for x in range(3, 6): # from 3 (inclusive) till 6 (exclusive) print(x)
for x in range(4, 10, 2): # from 4 till 10 (exclusive), 2 by 2 print(x)
for x in range(10, 4, -2): # from 10 till 4 (exclusive), by - print(x) print ("loop for elements of a list:") primes = [2, 3, 5, 7, 11, 13, 17, 19] # This is a list. for prime in primes: print(prime)
Different solutions for the same problem:
Write a Python for loop that prints 4-digit positive numbers that ends with 77, in increasing order.
I.e. print 1077 1177 1277 .... 9877 9977
for n in range(1000, 10000): # Generate all 4-digit positive numbers if n % 100 == 77: # Check if last 2-digits is 77. print(n)
for n in range(1077, 10000, 100): # Generate 1077 1177 1277 ... 9977 print(n)
for k in range(10, 100): # Generate left-most 2 digits: 10 11 ... 99 n = k * 100 + 77 print(n) # or: print(k * 100 + 77) without using n Solution 2 is best, because it only generates the necessary numbers and doesn't perform any extra iteration or any extra computation.
Find the sum of numbers divisible by n from n1 to n2 (both inclusive). n1, n2 and n are integers.
sum1 = 0 for k in range(n1, n2+1): # Generate all numbers from n1 to n if k % n == 0: # Check if number is divisible by n sum1 += k # Add to sum print(sum1)
if n1 % n == 0: # If n1 is divisible by n, k1 = n1 # then start number is n else: # Find smallest number greater than n1 and divisible by n. k1 = n1 - n1 % n + n sum2 = 0 for k in range(k1, n2+1, n): sum2 += k print(sum2)
If there are loops inside other loops, then this structure is called " nested loops ".
Nested for loop examples: for n10 in range(10, 40, 10): # Will produce values: 10 20 30 for n1 in range(1, 4): # Will produce values: 1 2 3 print(n10 + n1)
for n10 in range(10, 40, 10): # Will produce values: 10 20 30 for n1 in range(1, 4): # Will produce values: 1 2 3 print(n10 + n1, end=" ") print()
for f in range(1,5): print("f=", f, "start") for n in range(1,4): print("n=", n) print("f=", f, "end")
print("Triangle of asterisks") for r in range(1, 5): # r: 1, 2, 3, 4 for c in range(r): print("*", end="") print()
break statement: The break statement causes to terminate the loop before it has looped through all the items. The execution continues after the loop. for n in range(1, 10): if n >= 5: break print(n)
k = 827419 while k > 0: if k % 2 == 0: break k //= 10 # k = k // 10
fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break print (20 * "=") for x in fruits: if x == "banana": break print(x)
continue statement: The continue statement causes Python to skip immediately the rest of the current iteration (stop the current iteration), and continue with the next iteration. for n in range(1, 10): if n >= 5 and n <= 7: continue # continue with next iteration print(n) for n in range(10, 41): if n % 2 == 0: # if n is even continue # then continue with next iteration print(n) str = 'Oz48gur19luk' total = 0 # The sum of the digits seen so far. count = 0 # The number of digits seen so far. for c in str: if not c.isdigit(): # If not digit, continue # then continue with next character. count = count + 1 total = total + int(c) print("Number of digits =", count, " Sum of digits =", total)
Exercises:
A function is a piece of program that takes zero or more parameters, and performs a well defined task.
Function Call:
The general form of a function call is as follows:
function_name(arguments)
Function Arguments:
Arguments are placed between parentheses and separated by a comma.
An argument is an expression that appears between the parentheses of a function call. int(7.8) print(a, b+c) abs(x) abs(n - 7) int(1.5**2) round(a - b / c, 2)
The rules to executing a function call:
If a function returns a value, then its function call can be used in expressions: aa = abs(-7 + 2) + abs(3.3 * -2) * 2 # 5 + 6.6 * 2 = 18. result = max(7, 12) * abs(-2) # 12 * 2 = 24 for k in range(1, 40, 7): # => [1, 8, 15, 22, 29, 36]
We can also use function calls as arguments to other functions: pow(abs(-2), round(4.3)) # pow(2, 4) => 16 n = int(input("Enter an integer number: ")) R = float(input("Enter a number: ")) a = int(5 + float("4.8") * 2) # --> 14
Python comes with many built-in functions that perform common operations.
Built-in Python Functions:
abs() delattr() globals() locals() property() str() all() dict() hasattr() long() range() sum() any() dir() hash() map() raw_input() super() basestring() divmod() help() max() reduce() tuple() bin() enumerate() hex() memoryview() reload() type() bool() eval() id() min() repr() unichr() bytearray() execfile() input() next() reversed() unicode() callable() file() int() object() round() vars() chr() filter() isinstance() oct() set() xrange() classmethod() float() issubclass() open() setattr() zip() cmp() format() iter() ord() slice() import() compile() frozenset() len() pow() sorted() complex() getattr() list() print() staticmethod()
Examples of function calls: print(a, b, c) int(7.84) # convert to int Result: 7 int("1919") # convert to int Result: 1919
def isPrime(num): if num < 2: return False for j in range(2, num//2+1): # or: in range(2, round(num**0.5)+1) if num % j == 0: # if j is divisor of n, return False # then num is not a prime number return True
a = int(input("Enter an integer number: ")) if isPrime(a): print(a, "is a prime number.") else: print(a, "is NOT a prime number.")
print("Prime numbers from 100 to 200 are:") for n in range(100, 201): if isPrime(n): print(n , end = ' ')
Variables that are created outside of a function (as in all of the examples in the previous pages) are known as global variables. Global variables can be used anywhere, both inside of functions and outside. x = "awesome" def myfunc(): print("Python is " + x) # global
myfunc()
x = "awesome" def myfunc(): x = "fantastic" # local print("Python is " + x) myfunc() print("Python is " + x) Python is awesome Python is fantastic Python is awesome
Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword. def myfunc(): global x # now x is a global variable x = "fantastic" myfunc() print("Python is " + x) # since x is a global variable, it is available here
Exercises:
In computer science , a string is a finite sequence of characters (i.e., letters, numerals, symbols and punctuation marks, etc.). An important characteristic of each string is its length, which is the number of characters in it. The length can be any natural number (i.e., zero or any positive integer).
Each character is represented by a number using ASCII encoding (ASCII Code).
Some important ASCII codes: ' ' (space): 32 (20H), '0' : 48 (30H), 'A': 65 (41H), 'a': 97 (61H).
Strings can be assigned and can be compared to other strings.
String Length: len() function returns the number of characters in a string. len("Albert Einstein") -> 15 len('123!') -> 4
String Constants String constants are delimited with either a single quote ('), double quote ("), triple single quote (''') or triple double quote ("""). The opening and closing quotes must match. "" # Null string or empty string "?" "k" "7" "\n" # Strings with a single character 'Antalya' "Antalya is beautiful" """Jane's friend asked:\n"Are you alien?".""" # \n : newline. "René Descartes' # ERROR: opening and closing quotes do not match print('That's beautiful.\n') # "That's beautiful.\n" print("A single \ back slash. Time is\nnot\t"linear".") print(1, "\t", 2, "\n", 4, "\t", 8)
String Operators:
Operator Description Examples
strings.
"I love" + " nature!" "Good" + " morning" + "!" surname + ", " + name
Comparing Strings:
Case Sensitive Comparison: (ASCII codes are used) "ZZZ" < "aaa" "Abcd" < "Abcd " "aaZZZZ" < "aaa" "CS99" > "CS8888" "KZBZHGV" < "KZa" "CS9999" < "Cs88" "abcd" > "ABCD" "ABA" > "AB9999"
Case Insensitive Comparison: (Upper and lower case of same letter are treated as equal.) "ZZZ" > "aaa" "CS990a" == "Cs990A" "KZZZH8" > "KZa" "CS990" > "Cs8888" "abcd" == "ABCD" "CS990a " > "Cs990A"