0% found this document useful (0 votes)
17 views31 pages

CS DS 1100 Variables and Expressions Week2 Annotated

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)
17 views31 pages

CS DS 1100 Variables and Expressions Week2 Annotated

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/ 31

CS 2212

Discrete Structures

Course Introduction
CS 2212
CS/DS 1100
DISCRETE STRUCTURE
Applied Programming and
Problem Solving with Python
Lecture-Week 02 A
Identifier

Python Identifier
Identifier
is a name used in programming languages
Identifier

to identify a

variable

function

module
Identifier: Naming rules
Alphabetic Characters:
- Must begin with a letter (either uppercase or lowercase)
or an underscore (_).
Identifier

Digits:
- After the first character, identifiers can include digits (0-9)
Underscore:
- May contain underscores
- Used to separate words
Case Sensitivity:
- Case-sensitive in most programming languages
- myName and myname are different identifiers
Reserved Keywords:
- Cannot be the same as reserved keywords
Naming Convention

camelCase

PascalCase

snake_case
Naming Convention

camelCase First letter of the first word is lowercase, and the first
letter of each subsequent word is capitalized
Languange: JavaScript and Java

First letter of the first word is capitalized, and the first


PascalCase letter of each subsequent word is capitalized
Language: C#, Java, and .NET.

snake_case Words are separated by underscores, and all letters


are typically lowercase.
Language: Python and Ruby
Valid Variable Names Invalid Variable Names

my_name sum
Variables

student_name True
student_gpa list
studentGpa
False
studentScore
None
Valid Variable Names Invalid Variable Names

my_name sum
Variables

student_name True You will find them


student_gpa with green-colored
list text on the Jupyter
studentGpa Notebook.
False
studentScore
None
You CANNOT use these keywords as an IDENTIFIER
Identifier

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Statements

Python Statement
Write a program to calculate a student’s total average score based on
the following information.

exam1 = 90 #15%
Python code

exam2 = 95 #15%
finalExam = 93 #25%

paScore = 98 #25%
zyScore = 90 #10%
tophatScore = 90 #10%

avgScore = (exam1*0.15) + (exam2*0.15) +


(finalExam*0.25) + (paScore*0.25) + (zyScore*0.1) +
(tophatScore*0.1)
Comments

Comments
Multi-line '''Initial temperature
comment in Celsius
'''
celsius = 28.5
Formatting

Single-line
# Convert Celsius to Fahrenheit
comment
fahrenheit = (celsius * 9/5) + 32
print('Temperature in Fahrenheit is:' + str(fahrenheit))
print(f"Temperature in Fahrenheit is: {fahrenheit:.1f} F")

# Modifying the temperature in Celsius


celsius = 35.5
fahrenheit = (celsius * 9/5) + 32
print(‘Temperature in Fahrenheit is:' + str(fahrenheit) + " C")
Comments

Formatted Print
# Initial temperature in Celsius
celsius = 28.5

# Convert Celsius to Fahrenheit Formatted string is in between “ ”


Formatting

fahrenheit = (celsius * 9/5) + 32


print('Temperature in Fahrenheit is:' + str(fahrenheit))
print(f"Temperature in Fahrenheit is: {fahrenheit:.1f} F")
{ } works as a placeholder
# Modifying the temperature in Celsius
celsius = 35.5 .1f means one digits after
decimal point
fahrenheit = (celsius * 9/5) + 32
print(‘Temperature in Fahrenheit is:' + str(fahrenheit) + " C")
Arithmetic Expressions

Arithmetic Expressions
Arithmetic Expressions
float is a data type for floating-point numbers.
Two digits after the decimal point print(f'{myFloat:.2f}')

Arithmetic Operator/Convention
Description
operator ()
+ addition
exponent **
- subtraction
unary -
* multiplication
*/%
/ division
+-
x ** y (x to the power of
**
y) left-to-right
Compound Operators

Compound Operators
Compound Operators

Expression with Equivalent


Compound operator
compound operator expression
Addition age += 1 age = age + 1
Subtraction age -= 1 age = age - 1
Multiplication age *= 1 age = age * 1
Division age /= 1 age = age / 1
Modulo age %= 1 age = age % 1
Note: regardless of the data types of the operands,
the division operator will always result in a float type
Division Operator /

X = 1 / 2 # Evaluates to 0.5
X = 1 / 2.0 # Evaluates to 0.5
X = 1.0 / 2 # Evaluates to 0.5
X = 1.0 / 2.0 # Evaluates to 0.5
Implicit conversion
A = 1
B = 2
X = A / B # Evaluates to 0.5
• Type conversion that is implicit
Implicit and Explicit Type Conversions
• The conversion is done automatically by the interpreter

Convert a String to a Double in Python Using the float() Function.

Explicit conversion
an_int = int(7.8)
a_float = float(7) OUTPUT
7
print(an_int)
7.0
print(a_float)

Note: commas are NOT allowed in an integer literal!


Operator: // vs %

Floored division (//) MODULO Operator (%)


value = 123 value = 123
value = value//10 value = value % 10
print(value) print(value)

12 3
Input()

input() function
Get input from user
How old are you?
User’s Input

This Photo by Unknown Author is licensed under CC BY-NC-ND


Explicit conversion
Input/Output

# Get age input from the user


age = int(input("Please enter your age: "))

years_to_vote = 18 - age
print(f"You are {years_to_vote} years away from
being eligible to vote in the USA.")
The round Function

print(round(3.955555,2))
print(round(-3.1))
print(round(3.1))
print(round(-3.9))

3.96
-3
3
-4
Math Module

import math
Calling math Functions

import math

square_root = math.sqrt(121.0)
print(square_root) The math.fabs() method returns
the absolute value of a number, as
a float
print(math.fabs(-50) * 2)

11.0
100.0
Number representation and theoretic functions
The math Module

ceil(x) Round up value fabs(x) Absolute value


factorial(x) factorial (3) = 6 floor(x) Round down value

Power, exponential, and logarithmic functions


Natural logarithm;
exp(x) Exponential function = ex log(x, (base))
base is optional
pow(x, y) Raise x to power y sqrt(x) Square root
math.floor() and ceil()

import math

floor_pos = math.floor(3.9) # 3
floor_neg = math.floor(-3.1) # -4

import math

floor_pos = math.ceil(3.1) # 4
−∞ 0 +∞
floor_neg = math.ceil(-3.9) # -3

pcwallart.com
This Photo by Unknown Author is licensed under CC BY-NC This Photo by Unknown Author is licensed under CC BY-NC

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy