Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Python Programming Language Study Sheet

Uploaded by

efe.yalcinkaya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Python Programming Language Study Sheet

Uploaded by

efe.yalcinkaya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Python Programming Language

Study Sheet

Design Lesson
Kemal İKİZOĞLU

v1: 25.12.2023
v2:10.03.2024
Table of contents:
Algorithms:......................................................................................................................................... 4
How can we create an algorithm?.....................................................................................................4
Pseudocode:...................................................................................................................................4
Flowchart........................................................................................................................................ 4
Use Python programming language in Information Technology fields:....................................... 5
Python Commands.............................................................................................................................5
print(“value”):.................................................................................................................................. 5
Escape Characters:........................................................................................................................ 5
Math Operators:..................................................................................................................................6
Inputs:..................................................................................................................................................6
Variable:...............................................................................................................................................6
Variable Create Criteria:.....................................................................................................................7
Variable Types:................................................................................................................................... 7
Programming Samples:..................................................................................................................... 7
Calculator:.......................................................................................................................................7
Average Calculator:........................................................................................................................ 8
Triangle’s Perimeter and Area Calculator:...................................................................................... 8
Square’s Perimeter and Area Calculator:....................................................................................... 9
String Tips:..........................................................................................................................................9
Data Transform:................................................................................................................................ 10
IF Statements:...................................................................................................................................10
IF - ELSE Statements:........................................................................................................................ 11
Comparison Operators:...................................................................................................................... 12
IF - ELIF - ELSE Statements:............................................................................................................. 13
Traffic Light Color Example:..........................................................................................................13
Cinema Ticket Example:...............................................................................................................14
Logical Operators:.............................................................................................................................. 15
Students’ Grades Example:.......................................................................................................... 15
Loops:................................................................................................................................................16
For Loop:...................................................................................................................................... 16
Break Command:................................................................................................................................17
Random Python Library:..................................................................................................................18
Guess Game:................................................................................................................................19
While Loop:................................................................................................................................. 20
Infinite Loop:................................................................................................................................. 20
Guess Game:................................................................................................................................22
User Login Example:.................................................................................................................... 22
Online Hate Speech:.........................................................................................................................23
Digital Footprint:...............................................................................................................................23
Strong Password Criteria:............................................................................................................... 23
Which information must be secret on the net?............................................................................. 23
Which information can I share on the net?....................................................................................24
Algorithms:
Computers and mobile devices are simply machines that perform three main tasks. It takes the
entered information (INPUT), processes it (PROCESSING) and outputs a result (OUTPUT) from
this processed data.

The algorithm is a set of rules of obtain the expected output from the given input. Before writing
an application, we write procedures using the logical steps required to solve the problem with an
algorithm. The algorithm shows us all the process steps from start to finish.

How can we create an algorithm?


There are two ways to represent an algorithm: Pseudocode and flowchart.

Pseudocode:
Pseudocode is an informal way of programming description that does not require any strict
programming language syntax or underlying technology considerations.

Pseudocode Sample:
1- Start (think first step)
2- Need two numbers (get or think)
3- Sum these numbers
4- Write result to screen
5- End

Flowchart
The flowchart is a diagrammatic representation of an algorithm, a step-by-step approach to
solving a task. The flowchart shows the steps as boxes of various kinds and their order by
connecting the boxes with arrows.

Flowchart Sample:
Use Python programming language in Information
Technology fields:
● Artificial Intelligence
● Data Analytics
● Data Visualization
● Programming Applications
● Web Development
● Game Development
● Language Development
● Search Engine Optimization

Python Commands

print(“value”):
Print command writes results on the screen. print (“Hello World”)

Escape Characters:
\n : When you use this command, continuing values are written to the bottom line.

Command: Result:

print(“Kemal\n İKİZOĞLU”) Kemal


İKİZOĞLU

\t : When you use this command, gives one tab space between values.

Command: Result:

print(“Kemal\t İKİZOĞLU”) Kemal İKİZOĞLU

# : Single line comment. When you use in your code, you don't see any result on screen. It’s just
for programmers and you.

Sample: #This command is a comment sign.


Math Operators:

