Day 1: Input and Variables
CMSC 201: Variables and Data
Day 1 Agenda:
Office hours: Tu/Th 2PM-3PM in ITE 373 (or email me whenever! sdonahue@umbc.edu)
GL and Linux
Another look at the terminal
Keybinds (emacs style!):
- CTRL-l: clear screen
- CTRL-a: start of line
- CTRL-e: end of line
- CTRL-p or up arrow: previous
- CTRL-n or down arrow: previous
Using nano
nano file.py
Side topic: getting help on homework and asking good questions. Please include your question detials up front!
Who cares?
Variables and data are the bread and butter of all programs.
Let's do something! Let's do Baldur's Gate 3 dice rolling :) We'll use input, variables, and a bit of conditionals. ( Ours will be text only :) )
Let's learn the tools we need :)
Data types
- bool: True or False
- int: integer, whole number (-1,1,2,3,278465)
- float: floating point (decimal)
- string: strings, sequence of characters, "hello"
cool_int = 5 my_float = 2.0 print(my_float) print(True, "nice string", cool_int)
An alternative form of printing variables: format strings.
Side topic: compiled vs interpreted: compiled programs are unreadable without specialized tools. Interpreted programs (like Python) are not compiled and are "directly" executed from the code you read and write.
Input function
input() lets us get a string input from the user.
my_input = input() print(input)
Escape characters
Character | Rendered as |
---|---|
\n | Newline |
\r | Carriage return |
\t | Tab |
\\ | \ |
\’ or \” | ' or " |
print("hello\n") print("hi hows it going\rhey") print("they said: \"hi\"")
Operations
Operation | Examples | ||
---|---|---|---|
Adding | 2 + 3 | x += 4 | "hi how are" + " you" |
Multiplying | 100 * 4 | y *= z | "a" * 50 |
Subtraction | 10 - 7 | x -= 41 | |
Division | 70 / 7 | x /= 5 | |
Integer division | 71 // 7 | y //= 5 | |
Modulus | 80 % 7 | y %= 10 |
PEP8 Standard: how should your code look?
- Full post: https://www.python.org/dev/peps/pep-0008/
- Tabs or spaces? spaces
- Name your variables and functions? snake_case (not camelCase or PascalCase)
my_bool = True if my_bool: print("it's true!")
Let's write the code!
A dice roll program: take user input, throw dice, check if passed!
import random print("You're doing your CMSC201 homework at 11:30PM on a friday. Will you succeed????") dice_sides = 20 ## random dice roll roll = int(random.random() * dice_sides) + 1 ## add our bonuses hero_bonus = int(input("What is your bonus: ")) ## determine if it was successful dc = 10 combined_roll = roll + bonus print("Roll:", combined_roll, "original roll:", roll) if combined_roll >= dc: print("Victory!") else: print("Fail!")