0% found this document useful (0 votes)
20 views24 pages

DOT 1003 - Fundamentals of Programming - Week 7

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)
20 views24 pages

DOT 1003 - Fundamentals of Programming - Week 7

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

Fundamentals of

Programming
Week 7 - Tuple, Set, Local&Global
Variables, Introduction to Error Handling

18.11.2024 | DOT 1003 | Mahmut Can Kovan


Agenda
● Tuple
● Set
● Local and Global Variables
● Error Handling

141
Tuple
>my_tuple = (0,1)
>my_tuple[0] = 1

>TypeError: 'tuple' object does not support item


assignment
● immutable and regular
parentheses list >my_coordinates = {}
>my_coordinates[(0,0)] = "Center"
● Values of tuple cannot be >my_coordinates[(1,0)] = "Right"
>my_coordinates[(-1,0)] = "Left"
changed after defined. >print(my_coordinates[(0,0)])

● can be used as keys in dictionary >Center


● parentheses not necessary

>def my_fancy_function(fancy_input)
> #do magic
> return ans1, ans2 #return tuples
>my_tuple = my_fancy_function(my_input)

>

142
Programming Task 67
● Create a function named coordinator which takes two arguments as
integer and return tuples

>(5,6) >def coordinator(x,y): #function here


>
>my_coordinates = coordinator(5,6)
>print(my_coordinates)

143
Programming Task 68
● use that function to fill coordinate dictionary. Add these coordinates
as keys and location names as values

>position: (0,0), name: Home >my_coordinates = {}


>position: (1,1), name: Work >def coordinator(x,y): #function here
>position: (-1,-1), name: School >
>my_coordinates[coordinator(0,0)] = "Home"
>my_coordinates[coordinator(1,1)] = "Work"
>my_coordinates[coordinator(-1,-1)] = "School"
>
>for k,v in my_coordinates.items():
> print(f"position: {k} name: {v}")

144
Programming Task 69
● Please create a function named print_best_weapon which takes a list
of tuples as argument and no return parameters
● Your function should find the best meele weapon and print its name

>sword >weapon1 = ("blade", 10)


>weapon2 = ("sabre", 35)
>weapon3 = ("sword", 50)
>meele_weapon = [weapon1, weapon2, weapon3]
>print_best_weapon(meele_weapon)
>
>def best_weapon(weapon_list: list):
>#TODO

145
Programming Task 70
● Ask user for new input or exit. If enter exit, print the board
● Use the function you created at task 67 for creating tuples using user
input.
● add these inputs to the list named user_input
● change the my_table list using user input from _ to * after the exit
command
>_ _ _ >game_table = [[_,_,_],[_,_,_],[_,_,_]]
>_ _ _ >user_inputs = []
>_ _ _ >#Your code here
>please type new or exit: new >
>please enter x: 0 >
>
>please enter y: 0
>
>please type new or exit: exit >
>* _ _
>_ _ _
>_ _ _ 146
Set
>my_set = {0,1}
>print(my_set[1])

>TypeError: 'set' object does not support


indexing
● mutable and unordered.
● Every item is unique. There is no >my_set = set()
>my_set.add("Gauntlet")
duplicate items in set >my_set.add("Sword")
>my_set.add("Bow")
● You can create empty set using >my_set.add("Spear")
>my_set.remove("Gauntlet")
set() function >my_set.add("Sword")

You can’t change the items but


>
● >for item in my_set:

add/remove is possible
print(item)

● Boolean True and integer 1 is the >print("javelin" in my_set)

same thing for set. Thus, they >Spear


treated like duplicate items >Sword
>Bow
>False
147
Programming Task 71
● Please create a empty set.
● ask user for unique element until user enters exit
● print these elements after exit command

>Enter an element for set: List >


>Enter an element for set: Dictionary
>Enter an element for set: Tuple
>Enter an element for set: Set
>Enter an element for set: xit
>List
>Dictionary
>Tuple
>Set
148
Programming Task 72
● Please create a empty set.
● ask user for unique element until user enters exit
● if user enter an element which already exists, print a warning message
● print these elements after exit command

>Enter an element for set: List >


>Enter an element for set: Dictionary >
>Enter an element for set: List >
>List is already in our set. >
>Enter an element for set: Set
>Enter an element for set: exit
>List
>Dictionary
>Set
149
Local Variables
>def my_dumb_func():
● Every variable has a scope, which > my_var = "Gandalf"
> print(my_var)
defines where the variable is >

accessible.
>my_dumb_func()
>print(my_var)
● If a variable is only accessible in a
>Gandalf
limited (or defined) section of the >NameError: name 'my_var' is not defined
program, this is a local variable

150
Global Variables >def my_dumb_func():
>
>
>
my_var = "Saruman"
print(my_var)

>my_var = "Gandalf"
● A variable which accessible from >my_dumb_func()
>print(my_var)
everywhere in the program
● Global variables are useful when >Saruman
>Gandalf
we need to have higher level
information >def my_dumb_func():
> #global my_var
>def my_dumb_func(): > print(my_var)
> print(my_var) > my_var = "Saruman"
> >
>my_var = "Gandalf" >my_var = "Gandalf"
>my_dumb_func() >my_dumb_func()
>print(my_var) >print(my_var)

>Gandalf UnboundLocalError: local variable 'my_var'


>Gandalf referenced before assignment
151
Global Variables
● We can use global keywords to >def my_dumb_func():
> global my_var
mean to change the global >
>
my_var = "Saruman"
print(my_var)
variable within a function >
>my_var = "Gandalf"
>my_dumb_func()
>print(my_var)

Saruman
Saruman