Addition (+) x+y print(12 + 5) : 17

Subtraction (-) x-y print(9 - 4) : 5

Multiplication(*) x*y print(5 * 5) : 25

Division (/) x/y print(30 / 3) : 10

Mode (%) x%y print(24 % 5) : 4

Exponentiation(**) x ** y print(2 ** 5) : 32

If you use a different math process inside a single row, you should use common parenthesis in
your code.

print ((28 / 14 ) + (5 * 3 - 8)) :

Inputs:
When you get ınformation from people, we use this command. input(“description of input”)

Sample:

input(“Enter your favorite color”)


input(“Write first exam point”)

Variable:
Variable may represent a number, a vector, a matrix, a function, the argument of a function, a
set, or an element of a set. Data that keeps a given value in the computer's memory while
programming and allows us to use it wherever we want is called.
Variable Create Criteria:
● It can be short like x, y or long like first name and surname.

● It must begin with a letter or underscore.


● It cannot start with a number!
● It is case sensitive. In other words, the AGE variable and the age variable are not the
same!
● Variable names must not contain Turkish characters.

Variable Samples:

True Variable Use False Variable Use

● x_=12 ● va riable=10
● alfa=”Loremipsum” ● 9Class=17
● L2= True ● ÇayTime=5
● User_Pass=”120293" ● Sandviç=Monday
● _LHZ = “Car” ● Let’s=Friends
● $letsay=”Friday” ● Name Surname
● Name_Surname

Variable Types:
Integer (int) : The integer variable type uses whole numbers and numbers. 10, 100,
453,10931231123
Float (float) : The float variable type uses decimal numbers. 3.14, 62.5, 10.9
String (str) : The string variable type uses characters, text, sentences. Python, Hello, ENKA,
Boolean: The boolean variable type uses logic mean as True or False. Is this right? True.

Programming Samples:

Calculator:

We are getting value informations from users. We need to use input command here. When we
get each number here we transfer it to a variable for remember each value.
Code: Screen Result:

a = int(input("Enter first number ")) Enter first number 5


b = int(input("Enter second number ")) Enter second number 2
c = int(input("Enter third number ")) Enter third number 6
d = int(input("Enter fourth number ")) Enter fourth number 1
print("SUM = ", a+b+c+d) SUM = 14

Average Calculator:

We are getting two exam points and four quiz point values from users. We need to use input
command here. When we get each point value here we transfer to a variable for remember
each value again.

Code: Screen Result:

exam1 = int(input("Enter the score for Exam 1: ")) Enter the score for Exam 1: 12
exam2 = int(input("Enter the score for Exam 2: ")) Enter the score for Exam 2: 14
quiz1 = int(input("Enter the score for Quiz 1: ")) Enter the score for Quiz 1: 11
Enter the score for Quiz 2: 22
quiz2 = int(input("Enter the score for Quiz 2: "))
Enter the score for Quiz 3: 33
quiz3 = int(input("Enter the score for Quiz 3: ")) Enter the score for Quiz 4: 44
quiz4 = int(input("Enter the score for Quiz 4: ")) Your average score is 20.25

average = (exam1 + exam2 + quiz1 + quiz2 +


quiz3 + quiz4) / 6

print("Your average score is ",average)

Triangle’s Perimeter and Area Calculator:

We are calculating the perimeter and area of a triangle. In this sample, we think that each three
sides of triangle is equal. ( a side = b side = c side)

Code: Screen Result:


