0% found this document useful (0 votes)
14 views39 pages

Week 4

Uploaded by

Fack You
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)
14 views39 pages

Week 4

Uploaded by

Fack You
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
You are on page 1/ 39

Python Principles

CBROPS
Week 4 Lab
 Beautiful is better than ugly The Zen of Python
 Explicit is better than implicit.
 Simple is better than complex.
 Complex is better than complicated.
 Flat is better than nested.
 Sparse is better than dense.
 Readability counts.
 Special cases aren't special enough to break
the rules.
 Although practicality beats purity.
 Errors should never pass silently. (Unless
explicitly silenced.)
 In the face of ambiguity, refuse the
temptation to guess.
 There should be one-- and preferably only
one --obvious way to do it.
 Now is better than never.
 Although never is often better than right
now.
 If the implementation is hard to explain, it's
a bad idea.
 If the implementation is easy to explain, it
may be a good idea.
Operators

** --Exponent

% --Modulus

// --Integer division/Floored Exponent

/ --Division

* --Multiplication

- --Subtraction

+ --Addition
Expressions

Expressions are values combined with


operators, and they always evaluate down to a
single value.

White space between operators does not


conflict.

The precedence of Python math operators is


very similar to that of mathematics.
The ** operator is evaluated first. The *, /, //,
and % operators are evaluated next; from left to
right. The + and – operators are evaluated last.

Like mathematics you can override the usual


precedence with parentheses.
Data

A data type is a category for a value.


Every value belongs to a data type.
#Integer: A whole Number:
EX: >> sp = 1
--A Boolean is an integer of 1 or 0

#Float: A number that can be fractional:


EX: >> sp = 1.1

#String: A quotation of characters and/or numbers:


EX: sp = ‘hello world’
--Strings in python are also known as strs(pronounced
stirs).
--Strings are surrounded by quotes or double quotes.
Assignment Statements
Storing a value in a variable is called
an assignment statement.

You can call back a value in a variable


after the assignment statement
purely by name.

Unlike other languages discussed in


the class and up to this class, you do
not need the dollar sign.

Storing a value the first time in a


variable is called “Initialized”
Variables

Variables do have a nomenclature


they have to follow.

It can only be one word with no


spaces.

It can only be numbers, characters,


and the underscore.

It can’t begin with a number


Hands on Time!

You may easily follow along with any


linux VM of your choice with python3
installed.
The interactive shell is good for
running one line at a time but is not
good for writing entire programs. You
should use an application for that .
Python 3.11.2 (main, Mar 13 2023,
12:18:29) [GCC 12.2.0] on linux
To open the interactive shell type Type "help", "copyright", "credits" or
"license" for more information.
python >>>

You can enter the commands directly


into the shell.

Assignments statements initialized


during the session are remembered
only during the session unless
exported.
Python 3.11.2 (main, Mar 13 2023,
12:18:29) [GCC 12.2.0] on linux

To exit type Type "help", "copyright", "credits" or


"license" for more information.
>>> exit()
exit()

We will start out with a simple script


as out first.

My preference for creating and


testing scripts is nano.
GNU nano 7.2

To open nano in terminal, pick your


working directory and type in

nano

Ctrl + O is save

Ctrl + X is exit
#This is a Comment

# Denotes a comment and is not run


First Script

print() prints the output. #Print the Question


print(‘What is your name?’)
len() obtains the length #Assignment statement using user input
myname = input()
#Combining two strings on a callback and printing
input() gets user input. them
print(‘Welcome back to learning labs’ + myname)
You can convert between variable #Getting and printing length of variable
categories on callback of a previous print(‘The length of your name is:’)
print(len(myname))
assignment statement.

str() converts to a string

int() converts to an integer o int() on a


float will round it down

float() converts to a float.

You can convert a callback, but not


directly try to print an expression.
print(‘What is your name?’)
myname = input()
print(‘Welcome back to learning labs’ + myname)
print(‘The length of your name is:’)
print(len(myname))

Write out with Ctrl + O

Name it name.py

Then press Ctrl + X to exit


$> python name.py

What is your name?


student
Welcome back to learning labsstudent
The length of your name is:
Type in 7

python name.py

then type in your name


Flow Control

Flow control statements decide which


lines of code execute under which
conditions.

Flow controls statements start with a


condition.
Flow Control Operators
Comparison Operators

== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Two equals signs “asks” if a value is
true

= One equal sign is an assignment


statement!
Flow Control Conditions
Conditions always evaluate down to a
single Boolean value of true or false.

They are followed with a block of code


called the clause.

Lines of code are grouped together in


blocks.

--->You can tell when a block begins


or ends by indentation.

Blocks begin when the


indentation increases.

Blocks can contain blocks.

Blocks end when the indentation


decreases to 0 or to a containing block’s
indent
Hands on Time!

We have more scripts!


