0% found this document useful (0 votes)
3 views17 pages

Python Programming Overview and Operators

Uploaded by

ozkansudenur65
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views17 pages

Python Programming Overview and Operators

Uploaded by

ozkansudenur65
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

System Programming Ödev & Not

Lecture: System Programming

Fullname: Süleyman Özgür Özarpacı


Student Number: 1030516784
Python Programming
Why Python ?
What can Python do?
Operators
Arithmetic Operators
Assignment Operators
Comparison Operators (Boolean Operators)
Logical Operators
Identity Operators
Python Membership Operators
Variable Types
Setting the Data Type
Print
Executing
File I/O
Input
Casting
Random
Conditions (if-elif-else)
Eval-Exec
String Formatting
Length Function
Not Operator
Assignment Operator
in Operator
Identity Number
is Operator
Loops
While
For

Python Programming

System Programming Ödev & Not 1


Python is a popular programming language with multi-platform support. Python’s design
philosophy emphasizes code readability with the use of significant identation. Beside, Python
is a high-level, interpreted, general-purpose programming language.

Why Python ?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).

Python has a simple syntax similar to the English language.

Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.

Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.

Python can be treated in a procedural way, an object-oriented way or a functional way.

What can Python do?


Python can be used on a server to create web applications.

Python can be used alongside software to create workflows.

Python can connect to database systems. It can also read and modify files.

Python can be used to handle big data and perform complex mathematics.

Python can be used for rapid prototyping, or for production-ready software development.

Operators
Python divides the operators in the following groups:

Arithmetic operators

Assignment operators

Comparison operators

Logical operators

Identity operators

Membership operators

Bitwise operators

Arithmetic Operators

System Programming Ödev & Not 2


Arithmetic operators are used with numeric values to perform common mathematical
operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

Assignment Operators
Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Comparison Operators (Boolean Operators)


These comparison operators return boolean type variables. For example, "5 == 5" is True, so
this returns a True boolean value. In integer values, everything is True except zero. In string
values, null or empty string is False, but other than that, those are True.

System Programming Ödev & Not 3


Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical Operators
Logical operators are used to combine conditional statements:

Operator Descripton Example

Returns True if both statements


and x < 5 and x < 10
are true
Returns True if one of the
or x < 5 or x < 4
statements is true
Reverse the result, returns False
not not(x < 5 and x < 10)
if the result is true

Identity Operators
Operator Description Example

Returns True if both variables


is x is y
are the same object
Returns True if both variables
is not x is not y
are not the same object

Python Membership Operators


Operator Description Example

Returns True if a sequence with


in the specified value is present in x in y
the object

Returns True if a sequence with


not in the specified value is not present x not in y
in the object

System Programming Ödev & Not 4


Variable Types
Variable types are used in programming to keep, change and process the data that comes
from a user and machine. For example, integer, double, or float are used if the variable is a
number and array, list, and map are used for lists etc. Thus, the machines can use the RAM
more effectively. Built-in variable types in Python are as follows:

Type Equals to

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

The Type function returns the type of the variable. For example:

x = 5
print(type(x))

Setting the Data Type


Example Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

System Programming Ödev & Not 5


Example Type

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType

Print
Print functions print a string on the command line. As in every programming tutorial, we write
our first "Hello World" on the command line.

Open your favorite IDE or regular notepad and then add this into your file:

print("Hello World!")

You can merge 2 strings like:

print("Hello " + "World!")