152
Programming Task 74
● Which variables global and which variables are local?
>def ask_name():
> my_ans = ""
> return input("Please enter a character from Lord of the Rings")
>
>def ask_age():
> my_ans = int(input(f"How old are {name}: "))
> return my_ans
>
>real_age = 55000
>name = ask_name()
>question = f"Here is the questions about {name}"
>print("")
>user_guess = ask_age()
>if real_age == user_guess:
> my_ans = "You’re Right"
> print(my_ans)
>else:
> print("Nope")
153
Programming Task 75
● Find the problem and fix it.

>def start_game(): >


> score = 10 >
> print(f"Game started! Current score: {score}") >
> >
>def increase_score(): >
> score += 5 >
> print(f"Score increased! Current score: {score}") >
> >
>def display_score(): >
> print(f"Final score: {score}") >
> >
>score = 0 >
>start_game() >
>increase_score() >
>display_score() >

154
Error Handling
>x,y = 10,0
>print(f"{x} divided by {y} is {x / y}")

>ZeroDivisionError: division by zero

● We should handle runtime errors >my_input = int(input("Please Enter a Number: "))


and keep our program work >print(f"Here is your number: {my_input} ")
○ ZeroDivisionError
○ ValueError >Please Enter a Number: üç
>ValueError: invalid literal for int() with base
○ TypeError 10:'üç'
○ IndexError
○ File Handling Errors
>my_input = int(input("Please Enter a Number: "))
■ PermissionError >print(f"length is {len(my_input)} ")
■ FileNotFoundError
■ UnsupportedOperations >Please Enter a Number: üç
● Most of these errors occurs >TypeError: object of type 'int' has no len()

because of invalid input >print("Half-Life"[9])

>IndexError: string index out of range


155
Error Handling
>#Dumb Divider
>x = int(input("Please enter a number: "))
>flag = True
>while flag:
> try:
> y = int(input("Please enter divider: "))
● We can use try and except > print(f"{x} divided by {y} is {x / y}")

statements to prevent this kind of


> flag = False
> except ZeroDivisionError:

runtime errors
> print("invalid input")


try: >Please enter a number: 10
age = int(input("How old is Gandalf: ")) >Please enter a divider: 0
except ValueError: >Invalid Input
age = -1 >Please enter a divider: 1
>10 divided by 1 is 10
if age >= 0 and age <= 55000:
print("Plausible")
else:
print("Invalid Input")

>How old is Gandalf: üç


>Invalid Input

156
Programming Task 76
● Please create a function named age_calc which asks integer input and
return it
● If user enters invalid type of input, send a message and ask again for
proper input

>What is your birthyear? Üç >def age_calc():


>Invalid Input. >#your code
>What is your birthyear? 2000 >
>You are 24 years old >print(f"You are {age_calc()} years old")

157
Error Handling
>#Dumb Divider
>x = int(input("Please enter a number: "))
>flag = True
>while flag:
> try:
> y = int(input("Please enter divider: "))
● We can use multiple except > print(f"{x} divided by {y} is {x / y}")

statements for try statements


> flag = False
> except ZeroDivisionError:

We can use except statements


> print("You can’t enter 0 as divider")
● > except ValueError:
without specifying errors. >
>
print("Invalid Value")
except:
However this could be hiding the print("Some kind of error occured")

actual error. >Please enter a number: 10


>Please enter a divider: sifir
>Invalid Value
>Please enter a divider: 0
>You can’t enter 0 as divider
>Please enter a divider: 1
>10 divided by 1 is 10.0

158
Programming Task 77
● What would this code throw? Syntax error or runtime error or
something else happen? Please fix this
>#Dumb Divider >
>x = int(input("Please enter a number: ")) >
>flag = True >
>while flag: >
> try: >
> y = int(input("Please enter divider: ")) >
> print(f"{x} divided by {y} is {x / y}") >
> flag = False >
> except: >
> print("Some kind of error occured") >
> except ZeroDivisionError: >
> print("You can’t enter 0 as divider") >
> except ValueError: >
> print("Invalid Value") >
>

159
Programming Task 78
● Please create a function named new_game which ask users for game
name and release date return this values as tuple.
● if parameters are not valid, throw a
ValueError exception for this: >def new_game():
>#TODO
○ empty name >
○ longer than 40char name >game_list = []
>flag = True
○ negative release date >while flag:
○ release date greater than 2024 > user_command = input("add or exit: ")
> if user_command == "exit":
> flag = False
>add or exit: add > elif user_command == "add":
>game name: Half-Life > game_list.append(new_game())
>release year: 1998 >
>add or exit: exit >for game in game_list:
>Game name: Half-Life, Release Year: 1998 > print(f"Name: {game[0]}, Year: {game[1]}")
160
Error Handling
>#Iterative Factorial Calculator
>def factorial(n):
> if n < 0:
> raise ValueError("No negative value")
> k = 1
> for i in range(2,n+1):
● We can also raise an error > k*= i

purposefully using raise


> return k
>

statement.
>print(factorial(5))
>print(factorial(-1))

>120
>ValueError: No negative value

161
Programming Task 79
● Please add try&catch statements to this code.

>#Iterative Factorial Calculator >


>def factorial(n): >
> if n < 0: >
> raise ValueError("No negative value") >
> k = 1 >
> for i in range(2,n+1): >
> k*= i >
> return k >
> >
>print(factorial(5)) >
>print(factorial(-1)) >
> >
> >
> >
> >

162
End of the Week
Thanks Materials
[email protected]
● Beginning C# Object-Oriented
Programming, Second Edition
● www.freecodecamp.com
● www.geeksforgeeks.com
Assignment ● www.w3schools.com
● Null ● https://learn.microsoft.com/
● https://code.visualstudio.com/
● https://www.bytehide.com/blog/

163

You might also like