Grok 3 Instructions
For in-depth information, go to Python 3.13 Documentation
- string operation:
- calculations:
- list operations:
- loops:
- def function:
def say_hello(): print('Hello, coder!') say_hello() # Hello, coder!
def greet(name): print(f'Hi {name}! Ready to code?') greet('Doe') # Hi Doe! Ready to code?
def add_numbers(a,b): return a+b result = add_numbers(5,6) print(result) # 11
def pluralize_fruit(fruits): modified = [fruit + 's' for fruit in fruits] return modified plural = pluralize_fruit(fruits[1:3]) # ['bananas', 'grapes']
numbers = [1,4,3,2,5,6,7,8,9,10] def greater_than_five(num): return num > 5 filtered = list(filter(greater_than_five, numbers)) print(filtered) # [6, 7, 8, 9, 10]
- Conditionals (if Statements):
age = 20 if age >= 18: print('You are eligible to vote.')
age = 15 if age >= 18: print('You are an adult.') else: print('You are a minor.')
score = 85 if score >=90: print('A grade') elif score >= 80: print('B grade') else: print('Keep trying!')
# print numbers until an odd number is found numbers = [4,2,6,5,7,8,9,10] for x in numbers: print(x) if x % 2 == 1: break # 4 2 6 5
def long(fruit): if len(fruit) > 5: return True else: return False long_fruits = [fruit for fruit in fruits if long(fruit)] #['banana', 'pineapple', 'watermelon']
or using the filter() function:
fruits = ['apple', 'banana', 'guava', 'kiwi', 'pineapple', 'grape', 'watermelon', 'lemon'] def long(fruit): return len(fruit) > 5 filtered = list(filter(long, fruits)) print(filtered) # ['banana', 'pineapple', 'watermelon']
def check_fruit(fruit): if len(fruit) > 5: return f'{fruit} is long!' elif len(fruit) == 5: return f'{fruit} is medium!' else: return f'{fruit} is short!' for fruit in fruits: print(check_fruit(fruit)) # apple is medium! # banana is long! # grape is medium! # guava is medium! # kiwi is short! # lemon is medium! # pineapple is long! # watermelon is long!
def rate_food(food): if food.startswith('p'): return f'{food}: Love it!' elif len(food) > 5: return f'{food}: Too long!' else: return f'{food}: Okay!' foods = ['pasta', 'sushi', 'macroons', 'crepes'] for food in foods: print(rate_food(food)) # pasta: Love it! # sushi: Okay! # macroons: Too long! # crepes: Too long!
- Dictionaries: A dictionary is as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary)
- with open('filename', 'mode') as file: For more info Python open
"with" ensures the file closes properly after writing.
filename: Specifies the name of the file to be opened. (creates it if it doesn’t exist, overwrites if it does)
mode: Determines the mode in which the file is opened.
For example:
Name = 'Doe' # string
Age = 30 # integer
Height = 5.9 # float
is_adult = True # boolean
print (f'{Name} is {Age} years old, {Height} feet tall and is an adult: {is_adult}') # Doe is 30 years old, 5.9 feet tall and is an adult: True
x = 10
y = 3
print (x+y) # addition (13)
print (x//y) # integer division (3)
print (x%y) # modulo (1)
fruits = ['apple', 'banana', 'guava', 'kiwi']
fruits.append('orange') # add 'orange' to the end of the list
fruits.insert(1, 'mango') # insert 'mango' at index 1
fruits.pop(-1) # remove the last element
fruits.remove('mango') # remove the first occurence of 'mango'
print(fruits[0]) # print the first element (apple)
print(fruits[-1]) # print the last element (banana)
print(fruits[1:3]) # print the second and third element (banana, guava)
fruits.index('apple') # 0
more_fruits = ['pineapple', 'grape']
fruits.extend(more_fruits) # add more_fruits to fruits
fruits += ['watermelon', 'lemon'] # add more fruits to fruits
fruits.sort() # sort the list in ascending order
fruits.sort(reverse=True) # sort the list in descending order
fruits.reverse() # reverses the list order
upper_fruits = [fruit.upper() for fruit in fruits] # convert each fruit to uppercase
plural = [fruit + 's' for fruit in fruits]
print(plural) # add 's' to each fruit # ['watermelons', 'pineapples', 'oranges', 'lemons', 'grapes', 'bananas', 'apples']
len(fruits) # 8
for fruit in fruits:
print(f'I like {fruit}s.') # print each fruit in the list
# I like apples.
# I like bananas.
# I like grapes.
# I like guavas.
# I like kiwis.
# I like lemons.
# I like pineapples.
# I like watermelons.
# print even numbers
numbers = [1,4,3,2,5,6,7,8,9,10]
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers) # [4, 2, 6, 8, 10]
# print numbers greater than 5
numbers = [1,4,3,2,5,6,7,8,9,10]
big_numbers = [num for num in numbers if num > 5]
print(big_numbers) # [6, 7, 8, 9, 10]
food_ratings = {'sushi':'Love it!', 'pasta':'Yummy!', 'pizza':'Great!'}
food_ratings['sushi'] # 'Love it!'
food_ratings['macarons']='Super!' # add a new key-value pair
food_ratings['pizza']='Okay!' # update the value of an existing key
del food_ratings['pizza'] # remove a key-value pair
food_ratings['macarons'] # 'Super!'
food_ratings.keys() # dict_keys(['sushi', 'pasta', 'macarons'])
food_ratings.values() # dict_values(['Love it!', 'Yummy!', 'Super!'])
food_ratings.items() # dict_items([('sushi', 'Love it!'), ('pasta', 'Yummy!'), ('macarons', 'Super!')])
sorted(food_ratings) # ['macarons', 'pasta', 'sushi']
sorted(food_ratings.values()) # ['Love it!', 'Super!', 'Yummy!']
'sushi' in food_ratings # True
'pasta' not in food_ratings # False
for food, rating in food_ratings.items():
print(f'I think {food} is {rating}')
# I think sushi is Love it!
# I think pasta is Yummy!
# I think macarons is Super!
if 'tacos' in food_ratings:
print("I've rated tacos.")
else:
print("No tacos yet.")
def create_ratings(foods):
ratings = {}
for food in foods:
if food.startswith('p'):
ratings[food] = 'Love it!'
elif len(food) < 6:
ratings[food] = 'Meh!'
else:
ratings[food] = 'Yum!'
return ratings
foods = ['pasta', 'sushi', 'macarons', 'crepes', 'barbecue']
food_dict = create_ratings(foods)
for food, rating in food_dict.items():
print(f'I think {food} is {rating}')
# I think pasta is Love it!
# I think sushi is Meh!
# I think macarons is Yum!
# I think crepes is Yum!
# I think barbecue is Yum!

# writing to the file
food_pref = {'sushi':'Love it!', 'pasta':'Yummy', 'macarons':'Super!'}
with open('food_ratings.txt', 'w') as file:
for food, rating in food_pref.items():
file.write(f'{food}: {rating}\n') # \n is a newline character
# Reading and printing the file contents
with open('food_ratings.txt', 'r') as file:
print(file.read())
# sushi: Love it!
# pasta: Yummy
# macarons: Super!
# export to excel
import pandas as pd
# Convert dictionary to DataFrame
df = pd.DataFrame(list(food_pref.items()), columns=['Food', 'Rating'])
# Export to Excel
df.to_excel('food_ratings.xlsx', index=False)
# append to the file
more_food_pref = {'barbecue':'Great!'}
# append to food_ratings.txt
with open('food_ratings.txt', 'a') as file:
for food, rating in more_food_pref.items():
file.write(f'{food}: {rating}\n')
# read and print the updated file
with open('food_ratings.txt', 'r') as file:
print(file.read())
# sushi: Love it!
# pasta: Yummy
# macarons: Super!
# barbecue: Great!