Programming Essentials in Python Introduction To Python
Programming Essentials in Python Introduction To Python
Introduction to Python
Supervisor Dr. Laki Sandor Instructor Dhulfiqar A Alwahab
lakis@inf.elte.hu aalwahab@inf.elte.hu
Task 1
• Open newfile in pyhton and type
• Print (‘this is test 1 ’) --- what is the output ? Read it !
• Print (‘this is test 1 ’ what is the output ? Read it !
• Prin ( ‘this is the test 1 ’) what is the output ? Read it !
Introduction to Python
As you can see, the first program
consists of the following parts:
• Hello, World!
• the word print;
print("Hello, World!") • an opening parenthesis;
• a quotation mark;
• a line of text: Hello, World!;
The print() function • another quotation mark;
• a closing parenthesis.
Where do the functions come from?
1. They may come from Python itself; ( built-in)
2. they may come from one or more of Python's add-ons named modules;
some of the modules come with Python, others may require separate
installation.
3. you can write them yourself, placing as many functions as you want and
need inside your program to make it simpler, clearer and more elegant.
Introduction to Python
• In spite of the number of needed/provided arguments, Python functions
strongly demand the presence of a pair of parentheses - opening and
closing ones, respectively.
• Arguments
Does the print() function in our example have any arguments?
Introduction to Python
• LAB-1.1 ( 5 minutes)
• use the print() function to print the line Hello, Python! to the screen. Use double
quotes around the string;
• having done that, use the print() function again, but this time print your first name;
• remove the double quotes and run your code. Watch Python's reaction. What kind of
error is thrown?
• then, remove the parentheses, put back the double quotes, and run your code again.
What kind of error is thrown this time?
• experiment as much as you can. Change double quotes to single quotes, use multiple
print() functions on the same line, and then on different lines. See what happens.
Introduction to Python
• The print() function - instructions
• print("The itsy bitsy spider climbed up the waterspout.")
• print()
• print("Down came the rain and washed the spider out.")
Output will be
The itsy bitsy spider climbed up the waterspout.
Introduction to Python
• The print() function - using multiple arguments
The itsy bitsy spider climbed up the waterspout.
Strings
Strings are used when you need to process text (like names of all kinds,
addresses, novels, etc.), not numbers.
I like "Monty Python"
print("I like \"Monty Python\"") print('I like "Monty Python"')
"I'm"
""learning""
"""Python"""
Introduction to Python
exponentiation print(2 ** 3)=8 remainder print(14 % 4)=2
print(2 ** 3.)=8.0 (modulo) print(12 % 4.5)=3.0
• Python as a calculator print(2. ** 3)=8.0
print(2. ** 3.)=8.0
print(2+2)=4 multiplication print(2 * 3)=6 addition print(-4 - 4)=-8
print(2 * 3.)=6.0 print(4. - 8)=-4.0
Operators and their priorities print(2. * 3)=6.0
print(2. * 3.)=6.0
print(-1.1)=-
print(+2)=2
2+3*5
division print(6 / 3)=2.0
Operators and their bindings print(6 / 3.)=2.0
print(6. / 3)=2.0
print(6. / 3.)=2.0
print(9 % 6 % 2) (left binding)
integer division print(6 // 3)=2
print(2 ** 2 ** 3)(right binding) print(6 // 3.)=2.0
print(6. // 3)=2.0
print(6. // 3.)=2.0
Introduction to Python
Priority Operator
1 +, - unary
2 **
3 *, /, %
4 +, - binary
print(2 * 3 % 5)=1
•LAB 2
• Here is a short story:
• Once upon a time in Appleland, John had three apples, Mary had five apples, and Adam had six apples. They were all
very happy and lived for a long time. End of story.
• Your task is to:
• create the variables: john, mary, and adam;
• assign values to the variables. The values must be equal to the numbers of fruit possessed by John, Mary, and Adam
respectively;
• having stored the numbers in the variables, print the variables on one line, and separate each of them with a comma;
• now create a new variable named totalApples equal to addition of the three former variables.
• print the value stored in totalApples to the console;
• experiment with your code: create new variables, assign different values to them, and perform various arithmetic
operations on them (e.g., +, -, *, /, //, etc.). Try to print a string and an integer together on one line, e.g., "Total number
of apples:" and totalApples.
Introduction to Python
• Shortcut operators
x=x*2 x *= 2
sheep = sheep + 1 sheep += 1
i=i+2*j i += 2 * j
var = var / 2 var /= 2
rem = rem % 10 rem %= 10
j = j - (i + var + rem) j -= (i + var + rem)
x = x ** 2 x **= 2
Introduction to Python
• LAB 3
Scenario
• Miles and kilometers are units of length or distance. kilometers = 12.25
• Bearing in mind that 1 mile is equal to approximately 1.61 kilometers, miles = 7.38
complete the program in the editor so that it converts:
1. miles to kilometers; miles_to_kilometers = ###
2. kilometers to miles. kilometers_to_miles = ###
• Do not change anything in the existing code. Write your code in the
places indicated by ###. Test your program with the data we've print(miles, "miles is", round(miles_to_kilometers, 2),
provided in the source code. "kilometers")
• Pay particular attention to what is going on inside the print() function. print(kilometers, "kilometers is",
Analyze how we provide multiple arguments to the function, and how round(kilometers_to_miles, 2), "miles")
we output the expected data.
• Note that some of the arguments inside the print() function are strings
(e.g., "miles is", whereas some other are variables (e.g., miles).
Expected output
7.38 miles is 11.88 kilometers
12.25 kilometers is 7.61 miles
Introduction to Python
• LAB 4
• Scenario
• Take a look at the code in the editor: it reads a float x = # hardcode your test data here
value, puts it into a variable named x, and prints the x = float(x)
value of a variable named y. Your task is to complete
the code in order to evaluate the following expression: # write your code here
print("y =", y)
• 3x3 - 2x2 + 3x - 1
• The result should be assigned to y.
• Remember that classical algebraic notation likes to omit
the multiplication operator - you need to use it
explicitly. Note how we change data type to make sure
Sample input
that x is of type float.
x=0
• Keep your code clean and readable, and test it using the
data we've provided, each time assigning it to the x x=1
variable (by hardcoding it). Don't be discouraged by any x = -1
initial failures. Be persistent and inquisitive.
Expected Output
y = -1.0
y = 3.0
y = -9.0
Introduction to Python
• Check-point ( what is the output )
var = 2 # print("String #1")
var = 3 print("String #2")
print(var)
my_var # This is In Python, a comment is a piece of text that begins
m a multiline with a # (hash) sign and extends to the end of the line.
101 comment. #
averylongvariablename Example
m101 print("Hello!") # This program evaluates the hypotenuse c.
m 101
Del
del
a = '1' NOTE: If you'd like to quickly comment or uncomment
b = "1"
print(a + b) multiple lines of code, select the line(s) you wish to
a=6 modify and use the following keyboard shortcut: CTRL
b=3
a /= 2 * b
+ / (Windows) or CMD + / (Mac OS).
print(a)
Introduction to Python
The + (plus) sign, when applied to two strings, becomes a concatenation operator:
string + string
• Replication
The * (asterisk) sign, when applied to a string and number (or a number and string,
as it remains commutative in this position) becomes a replication operator:
string * number
number * string Example 1, Example 2, run this code
print("+" + 10 * "-" + "+")
"James" * 3 gives "JamesJamesJames"
print(("|" + " " * 10 + "|\n") * 5, end="")
3 * "an" gives "ananan"
print("+" + 10 * "-" + "+")
5 * "2" (or "2" * 5) gives "22222" (not 10!)
Introduction to Python
• Type conversion: str()
convert a number into a string : str(number)
What is the output of the following snippet?
x = int(input("Enter a number: "))
# the user enters 2
print(x * "5")
______
Example
What is the expected output of the following
leg_a = float(input("Input first leg length: "))
snippet?
leg_b = float(input("Input second leg length: "))
x = input("Enter a number: ")
print("Hypotenuse length is " + str((leg_a**2 + leg_b**2) ** .5))
# the user enters 2
print(type(x))
Introduction to Python
• LAB
Scenario
• Your task is to complete the code in order # input a float value for variable a here
to evaluate the results of four basic # input a float value for variable b here
arithmetic operations.
• The results have to be printed to the # output the result of addition here
console. # output the result of subtraction here
• You may not be able to protect the code # output the result of multiplication here
from a user who wants to divide by zero. # output the result of division here
That's okay, don't worry about it for now.
• Test your code - does it produce the results print("\nThat's all, folks!")
you expect?
• We won't show you any test data - that
would be too simple.
Introduction to Python
• LAB
Scenario
Your task is to prepare a simple code able to
evaluate the end time of a period of time,
given as a number of minutes (it could be hour = int(input("Starting time (hours): "))
arbitrarily large). The start time is given as a mins = int(input("Starting time (minutes): "))
pair of hours (0..23) and minutes (0..59). The dura = int(input("Event duration (minutes): "))
result has to be printed to the console.
For example, if an event starts at 12:17 and # put your code here
lasts 59 minutes, it will end at 13:16.
Don't worry about any imperfections in your
code - it's okay if it accepts an invalid time -
the most important thing is that the code
produce valid results for valid input data.
Test your code carefully. Hint: using the %
operator may be the key to success.
Introduction to Python
Comparison:
• equality operator (==) print(2==2) output will be true
• Inequality: the not equal to operator (!=) print(2!=2) output will be false
• greater than (>) print (2>2) output will be false
• greater than or equal to (≥) output only true or false
• less than or equal to (≤) output only true or false
Priority Operator
1 +, - unary
2 **
3 *, /, //, %
4 +, - binary
5 <, <=, >, >=
6 ==, !=
Introduction to Python
• Conditions and conditional execution
if true_or_not:
4spaces OR tab (not both) do_this_if_true
If –else Nested if-else statements
if true_or_false_condition: if the_weather_is_good: The elif statement
if sheep_counter >= 120: perform_if_condition_true if nice_restaurant_is_found: if the_weather_is_good
make_a_bed() else: have_lunch() go_for_a_walk()
take_a_shower() perform_if_condition_false
else: elif tickets_are_available:
sleep_and_dream() -------------------------------------------
if the_weather_is_good: eat_a_sandwich() go_to_the_theater()
feed_the_sheepdogs()
go_for_a_walk() else: elif table_is_available:
Error in indentation
have_fun() if tickets_are_available: go_for_lunch()
else: go_to_the_theater() else:
go_to_a_theater() else: play_chess_at_home()
enjoy_the_movie() go_shopping()
have_lunch()
Find the largest of three numbers