# 1. Prompt the user to enter a number.
Here is an example of the if flow user_input = input("Enter a number: ")
# 2. Read the input as a float and store it in a variable.
control statement in use number = float(user_input)
# 3. Use an if statement to check whether the number is
positive, negative, or zero.
if number > 0:
print(f"{number} is a positive number.")
elif number < 0:
print(f"{number} is a negative number.")
else:
print(f"{number} is zero.")
import random
# 1. Generate a random number between 1 and 100.
Here is an example of the while flow secret_number = random.randint(1, 100)
attempts = 0
control statement in use print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print("Can you guess what it is?")
# 2. Create a while loop that continues until the user guesses the correct number.
while True:
# 3. Prompt the user to guess the number and store their input in a variable.
guess = int(input("Enter your guess: "))
attempts += 1
# 4. Check if the guess is correct.
if guess == secret_number:
print(f"Congratulations! You guessed the correct
number in {attempts} attempts.")
break
elif guess < secret_number:
print("Too low! Try guessing higher.")
else:
print("Too high! Try guessing lower.")
# 1. Create a list of numbers.
numbers = [1, 2, 3, 4, 5]
Here is an example of the for flow # 2. Use a "for" loop to iterate through the list and print each number.
print("Numbers in the list:")
control statement in use for num in numbers:
print(num)
# 3. Calculate and print the sum of all the numbers in the list.
sum_of_numbers = sum(numbers)
print(f"Sum of all numbers: {sum_of_numbers}")
# 4. Find and print the largest number in the list.
largest_number = max(numbers)
print(f"Largest number: {largest_number}")
# 5. Create a new empty list and append only the even numbers.
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print("Even numbers in the list:")
print(even_numbers)
# 6. Create another new empty list and append the squares of each number.
squared_numbers = []
for num in numbers:
squared_numbers.append(num ** 2)
print("Squares of numbers in the list:")
print(squared_numbers)
Breaks

There is a shortcut to getting a


program to break out of a while’s loop
clause early.

If a logic encounters a break


statement it will exit the loop mid
clause.
Hands on Time!

We have more scripts!


Name = “”
while Name != ‘your name’:
print(‘Please type your name’)
This loop will stubbornly ask your Name = input()
name in an infinite loop until you say print(‘Thank you!’)
“your name”.

We can simplify and more efficiently


perform the same task with a
Boolean and a break
while True:
print(‘Please type your name’)
name = input()
if name == ‘your name’:
This prevents an infinite loop break
print(‘Thank you!’)
Ranges

Ranges can be used to count a


boolean value as true to continue the
clause of a loop a set number of
times.

You need:
# for
# A variable
# in
# A call to range()
# A colon :
# An indent
Hands on Time!

We have more scripts!


print(‘Hello World’)
for i in range(5):
print(‘testing (‘ + str(i) + ‘)’)
Here is an example of a hello world in
a range of 5
total = 0
for num in range(101):
total = total + num
Here is a way to add up all numbers print(total)
from 1-100
print(‘hello world’)
i=0
while i < 5:
You can use the while loop to act print(‘test ( ‘ + str(i) + ‘ ) ‘ )
similar as a for loop, but a for loop is i=i+1
still more concise.
Functions and modules

Python can call a basic set of


functions called built-in functions,
including print(), input(), and len().

Python also comes with the standard


library.

Each module is a python program


that contains a related group of
functions.
Modules
Before you can use functions in a
module you need:

# The import keyword


# The name of the module
# Potentially more modules as long as
they are separated by commas.

Do not overwrite module names. If


you save your script the same name
as a module name, it may try to
import your recently created script
instead of the original module.
import random
for i in range(5):
print(random.randint(1,10))

An example of the random module:


import math
# Example 1: Calculate the square root
num = 25
square_root = math.sqrt(num)
print(f"Square root of {num} is {square_root}")
# Example 2: Calculate the factorial
An example of the math module factorial = math.factorial(5)
print(f"Factorial of 5 is {factorial}")
# Example 3: Calculate trigonometric functions
angle = math.pi / 4 # 45 degrees in radians
sine = math.sin(angle)
cosine = math.cos(angle)
print(f"Sine: {sine}, Cosine: {cosine}")
import datetime
# Example 1: Get the current date and time current_time =
datetime.datetime.now() print(f"Current date and time: {current_time}")
# Example 2: Format a date as a string
formatted_date = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")
# Example 3: Calculate the difference between two dates
birth_date = datetime.datetime(1990, 5, 15)
today = datetime.datetime.now()
An example of the datetime module age = today - birth_date
print(f"Age: {age.days} days")
import sys
Programs always terminate when while True:
they reach the bottom. print(‘Type exit to exit’)
response = input()
You can cause the program to if response == ‘exit’:
sys.exit()
terminate before reaching this with print(‘You typed ‘ + response + ‘.’)
sys.exit()

An example: This program will only


exit when it reaches sys.exit()
End

Work on Assignments

Request your golden tickets

Make up hours

Remember to clock out at 8:30

You might also like