Fo multiline prints or strings you can use """ .

print("""
Your long
Multilined
Content
Here
""")

Executing
Python programs have a ".py" suffix. So if you want to write a hello world application, you
must save it as a ".py" file. For example: "hello_world.py". Now you are ready to run your
code. Open the command line and write:

python hello_world.py

System Programming Ödev & Not 6


Now you should see:

Hello World!

File I/O
For opening files, we can use the open function. For example, if you want to open a file
named "[Link]", you have to write the code below. The first parameter is the file name,
and the second parameter is what you are going to do. In our example, we are going to write
some strings.

f = open("[Link]", "w")

But don’t forget to close your file after you've done your work.

[Link]()

We are learned how to open files. Now open a file and write Hello World in it.

f = open("[Link]", "w")
print("Hello World", file=f);
[Link]()

If you want to write immidiately, you must add third parameter as “flush = True”.

f = open("[Link]", "w")
print("Hello World", file=f, flush = True);
[Link]()

Not: Print command not appends to file. It writes above the file. If there is information in the
file, It was deleted after print.

f = open("[Link]", "w")
print("Hello World 1", file=f);
print("Hello World 2", file=f);
print("Hello World 3", file=f);
print("Hello World 4", file=f);
[Link]()

System Programming Ödev & Not 7


This code outputs this:

Hello World 1
Hello World 2
Hello World 3
Hello World 4

Input
If you want to get input from a user, you can use the input function. In this example, we are
going to get the user’s name as an input and print "Hello {name}". {name} going to be
replaced as the user’s input.

answer = input("What is your name?\n")


print("Hello " + answer)

If a user gave us "Süleyman" as an example. This code outputs:

Hello Süleyman

Casting
There are 3 types of casting in Python. String, integer and float.

str() // -> Convert to STR


int() // -> Convert to Int
float() // -> Convert to Float

There is an equivalent in Python like:

name = "Suleyman Ozgur Ozarpaci" # This is a string type variable


student_number = 1030516784 # This is an integer type variable
final = 72.6 # This is a string type variable

Note: YOU CAN’T PRINT AN INTEGER OR A FLOAT. YOU MUST CAST TO STRING.

For example get user’s midterm exam and final exam then calculate as this formula: midterm
* 0.4 + final * 0.6 so we must cast our input to integer for addition and multiplication. Add(+)

System Programming Ödev & Not 8


operator merges 2 strings but adds 2 integers or floats. So our code is like this.

midterm = input("What is your midterm score: ")


# cast midterm as integer. string to integer conversion.
midterm = int(midterm)

final = input("What is your final score: ")


# cast final as integer. string to integer conversion.
final = int(final)

calculation = final * 0.6 + midterm * 0.4


# cast calculation as string. float to string conversion.
print("Your calculated score is: " + str(calculation))

There is an example output:

What is your midterm score: 85


What is your final score: 55
Your calculated score is: 67.0

Random

import random

print([Link](1, 10))

Conditions (if-elif-else)
In the real world, we have conditions like you have to go outside and you look out the window.
Then you see it’s raining. What are you going to do next? You're going to take an umbrella,
right? Then this can be defined as "if it’s raining, then take an umbrella." In Python, we have 3
conditions.

if condition:
# if condition is True run this block
elif condition:
# if elif condition is True then run this block
else:
# if, if and elif is false then run this block

Python supports all the usual logical conditions from mathematics:

System Programming Ödev & Not 9


Equals: a == b

Not Equals: a != b

Less than: a < b

Less than or equal to: a <= b

Greater than: a > b

Greater than or equal to: a >= b

For example, calculate the user’s midterm and final score. If it’s less than 50 and greater than
0, print FAIL. If it’s greater and equals 50 and less than 100, print PASS. Else print invalid.
Our code is like this:

midterm = input("What is your midterm score: ")


# cast midterm as integer. string to integer conversion.
midterm = int(midterm)

final = input("What is your final score: ")


# cast final as integer. string to integer conversion.
final = int(final)

calculation = final * 0.6 + midterm * 0.4


# cast calculation as string. float to string conversion.
print("Your calculated score is: " + str(calculation))

if calculation >= 0 and calculation < 50:


print("Result: FAILED")
elif calculation >= 50 and calculation <= 100:
print("Result: PASSED")
else:
print("Result: INVALID")

For example, I am going to test and write outputs on different values.

What is your midterm score: 15


What is your final score: 45
Your calculated score is: 33.0
Result: FAILED

What is your midterm score: 85


What is your final score: 65
Your calculated score is: 73.0
Result: PASSED

System Programming Ödev & Not 10


What is your midterm score: -15
What is your final score: -10
Your calculated score is: -12.0
Result: INVALID

You can see we are getting 3 different score results.

Eval-Exec
According to an answer on Stackoverflow:
Basically, eval is used to evaluate a single dynamically generated Python expression,
and exec is used to execute dynamically generated Python code only for its side effects.
eval and exec have these two differences:

1. evalaccepts only a single expression, exec can take a code block that has Python
statements: loops, try: except: , class and function/method def initions and so on.

An expression in Python is whatever you can have as the value in a variable assignment:

a_variable = (anything you can put within these parentheses is an expression)

2. eval returns the value of the given expression, whereas exec ignores the return value
from its code, and always returns None (in Python 2 it is a statement and cannot be used
as an expression, so it really does not return anything).

This is what eval and exec basically is.


Let’s make an example for understand functions correct: get simple matematic expression
and then print the result. For example user inputs “5 + 15” and result should be 20. So code
should look like this.

print("""
Please write your expression like:
Addition: 15 + 5,
Subtraction: 15 - 5,
Divison: 15 / 5,
Multiplication: 15 * 5,
Exponentiation: 2 ** 3 => 2^3
""")

user_input = input("Write: ")


# Check if user input empty string
if user_input != "":
result = eval(user_input)

System Programming Ödev & Not 11


print("Result:" + str(result))
else:
print("You didn't write anything.")

Let’s test out code. This is output of “55 + 22” expression.

Please write your expression like:


Addition: 15 + 5,
Subtraction: 15 - 5,
Divison: 15 / 5,
Multiplication: 15 * 5,
Exponentiation: 2 ** 3 => 2^3

Write: 55 + 22
Result:77

Let’s check empty expression.

Please write your expression like:


Addition: 15 + 5,
Subtraction: 15 - 5,
Divison: 15 / 5,
Multiplication: 15 * 5,
Exponentiation: 2 ** 3 => 2^3

Write:
You didn't write anything.

String Formatting
Python allows us to format strings. Sometimes we need to print some strings, like
templates. "Hello {name}", "You added {item} to your cart" or "You have {points} point but you
need to at least {minPoint} points" are good example for this. Format function replace {} as
our input. So lets make an example. Ask for the user’s name, last name, age and school
name. Then print according to this template: "Hi, i am {name} {username} and i am {age}
years old. I am study in {school}. The code should look like this:

name = input("Tell me your name: ")


lastname = input("Tell me your lastname: ")
age = input("Tell me your age: ")
school = input("Tell me your school: ")
print("Hi i am {} {} and i am {} years old. I am study in {}".format(name, lastname, age, school))

As an example, i am going to fill this template with my information. It outputs this:

System Programming Ödev & Not 12


Tell me your name: Suleyman Ozgur
Tell me your lastname: Ozarpaci
Tell me your age: 25
Tell me your school: Erciyes University
Hi i am Suleyman Ozgur Ozarpaci and i am 25 years old. I am study in Erciyes University

As you see, brackets ({}) replaced with my inputs by their order in format parameters. In
addition, you can format numbers and decimals. For example, if you write like this "{:.2f}",
your number will be formatted with just 2 decimals. If "Order Total: {:.2f}" is your template and
the input is 75.195 then your output is "Order Total: 75.195". You can see it takes only 2
decimals.
The last is the used index number. It starts from zero. For example, if you want to use a
template like this: "Hi {1}, welcome back. Your point: {0}" you have to use this format
format(point, name). As you see, the point’s index is zero as the name’s index is one. You
can use this multiple indexes like "His name is {0} and {0} is {1} years old.". In this example,
both {0} going to be replaced as names.

Length Function
If you want to get the length of a string or an array, there is a function called len. For example,
let's ask a user for a string and print the length of the string that user gives us.

print("Please give a string to print the length:")


example_string = input()
length_of_the_string = len(example_string)
print("Your string's length is:" + str(length_of_the_string))

I am going to give an input which is my student identity number. This program must give me a
length of 10.

So if you want to get an array item count, you can use it for an array too. Let’s print the
number of days the weekdays. Now our code looks like this:

System Programming Ödev & Not 13


weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
length_of_the_week = len(weekdays)
print("There is " + str(length_of_the_week) + " days in a week.")

This code outputs:

There is 7 days in a week.

Not Operator
not operator inverts the boolean result. Think you have an isAdmin boolean value. So if user
is NOT admin, “not isAdmin” returns true because isAdmin variable is false and “not” inverts
the value false to true.

parola = ""
print(bool(parola)) # returns false
print(bool(not parola)) #return true

Assignment Operator
= Assign

a = 23 # assign 23 value to a variable

+= Add then assign

a = 23 a = 23
a += 5 a = a + 5
#a equals to 28 # a equals to 28

-= Sub then assign *= Multiply then assign /= Divide then assign

**= Power of

a = 12
a **= 2
# a equals to 144

System Programming Ödev & Not 14


%= Mod

//= division division then assign

a = 5
a //= 2
# a is equals to 2

:= Walrus (Python 3.8)

in Operator
is operator checks a value inclues in variable. returns bool.

a = "abcd"
"a" in a
# returns true because variable contains "a" value
"f" in a
# returns false because variable does not containes "f" value

Identity Number
id is short for identity.

a = 100
id(a)
# returns identification of 100 value in a

a = 100
b = 100
id(a)
id(b)
# returns same id numbers but if 100 is string then id's going to be different

System Programming Ödev & Not 15


This shows us Python does not creates new memory location for same value. So a and b
points same memory location.

is Operator
is operator checks the equality of variables as id’s so is not like “==” operator.

a = 1000
a is 1000
# returns false. to fix that we must do like this:

print(id(a) == id(1000))
# now this code returns true

Loops
While

count = 0
while (count < 3):
count = count + 1
print("Hello Geek")

You can add else

count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")

You can break the loop with break statement

while True:
q = input("press q if you want to quit")
if (q == "q"):
print("quiting")
break

System Programming Ödev & Not 16


For

n = 4
for i in range(0, n):
print(i)

print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)

# Iterating over a tuple (immutable)


print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)

# Iterating over a String


print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)

# Iterating over dictionary


print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
print("%s %d" %(i, d[i]))

#Iterating over a set


print("\nSet Iteration")
set1 = {1,2,3,4,5,6}
for i in set1:
print(i)

System Programming Ödev & Not 17

You might also like