상세 컨텐츠

본문 제목

Control Flow

Python

by techbard 2024. 11. 25. 21:16

본문

반응형

 

# while loop, dict, type annotation의 사용
import random

count: int = 5
# Generate 'n' unique random numbers within a range
ran_nums: list = random.sample(range(10), count)
d: dict = {num: 'even/odd' for num in ran_nums}

while count > 0:
    cur_num: int = ran_nums[count-1]
    if cur_num % 2 == 0 :
        d[cur_num] = 'even'
    else:
        d[cur_num] = 'odd'
    count -= 1

print(d)

# 결과
{2: 'even', 8: 'even', 7: 'odd', 9: 'odd', 3: 'odd'}

 

# I must stress, though that your priority
# should always be readability.
# And that while shortened code might look
# cool at first, in the long run it will absolutely
# waste everybody's time.
# It's up to you to decide whether it's readable or not.

name: int = 2
# one liner solution (== shorthand if else statement)
result: str = 'Above 0' if name > 0 else '0 or below'
print(result)

# 다만, shorthand로 구현하면 중간에 추가 코드 블럭을 넣을 수 없다.
condition: bool = True
var: str = 'True' if condition else 'False'
print(var)

# 결과
Above 0
True

 

# for-loop: allows us to iterate through any iterable and to execute code
# on each iteration.

# type hint. list내의 요소의 타입도 명시 가능하다.
people: list[str] = ['Bob', 'James', 'Maria']

for person in people:
    if len(person) > 4:
        print(f"{person} has a long name.")
    else:
        print(f"{person} has a short name.")

# 결과
Bob has a short name.
James has a long name.
Maria has a long name.

 

# while - loop
import time

connected: bool = True

while connected:
    print("Using internet...")
    time.sleep(3)
    connected = False

print("Connection ended...")

# 결과
Using internet...
Connection ended...

 

# while - loop example

print("Welcome to Calc plus!")
print('\t Add positive numbers, or enter "0" to exit.')

total = []
while True:
    user_input: int = int(input("Enter a number: "))
    if user_input < 0:
        print("!!!Please enter a positive number.")
        continue
    elif user_input == 0:
        print(f"Sum of your input: {sum(total)}")
        break
    else:
        total.append(user_input)

# 결과
Welcome to Calc plus!
	 Add positive numbers, or enter "0" to exit.
Enter a number: 10
Enter a number: 20
Enter a number: -5
!!!Please enter a positive number.
Enter a number: 0
Sum of your input: 30

 

# RPS

import random
import sys

moves: dict = {'rock': 'Rock', 'paper': 'Paper', 'scissors': 'Scissors'}
valid_moves: list[str] = list(moves.keys())

while True:
    user_move: str = input('Rock, paper, or scissors? >> ').lower()
    
    if user_move == 'exit':
        print("Thanks for playing!")
        sys.exit()
        
    elif user_move not in valid_moves:
        print("You entered invalid moves. try again...")
        continue
    
    ai_move: str = random.choice(valid_moves)

    print("-----")
    print(f"You: {moves[user_move]}")
    print(f"AI: {moves[ai_move]}")
    
    # Check moves
    if user_move == ai_move:
        print("It's a tie!")
    elif user_move == 'rock' and ai_move == 'scissors':
        print("You win!")
    elif user_move == 'scissors' and ai_move == 'paper':
        print("You win!")
    elif user_move == 'paper' and ai_move == 'rock':
        print("You win!")
    else:
        print("AI win...")
 
 # 결과
 Rock, paper, or scissors? >> paper
-----
You: Paper
AI: Paper
It's a tie!
Rock, paper, or scissors? >> exit
Thanks for playing!

 

# Guess number game

import random
import sys

def create_guess_num():
    return random.randint(1, 100)

user_try = 1
guess_num = create_guess_num()
print(f"Welcome to guess number game")

while True:
    try:
        user_num = int(input("\tGuess one number (1-100) or exit to 0 >> "))
        if user_num < 0:
            raise ValueError
        if user_num == 0:
            print("Bye! now.")
            sys.exit()
    except ValueError:
        print("\tInvalid number. try again.")
        continue
   
    if user_num < guess_num:
        print("\tIt's a high number.")
    elif user_num > guess_num:
        print("\tIt's a low number.")
    elif user_num == guess_num:
        print("\t=====")
        print(f"\tCorrect! Guess num: {guess_num}, you tried {user_try} rounds.")
        print("\t=====")
        sys.exit()
    user_try += 1

# 결과
Welcome to guess number game
	Guess one number (0-100) or exit to 0 >> 50
	It's a high number.
	Guess one number (0-100) or exit to 0 >> 75
	It's a high number.
	Guess one number (0-100) or exit to 0 >> 85
	It's a high number.
	Guess one number (0-100) or exit to 0 >> 90
	It's a high number.
	Guess one number (0-100) or exit to 0 >> 95
	It's a low number.
	Guess one number (0-100) or exit to 0 >> 93
	It's a low number.
	Guess one number (0-100) or exit to 0 >> 92
	It's a low number.
	Guess one number (0-100) or exit to 0 >> 91
	=====
	Correct! Guess num: 91, you tried 8 rounds.
	=====
반응형

관련글 더보기

댓글 영역