save Python files with the .py
extension to indicate
they’re Python scripts.
Save a file named hello.py
:
print("hello, world")
Prints “hello, world” to the screen. The function
print()
is used to display text or other output in
Python.
Run using to use the command line or terminal or bash. (run python code dirrectly in python console by typing python to get to python prompt then crtrl z to exit out and back to term)
python hello.py
Should output:
hello, world
A variable is a container to store data, such as numbers or text. Ask users for input to make your program more interactive.
# Ask the user for their name
name = input("What's your name? ")
# Print a personalized greeting
print(f"Hello, {name}")
Here, input()
is used to take user input. The user’s
input is stored in a variable called name
, and then it’s
used to greet them using an f-string
, which allows
inserting variables directly into strings.
You can also improve your greeting by cleaning up any extra whitespace or capitalization issues:
# Ask the user for their name and remove extra spaces
name = input("What's your name? ").strip().title()
# Print a cleaned-up personalized greeting
print(f"Hello, {name}")
In this code:
strip()
removes any leading or trailing whitespace from
the user’s input.title()
capitalizes the first letter of each word.Python can be used as a simple calculator to add, subtract, multiply, or divide numbers. You can also ask users to input numbers to perform calculations.
# Ask the user for two numbers
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
# Calculate and print the sum
sum = x + y
print(f"The sum of {x} and {y} is {sum}")
Here, the int()
function is used to convert the user’s
input into an integer so that mathematical operations can be performed.
By default, input()
gives a string, and converting it is
necessary to treat it as a number.
You can add more operations to the calculator:
# Ask the user for two numbers
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
# Perform different operations
print(f"The sum is: {x + y}")
print(f"The difference is: {x - y}")
print(f"The product is: {x * y}")
print(f"The quotient is: {x / y}")
Perform addition, subtraction, multiplication, and division (
/
) operator. ## 4. Combining Strings and
Numbers
Display a result that combines both text and numbers. Use formatted strings.
x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
# Calculate the product
product = x * y
# Print the result in a full sentence
print(f"The product of {x} and {y} is {product}.")
This code asks the user for two numbers, calculates their product, and prints the result.
Sometimes users enter invalid data. Improve our calculator to handle such cases.
try-except
to Handle Input Errorstry:
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print(f"The sum is: {x + y}")
except ValueError:
print("Please enter a valid number.")
Use a try-except
block to catch errors when the user
enters something that isn’t a number. If they enter an invalid value,
the program prints an error message.
input()
.print()
function is used to display
information.strip()
, title()
, and
int()
help clean up user input and convert data types.+
, -
,
*
, /
) to perform calculations.try-except
.Create a new file in the terminal, use the command
touch
. The touch
command is commonly used to
create an empty file or update the timestamp of an existing file.
touch
In the terminal, type:
touch my_module.py
Creates an empty file named my_module.py
in the current
directory. (like nano/ ~.bashrc)
Next: Craete a simple Python module. A module is essentially a Python file containing reusable code, such as functions or classes, which can be imported into other scripts.
Make mod. called math_utils.py
to add afew more
functions to our calc.
It should 1. Define a Python module with multiple functions. 2. Make the functions more reusable and include slightly advanced concepts. 3. Import and use this module from another script.
math_utils.py
)Run this in terminal:
touch math_utils.py
Open math_utils.py
and add functions to it. Use code
editor, such as VS Code, sublime if available is IMO the best code
editor. Save as .py - they run in gitbash - easier on system than VScode
or VS when colmputing with simple python scripts.
Code to add:
# math_utils.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return "Error: Division by zero is undefined."
return x / y
def power(base, exponent):
"""Returns the base raised to the power of exponent."""
return base ** exponent
def factorial(n):
"""Returns the factorial of a given number n."""
if n < 0:
return "Error: Factorial is not defined for negative numbers."
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
def gcd(a, b):
"""Returns the greatest common divisor of a and b."""
while b:
a, b = b, a % b
return a
add
,
subtract
, multiply
, divide
):
These functions perform basic operations.power
): Raises a
number to the power of another.factorial
):
Calculates the factorial of a non-negative integer.gcd
): Finds the greatest
common divisor of two integers using the Euclidean algorithm.Create a script named main.py
that’ll use
math_utils
module. First, create the file:
touch main.py
Add to code:
# main.py
import math_utils
# Take user inputs for arithmetic operations
x = int(input("Enter the first number: "))
y = int(input("Enter the second number: "))
print(f"Sum: {math_utils.add(x, y)}")
print(f"Difference: {math_utils.subtract(x, y)}")
print(f"Product: {math_utils.multiply(x, y)}")
print(f"Quotient: {math_utils.divide(x, y)}")
# Take user inputs for more advanced functions
base = int(input("Enter the base number: "))
exponent = int(input("Enter the exponent: "))
print(f"{base} raised to the power of {exponent}: {math_utils.power(base, exponent)}")
n = int(input("Enter a number to find its factorial: "))
print(f"Factorial of {n}: {math_utils.factorial(n)}")
a = int(input("Enter the first number to find GCD: "))
b = int(input("Enter the second number to find GCD: "))
print(f"GCD of {a} and {b}: {math_utils.gcd(a, b)}")
To run the script, use:
python main.py
Typical interaction with main.py
Enter the first number: 5
Enter the second number: 10
Sum: 15
Difference: -5
Product: 50
Quotient: 0.5
Enter the base number: 2
Enter the exponent: 3
2 raised to the power of 3: 8
Enter a number to find its factorial: 5
Factorial of 5: 120
Enter the first number to find GCD: 54
Enter the second number to find GCD: 24
GCD of 54 and 24: 6
touch
to create
empty files such as math_utils.py
and
main.py
.math_utils.py
to handle different mathematical tasks.math_utils
in
main.py
to use the functions you defined.Play with math_utils
adding more functions like square
root, prime checking, etc, play around with code, use python references.
Practice using in different tools. Practice calling from different
platforms. Memorize basics and keyboard shortcuts. The heavy lifting
isn’t as heavy if you know the basics. They’re the safety net. Be safe.
Then advance.
As with in the cutthroat kitchen - KNOW THE LAYOUT OF THE LAND. LEARN THE TOOLS. USE THE TOOLS. Coding skills irrelevant if you can’t efficiently get to a notebook, window, linux line etc. WSL, UBUNTU, CMD, GIT, Windows (and/or Mac). Learn commands, Memorize commands. Be able to quickly and efficiently navigate around a computer and the programs within it.
'''
The parentheses with nothing inside means that this function at the moment
is not going to take any inputs, no arguments there too.
The colon means, stay tuned for some indentation.
Everything that's indented beneath this line of code
is going to be part of this function.
'''
def hello():
print("hello")
name = input("What's your name? ")
hello(name)
# "Hello.py"
# Ask for name
name = input ("What's your name? ")
# Remove whitespace from str
name = name.strip()
# Capitalize user's name
name = name.capitalize()
# Address user - fstring
print (f"Hello, {name}")
# pseudo code
# or print ("hello,") n/ print(name)
"""
outline code
buildingblocks
what do i want to do
what do i want to accomplish
this is all part of pseudocode
input prompts string - text
next return values and define values
"""
"""
run in terminal using : python hello.py
anything between triple double quotes is a comment
you can also use single quote to comment
"""
# Say hello
print("hello, " + name)
# pass in more arguments
print("hello,", name)
# str = string
# override move to next line in print statement
# docs/python.org/3/library/functions.html#print
print(name)
"""
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
parameters vs arguments - what problem can take vs what youre tryiong to apply
= means assignment
== means equals as value
"""
# So
print("hello, ", end="")
print(name)
# look at difference
print("hello,", name, sep="???")
# using actual quotes - escaping out
print("hello, \"friend\"")
# Again for practice and muscle memory
you = input("What should I call you? ")
# Remove whitespace from str
you = you.strip()
# Capitalize user's name
you = you.capitalize()
# Title Based Cazpitalization
you = you.title()
# or
# name = name.title()
# Say hello to user
print(f"hello, {you}")
# Again
nickname = input("What is your nickname? ")
nickname = nickname.strip()
nickname = nickname.capitalize()
# Title Based Cazpitalization
nickname = nickname.title()
print(f"hello, {nickname}")
print("hello, \"friend\"")
#Condensed
#Ask for name
username = input("What is your username? ").strip().title()
# Say Whats up to user
print(f"What's shakin', {username}?")
# method is a funtiopn that's built in to type of value like these functions (f string etc)
# Adding name split
splitname = input ("What's your name? ").strip().title()
# Split users name into first, middle and last
first, middle, last, = splitname.split(" ")
# Say what's up
print(f'Sup, {splitname}')
# now only address by first anme
print(f"/Sup, {first}")
# integer is int
'''
number without decimal
+ - * / %
interactive mode
'''
'''
running within python interpreter
immediate translation/interactive code
print("....")
1+1
8/2
etc for interactive mode
'''
# create calculator.py
"Calculator.py"
# basic arithmetic
a=4
b = 5
c = 12
print(a + b + c)
# Using input
x = input("What is x? ")
y = input("What is y? ")
z = int(x) + int(y)
print(z)
# Do we actually need z? using it right away and won't call it again - so why waste variable and take time defining?
# Let's nest it here instead of i - I'll nest and immediately call for it
g = int(input("What is g? "))
h = int(input("What is h? "))
print(g + h)
# Overnesting is a real thing - when we start having longer lines of code it gets to be a clusterf
# making it harder to decipher whatr we want to do and more cumbersome when it comes to modifying code and tweaking.
# Consider visceral reation to code, likelihood if mistakes and value it brings. More erros and propensity tp mess up isn't worth it
print(int(input("What's x? ")) + int(input("What's y? "))) # this is valid but it's prone to typos and of the code is longer - easier to f up
# decimals FLOATS
j = float(input("What's j? "))
k = float(input("What's k? "))
print(j + k)
# ROUND FUNCTION: round(number[, ndigits])
# [ ] these specify optional values
l = round (j + k)
# or
print(l)
# Concatenate w f string - change system settings period/commas etc for separators
print(f"{l}") # or print("l") - that will literally print l
#Include rounding and separators # Include commas
print(f"{l:,}")
# Division
m = float(input("What is m? "))
n = float(input("What is n? "))
o = m/n
print(o)
o = round(m / n, 2) # round to 2 digits
# or
# o = round(m / n) - this is without rounding
print(o)
# ** OR **
# fstring to round to 2 digits
print(f"{o:.2f}")
'''
The parentheses with nothing inside means that this function at the moment
is not going to take any inputs, no arguments there too.
The colon means, stay tuned for some indentation.
Everything that's indented beneath this line of code
is going to be part of this function.
'''
def hello():
print("hello")
hello
name = input("What's your name? ")
# extending beyond:
def hello(to="world"):
print("hello," to)
hello()
name = input("What's your name? ")
hello(name)
## good habits:
def main():
name = input("What's your name? ")
hello(name)
def hello(to="world"):
print("hello,", to)
# NOW MAKE SURE YOU CALL THE DAMN FUNCTION
main()
'''
# wrong:
## good habits:
def main():
name = input("What's your name? ")
hello()
def hello():
print("hello,", name)
main()
# this is a scope issue.. it's only existing in the context in which I defined it. this is wrong.
'''
# Side-effect only proints to screen.
# RETURN use return to actully return a value.
def main():
x = int(input("What's x? "))
print("x squared is", square(x))
main()
# need to define square to call it for a return value to another funtion
# so:
def main():
x = int(input("What's x? "))
print("x squared is", square(x))
def square(n):
return n*n
# or return n ** 2 # raise n to the power of 2 ( two astericks means it raises the thing on the left to the power of the thing on the right)
# or return pow(n, 2)
'''
POW for raising something to the power that
takes two arguments, the first of which is the number, the second of which
is the exponent.
''''
'''
We've defined a function called Main and I've implemented two lines.
The first of these lines prompts the user for a value
x and converts it to an INT and stores it in a variable called x.
So I've implemented my very own function that returns the square of a value
and because I'm using the return keyword, that
ensures that I can pass the return value of this, just
like the return value of input or INT or float, to another function,
'''
main()
SMU MSDS Bootcamp December 2022 Professor: Scott Saenz , TA: Stephen Tahan Dir: Sean Fleming