until first coding challenge

This commit is contained in:
waldek 2021-10-27 16:39:11 +02:00
parent ee2ebdac59
commit 6e12056589
1 changed files with 154 additions and 3 deletions

View File

@ -189,6 +189,16 @@ The [prompt](https://en.wikipedia.org/wiki/Command-line_interface#Command_prompt
This is one of the slight nuances between running scripts and using the shell. This is one of the slight nuances between running scripts and using the shell.
The shell is more *verbose* and will explicitly tell you what a function returns, unless it doesn't return anything. The shell is more *verbose* and will explicitly tell you what a function returns, unless it doesn't return anything.
## Some functions are blocking
When we call `print` the function is executed immediately and the python interpreter continues with the next line.
The `input` function is slightly different.
It is called a **blocking** function.
When a blocking function is called the program is *waiting* for some action.
Once the condition is met, the program continues.
It's important to be aware of this but don't overthink it.
We'll get back to this behaviour later.
## Functions can return something ## Functions can return something
So, functions can **return** something but how can we *use* the returned objects? So, functions can **return** something but how can we *use* the returned objects?
@ -242,22 +252,163 @@ The most logical type would be a `str` that represents the *question* to ask the
Let's try it out. Let's try it out.
```python3 ```python3
answer = input("What is your name?")
print("Well hello {}!".format(answer))
``` ```
🏃 Try it
---
Modify the questions you asked before so they have a proper prompt via the `input` function.
Ask multiple questions and combine the answers to print on one line with different `print` formatting.
# Taking input and evaluation # Taking input and evaluation
TODO say hello plus ask for age We can do a lot more with the input from users than just print it back out.
It can be used to make logical choices based on the return **value**.
This is a lot easier than you think.
Imagine you ask me my age.
When I respond with *35* you'll think to yourself *"that's old!"*.
If I would be younger then *30* you would think I'm young.
We can implement this logic in python with easy to read syntax.
First we'll take a python **shell** to experiment a bit.
* slightly insist on *blocking* nature of `input()` ```python3
>>> 35 > 30
True
>>> 25 > 30
False
>>> 30 > 30
False
>>> 30 >= 30
True
>>>
```
The `True` and `False` you see are also objects but of the type `bool`.
If you want to read up a bit more on boolean logic I can advise you [this](https://en.wikipedia.org/wiki/Boolean_algebra) page and also [this](https://realpython.com/lessons/boolean-logic/).
This boolean logic open the door towards **conditional logic**.
## Conditional logic ## Conditional logic
* introduction to `if`, `elif` and `else` Let's convert the quote below to logical statements.
> If you are younger than 27 you are still young so if you're older than 27 you're considered old, but if you are 27 on the dot your life might be at [risk](https://en.wikipedia.org/wiki/27_Club)!
```python3
age = 35
if age < 27:
print("you are still very young, enjoy it!")
elif age > 27:
print("watch out for those hips oldie...")
else:
print("you are at a dangerous crossroad in life!")
```
## Class string methods ## Class string methods
Let's take the logic above and implement it in a real program.
I would like the program to ask the user for his/her name and age.
After both questions are asked I would like the program to show a personalized message to the user.
The code below is functional but requires quite a bit of explaining!
```python3
name = input("What is you name?")
age = input("What is you age?")
if age.isdigit():
age = int(age)
else:
print("{} is not a valid age".format(age))
exit(1)
if age < 27:
print("My god {}, you are still very young, enjoy it!".format(name))
elif age > 27:
print("Wow {}! Watch out for those hips oldie...".format(name))
else:
print("{}, you are at a dangerous crossroad in life!".format(name.capitalize()))
```
An object of the type `str` has multiple **methods** that can be applied on itself.
It might not have been obvious but the *string formatting* via `"hello {}".format("world")` we did above is exactly this.
We **call** the `.format` **method** on a `str` object.
Strings have a handful of methods we can call.
Pycharm lists these methods when you type `.` after a string.
In the **shell** we can visualize this as well.
For those of you not familiar with shells have a look at [tab completion](https://en.wikipedia.org/wiki/Command-line_completion).
```python3
>>> name = "wouter"
>>> name.
name.capitalize( name.format( name.isidentifier( name.ljust( name.rfind( name.startswith(
name.casefold( name.format_map( name.islower( name.lower( name.rindex( name.strip(
name.center( name.index( name.isnumeric( name.lstrip( name.rjust( name.swapcase(
name.count( name.isalnum( name.isprintable( name.maketrans( name.rpartition( name.title(
name.encode( name.isalpha( name.isspace( name.partition( name.rsplit( name.translate(
name.endswith( name.isascii( name.istitle( name.removeprefix( name.rstrip( name.upper(
name.expandtabs( name.isdecimal( name.isupper( name.removesuffix( name.split( name.zfill(
name.find( name.isdigit( name.join( name.replace( name.splitlines(
>>> name.capitalize()
'Wouter'
>>> name.isd
name.isdecimal( name.isdigit(
>>> name.isdigit()
False
>>> age = "35"
>>> age.isdigit()
True
>>>
```
⛑ **Remember CTRL-q opens the documentation in Pycharm and don't forget to actually use it!**
# Coding challenge - Celsius to Fahrenheit converter # Coding challenge - Celsius to Fahrenheit converter
Your first challenge!
I would like you to write a program that converts celcius to farenheit.
The result of this program *could* be as follows.
```bash
➜ ~ git:(master) ✗ python3 ex_celcius_to_farenheit.py
What's the temperature?30
30°C equals 86.0°F
Go turn off the heating!
➜ ~ git:(master) ✗ python3 ex_celcius_to_farenheit.py
What's the temperature?4
4°C equals 39.2°F
Brrrr, that's cold!
➜ ~ git:(master) ✗ python3 ex_celcius_to_farenheit.py
What's the temperature?blabla
I can't understand you...
➜ ~ git:(master) ✗
```
<details>
<summary>Spoiler warning</summary>
```python3
result = input("What's the temperature?")
if result.isdigit():
celsius = int(result)
else:
print("I can't understand you...")
exit(1)
farenheit = celsius * (9/5) + 32
print("{}°C equals {}°F".format(celsius, farenheit))
if celsius < 15:
print("Brrrr, that's cold!")
else:
print("Go turn off the heating!")
```
</details>
# A text based adventure game # A text based adventure game
TODO mini text based adventure game to point out the complexity of conditional logic and flow control TODO mini text based adventure game to point out the complexity of conditional logic and flow control