side = int(input("Enter a side of triangle: ")) Enter a side of triangle: 5
height = int(input("Enter height value of triangle: Enter height value of triangle: 2
")) Triangle perimeter: 15
Triangle area: 5.0
perimeter = side * 3
area = (side * height) / 2
print(“Triangle perimeter: “, perimeter)
print(“Triangle area: “, area)

Square’s Perimeter and Area Calculator:

We are calculating the perimeter and area of a square.

Code: Screen Result:

side = int(input("Enter a side of square: ")) Enter a side of square: 5


Square perimeter: 20
perimeter = side * 4 Square area: 25
area = side * side
print(“Square perimeter: “, perimeter)
print(“Square area: “, area)

String Tips:
Merge with plus symbol: Merge with comma symbol:

print(" Square Area : " + str(area) + "m2" ) print("Square's Area : " , area , "m2")

Samples:

Code with plus symbol: Result

name ='Kerem' I am Kerem and I am 20 years old.


age = 20
print("I am " + name + " and I am " + str(age) + " years
old.")
Code with comma symbol: Result

name ='Kerem' I am Kerem and I am 20 years old.


age = 20
print("I am " , name , " and I am " , age , " years old.")

Data Transform:
Data transform provides change between data types. If you have a float value, you can convert to integer
value.

Example:

3.14 is the float value. But I need integer value. When I use int(3.14) this value, I can reach an integer value.
This is 3. Reverse is possible too. 8 is an integer value. I need a float value. When I use float(8) this value, I
can reach a float of this value. This is 8.0 .

Integer value: 10. When I use float(10) this value is transforming a float value. Result is 10.0

Float value: 71.2. When I use int(71.2) this value is transforming an integer value.Result is 71.

IF Statements:
In computer programming, we use the if statement to run a block code only when a certain condition
is met. For example, assigning grades (A, B, C) based on marks obtained by a student.

if the percentage is above 90, assign grade A.

Base: Example

if (condition): if point > 50:


<statements> print(“You passed!”)

Samples:

Code Result

number = 10 The number is less than 15.

if number < 15:


print("The number is less than 15.")
Code Result

point= int(input("Please enter lesson point: ")) Please enter lesson point: 90
You passed this lesson.
if point > 85:
print("You passed this lesson.")

IF - ELSE Statements:
The if statement alone tells us that it will execute a block of statements if a condition is true, but not if
the condition is false. However, if we want to do something else in case the condition is false, we
can use the else statement together with the if statement.

Base: Example

if (condition): if point > 50:


Condition is true print(“You passed!”)
else: else:
Condition is false print(“Failed!”)

Samples:

Code Result

num1 = int(input("Enter number 1: ")) Enter number 1: 50


num2 = int(input("Enter number 2: ")) Enter number 2: 40
Number 1 is greater than number 2.
if num1 < num2:
print("Number 2 is greater than number 1.")
else:
print("Number 1 is greater than number 2.")
Comparison Operators:
Python supports the usual logical conditions from mathematics:

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

Samples:

Code Result

number= int(input("Enter a number: ")) Enter a number: 10


Number is even.
if (number% 2 == 0):
print("Number is even.")
else:
print("Number is odd.")

Code Result

password = input(“Enter your password: ”) Enter your password: s3cr3tK3y


Access granted!
if password == "s3cr3tK3y":
print("Access granted!")
else:
print("Access denied!")
IF - ELIF - ELSE Statements:
An elif statement is used when we want to specify several conditions in our code.

Code Result

value = 20 Value is equal to 20.

if value < 20 :
print("Value is less than 20. ")

elif value > 20:


print("Value is greater than 20.")

elif value == 20:


print("Value is equal to 20.")

else:
print(“Try again”)

Traffic Light Color Example:


Let’s write a python program that will check for the following conditions:
● If the light is green – Car is allowed to go
● If the light is yellow – Car has to wait
● If the light is red – Car has to stop
● Other signal – unrecognized signal.

Code Result

color = input("What is the traffic light color? : ") What is the traffic light color? : red
Car has to stop.
if color == "red":
print("Car has to stop")

elif color == "yellow":


print("Car has to wait")

elif color == "green":


print("Car is allowed to go")

else:
print("Unrecognized signal!")

If you write to the program as green, you will get a “Car is allowed to go” message on the result
screen.

Cinema Ticket Example:


Let’s write a cinema ticket app. Criterias:

● Select your 3 favorite films,


● Get user’s name and surname,
● Define film names to numbers
● Write to screen as a cinema ticket.

Code Result

print("Cinema Ticket App") Cinema Ticket App


print("-----------------") --------------------------
What’s your name?: Kemal İKİZOĞLU
ns = input("What's your name?: ") 1-Transformers, 2-Avatar, 3-TOPGUN
print("1-Transformers, 2-Avatar, 3-TOPGUN") Which film do you want to watch?: 3

film = str(input("Which film do you want to watch?: ")) Ticket Details:


if film == "1": -------------------
film = "Transformers" Your Name: Kemal İKİZOĞLU
Film Name: TOPGUN
elif film == "2": Have fun!
film = "Avatar"

elif film == "3":


film = "TOPGUN"

else:
film = "Wrong Selection!"

print("\nTicket Details:")
print("------------------")
print("Your Name: ", ns)
print("Film Name: ", film)
print("Have fun!")
Logical Operators:
and: This returns True if both x and y are true
Sample: point <=100 and point >= 85

or : This returns True if either x or y are true


Sample: x < 7 or x > 15

not : Returns True if the operand is false


Sample: not(x < 5 and < < 10)

Students’ Grades Example:


Your program should fulfill the following conditions:

● Grade A – 85 - 100 point


● Grade B – 70 - 84 point
● Grade C – 55 - 69 point
● Grade D – 45 - 54 point
● Grade E – 0 - 44 point
● others – Unrecognized

Code Result

point = int(input("Write your exam point: ")) Write your exam point: 75
Grade B
if point <=100 and point >= 85:
print("Grade A")

elif point <=84 and point >= 70:


print("Grade B")

elif point <=69 and point >= 55:


print("Grade C")

elif point <=54 and point >= 45:


print("Grade D")
elif point <=44 and point >= 0:
print("Grade F")

else:
print("Unrecognized point!")

If you write 90 point the program, you will see "Grade A" message on the screen. If you write K character the
program, you will see "Unrecognized point!" message on the screen.

Loops:
In computer programming, a loop is a sequence of instruction s that is continually repeated until a
certain condition is reached. Typically, a certain process is done, such as getting an item of data and
changing it, and then some condition is checked such as whether a counter has reached a
prescribed number.There are two loop types here: For and While Loop.

For Loop:
A for in loop is used for iterating over a sequence. (That is either a list, a tuple, a dictionary)

Base: Example

for i in range(number): for i in range(5):


statement print(i)

Number value might be just a number(10) or between two numbers in the range(10,20).

Code Result

for i in range(5): 1
print(i) 2
3
4

Code Result

for i in range(3): Good morning!


print(“Good morning!”) Good morning!
Good morning!
Code Result

50
for i in range(50,60,2): 52
print(i) 54
56
58

Important Note: Range can get three value. First value is start point of number. Second value is end point of
number. Third value is step number.

Code Result

for i in range(50,70,4): 50
print(i) 54
58
62
66

Weighted Sum Example:

Code Result

sum = 0 1
3
for i in range(1,10): 6
sum = sum + i 10
15
print(sum)
21
28
36
45

My sum value is 0. In each loop, my sum value is summing previous loop numbers.

Break Command:
The break command allows you to terminate and exit a loop.
Code Result

for i in range(10): 0
if i == 4: 1
break 2
print(i) 3

Code Result

for i in range(10): 0
if i % 2 == 0: 2
print(i) 4
6
8

Code Result

for i in range(10): 1
if i % 2 == 1: 3
print(i) 5
7
9

Code Result

colors = ("red", "green", "blue") red


green
for color in colors: blue
print(color)

Random Python Library:


The Python programming language has some fundamental libraries. Random library is one of the
Python libraries. This library generates random numbers in your program. For use, first define your
library in your program then generate a number between your range numbers.

import random

random.randrange(number1 , number2)

Sample: Let’s generate a number between 10 - 20 numbers.

Code Result

import random 14
s = random.randrange(10,20)

print(s)

Sample: Let’s generate two numbers between 10 - 20 numbers. Multiple these numbers and show
the result on the screen.

Code Result

import random Number 1 is 10


s1 = random.randrange(10,20) Number 2 is 19
s2 = random.randrange(10,20) 190
result = s1 * s2

print(“Number 1 is “, s1)
print(“Number 2 is ”, s2)
print(result)

Guess Game:
Let’s we prepare a guess game with For Loop. Game criterias:

● use random Python library,


● give 3 hearts to player
● Random range is between 0 - 10.

Code Result

import random Guess My Number


print("Guess My Number") --------------------------------
print("------------------") Guess a number between 0 - 10: 9
Your guess is bigger than number
heart=3 Guess a number between 0 - 10: 2
number=random.randint(0,10) Your guess is smaller than number
Guess a number between 0 - 10: 4
for i in range(heart): Congrats!
guess = int(input("Guess a number between 0 -
10: "))

if number == guess:
print("Congrats!")
break

elif number>guess and i!=heart-1:


print("Your guess is smaller than number.")

elif number<guess and i!=heart-1:


print("Your guess is bigger than number")

else:
print("The number was ", number, ".")

While Loop:
A while loop is used to execute a set of statements as long as a condition is true.

Base: Example

while (condition): b=1


<statements>
while b < 5:
print(b)
Infinite Loop:

Code Result

Infinite loop!
a=1 Infinite loop!
Infinite loop!
while a == 1: Infinite loop!
print("Infinite loop!") Infinite loop!
Infinite loop!
…….

This example is an infinite loop.

Code Result

i=1 1
2
while i < 6 : 3
print(i) 4
i += 1 5

Code Result

repeat = 1 How are you?: Fine


How are you?: Ok
while repeat <= 3: How are you?: Enough
repeat += 1
input("How are you?: ")

Code Result

i=1 1
2
while i < 5: 3
print(i) 4
i += 1 Loop completed
print("Loop completed")
Code Result

key = "true" If you quit press q: q


Closing…
while key == "true":
question = input("If you quit press q: ")
if question == "q":
print("Closing...")
break

Guess Game:
Let’s we prepare a guess game with For Loop. Game criterias:

● For guess, select a number,


● Guess range is 0-20 ,
● Sum wrong number in each loop.

Code Result

number = 5
sum = 0 Enter a number between 0-10: 5
Try again, 5
while True: Your number's sum is 5
value = int(input("Enter a number between 0-10: ")) Enter a number between 0-10: 3
if value == number: Try again, 3
print("You found it!") Your number's sum is 8
break Enter a number between 0-10: 7
sum+=value Try again, 7
print("Try again", value) Your number's sum is 15
print("Your number's sum is ", sum) Enter a number between 0-10: 6
You found it!

User Login Example:

In this example, we have username, password information. When user writes a true username and
password, show a message "Access granted!" on the result screen. If just username is wrong, show
a message is "wrong username". If just password is wrong, show "wrong password" message on the
result screen.

Code Result

username = "admin"
password = "piyt10" Enter your username: kemal
attempt = 0 Enter your password! 2024
Access denied! Please enter true
while attempt < 3: username and password!
uname = input("Enter your username: ")
passw = input("Enter your password!") Enter your username: admin
attempt = attempt + 1 Enter your password! 2222
Wrong password!
if uname == username and passw == password :
print("Access granted!\n") Enter your username: admin
break Enter your password! piyt10
elif uname != username and passw == password : Access granted!
print("Wrong username!\n")
elif uname == username and passw != password :
print("Wrong password!\n")

else:
print("Access denied! Please enter true
username and password!\n")

Online Hate Speech:


Online hate speech refers to negative statements made online against individuals or groups.
"I wish you were not among us", "Did you learn to take photographs", "We have seen people
like you a lot". These expressions, shared as comments on photos or articles, are a form of
online hate speech.

Digital Footprint:
The digital footprint is our data trace consisting of the pages we visit on the internet. For
example, a comment written on Facebook, a like given, or sharing a YouTube video on Twitter,
shooting or watching short videos on Youtube creates our footprint.
Strong Password Criteria:
To create a strong password, the following criteria should be taken into consideration:

● Must be at least 8 characters


● Must contain uppercase and lowercase letters
● Must contain numbers
● Must contain special characters (*-/+=?!)

Which information must be secret on the net?

● Identity number,
● Home address,
● Birthday, birthplace,
● Mobile number,
● Credit Card number,
● Contracts,
● Your school,
● Your district
● Bank accounts

Which information can I share on the net?


● Your name,
● Your nickname,
● Your interest,
● Your projects,
● Your social accounts

You might also like