Uploaded by sarankorn0329

PYTHON101

advertisement
PYTHON
STRINGS
String of xx : print(“xx”)
Input of “variables” :
• name = “Karina aespa”
• age = “21”
Funtions : type . and di erent functions will appear.
• print(name.upper()) -> KARINA AESPA
• .isupper or .islower -> true or false
• print(len(name)) -> count length of the word
• print(name[0]) -> K (K is @ postion 0)
• print(name.index(“n”) -> 5 (print out the position of de ned alphabet which is n)
• print(name.replace(“Karina”, “Winter”)) -> Winter aespa
NUMBERS
my_num = 8
print(my_num) -> 8
Funtions:
• to put a number next to a string :
print(str(my_num) + “is my fav number”) -> 8 is my fav number
** If no function str, it’s going to be error.
print(min(4,6))
-> 4 (because 4 is the minimum number)
•
• We can import special math functions by typing: from math import *
• Now we can use functions such as ceil, oor, and sqrt
GETTING INPUT FROM USERS
• Allowing a user to input information into our program, and store it inside a ‘variable’ so we are
able to do something with that variable(input).
• To get an input: type input(“”)
• Example 1:
• name = input(“Enter your name: ”)
Run:
Enter your name: type your name here
— After a user input info: —
fi
fl
ff
Enter your name: Winter
• Example 2:
• name = input(“Enter your name: ”)
• print(“Hello ” + name + “!”)
• age = input(“How old are you?: ”)
• print(name + “is ” + age + “ years old.”
Run:
Enter your name: Winter
Hello Winter!
How old are you?: 21
Winter is 21 years old.
BUILDING A BASIC CALCULATOR
• Example 1:
• num1 = input(“Enter a number: ”)
• num2 = input(“Enter another number: ”)
• answer = int(num1) + int(num2)
• print(“The answer is ” + str(answer))
** We need to put the function int before the variable because normally python will see any
input as ‘strings’ not a ‘number’ and it will not add up the answer but just type it together.
** To put add up numbers with decimals, replace int with oat
Run:
fl
Enter a number: 8
Enter another number: 7
The answer is 15
MAD LIBS GAME
• A game that you can enter random words and put it into a story randomly.
• We need to get inputs/variables from the users.
•
•
•
•
•
•
color = input(“Enter a color: ”)
plural_noun = input(“Enter a plural noun: ”)
celebrity = input(“Enter a celebrity: ”)
print(“Rose are ” + color)
print(plural_noun + “ are blue”)
print(“I love ” + celebrity)
Run:
Enter a color: White
Enter a plural noun: Wolves
Enter a celebrity: Karina
Roses are white
Wolves are blue
I love Karina
LISTS
• Manage and organize a large amount of data properly.
• Put related values together inside the same list and be able to use that whole list throughout the
program.
• Normally, a variable contains one value: friends = (“Karina”)
• ‘List’ allows you to store multiple values inside the same variable:
• Make a list by using a square bracket -> [ - ]
• You can store numbers, true/false, and strings inside a list
Run:
aespa = [“Karina”, “Winter”, “Giselle”, “Ningning”]
Or Aespa = [“Karina”, 2 , True]
• Each element in the list has its own index, starting with position 0 (Karina’s index = 0)
• We can refer to a speci c element in the list by using index number:
aespa = [“Karina”, “Winter”, “Giselle”, “Ningning”]
print(aespa[1] + “, ” + aespa[3])
___________________________________________________
Run:
fi
Winter, Ningning
• We can also specify the range by using:
• print(aespa[1:]) — this means we want all the elements that come after index 1 (Winter,
Giselle, Ningning #except Karina)
• print(aespa[1:3]) — this means we want the elements after position 1 but not after position
3 (Winter, Giselle)
** To modify or replace an element -> aespa[2] = “Taeyeon”
LIST FUNCTIONS
• Using functions with di erent sets of data/lists.
• Functions that can be used with multiple lists:
• To connect a list to another list: list1.extend(list2)
lucky_numbers = [2, 8, 15, 29]
aespa = [“Karina”, “Winter”, “Giselle”, “Ningning”]
aespa.extend(lucky_numbers)
print(aespa)
Run:
[‘Karina’, ‘Winter’, ‘Giselle’, ‘Ningning’, 2, 8, 15, 29]
• To add another item to the list: list.append(“item”)
** The added item will always show up at the end of the list.
• To insert a new item into a speci c position in the list: list.insert(index, “item”)
lucky_numbers = [2, 8, 15, 29]
aespa = [“Karina”, “Winter”, “Giselle”, “Ningning”]
aespa.insert(2, “Yeji”)
print(aespa)
Run:
[‘Karina’, ‘Winter’, ‘Yeji’, ’Giselle’, ‘Ningning’]
• To search for a speci c item/element in the list: print(list.index(“wanted item”))
• Python will give an index(position) of that wanted item as an answer.
• To put a list in alphabetical order: use list.sort( ), then print
• To create an identical list: list2 = list1.copy( )
aespa = [“Karina”, “Winter”, “Giselle”, “Ningning”]
aespa2 = aespa.copy()
print(aespa2)
Run:
fi
ff
fi
[‘Karina’, ‘Winter’, ’Giselle’, ‘Ningning’]
TUPLES
•
•
•
•
A type of data structure.
A container where we can store di erent values.
Similar to a list, BUT, a tuple can’t be modi ed. (Used with a data that won’t be changed)
To create a tuple: tuple = (item)
FUNCTIONS
A collection of codes that perform a speci c task.
A core concept of python programming.
Allows us to break up our codes into many parts that are doing di erent tasks.
Using: def name( ):
• This means all the codes that come after this line, it’s going to be inside our functions.
• Separated by the indentation
• We need to call the function to run by typing the name of the function again: aespa( )
def aespa( ):
print(“Hello aespa!”)
aespa( ) #this is to call the function.
Run:
Hello aespa!
def aespa( name):
print(“Hello ” + name)
aespa(“Karina”)
Run:
ff
fi
fi
Hello Karina
ff
•
•
•
•
RETURN STATEMENT
• One of the functions that is used to perform further computational in your programs. It makes
your functions send Python objects back to the caller code.
• Data processed within a function is only accessible within the function. EXCEPT, we use the
return statement to send the data elsewhere in the program.
• The return keyword in Python exits a function and tells Python to run the rest of the main
program. The return keyword can send a value back to the main program.
Price = 200
def calculate_change(amount_given):
return amount_given - price
result = calculate_change(550)
print(result)
Run:
350
IF STATEMENT
ff
ff
• Allows the program to respond to the input given by the user.
• This function of Python will react to the di erent data di erently. (Certain values will do certain
things)
• Specify conditions: if the condition is true -> we will do a certain thing.
but if the condition is false -> we will do another thing.
• Example:
I’m at a restaurant
If I want meat
I order a steak
otherwise if I want pasta
I order spaghetti
Otherwise
I order a salad
• Structure:
• 1) specify a condition:
• 2) use the function:
• if condition:
• print(“condition that is true”)
** the colon indicates that the following codes will only be executed when the
condition is true
• else:
** = otherwise, got printed when the statement is false
aespa_leader = True
aespa_member = True
if aespa_leader and aespa_member:
print("You are Karina, leader of aespa!")
elif aespa_member and not(aespa_leader):
print("You are aespa's member!")
else:
print("You are not aespa!")
Run:
You are Karina, leader of aespa!
aespa_leader = False
aespa_member = True
if aespa_leader and aespa_member:
print("You are Karina, leader of aespa!")
elif aespa_member and not(aespa_leader):
print("You are aespa's member!")
else:
print("You are not aespa!")
Run:
You are aespa’s member!
** If both conditions are false: It’s going to print out “You are not aespa!”
IF STATEMENTS & COMPARISONS
• Rather than just a yes or no question, we can use this function to compare di erent numbers or
di erent strings and do something about that answer.
def max_num(num1, num2, num3):
#provide the parameters
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
#If both are false, print num3
print(max_num(7,12,18))
Run:
18
• There are di erent comparison operators -> ‘==‘, ‘!=‘, ‘>=‘
• Use If statements to create a calculator:
num1 = float(input("Enter first number:
"))
operator = input("Enter operator: ")
num2 = float(input("Enter second number:
"))
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "/":
print(num1/num2)
elif operator == "*":
print(num1*num2)
else:
print("Invalid Operator")
Run:
Enter first number : 7
Enter operator : *
Enter second number : 4
ff
ff
ff
28
DICTIONARIES
• A dictionary is a special structure in python which allows us to store info that is called “KeyValue Pairs”
• We can access a speci c Key-Value pair in di erent ways:
• print(DictionaryName[“Key”]
• print(DictionaryName.get(“Key”))
** Using .get function allows you to store a default value of something that is not in the list.
For example : print(aespaMembers.get(“Yeji”, “Not an aespa’s member.”))
• Dictionaries allow us to store di erent types of data
• Structure:
DictionaryTitle = {
“key”: “value”,
“key”: “value”,
“key”: “value”
}
Example:
ff
ff
fi
aespaMembers = {
“Kar”: “Karina”,
“Gis”: “Giselle”,
”Nin”: “Ningning”,
“Win”: “Winter”
}
LOOPS
• A structure in python that allows us to loop through and execute a block of codes multiple
times.
• The program is going to loop repeatedly until a certain condition is false.
i = 1
while i <= 10:
print(i)
i = i+1
print("Done With Loop”)
Run:
1
2
3
4
5
6
7
8
9
10
Done With Loop
• LOGIC OF PYTHON’S WHILE LOOP:
1. we specify i = 1
2. While i is still less than or equal to 10 -> print i
3. Condition is that i is equal to i+1, until it is higher than 10
4. If i exceeds 10 -> print Done With Loop
BUILDING A GUESSING GAME (BASIC)
• Using while loops
• Rule: Guess the word until you get it right with unlimited guesses.
secret_word = "aespa"
guess = ""
print("Hint = Korean girl group")
while guess != secret_word:
guess = input("Enter your guess: ")
print("YOU WIN!")
Run:
Hint = Korean girl group
Enter your guess: Itzy
Enter your guess: Red Velvet
Enter your guess: WJSN
Enter your guess: SNSD
Enter your guess: aespa
YOU WIN!
• Complex Guessing Game:
- Limited guesses (3 trials)
- 2 possible ways to code this game:
#GUESSING GAME VER. 1
secret_word = "aespa"
guess = ""
guess_count = 0
print(“Hint: Famous Korean girl group")
while guess != secret_word and guess_count < 3:
guess = input("Enter your guess: ")
guess_count = guess_count+1
if guess == secret_word and guess_count <= 3:
print("YOU WIN!”)
else:
print(“Out of guesses, YOU LOSE!”)
Run:
Hint: Famous Korean girl group
Enter your guess: Itzy
Enter your guess: SNSD
Enter your guess: WJSN
Out of guesses, YOU LOSE!
#lose becuz run out of guesses
#GUESSING GAME VER. 2
secret_word = "aespa"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
print("Hint: Famous Korean Girl Group")
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Enter your guess: ")
guess_count = guess_count+1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of guesses,YOU LOSE!")
else:
print("You Win!")
Run:
Hint: Famous Korean girl group
Enter your guess: Itzy
Enter your guess: SNSD
Enter your guess: aespa
You Win!
FOR LOOPS
• ‘For Loops’ : a special type of loops in python which allows us to loop over di erent collections.
• We can loop through a string, array, list, tuple, etc.
#Iterate thru a list
aespa = [“Karina”, “Giselle”, “Winter”, “Ningning”]
for member in aespa:
print(member)
Run:
ff
Karina
Giselle
Winter
Ningning
#Iterate thru a string
aespa = “POWER”
for x in aespa:
print(x)
Run:
P
O
W
E
R
#Break statement in FOR LOOP
aespa = [“Karina”, “Giselle”, “Winter”, “Ningning”]
for x in aespa:
print(x)
If x == “Winter”:
break
Run:
Karina
Giselle
Winter
Download